o
    yih4                     @   s  d dl mZ d dlmZmZmZmZ d dlZd dl	Z	d dl	m
Z
 d dlmZ d dlmZ d dlmZ d dlmZ d d	lmZmZ erId d
lmZ nG dd deZddgZer[d dlZG dd deZG dd deZejZdde
de
de
de
dede
fddZG dd deZ dS )    )deepcopy)AnyListOptionalUnionN)Tensor)Function)Module)Metric)rank_zero_info)_SCIPY_AVAILABLE_TORCH_FIDELITY_AVAILABLE)FeatureExtractorInceptionV3c                   @   s   e Zd ZdS )r   N)__name__
__module____qualname__ r   r   J/home/ubuntu/.local/lib/python3.10/site-packages/torchmetrics/image/fid.pyr      s    r   FrechetInceptionDistanceFIDc                	       sf   e Zd Z	ddedee dee ddf fddZdedd f fd	d
Zde	de	f fddZ
  ZS )NoTrainInceptionV3Nnamefeatures_listfeature_extractor_weights_pathreturnc                    s   t  ||| |   d S N)super__init__eval)selfr   r   r   	__class__r   r   r   *   s   zNoTrainInceptionV3.__init__modec                    s   t  dS )zRthe inception network should not be able to be switched away from evaluation mode.F)r   train)r   r"   r    r   r   r#   4   s   zNoTrainInceptionV3.trainxc                    s"   t  |}|d |jd dS )Nr   )r   forwardreshapeshape)r   r$   outr    r   r   r&   8   s   zNoTrainInceptionV3.forwardr   )r   r   r   strr   r   r   boolr#   r   r&   __classcell__r   r   r    r   r   )   s    
r   c                   @   sD   e Zd ZdZedededefddZedededefdd	Zd
S )MatrixSquareRootzoSquare root of a positive definite matrix.

    All credit to `Square Root of a Positive Definite Matrix`_
    ctx
input_datar   c                 C   sL   |    tj}tjj|dd\}}t	
|j|}| | |S )NF)disp)detachcpunumpyastypenpfloat_scipylinalgsqrtmtorch
from_numpyrealtosave_for_backward)r.   r/   m	scipy_res_r9   r   r   r   r&   C   s
   
zMatrixSquareRoot.forwardgrad_outputc                 C   sf   d }| j d r1| j\}|j  tj}|j  tj}tj	
|||}t||}|S )Nr   )needs_input_gradsaved_tensorsdatar2   r3   r4   r5   r6   r7   r8   solve_sylvesterr:   r;   r=   )r.   rB   
grad_inputr9   gm
grad_sqrtmr   r   r   backwardM   s   
zMatrixSquareRoot.backwardN)	r   r   r   __doc__staticmethodr   r   r&   rJ   r   r   r   r   r-   =   s    	r-   ư>mu1sigma1mu2sigma2epsr   c           	      C   s   | | }t ||}t| s4td| d tj|d| j| j	d| }t || || }t
|}||t
| t
| d|  S )a  Adjusted version of `Fid Score`_

    The Frechet Inception Distance between two multivariate Gaussians X_x ~ N(mu_1, sigm_1)
    and X_y ~ N(mu_2, sigm_2) is d^2 = ||mu_1 - mu_2||^2 + Tr(sigm_1 + sigm_2 - 2*sqrt(sigm_1*sigm_2)).

    Args:
        mu1: mean of activations calculated on predicted (x) samples
        sigma1: covariance matrix over activations calculated on predicted (x) samples
        mu2: mean of activations calculated on target (y) samples
        sigma2: covariance matrix over activations calculated on target (y) samples
        eps: offset constant - used if sigma_1 @ sigma_2 matrix is singular

    Returns:
        Scalar value of the distance between sets.
    z2FID calculation produces singular product; adding z$ to diagonal of covariance estimatesr   )devicedtype   )r9   mmr:   isfiniteallr   eyesizerS   rT   tracedot)	rN   rO   rP   rQ   rR   diffcovmeanoffset
