o
    .wi=                     @   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 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sOdgZddgiZdedededefddZd$dedededee dedefddZ	d$dededede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)Metric)rank_zero_warn)dim_zero_cat)_MATPLOTLIB_AVAILABLE_TORCH_FIDELITY_AVAILABLE)_AX_TYPE_PLOT_OUT_TYPEKernelInceptionDistance.plot)KernelInceptionDistancer   torch_fidelityk_xxk_xyk_yyreturnc                 C   s   | j d }t| }t|}| jdd| }|jdd| }|jdd}| }	| }
| }|	|
 ||d   }|d| |d  8 }|S )Adapted from `KID Score`_.r   )dim      )shapetorchdiagsum)r   r   r   mdiag_xdiag_y
kt_xx_sums
kt_yy_sums	k_xy_sums	kt_xx_sum	kt_yy_sumk_xy_sumvalue r+   S/home/ubuntu/sommelier/.venv/lib/python3.10/site-packages/torchmetrics/image/kid.pymaximum_mean_discrepancy"   s   


r-            ?f1f2degreegammacoefc                 C   s,   |du rd| j d  }| |j | | | S )r   Nr/   r   )r   T)r0   r1   r2   r3   r4   r+   r+   r,   poly_kernel6   s   r6   f_realf_fakec                 C   s<   t | | |||}t |||||}t | ||||}t|||S )r   )r6   r-   )r7   r8   r2   r3   r4   k_11k_22k_12r+   r+   r,   poly_mmd=   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< 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ef dedededee
 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eef 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   a4  Calculate Kernel Inception Distance (KID) which is used to access the quality of generated images.

    .. math::
        KID = MMD(f_{real}, f_{fake})^2

    where :math:`MMD` is the maximum mean discrepancy and :math:`I_{real}, I_{fake}` are extracted features
    from real and fake images, see `kid ref1`_ for more details. In particular, calculating the MMD requires the
    evaluation of a polynomial kernel function :math:`k`

    .. math::
        k(x,y) = (\gamma * x^T y + coef)^{degree}

    which controls the distance between two features. In practise the MMD is calculated over a number of
    subsets to be able to both get the mean and standard deviation of KID.

    Using the default feature extraction (Inception v3 using the original weights from `kid 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. ``normalize`` argument won't have any
    effect and 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.

    .. 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 of shape ``(N,C,H,W)``
    - ``real`` (`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

    - ``kid_mean`` (:class:`~torch.Tensor`): float scalar tensor with mean value over subsets
    - ``kid_std`` (:class:`~torch.Tensor`): float scalar tensor with standard deviation value over subsets

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

            - an str or integer will indicate the inceptionv3 feature layer to choose. Can be one of the following:
              'logits_unbiased', 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.

        subsets: Number of subsets to calculate the mean and standard deviation scores over
        subset_size: Number of randomly picked samples in each subset
        degree: Degree of the polynomial kernel function
        gamma: Scale-length of polynomial kernel. If set to ``None`` will be automatically set to the feature size
        coef: Bias term in the polynomial kernel.
        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)``
        ValueError:
            If ``subsets`` is not an integer larger than 0
        ValueError:
            If ``subset_size`` is not an integer larger than 0
        ValueError:
            If ``degree`` is not an integer larger than 0
        ValueError:
            If ``gamma`` is neither ``None`` or a float larger than 0
        ValueError:
            If ``coef`` is not an float larger than 0
        ValueError:
            If ``reset_real_features`` is not an ``bool``

    Example:
        >>> from torch import randint
        >>> from torchmetrics.image.kid import KernelInceptionDistance
        >>> kid = KernelInceptionDistance(subset_size=50)
        >>> # 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)
        >>> kid.update(imgs_dist1, real=True)
        >>> kid.update(imgs_dist2, real=False)
        >>> kid.compute()
        (tensor(0.0312), tensor(0.0025))

    Fhigher_is_betteris_differentiablefull_state_updateg        plot_lower_boundr/   plot_upper_boundreal_featuresfake_features	inceptionfeature_network   d     r.   NTfeaturesubsetssubset_sizer2   r3   r4   reset_real_features	normalizekwargsr   c	                    s  t  jdi |	 tdt d| _t|ttfr:tst	dd}
||
vr/t
d|
 d| dtdt|gd	| _nt|trF|| _d
