a
    dBI                     @   s4  d dl mZ d dlmZmZmZmZmZm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mZmZ d d	lmZmZ esd
gng Zesedg7 Zerd dlmZ d dlmZ d dlmZ n G dd deZdZdZddgZesddgZG dd deZ e
e
e
e
e
dddZ!G dd deZ"dS )    )deepcopy)AnyListOptionalSequenceTupleUnionN)Tensor)Module)adaptive_avg_pool2d)Metric)_MATPLOTLIB_AVAILABLE_TORCH_FIDELITY_AVAILABLE_TORCH_GREATER_EQUAL_1_9)_AX_TYPE_PLOT_OUT_TYPE!FrechetInceptionDistance.__init__FrechetInceptionDistance.plot)FeatureExtractorInceptionV3)vassert))interpolate_bilinear_2d_like_tensorflow1xc                   @   s   e Zd ZdS )_FeatureExtractorInceptionV3N)__name__
__module____qualname__ r   r   _/var/www/html/stable-diffusion-webui/venv/lib/python3.9/site-packages/torchmetrics/image/fid.pyr   %   s   r   FrechetInceptionDistancec                       sr   e Zd ZdZdeee ee dd fddZed d fddZ	e
ee
d	f d
ddZe
e
d
ddZ  ZS )NoTrainInceptionV3z*Module that nevers leaves evaluation mode.N)namefeatures_listfeature_extractor_weights_pathreturnc                    s   t  ||| |   d S N)super__init__eval)selfr   r    r!   	__class__r   r   r%   4   s    zNoTrainInceptionV3.__init__)moder"   c                    s   t  dS )z.Force network to always be in evaluation mode.F)r$   train)r'   r*   r(   r   r   r+   >   s    zNoTrainInceptionV3.train.)xr"   c                    s  t t|o|jtjkd i  | j }t| dr@|| j	n
|tj
}t|| j| jfdd}|d d }| |}| |}| |}| |}d|v rt|ddd	d	 d< |d t|d
krt fdd| jD S | |}| |}| |}d|v r\t|ddd	d	 d< |d t|d
kr\t fdd| jD S | |}| |}| |}| |}| |}| |}| |}|  |}d|v rt|ddd	d	 d< |d t|d
krt fdd| jD S | !|}| "|}| #|}| $|}t%|d}d|v rx| d< |d t|d
krxt fdd| jD S d|v r|&| j'j(j)}| d< |d t|d
krt fdd| jD S || j'j*+d
 }n
| '|}| d< t fdd| jD S )a  Forward method of inception net.

        Copy of the forward method from this file:
        https://github.com/toshas/torch-fidelity/blob/master/torch_fidelity/feature_extractor_inceptionv3.py
        with a single line change regarding the casting of `x` in the beginning.

        Corresponding license file (Apache License, Version 2.0):
        https://github.com/toshas/torch-fidelity/blob/master/LICENSE.md

        z6Expecting image as torch.Tensor with dtype=torch.uint8_dtypeF)sizeZalign_corners   Z64)   r0   )Zoutput_sizer   c                 3   s   | ]} | V  qd S r#   r   .0afeaturesr   r   	<genexpr>b       z=NoTrainInceptionV3._torch_fidelity_forward.<locals>.<genexpr>Z192c                 3   s   | ]} | V  qd S r#   r   r2   r5   r   r   r7   l   r8   Z768c                 3   s   | ]} | V  qd S r#   r   r2   r5   r   r   r7   {   r8   r0   Z2048c                 3   s   | ]} | V  qd S r#   r   r2   r5   r   r   r7      r8   Zlogits_unbiasedc                 3   s   | ]} | V  qd S r#   r   r2   r5   r   r   r7      r8   Zlogitsc                 3   s   | ]} | V  qd S r#   r   r2   r5   r   r   r7      r8   ),r   torchZ	is_tensordtypeuint8r    copyhasattrtor-   floatr   ZINPUT_IMAGE_SIZEZConv2d_1a_3x3ZConv2d_2a_3x3ZConv2d_2b_3x3Z	MaxPool_1r   squeezeremovelentupleZConv2d_3b_1x1ZConv2d_4a_3x3Z	MaxPool_2ZMixed_5bZMixed_5cZMixed_5dZMixed_6aZMixed_6bZMixed_6cZMixed_6dZMixed_6eZMixed_7aZMixed_7bZMixed_7cZAvgPoolflattenmmZfcZweightTZbias	unsqueeze)r'   r,   Zremaining_featuresr   r5   r   _torch_fidelity_forwardB   sx    
