o
    yi//                     @   s  d dl 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 d dlmZ d d	lm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 )"    )AnyListOptionalTupleUnionN)Tensor)Module)NoTrainInceptionV3)Metric)rank_zero_warn)dim_zero_cat)_TORCH_FIDELITY_AVAILABLE)KernelInceptionDistanceKID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(   J/home/ubuntu/.local/lib/python3.10/site-packages/torchmetrics/image/kid.pymaximum_mean_discrepancy   s   


r*            ?f1f2degreegammacoefc                 C   s0   |du rd| j d  }| |j | | | }|S )r   Nr,   r   )r   T)r-   r.   r/   r0   r1   kernelr(   r(   r)   poly_kernel1   s   r4   f_realf_fakec                 C   s<   t | | |||}t |||||}t | ||||}t|||S )r   )r4   r*   )r5   r6   r/   r0   r1   k_11k_22k_12r(   r(   r)   poly_mmd9   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< e	e
 ed< e	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  ZS )%r   a  Calculates Kernel Inception Distance (KID) which is used to access the quality of generated images. Given
    by.

    .. 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 ``(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 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 mean 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 niether ``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:
        >>> import torch
        >>> _ = torch.manual_seed(123)
        >>> from torchmetrics.image.kid import KernelInceptionDistance
        >>> kid = KernelInceptionDistance(subset_size=50)
        >>> # 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)
        >>> kid.update(imgs_dist1, real=True)
        >>> kid.update(imgs_dist2, real=False)
        >>> kid_mean, kid_std = kid.compute()
        >>> print((kid_mean, kid_std))
        (tensor(0.0337), tensor(0.0023))
    Fhigher_is_betteris_differentiablefull_state_updatereal_featuresfake_features   d     r+   Nr,   Tfeaturesubsetssubset_sizer/   r0   r1   reset_real_features	normalizekwargsr   c	                    s  t  jdi |	 tdt t|ttfr7tstdd}
||
vr,t	d|
 d| dt
dt|gd| _nt|tr@|| _ntd	t|trM|d
ksQt	d|| _t|tr]|d
ksat	d|| _t|trm|d
ksqt	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.zKernel Inception Distance metric requires that `Torch-fidelity` is installed. Either install as `pip install torchmetrics[image]` or `pip install torch-fidelity`.)logits_unbiased@      i   r@   z3Integer input to argument `feature` must be one of z
, but got .zinception-v3-compat)namefeatures_listz'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 0z4Arugment `reset_real_features` expected to be a boolz*Argument `normalize` expected to be a boolr>   )dist_reduce_fxr?   r(   )super__init__r   UserWarning
isinstancestrintr   ModuleNotFoundError
ValueErrorr	   	inceptionr   	TypeErrorrD   rE   r/   floatr0   r1   boolrF   rG   	add_state)selfrC   rD   rE   r/   r0   r1   rF   rG   rH   valid_int_input	__class__r(   r)   rQ      sT   


z KernelInceptionDistance.__init__imgsrealc                 C   sD   | j r	|d  n|}| |}|r| j| dS | j| dS )z)Update the state with extracted features.   N)rG   byterX   r>   appendr?   )r]   ra   rb   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 )zCalculate KID score based on accumulated extracted features from the two distributions.

        Implementation inspired by `Fid Score`_
        r   zCArgument `subset_size` should be smaller than the number of samplesNF)unbiased)r   r>   r?   r   rE   rW   rangerD   r   randpermr:   r/   r0   r1   re   stackmeanstd)r]   r>   r?   n_samples_realn_samples_fakekid_scores__permr5   r6   o
kid_scoresr(   r(   r)   compute   s$   








zKernelInceptionDistance.computec                    s8   | j s| jd}t   || jd< d S t   d S )Nr>   )rF   	_defaultspoprP   reset)r]   r'   r_   r(   r)   rx     s
   
zKernelInceptionDistance.reset)r@   rA   rB   r+   Nr,   TF)r   N)__name__
__module____qualname____doc__r;   r[   __annotations__r<   r=   r   r   r   rT   rU   r   r   rZ   r   rQ   rg   r   ru   rx   __classcell__r(   r(   r_   r)   r   C   sN   
 X	
F
r   )r+   Nr,   )typingr   r   r   r   r   r   r   torch.nnr   torchmetrics.image.fidr	   torchmetrics.metricr
   torchmetrics.utilitiesr   torchmetrics.utilities.datar   torchmetrics.utilities.importsr   __doctest_requires__r*   rU   rZ   r4   r:   r   r(   r(   r(   r)   <module>   s6   
(	