tr_covmeanr   r   r   _compute_fidb   s   
&ra   c                       s   e Zd ZU dZdZeed< dZeed< dZeed< e	ed< e	ed< e	ed< e	ed	< e	ed
< e	ed< 			dde
eef dedededdf
 fddZde	deddfddZde	fddZd fddZ  ZS ) r   u[  Calculates Fréchet inception distance (FID_) which is used to access the quality of generated images. Given
    by.

    .. math::
        FID = |\mu - \mu_w| + tr(\Sigma + \Sigma_w - 2(\Sigma \Sigma_w)^{\frac{1}{2}})

    where :math:`\mathcal{N}(\mu, \Sigma)` is the multivariate normal distribution estimated from Inception v3
    (`fid ref1`_) features calculated on real life images and :math:`\mathcal{N}(\mu_w, \Sigma_w)` is the
    multivariate normal distribution estimated from Inception v3 features calculated on generated (fake) images.
    The metric was originally proposed in `fid ref1`_.

    Using the default feature extraction (Inception v3 using the original weights from `fid ref2`_), the input is
    expected to be mini-batches of 3-channel RGB images of shape ``(3 x H x W)``. If argument ``normalize``
    is ``True`` images are expected to be dtype ``float`` and have values in the ``[0, 1]`` range, else if
    ``normalize`` is set to ``False`` images are expected to have dtype ``uint8`` and take values in the ``[0, 255]``
    range. All images will be resized to 299 x 299 which is the size of the original training data. The boolian
    flag ``real`` determines if the images should update the statistics of the real distribution or the
    fake distribution.

    .. note:: using this metrics requires you to have ``scipy`` install. Either install as ``pip install
        torchmetrics[image]`` or ``pip install scipy``

    .. note:: using this metric with the default feature extractor requires that ``torch-fidelity``
        is installed. Either install as ``pip install torchmetrics[image]`` or
        ``pip install torch-fidelity``

    As input to ``forward`` and ``update`` the metric accepts the following input

    - ``imgs`` (:class:`~torch.Tensor`): tensor with images feed to the feature extractor with
    - ``real`` (:class:`~bool`): bool indicating if ``imgs`` belong to the real or the fake distribution

    As output of `forward` and `compute` the metric returns the following output

    - ``fid`` (:class:`~torch.Tensor`): float scalar tensor with mean FID value over samples

    Args:
        feature:
            Either an integer or ``nn.Module``:

            - an integer will indicate the inceptionv3 feature layer to choose. Can be one of the following:
              64, 192, 768, 2048
            - an ``nn.Module`` for using a custom feature extractor. Expects that its forward method returns
              an ``(N,d)`` matrix where ``N`` is the batch size and ``d`` is the feature size.

        reset_real_features: Whether to also reset the real features. Since in many cases the real dataset does not
            change, the features can cached them to avoid recomputing them which is costly. Set this to ``False`` if
            your dataset does not change.
        kwargs: Additional keyword arguments, see :ref:`Metric kwargs` for more info.

    Raises:
        ValueError:
            If ``feature`` is set to an ``int`` (default settings) and ``torch-fidelity`` is not installed
        ValueError:
            If ``feature`` is set to an ``int`` not in [64, 192, 768, 2048]
        TypeError:
            If ``feature`` is not an ``str``, ``int`` or ``torch.nn.Module``
        ValueError:
            If ``reset_real_features`` is not an ``bool``

    Example:
        >>> import torch
        >>> _ = torch.manual_seed(123)
        >>> from torchmetrics.image.fid import FrechetInceptionDistance
        >>> fid = FrechetInceptionDistance(feature=64)
        >>> # generate two slightly overlapping image intensity distributions
        >>> imgs_dist1 = torch.randint(0, 200, (100, 3, 299, 299), dtype=torch.uint8)
        >>> imgs_dist2 = torch.randint(100, 255, (100, 3, 299, 299), dtype=torch.uint8)
        >>> fid.update(imgs_dist1, real=True)
        >>> fid.update(imgs_dist2, real=False)
        >>> fid.compute()
        tensor(12.7202)
    Fhigher_is_betteris_differentiablefull_state_updatereal_features_sumreal_features_cov_sumreal_features_num_samplesfake_features_sumfake_features_cov_sumfake_features_num_samples   Tfeaturereset_real_features	normalizekwargsr   Nc           	         s~  t  jdi | t|tr4|}tstdg d}||vr)td| d| dtdt|gd| _	nt|t
rO|| _	tjdd	d
tjd}| 	|jd }ntdt|ts\td|| _t|tshtd|| _||f}| jdt| dd | jdt| dd | jdtd dd | jdt| dd | jdt| dd | jdtd dd d S )NzFrechetInceptionDistance metric requires that `Torch-fidelity` is installed. Either install as `pip install torchmetrics[image]` or `pip install torch-fidelity`.)@      i   rk   z3Integer input to argument `feature` must be one of z
, but got .zinception-v3-compat)r   r   r      )      +  rv   )rT   r%   z'Got unknown input to argument `feature`z4Argument `reset_real_features` expected to be a boolz*Argument `normalize` expected to be a boolre   sum)dist_reduce_fxrf   rg   rh   ri   rj   r   )r   r   
isinstanceintr   ModuleNotFoundError
ValueErrorr   r*   	inceptionr	   r:   randintuint8r(   	TypeErrorr+   rm   rn   	add_statezerosdoubletensorlong)	r   rl   rm   rn   ro   num_featuresvalid_int_inputdummy_imagemx_nb_feetsr    r   r   r      s>   



z!FrechetInceptionDistance.__init__imgsr<   c                 C   s   | j r	|d  n|}| |}|j| _| }| dkr#|d}|rH|  j|j	dd7  _|  j
| |7  _
|  j|jd 7  _dS |  j|j	dd7  _|  j| |7  _|  j|jd 7  _dS )z)Update the state with extracted features.rs   rt   r   )dimN)rn   byter}   rT   
orig_dtyper   r   	unsqueezere   rw   rf   trV   rg   r(   rh   ri   rj   )r   r   r<   featuresr   r   r   update  s   

zFrechetInceptionDistance.updatec                 C   s   | j | j d}| j| j d}| j| j| |  }|| jd  }| j| j| |  }|| jd  }t	|
d||
d|| jS )zWCalculate FID score based on accumulated extracted features from the two distributions.r   rt   )re   rg   r   rh   rj   rf   r   rV   ri   ra   squeezer=   r   )r   	mean_real	mean_fakecov_real_numcov_realcov_fake_numcov_faker   r   r   compute  s   "z FrechetInceptionDistance.computec                    sR   | j s"t| j}t| j}t| j}t   || _|| _|| _d S t   d S r   )rm   r   re   rf   rg   r   reset)r   re   rf   rg   r    r   r   r   "  s   




zFrechetInceptionDistance.reset)rk   TF)r   N)r   r   r   rK   rb   r+   __annotations__rc   rd   r   r   rz   r	   r   r   r   r   r   r,   r   r   r    r   r      s8   
 I
0)rM   )!copyr   typingr   r   r   r   r3   r5   r:   r   torch.autogradr   torch.nnr	   torchmetrics.metricr
   torchmetrics.utilitiesr   torchmetrics.utilities.importsr   r   ,torch_fidelity.feature_extractor_inceptionv3r   __doctest_skip__r7   r   r-   applyr9   floatra   r   r   r   r   r   <module>   s*   "$