"





























z*NoTrainInceptionV3._torch_fidelity_forwardc                 C   s    |  |}|d |jd dS )z8Forward pass of neural network with reshaping of output.r   r1   )rH   Zreshapeshape)r'   r,   outr   r   r   forward   s    
zNoTrainInceptionV3.forward)N)r   r   r   __doc__strr   r   r%   boolr+   r	   r   rH   rK   __classcell__r   r   r(   r   r   1   s    
Vr   )mu1sigma1mu2sigma2r"   c                 C   sR   | |   jdd}| |  }tj||  jjdd}|| d|  S )ar  Compute 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

    Returns:
        Scalar value of the distance between sets.

    r1   dim   )Zsquaresumtracer9   ZlinalgZeigvalssqrtreal)rP   rQ   rR   rS   r4   bcr   r   r   _compute_fid   s    r]   c                       s  e Zd ZU dZdZeed< 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< eed< d$eeef eeedd fddZeeddddZedddZdd fddZeeejf dd fdd Zd%eeeee f  ee ed!d"d#Z  ZS )&r   uK  Calculate Fréchet inception distance (FID_) which is used to access the quality of generated images.

    .. math::
        FID = \|\mu - \mu_w\|^2 + 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 ``(3xHxW)``. 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.

    This metric is known to be unstable in its calculatations, and we recommend for the best results using this metric
    that you calculate using `torch.float64` (default is `torch.float32`) which can be set using the `.set_dtype`
    method of the metric.

    .. note:: using this metrics requires you to have torch 1.9 or higher installed

    .. 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 be 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 torch version is lower than 1.9
        ModuleNotFoundError:
            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_updateg        plot_lower_boundreal_features_sumreal_features_cov_sumreal_features_num_samplesfake_features_sumfake_features_cov_sumfake_features_num_samples	inception   TN)featurereset_real_features	normalizekwargsr"   c           	         s  t  jf i | tstdt|trp|}ts8tdd}||vrZtd| d| dtdt	|gd| _
n>t|tr|| _
tjd	d
dtjd}| 
|jd }ntdt|tstd|| _t|tst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 )NzQFrechetInceptionDistance metric requires that PyTorch is version 1.9.0 or higher.zFrechetInceptionDistance metric requires that `Torch-fidelity` is installed. Either install as `pip install torchmetrics[image]` or `pip install torch-fidelity`.)@      i   ri   z3Integer input to argument `feature` must be one of z
, but got .zinception-v3-compat)r   r    r      )r0      +  rs   )r:   r1   z'Got unknown input to argument `feature`z4Argument `reset_real_features` expected to be a boolz*Argument `normalize` expected to be a boolrb   rW   )Zdist_reduce_fxrc   rd   re   rf   rg   )r$   r%   r   
ValueError
isinstanceintr   ModuleNotFoundErrorr   rM   rh   r
   r9   randintr;   rI   	TypeErrorrN   rk   rl   Z	add_statezerosdoubleZtensorlong)	r'   rj   rk   rl   rm   Znum_featuresZvalid_int_inputZdummy_imageZmx_nb_feetsr(   r   r   r%     sB    