| _ntdt|trS|dksWt
d|| _t|trc|dksgt
d|| _t|trs|dkswt
d|| _|d urt|tr|dkst
d|| _t|tr|dkst
d|| _t|tst
d|| _t|tst
d|| _| jdg d d | jdg d d d S )NzMetric `Kernel Inception Distance` will save all extracted features in buffer. For large datasets this may lead to large memory footprint.FzKernel Inception Distance metric requires that `Torch-fidelity` is installed. Either install as `pip install torchmetrics[image]` or `pip install torch-fidelity`.)logits_unbiased@      i   rF   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`r   z7Argument `subsets` expected to be integer larger than 0z;Argument `subset_size` expected to be integer larger than 0z6Argument `degree` expected to be integer larger than 0z=Argument `gamma` expected to be `None` or float larger than 0z2Argument `coef` expected to be float larger than 0z4Argument `reset_real_features` expected to be a boolz*Argument `normalize` expected to be a boolrB   )dist_reduce_fxrC   r+   )super__init__r   UserWarningused_custom_model
isinstancestrintr   ModuleNotFoundError
ValueErrorr	   rD   r   	TypeErrorrJ   rK   r2   floatr3   r4   boolrL   rM   	add_state)selfrI   rJ   rK   r2   r3   r4   rL   rM   rN   valid_int_input	__class__r+   r,   rW      sX   


z KernelInceptionDistance.__init__imgsrealc                 C   sJ   | j r| js|d  n|}| |}|r| j| dS | j| 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.

           N)rM   rY   byterD   rB   appendrC   )rc   rg   rh   featuresr+   r+   r,   update   s
   	
zKernelInceptionDistance.updatec                 C   s   t | j}t | j}|jd }|| jk rtd|jd }|| jk r&tdg }t| jD ].}t	|}||d| j  }t	|}||d| j  }	t
||	| j| j| j}
||
 q-t|}| |jddfS )aq  Calculate KID score based on accumulated extracted features from the two distributions.

        Implementation inspired by `Fid Score`_

        Returns:
            kid_mean (:class:`~torch.Tensor`): float scalar tensor with mean value over subsets
            kid_std (:class:`~torch.Tensor`): float scalar tensor with standard deviation value over subsets

        r   zCArgument `subset_size` should be smaller than the number of samplesNF)unbiased)r   rB   rC   r   rK   r^   rangerJ   r   randpermr<   r2   r3   r4   rk   stackmeanstd)rc   rB   rC   n_samples_realn_samples_fakekid_scores__permr7   r8   o
kid_scoresr+   r+   r,   compute  s$   









zKernelInceptionDistance.computec                    s8   | j s| jd}t   || jd< dS t   dS )zReset metric states.rB   N)rL   	_defaultspoprV   reset)rc   r*   re   r+   r,   r~   +  s
   
zKernelInceptionDistance.resetvalaxc                 C   s   |p|   d }| ||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.kid import KernelInceptionDistance
            >>> imgs_dist1 = torch.randint(0, 200, (30, 3, 299, 299), dtype=torch.uint8)
            >>> imgs_dist2 = torch.randint(100, 255, (30, 3, 299, 299), dtype=torch.uint8)
            >>> metric = KernelInceptionDistance(subsets=3, subset_size=20)
            >>> 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.kid import KernelInceptionDistance
            >>> imgs_dist1 = lambda: torch.randint(0, 200, (30, 3, 299, 299), dtype=torch.uint8)
            >>> imgs_dist2 = lambda: torch.randint(100, 255, (30, 3, 299, 299), dtype=torch.uint8)
            >>> metric = KernelInceptionDistance(subsets=3, subset_size=20)
            >>> values = [ ]
            >>> for _ in range(3):
            ...     metric.update(imgs_dist1(), real=True)
            ...     metric.update(imgs_dist2(), real=False)
            ...     values.append(metric.compute()[0])
            ...     metric.reset()
            >>> fig_, ax_ = metric.plot(values)

        r   )r{   _plot)rc   r   r   r+   r+   r,   plot5  s   0r   )rF   rG   rH   r.   Nr/   TF)r   N)NN)__name__
__module____qualname____doc__r=   ra   __annotations__r>   r?   r@   r`   rA   r   r   r   rE   r[   r   r\   r   r   rW   rm   tupler{   r~   r   r   r   r   __classcell__r+   r+   re   r,   r   G   sf   
 ^	
I r   )r.   Nr/   )!collections.abcr   typingr   r   r   r   r   r   torch.nnr   torchmetrics.image.fidr	   torchmetrics.metricr
   torchmetrics.utilitiesr   torchmetrics.utilities.datar   torchmetrics.utilities.importsr   r   torchmetrics.utilities.plotr   r   __doctest_skip____doctest_requires__r-   r\   r`   r6   r<   r   r+   r+   r+   r,   <module>   s>   
(

