Ë
    þÍ:jW  ã            
       ó*  — 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sdgZerd dlmZ d dlmZ d dlmZ n G d„ de«      ZdZdZddgZ G d„ de«      Zde	de	de	de	de	f
d„Z G d„ de«      Z y)é    )ÚSequence)Údeepcopy)ÚAnyÚOptionalÚUnionN)ÚTensor)ÚModule)Úadaptive_avg_pool2d)ÚMetric)Ú_MATPLOTLIB_AVAILABLEÚ_TORCH_FIDELITY_AVAILABLE)Ú_AX_TYPEÚ_PLOT_OUT_TYPEzFrechetInceptionDistance.plot)ÚFeatureExtractorInceptionV3)Úvassert)Ú)interpolate_bilinear_2d_like_tensorflow1xc                   ó   — e Zd Zy)Ú_FeatureExtractorInceptionV3N)Ú__name__Ú
__module__Ú__qualname__© ó    úk/home/mcse/projects/srt_converter/srt-converter-venv/lib/python3.12/site-packages/torchmetrics/image/fid.pyr   r   $   s   „ Ør   r   ÚFrechetInceptionDistancec                   ó”   ‡ — e Zd ZU dZeed<   	 	 ddedee   dee   de	ddf
ˆ fd	„Z
d
e	dd fˆ fd„Zdedeedf   fd„Zdedefd„Zˆ xZS )ÚNoTrainInceptionV3z)Module that never leaves evaluation mode.ÚINPUT_IMAGE_SIZENÚnameÚfeatures_listÚfeature_extractor_weights_pathÚ	antialiasÚreturnc                 óx   •— t         st        d«      ‚t        ‰| �  |||«       || _        | j                  «        y )Nz›NoTrainInceptionV3 module requires that `Torch-fidelity` is installed. Either install as `pip install torchmetrics[image]` or `pip install torch-fidelity`.)r   ÚModuleNotFoundErrorÚsuperÚ__init__Úuse_antialiasÚeval)Úselfr   r    r!   r"   Ú	__class__s        €r   r'   zNoTrainInceptionV3.__init__2   s@   ø€ õ )Ü%ðhóð ô
 	‰Ñ˜˜}Ð.LÔMØ&ˆÔà�	‰	�r   Úmodec                 ó"   •— t         ‰| �  d«      S )z.Force network to always be in evaluation mode.F)r&   Útrain)r*   r,   r+   s     €r   r.   zNoTrainInceptionV3.trainD   s   ø€ ä‰w‰}˜UÓ#Ð#r   Úx.c                 óº	  ‡— t        t        j                  |«      xr |j                  t        j                  k(  d«       i Š| j
                  j                  «       }t        | d«      r|j                  | j                  «      n|j                  t        j                  «      }| j                  rEt        j                  j                  j                  || j                  | j                  fddd¬«      }n$t!        || j                  | j                  fd¬«      }|dz
  dz  }| j#                  |«      }| j%                  |«      }| j'                  |«      }| j)                  |«      }d	|v rkt+        |d
¬«      j-                  d«      j-                  d«      ‰d	<   |j/                  d	«       t1        |«      dk(  rt3        ˆfd„| j
                  D «       «      S | j5                  |«      }| j7                  |«      }| j9                  |«      }d|v rkt+        |d
¬«      j-                  d«      j-                  d«      ‰d<   |j/                  d«       t1        |«      dk(  rt3        ˆfd„| j
                  D «       «      S | j;                  |«      }| j=                  |«      }| j?                  |«      }| jA                  |«      }| jC                  |«      }| jE                  |«      }| jG                  |«      }| jI                  |«      }d|v rkt+        |d