r   )imgsrZ   r"   c                 C   s   | j r|d  n|}| |}|j| _| }| dkrF|d}|r|  j|j	dd7  _|  j
| |7  _
|  j|jd 7  _nB|  j|j	dd7  _|  j| |7  _|  j|jd 7  _dS )z)Update the state with extracted features.rq   r0   r   rT   N)rl   byterh   r:   
orig_dtyper{   rU   rG   rb   rW   rc   trE   rd   rI   re   rf   rg   )r'   r}   rZ   r6   r   r   r   updateE  s    

zFrechetInceptionDistance.update)r"   c                 C   s   | j dk s| jdk rtd| 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.rV   zVMore than one sample is required for both the real and fake distributed to compute FIDr   r0   )rd   rg   RuntimeErrorrb   rG   re   rc   r   rE   rf   r]   r@   r>   r   )r'   Z	mean_realZ	mean_fakeZcov_real_numZcov_realZcov_fake_numZcov_faker   r   r   computeW  s    z FrechetInceptionDistance.computec                    sP   | j sBt| j}t| j}t| j}t   || _|| _|| _n
t   dS )zReset metric states.N)rk   r   rb   rc   rd   r$   reset)r'   rb   rc   rd   r(   r   r   r   d  s    



zFrechetInceptionDistance.resetr   )dst_typer"   c                    s$   t  |}t|jtr ||j_|S )zTransfer all metric state to specific dtype. Special version of standard `type` method.

        Arguments:
            dst_type: the desired type as ``torch.dtype`` or string

        )r$   	set_dtyperu   rh   r   r-   )r'   r   rJ   r(   r   r   r   q  s    z"FrechetInceptionDistance.set_dtype)valaxr"   c                 C   s   |  ||S )aj  Plot a single or multiple values from the metric.

        Args:
            val: Either a single result from calling `metric.forward` or `metric.compute` or a list of these results.
                If no value is provided, will automatically call `metric.compute` and plot that result.
            ax: An matplotlib axis object. If provided will add plot to that axis

        Returns:
            Figure and Axes object

        Raises:
            ModuleNotFoundError:
                If `matplotlib` is not installed

        .. plot::
            :scale: 75

            >>> # Example plotting a single value
            >>> import torch
            >>> from torchmetrics.image.fid import FrechetInceptionDistance
            >>> 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)
            >>> metric = FrechetInceptionDistance(feature=64)
            >>> metric.update(imgs_dist1, real=True)
            >>> metric.update(imgs_dist2, real=False)
            >>> fig_, ax_ = metric.plot()

        .. plot::
            :scale: 75

            >>> # Example plotting multiple values
            >>> import torch
            >>> from torchmetrics.image.fid import FrechetInceptionDistance
            >>> imgs_dist1 = lambda: torch.randint(0, 200, (100, 3, 299, 299), dtype=torch.uint8)
            >>> imgs_dist2 = lambda: torch.randint(100, 255, (100, 3, 299, 299), dtype=torch.uint8)
            >>> metric = FrechetInceptionDistance(feature=64)
            >>> values = [ ]
            >>> for _ in range(3):
            ...     metric.update(imgs_dist1(), real=True)
            ...     metric.update(imgs_dist2(), real=False)
            ...     values.append(metric.compute())
            ...     metric.reset()
            >>> fig_, ax_ = metric.plot(values)

        )Z_plot)r'   r   r   r   r   r   plot}  s    0r   )ri   TF)NN)r   r   r   rL   r^   rN   __annotations__r_   r`   ra   r?   r	   r
   r   rv   r   r%   r   r   r   rM   r9   r:   r   r   r   r   r   r   rO   r   r   r(   r   r      s>   
M   
3 )#r<   r   typingr   r   r   r   r   r   r9   r	   Ztorch.nnr
   Ztorch.nn.functionalr   Ztorchmetrics.metricr   Ztorchmetrics.utilities.importsr   r   r   Ztorchmetrics.utilities.plotr   r   Z__doctest_skip__Z,torch_fidelity.feature_extractor_inceptionv3r   r   Ztorch_fidelity.helpersr   Z,torch_fidelity.interpolate_compat_tensorflowr   r   r]   r   r   r   r   r   <module>   s0    
m