o
    .wiS                  
   @   s  d dl mZ d dlmZ d dl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 d d
lmZmZ esGdgZer\d 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G dd deZde	de	de	de	de	f
ddZG dd deZ dS )    )Sequence)deepcopy)AnyOptionalUnionN)Tensor)Module)adaptive_avg_pool2d)Metric)_MATPLOTLIB_AVAILABLE_TORCH_FIDELITY_AVAILABLE)_AX_TYPE_PLOT_OUT_TYPEFrechetInceptionDistance.plot)FeatureExtractorInceptionV3)vassert))interpolate_bilinear_2d_like_tensorflow1xc                   @   s   e Zd ZdS )_FeatureExtractorInceptionV3N)__name__
__module____qualname__ r   r   S/home/ubuntu/sommelier/.venv/lib/python3.10/site-packages/torchmetrics/image/fid.pyr   $   s    r   FrechetInceptionDistancec                	       s   e Zd 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e
df fddZde
de
fddZ  ZS )NoTrainInceptionV3z)Module that never leaves evaluation mode.Nnamefeatures_listfeature_extractor_weights_pathreturnc                    s(   t stdt ||| |   d S )NzNoTrainInceptionV3 module requires that `Torch-fidelity` is installed. Either install as `pip install torchmetrics[image]` or `pip install torch-fidelity`.)r   ModuleNotFoundErrorsuper__init__eval)selfr   r   r   	__class__r   r   r!   0   s   zNoTrainInceptionV3.__init__modec                    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x.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 rtt|ddd	d	 d< |d t|d
krtt fdd| jD S | |}| |}| |}d|v rt|ddd	d	 d< |d t|d
krt fdd| jD S | |}| |}| |}| |}| |}| |}| |}|  |}d|v rt|ddd	d	 d< |d t|d
krt fdd| jD S | !|}| "|}| #|}| $|}t%|d}d|v r8| d< |d t|d
kr8t fdd| jD S d|v rk|&| j'j(j)}| d< |d t|d
krat 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)sizealign_corners   64)   r.   )output_sizer   c                 3       | ]} | V  qd S Nr   .0afeaturesr   r   	<genexpr>d       z=NoTrainInceptionV3._torch_fidelity_forward.<locals>.<genexpr>192c                 3   r1   r2   r   r3   r6   r   r   r8   n   r9   768c                 3   r1   r2   r   r3   r6   r   r   r8   }   r9   r.   2048c                 3   r1   r2   r   r3   r6   r   r   r8      r9   logits_unbiasedc                 3   r1   r2   r   r3   r6   r   r   r8      r9   logitsc                 3   r1   r2   r   r3   r6   r   r   r8      r9   ),r   torch	is_tensordtypeuint8r   copyhasattrtor)   floatr   INPUT_IMAGE_SIZEConv2d_1a_3x3Conv2d_2a_3x3Conv2d_2b_3x3	MaxPool_1r	   squeezeremovelentupleConv2d_3b_1x1Conv2d_4a_3x3	MaxPool_2Mixed_5bMixed_5cMixed_5dMixed_6aMixed_6bMixed_6cMixed_6dMixed_6eMixed_7aMixed_7bMixed_7cAvgPoolflattenmmfcweightTbias	unsqueeze)r#   r(   remaining_featuresr   r6   r   _torch_fidelity_forwardD   sx   
"



