¬«      j-                  d«      j-                  d«      ‰d<   |j/                  d«       t1        |«      dk(  rt3        ˆfd„| j
                  D «       «      S | jK                  |«      }| jM                  |«      }| jO                  |«      }| jQ                  |«      }t        jR                  |d«      }d|v rB|‰d<   |j/                  d«       t1        |«      dk(  rt3        ˆfd„| j
                  D «       «      S d|v rš|jU                  | jV                  jX                  jZ                  «      }|‰d<   |j/                  d«       t1        |«      dk(  rt3        ˆfd„| j
                  D «       «      S || jV                  j\                  j_                  d«      z   }n| jW                  |«      }|‰d<   t3        ˆf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Ú_dtypeÚbilinearFT)Úsizer,   Úalign_cornersr"   )r3   r4   é€   Ú64)é   r7   )Úoutput_sizeéÿÿÿÿr   c              3   ó(   •K  — | ]	  }‰|   –— Œ y ­w©Nr   ©Ú.0ÚaÚfeaturess     €r   ú	<genexpr>z=NoTrainInceptionV3._torch_fidelity_forward.<locals>.<genexpr>r   ó   øè ø€ ÒE¨Q˜X a�[ÑEùó   ƒÚ192c              3   ó(   •K  — | ]	  }‰|   –— Œ y ­wr;   r   r<   s     €r   r@   z=NoTrainInceptionV3._torch_fidelity_forward.<locals>.<genexpr>|   rA   rB   Ú768c              3   ó(   •K  — | ]	  }‰|   –— Œ y ­wr;   r   r<   s     €r   r@   z=NoTrainInceptionV3._torch_fidelity_forward.<locals>.<genexpr>‹   rA   rB   r7   Ú2048c              3   ó(   •K  — | ]	  }‰|   –— Œ y ­wr;   r   r<   s     €r   r@   z=NoTrainInceptionV3._torch_fidelity_forward.<locals>.<genexpr>—   rA   rB   Úlogits_unbiasedc              3   ó(   •K  — | ]	  }‰|   –— Œ y ­wr;   r   r<   s     €r   r@   z=NoTrainInceptionV3._torch_fidelity_forward.<locals>.<genexpr>Ÿ   rA   rB   Úlogitsc              3   ó(   •K  — | ]	  }‰|   –— Œ y ­wr;   r   r<   s     €r   r@   z=NoTrainInceptionV3._torch_fidelity_forward.<locals>.<genexpr>¦   s   øè ø€ Ò= Q�X˜a•[Ñ=ùrB   )0r   ÚtorchÚ	is_tensorÚdtypeÚuint8r    ÚcopyÚhasattrÚtor1   Úfloatr(   ÚnnÚ
functionalÚinterpolater   r   Ú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?   s      @r   Ú_torch_fidelity_forwardz*NoTrainInceptionV3._torch_fidelity_forwardH   s0  ø€ ô 	”—‘ Ó"Ò= q§w¡w´%·+±+Ñ'=Ð?wÔxØˆØ!×/Ñ/×4Ñ4Ó6Ðä!(¨¨xÔ!8ˆA�D‰D�—‘Ô¸a¿d¹dÄ5Ç;Á;Ó>OˆØ×ÒÜ—‘×#Ñ#×/Ñ/ØØ×+Ñ+¨T×-BÑ-BÐCØØ#Øð 0ó ‰Aô :ØØ×+Ñ+¨T×-BÑ-BÐCØ#ôˆAð �‰W˜‰Oˆà×Ñ˜qÓ!ˆØ×Ñ˜qÓ!ˆØ×Ñ˜qÓ!ˆØ�N‰N˜1ÓˆàÐ%Ñ%Ü0°ÀÔG×OÑOÐPRÓS×[Ñ[Ð\^Ó_ˆH�T‰NØ×%Ñ% dÔ+ÜÐ%Ó&¨!Ò+ÜÓE°$×2DÑ2DÔEÓEÐEà×Ñ˜qÓ!ˆØ×Ñ˜qÓ!ˆØ�N‰N˜1ÓˆàÐ&Ñ&Ü1°!ÀÔH×PÑPÐQSÓT×\Ñ\Ð]_Ó`ˆH�U‰OØ×%Ñ% eÔ,ÜÐ%Ó&¨!Ò+ÜÓE°$×2DÑ2DÔEÓEÐEà�M‰M˜!ÓˆØ�M‰M˜!ÓˆØ�M‰M˜!ÓˆØ�M‰M˜!ÓˆØ�M‰M˜!ÓˆØ�M‰M˜!ÓˆØ�M‰M˜!ÓˆØ�M‰M˜!ÓˆàÐ&Ñ&Ü1°!ÀÔH×PÑPÐQSÓT×\Ñ\Ð]_Ó`ˆH�U‰OØ×%Ñ% eÔ,ÜÐ%Ó&¨!Ò+ÜÓE°$×2DÑ2DÔEÓEÐEà�M‰M˜!ÓˆØ�M‰M˜!ÓˆØ�M‰M˜!ÓˆØ�L‰L˜‹OˆÜ�M‰M˜!˜QÓˆàÐ'Ñ'Ø ˆH�VÑØ×%Ñ% fÔ-ÜÐ%Ó&¨!Ò+ÜÓE°$×2DÑ2DÔEÓEÐEàÐ 2Ñ2Ø—‘�T—W‘W—^‘^×%Ñ%Ó&ˆAà*+ˆHÐ&Ñ'Ø×%Ñ%Ð&7Ô8ÜÐ%Ó&¨!Ò+ÜÓE°$×2DÑ2DÔEÓEÐEà�D—G‘G—L‘L×*Ñ*¨1Ó-Ñ-‰Aà—‘˜“
ˆAàˆ�ÑÜÓ=¨$×*<Ñ*<Ô=Ó=Ð=r   c                 óh   — | j                  |«      }|d   j                  |j                  d   d«      S )z8Forward pass of neural network with reshaping of output.r   r9   )rw   ÚreshapeÚshape)r*   r/   Úouts      r   ÚforwardzNoTrainInceptionV3.forward¨   s/   € à×*Ñ*¨1Ó-ˆØ�1‰v�~‰~˜aŸg™g a™j¨"Ó-Ð-r   )NT)r   r   r   Ú__doc__ÚintÚ__annotations__ÚstrÚlistr   Úboolr'   r.   r   r_   rw   r|   Ú__classcell__©r+   s   @r   r   r   -   s˜   ø… Ù3àÓð 9=Øñàðð ˜C‘yðð )1°©ð	ð
 ðð 
