o
    .wi-3                     @   s   d dl mZ d dl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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 ddgiZesPdgZddedededefddZ	ddedededededededefddZG dd deZdS )    )Sequence)AnyListOptionalUnionN)Tensor)Module)NoTrainInceptionV3_compute_fid)Metric)dim_zero_cat)_MATPLOTLIB_AVAILABLE_TORCH_FIDELITY_AVAILABLE)_AX_TYPE_PLOT_OUT_TYPE),MemorizationInformedFrechetInceptionDistance1MemorizationInformedFrechetInceptionDistance.plottorch_fidelityr   皙?	features1	features2cosine_distance_epsreturnc           	      C   s   | t j| dddk }|t j|dddk }|t j|ddd }|t j|ddd }dt t ||  }t |jddj}||k rG|S t 	|S )z9Compute the cosine distance between two sets of features.   dimr   T)r   keepdimg      ?)
torchsumnormabsmatmultmeanminvalues	ones_like)	r   r   r   features1_nozerofeatures2_nozeronorm_f1norm_f2d
mean_min_d r-   U/home/ubuntu/sommelier/.venv/lib/python3.10/site-packages/torchmetrics/image/mifid.py_compute_cosine_distance%   s   r/   mu1sigma1mu2sigma2c           	      C   s8   t | |||}t|||}|dkr||d  S t|S )zDCompute MIFID score given two sets of features and their statistics.g:0yE>g+=)r
   r/   r   
zeros_like)	r0   r1   r   r2   r3   r   r   	fid_valuedistancer-   r-   r.   _mifid_compute3   s   
r7   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
 ed< e	e
 ed< eed< dZeed	< 	
			d"deeef de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	d$deee
ee
 f  dee defd d!Z  ZS )%r   a  Calculate Memorization-Informed Frechet Inception Distance (MIFID_).

    MIFID is a improved variation of the Frechet Inception Distance (FID_) that penalizes memorization of the training
    set by the generator. It is calculated as

    .. math::
        MIFID = \frac{FID(F_{real}, F_{fake})}{M(F_{real}, F_{fake})}

    where :math:`FID` is the normal FID score and :math:`M` is the memorization penalty. The memorization penalty
    essentially corresponds to the average minimum cosine distance between the features of the real and fake
    distribution.

    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.

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

    .. 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

    - ``mifid`` (:class:`~torch.Tensor`): float scalar tensor with mean MIFID 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: Whether to normalize the input images. If ``True`` the input is expected to be in the range [0, 1]
            and converted to ``uint8``. If ``False`` the input is expected to already be in the range [0, 255] and of
            type ``uint8``. If a custom feature extractor is used, this argument is ignored.
        cosine_distance_eps: Epsilon value for the cosine distance. If the cosine distance is larger than this value
            it is set to 1 and thus ignored in the MIFID calculation.
        kwargs: Additional keyword arguments, see :ref:`Metric kwargs` for more info.

    Raises:
        RuntimeError:
            If ``torch`` is version less than 1.10
        ValueError:
            If ``feature`` is set to an ``int`` 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 randint
        >>> from torchmetrics.image.mifid import MemorizationInformedFrechetInceptionDistance
        >>> mifid = MemorizationInformedFrechetInceptionDistance(feature=64)
        >>> # generate two slightly overlapping image intensity distributions
        >>> imgs_dist1 = randint(0, 200, (100, 3, 299, 299), dtype=torch.uint8)
        >>> imgs_dist2 = randint(100, 255, (100, 3, 299, 299), dtype=torch.uint8)
        >>> mifid.update(imgs_dist1, real=True)
        >>> mifid.update(imgs_dist2, real=False)
        >>> mifid.compute()
        tensor(3003.3691)

    Fhigher_is_betteris_differentiablefull_state_updatereal_featuresfake_features	inceptionfeature_network   Tr   featurereset_real_features	normalizer   kwargsr   Nc                    s  t  jdi | d| _t|tr5tstdg d}||vr*td| d| dtdt	|gd| _
nt|trA|| _
d	| _ntd
t|tsNtd|| _t|tsZtd|| _t|trpd|  krodksttd td|| _| jdg d d | jdg d d d S )NFzMemorizationInformedFrechetInceptionDistance 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)namefeatures_listTz'Got unknown input to argument `feature`z4Argument `reset_real_features` expected to be a boolz*Argument `normalize` expected to be a boolr   r   zTArgument `cosine_distance_eps` expected to be a float greater than 0 and less than 1r;   )dist_reduce_fxr<   r-   )super__init__used_custom_model
isinstanceintr   ModuleNotFoundError
ValueErrorr	   strr=   r   	TypeErrorboolrA   rB   floatr   	add_state)selfr@   rA   rB   r   rC   valid_int_input	__class__r-   r.   rK      s<   



z5MemorizationInformedFrechetInceptionDistance.__init__imgsrealc                 C   sZ   | j r| js|d  n|}| |}|j| _| }|r%| j| dS | j	| dS )z)Update the state with extracted features.   N)
rB   rL   byter=   dtype
orig_dtypedoubler;   appendr<   )rV   rZ   r[   featuresr-   r-   r.   update   s   
z3MemorizationInformedFrechetInceptionDistance.updatec              	   C   sp   t | j}t | j}tj|ddtj|dd}}t| t| }}t||||||| jd	| j
S )zWCalculate FID score based on accumulated extracted features from the two distributions.r   r   )r   )r   r;   r<   r   r#   covr"   r7   r   tor_   )rV   r;   r<   	mean_real	mean_fakecov_realcov_faker-   r-   r.   compute   s   

z4MemorizationInformedFrechetInceptionDistance.computec                    s8   | j s| jd}t   || jd< dS t   dS )zReset metric states.r;   N)rA   	_defaultspoprJ   reset)rV   valuerX   r-   r.   rm      s
   
z2MemorizationInformedFrechetInceptionDistance.resetvalaxc                 C   s   |  ||S )a  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.mifid import MemorizationInformedFrechetInceptionDistance
            >>> 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 = MemorizationInformedFrechetInceptionDistance(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.mifid import MemorizationInformedFrechetInceptionDistance
            >>> 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 = MemorizationInformedFrechetInceptionDistance(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)rV   ro   rp   r-   r-   r.   plot   s   0r   )r?   TFr   )r   N)NN)__name__
__module____qualname____doc__r8   rS   __annotations__r9   r:   r   r   r   r>   rQ   r   rN   rT   r   rK   rc   rj   rm   r   r   r   r   rr   __classcell__r-   r-   rX   r.   r   C   sJ   
 S
0r   )r   )collections.abcr   typingr   r   r   r   r   r   torch.nnr   torchmetrics.image.fidr	   r
   torchmetrics.metricr   torchmetrics.utilities.datar   torchmetrics.utilities.importsr   r   torchmetrics.utilities.plotr   r   __doctest_requires____doctest_skip__rT   r/   r7   r   r-   r-   r-   r.   <module>   sH   