z*NoTrainInceptionV3._torch_fidelity_forwardc                 C   s    |  |}|d |jd dS )z8Forward pass of neural network with reshaping of output.r   r0   )rg   reshapeshape)r#   r(   outr   r   r   forward   s   
zNoTrainInceptionV3.forwardr2   )r   r   r   __doc__strlistr   r!   boolr'   r   rO   rg   rk   __classcell__r   r   r$   r   r   -   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.

    r0   dim   )squaresumtracer?   linalgeigvalssqrtreal)rq   rr   rs   rt   r5   bcr   r   r   _compute_fid   s   r   c                       sV  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Zeed< 					d-deeef dededeeeef de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d%eeejf dd&f fd'd(Z	d/d)eeeee f  d*ee defd+d,Z  ZS )0r   u<  Calculate Fréchet inception distance (FID_) which is used to assess 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.

    Using custom feature extractor is also possible. One can give a torch.nn.Module as `feature` argument. This
    custom feature extractor is expected to have output shape of ``(1, num_features)``. This would change the
    used feature extractor from default (Inception v3) to the given network. In case network doesn't have
    ``num_features`` attribute, a random tensor will be given to the network to infer feature dimensionality.
    Size of this tensor can be controlled by ``input_img_size`` argument and type of the tensor can be controlled
    with ``normalize`` argument (``True`` uses float32 tensors and ``False`` uses int8 tensors). In this case, update
    method expects to have the tensor given to `imgs` argument to be in the correct shape and type that is compatible
    to the custom feature extractor.

    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.

    .. hint::
        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.
        normalize:
            Argument for controlling the input image dtype normalization:

            - If default feature extractor is used, controls whether input imgs have values in range [0, 1] or not:

              - True: if input imgs have values ranged in [0, 1]. They are cast to int8/byte tensors.
              - False: if input imgs have values ranged in [0, 255]. No casting is done.

            - If custom feature extractor module is used, controls type of the input img tensors:

              - True: if input imgs are expected to be in the data type of torch.float32.
              - False: if input imgs are expected to be in the data type of torch.int8.
        input_img_size: tuple of integers. Indicates input img size to the custom feature extractor network if provided.
        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:
        >>> from torch import rand
        >>> 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.6388)

    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feature_network   T   +  r   Nfeaturereset_real_features	normalizeinput_img_sizer   kwargsr   c                    s  t  jdi | t|tstd|| _d| _t|trB|}ts%t	dd}||vr6td| d| dt
dt|g|d	| _n]t|tr|| _d
| _t| jdrst| jjtr_| jj}n@t| jjtrot| jj }n0td| jrtjdg|R dtji}	ntjdddg|R tjd}	| |	jd }nt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 )Nz*Argument `normalize` expected to be a boolFzFrechetInceptionDistance metric requires that `Torch-fidelity` is installed. Either install as `pip install torchmetrics[image]` or `pip install torch-fidelity`.)@      i   r   z3Integer input to argument `feature` must be one of z
, but got .zinception-v3-compat)r   r   r   Tnum_featureszCExpected `self.inception.num_features` to be of type int or Tensor.r.   rA   r      )rA   r0   z'Got unknown input to argument `feature`z4Argument `reset_real_features` expected to be a boolr   ry   )dist_reduce_fxr   r   r   r   r   r   )r    r!   
isinstancero   
ValueErrorr   used_custom_modelintr   r   r   rm   r   r   rD   r   r   item	TypeErrorr?   randfloat32randintrB   ri   r   	add_statezerosdoubletensorlong)r#   r   r   r   r   r   r   r   valid_int_inputdummy_imagemx_num_featsr$   r   r   r!   )  sZ   	





z!FrechetInceptionDistance.__init__imgsr~   c                 C   s   | j r| js|d  n|}| |}|j| _| }| dkr&|d}|rK|  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 )a  Update the state with extracted features.

        Args:
            imgs: Input img tensors to evaluate. If used custom feature extractor please
                make sure dtype and size is correct for the model.
            real: Whether given image is real or fake.

        r   r.   r   ru   N)r   r   byter   rA   
orig_dtyper   rv   re   r   ry   r   tr`   r   ri   r   r   r   )r#   r   r~   r7   r   r   r   updatel  s   	

zFrechetInceptionDistance.updatec                 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.rw   zVMore than one sample is required for both the real and fake distributed to compute FIDr   r.   )r   r   RuntimeErrorr   re   r   r   r   r`   r   r   rL   rE   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 )zReset metric states.N)r   r   r   r   r   r    reset)r#   r   r   r   r$   r   r   r     s   




zFrechetInceptionDistance.reset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_dtyper   r   r   r)   )r#   r   rj   r$   r   r   r     s   z"FrechetInceptionDistance.set_dtypevalaxc                 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)

        )_plot)r#   r   r   r   r   r   plot  s   0r   )r   TFr   N)r   N)NN) r   r   r   rl   r   ro   __annotations__r   r   r   rF   r   r   r   rm   r   r   rO   r   r   r!   r   r   r   r?   rA   r   r   r   r   r   rp   r   r   r$   r   r      s\   
 a
C )!collections.abcr   rC   r   typingr   r   r   r?   r   torch.nnr   torch.nn.functionalr	   torchmetrics.metricr
   torchmetrics.utilities.importsr   r   torchmetrics.utilities.plotr   r   __doctest_skip__,torch_fidelity.feature_extractor_inceptionv3r   r   torch_fidelity.helpersr   ,torch_fidelity.interpolate_compat_tensorflowr   r   r   r   r   r   r   r   <module>   s.   s