õð$$˜$ð $Ð#7õ $ð^>¨ð ^>°E¸&À#¸+Ñ4Fó ^>ð@.˜ð . F÷ .r   r   Úmu1Úsigma1Úmu2Úsigma2r#   c                 ó4  — | |z
  j                  «       j                  d¬«      }|j                  «       |j                  «       z   }t        j                  j                  ||z  «      j                  «       j                  j                  d¬«      }||z   d|z  z
  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.

    r9   ©Údimé   )ÚsquareÚsumÚtracerM   ÚlinalgÚeigvalsÚsqrtÚreal)r…   r†   r‡   rˆ   r>   ÚbÚcs          r   Ú_compute_fidr–   ®   s�   € ð  
ˆs‰×ÑÓ× Ñ  RÐ Ó(€AØ�‰‹˜Ÿ™›Ñ'€AÜ�‰×Ñ˜V f™_Ó-×2Ñ2Ó4×9Ñ9×=Ñ=À"Ð=ÓE€Aàˆq‰5�1�q‘5‰=Ðr   c                   óŽ  ‡ — 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eddfˆ fd„Zdededdfd„Zdefd„Zd&ˆ fd„Zdeeej2                  f   dd fˆ fd!„Z	 d'd"eeeee   f      d#ee   defd$„Zˆ xZS )(r   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.
        use_antialias: boolian flag to indicate whether to use antialiasing when resizing images. This will change the
            resize function to use bilinear interpolation with antialiasing, which is different from the original
            Inception v3 implementation. Does not apply to custom feature extractor networks.
        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_networkNÚfeatureÚreset_real_featuresÚ	normalizeÚinput_img_sizer!   r"   Úkwargsr#   c                 ó¤  •— t        ‰| �  di |¤Ž t        |t        «      st	        d«      ‚|| _        d| _        |}t        |t        «      rK|}t        st        d«      ‚d}	||	vrt	        d|	› d|› d�«      ‚t        dt        |«      g||¬	«      | _        �nVt        |t        «      �r:|| _        d
| _        t        | j                  d«      r˜t        | j                  j                  t        «      r| j                  j                  }næt        | j                  j                  t         «      r.t        | j                  j                  j#                  «       «      }n”t%        d«      ‚| j
                  r(t'        j(                  dg|¢­dt&        j*                  iŽ}
n+t'        j,                  dddg|¢­t&        j.                  ¬«      }
| j                  |
«      j0                  d   }nt%        d«      ‚t        |t        «      st	        d«      ‚|| _        ||f}| j5                  dt'        j6                  |«      j9                  «       d¬«       | j5                  dt'        j6                  |«      j9                  «       d¬«       | j5                  dt'        j:                  d«      j=                  «       d¬«       | j5                  dt'        j6                  |«      j9                  «       d¬«       | j5                  dt'        j6                  |«      j9                  «       d¬«       | j5                  dt'        j:                  d«      j=                  «       d¬«       y )Nz*Argument `normalize` expected to be a boolFz¡FrechetInceptionDistance metric requires that `Torch-fidelity` is installed. Either install as `pip install torchmetrics[image]` or `pip install torch-fidelity`.)é@   éÀ   i   é   z3Integer input to argument `feature` must be one of z
, but got ú.zinception-v3-compat)r   r    r!   r"   TÚnum_featureszCExpected `self.inception.num_features` to be of type int or Tensor.r7   rO   r   éÿ   )rO   r9   z'Got unknown input to argument `feature`z4Argument `reset_real_features` expected to be a boolrœ   rŽ   )Údist_reduce_fxr�   rž   rŸ   r    r¡   r   )r&   r'   Ú
isinstancer‚   Ú
ValueErrorr¦   Úused_custom_modelr~   r   r%   r   r€   r¢   r	   rR   r®   r   ÚitemÚ	TypeErrorrM   ÚrandÚfloat32ÚrandintrP   rz   r¥   Ú	add_stateÚzerosÚdoubleÚtensorÚlong)r*   r¤   r¥   r¦   r§   r!   r"   r¨   r®   Úvalid_int_inputÚdummy_imageÚmx_num_featsr+   s               €r   r'   z!FrechetInceptionDistance.__init__:  s¶  ø€ ô 	‰ÑÑ"˜6Ò"ä˜)¤TÔ*ÜÐIÓJÐJØ"ˆŒØ!&ˆÔØˆ	ä�gœsÔ#Ø"ˆLÝ,Ü)ðlóð ð 3ˆOØ˜oÑ-Ü ØIÈ/ÐIZÐZdÐelÐdmÐmnÐoóð ô 0Ø*Ü" 7›|˜nØ/MØ#ô	ˆDŽNô ˜¤Õ(Ø$ˆDŒNØ%)ˆDÔ"Ü�t—~‘~ ~Ô6Ü˜dŸn™n×9Ñ9¼3Ô?Ø#'§>¡>×#>Ñ#>‘LÜ §¡× ;Ñ ;¼VÔDÜ#& t§~¡~×'BÑ'B×'GÑ'GÓ'IÓ#J‘Lä#Ð$iÓjÐjà—>’>Ü"'§*¡*¨QÐ"U°Ò"UÄuÇ}Á}Ñ"U‘Kä"'§-¡-°°3¸Ð8L¸^Ñ8LÔTY×T_ÑT_Ô"`�KØ#Ÿ~™~¨kÓ:×@Ñ@ÀÑD‘äÐEÓFÐFäÐ-¬tÔ4ÜÐSÓTÐTØ#6ˆÔ à$ lÐ3ˆØ�‰Ð*¬E¯K©K¸Ó,E×,LÑ,LÓ,NÐ_dˆÔeØ�‰Ð.´·±¸LÓ0I×0PÑ0PÓ0RÐchˆÔiØ�‰Ð2´E·L±LÀ³O×4HÑ4HÓ4JÐ[`ˆÔaà�‰Ð*¬E¯K©K¸Ó,E×,LÑ,LÓ,NÐ_dˆÔeØ�‰Ð.´·±¸LÓ0I×0PÑ0PÓ0RÐchˆÔiØ�‰Ð2´E·L±LÀ³O×4HÑ4HÓ4JÐ[`ˆÕar   Úimgsr“   c                 óô  — | j                   r| j                  s|dz  j                  «       n|}| j                  |«      }|j                  | _        |j                  «       }|j                  «       dk(  r|j                  d«      }|rz| xj                  |j                  d¬«      z  c_	        | xj                  |j                  «       j                  |«      z  c_        | xj                  |j                  d   z  c_        y| xj                   |j                  d¬«      z  c_        | xj"                  |j                  «       j                  |«      z  c_        | xj$                  |j                  d   z  c_        y)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¯   r7   r   rŠ   N)r¦   r³   Úbyter¢   rO   Ú
orig_dtyper»   r‹   ru   rœ   rŽ   r�   Útrp   rž   rz   rŸ   r    r¡   )r*   rÁ   r“   r?   s       r   ÚupdatezFrechetInceptionDistance.update€  s  € ð '+§n¢n¸d×>TÒ>T��s‘
× Ñ Ô"Ð[_ˆØ—>‘> $Ó'ˆØ"Ÿ.™.ˆŒØ—?‘?Ó$ˆà�<‰<‹>˜QÒØ×)Ñ)¨!Ó,ˆHÙØ×"Ò" h§l¡l°q lÓ&9Ñ9Õ"Ø×&Ò&¨(¯*©*«,¯/©/¸(Ó*CÑCÕ&Ø×*Ò*¨d¯j©j¸©mÑ;Ö*à×"Ò" h§l¡l°q lÓ&9Ñ9Õ"Ø×&Ò&¨(¯*©*«,¯/©/¸(Ó*CÑCÕ&Ø×*Ò*¨d¯j©j¸©mÑ;Ö*r   c                 óª  — | j                   dk  s| j                  dk  rt        d«      ‚| j                  | j                   z  j	                  d«      }| j
                  | j                  z  j	                  d«      }| j                  | j                   |j                  «       j                  |«      z  z
  }|| j                   dz
  z  }| j                  | j                  |j                  «       j                  |«      z  z
  }|| j                  dz
  z  }t        |j                  d«      ||j                  d«      |«      j                  | j                  «      S )zWCalculate FID score based on accumulated extracted features from the two distributions.rŒ   zVMore than one sample is required for both the real and fake distributed to compute FIDr   r7   )rž   r¡   ÚRuntimeErrorrœ   ru   rŸ   r�   rÅ   rp   r    r–   r\   rS   rÄ   )r*   Ú	mean_realÚ	mean_fakeÚcov_real_numÚcov_realÚcov_fake_numÚcov_fakes          r   Úcomputez FrechetInceptionDistance.compute™  s4  € à×)Ñ)¨AÒ-°×1OÑ1OÐRSÒ1SÜÐwÓxÐxØ×+Ñ+¨d×.LÑ.LÑL×WÑWÐXYÓZˆ	Ø×+Ñ+¨d×.LÑ.LÑL×WÑWÐXYÓZˆ	à×1Ñ1°D×4RÑ4RÐU^×U`ÑU`ÓUb×UeÑUeÐfoÓUpÑ4pÑpˆØ 4×#AÑ#AÀAÑ#EÑFˆØ×1Ñ1°D×4RÑ4RÐU^×U`ÑU`ÓUb×UeÑUeÐfoÓUpÑ4pÑpˆØ 4×#AÑ#AÀAÑ#EÑFˆÜ˜I×-Ñ-¨aÓ0°(¸I×<MÑ<MÈaÓ<PÐRZÓ[×^Ñ^Ð_c×_nÑ_nÓoÐor   c                 ó   •— | j                   sct        | j                  «      }t        | j                  «      }t        | j                  «      }t
        ‰| �  «        || _        || _        || _        yt
        ‰| �  «        y)zReset metric states.N)r¥   r   rœ   r�   rž   r&   Úreset)r*   rœ   r�   rž   r+   s       €r   rÑ   zFrechetInceptionDistance.reset¦  si   ø€ à×'Ò'Ü (¨×)?Ñ)?Ó @ÐÜ$,¨T×-GÑ-GÓ$HÐ!Ü(0°×1OÑ1OÓ(PÐ%Ü‰G‰MŒOØ%6ˆDÔ"Ø)>ˆDÔ&Ø-FˆDÕ*ä‰G‰M�Or   Údst_typer   c                 ó|   •— t         ‰| �  |«      }t        |j                  t        «      r||j                  _        |S )z¹Transfer 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   r1   )r*   rÒ   r{   r+   s      €r   rÔ   z"FrechetInceptionDistance.set_dtype³  s4   ø€ ô ‰gÑ Ó)ˆÜ�c—m‘mÔ%7Ô8Ø#+ˆC�M‰MÔ Øˆ
r   ÚvalÚaxc                 ó&   — | j                  ||«      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Ö   s      r   ÚplotzFrechetInceptionDistance.plot¿  s   € ð` �z‰z˜#˜rÓ"Ð"r   )r¬   TF)é   é+  rÛ   NT)r#   N)NN) r   r   r   r}   r˜   r‚   r   r™   rš   r›   rT   r   r	   r£   r€   r   r~   r_   r   r   r'   rÆ   rÏ   rÑ   rM   rO   rÔ   r   r   r   rÙ   rƒ   r„   s   @r   r   r   Å   sŠ  ø… ñbðH #Ð�dÓ"Ø#Ð�tÓ#Ø#Ð�tÓ#Ø!Ð�eÓ!àÓØ!Ó!Ø%Ó%àÓØ!Ó!Ø%Ó%àÓØ&€O�SÓ&ð '+Ø$(ØØ/<Ø8<ØñDbà�s˜F�{Ñ#ðDbð "ðDbð ð	Dbð
 ˜c 3¨˜mÑ,ðDbð )1°©ðDbð ðDbð ðDbð 
õDbðL<˜6ð <¨ð <°$ó <ð2p˜ó põð
 %¨¨U¯[©[Ð(8Ñ"9ð 
¸hõ 
ð _cñ0#Ø˜E &¨(°6Ñ*:Ð":Ñ;Ñ<ð0#ØIQÐRZÑI[ð0#à	÷0#r   )!Úcollections.abcr   rQ   r   Útypingr   r   r   rM   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   ú<module>rç      s«   ðõ %Ý ß 'Ñ 'ã Ý Ý Ý 3å &ß [ß @áØ7Ð8ÐáÝxÝ.Þfô vô ð €GØ04Ð-à2Ð4SÐTÐô~.Ð5ô ~.ðB�fð  fð °6ð À6ð Èfó ô.j#˜võ j#r   