+
    åûjÞ;  ã                  ó‚   € ^ RI Ht ^ RIHtHtHt ^ RIt^ RIHu H	t
 ^ RIHt ^ RIHt  ! R R]P                  4      tR# )é    )Úannotations)ÚAnyÚOptionalÚSequenceN)Únn)Ú
ShapeErrorc                  ó’   a € ] tR t^ tRtRR V 3R llltR V 3R lltR V 3R lltRR R	 lltRR
 R llt	R R lt
R R ltRtV ;t# )ÚMS_SSIMLossa®  Compute the multi-scale SSIM plus L1 loss between two images.

``criterion = MS_SSIMLoss(sigmas, ...)`` builds one Gaussian mask per sigma. ``loss = criterion(img1, img2)``
mixes, at every pixel of two ``(B, C, H, W)`` images, one minus their multi-scale
SSIM with a Gaussian-filtered L1 difference, as in [1].

.. math::
    \text{loss}(x, y) = c \cdot \left(\alpha \cdot \mathcal{L_{MSSIM}}(x,y)
    + (1 - \alpha) \cdot G_{\sigma_M} * \mathcal{L_1}(x,y) / L\right)

Where:
    - :math:`\alpha` is ``alpha``, :math:`c` is ``compensation`` and :math:`L` is ``data_range``.
    - :math:`x` and :math:`y` are the reconstructed and true reference images.
    - :math:`\mathcal{L_{MSSIM}}` is one minus the mean over the channels of the MS-SSIM.
    - :math:`G_{\sigma_M}` is the Gaussian of the last entry :math:`\sigma_M` of ``sigmas``, the coarsest scale.
    - :math:`\mathcal{L_1}` is the L1 difference, averaged over the channels after the filter.

Reference:
    [1]: https://research.nvidia.com/sites/default/files/pubs/2017-03_Loss-Functions-for/NN_ImgProc.pdf#page11
    [2]: https://github.com/NVlabs/PL4NN/blob/master/src/loss.py (``MSSSIML1``)
    [3]: https://github.com/psyrocloud/MS-SSIM_L1_LOSS

Convention:
    - The MS-SSIM of a channel is its luminance at the coarsest scale times its contrast-structure at every scale,
      the formula of the reference implementation [2] of [1]. [2] evaluates it once per patch, at its centre; this
      loss evaluates it at every pixel.
    - "Multi-scale" means one Gaussian per entry of ``sigmas``, all at full resolution, as in [1], not the dyadic
      pyramid of Wang et al.; :ref:`Losses and metrics <losses-metrics-conventions>` compares it with pytorch-msssim
      and torchmetrics.
    - The last entry of ``sigmas`` is the coarsest scale, so the order matters: it sets the window,
      ``2 * int(2 * sigmas[-1]) + 1`` taps wide, the luminance term and the Gaussian of the L1 term.
    - The images are zero-padded by ``int(2 * sigmas[-1])`` pixels, 16 at the default, where
      :func:`~kornia.metrics.ssim` reflects, so the loss is biased in a band that wide along every border: the
      zeros attenuate the L1 term there but can raise the MS-SSIM term, so the band scores lower on the whole than
      reflect padding would at the default ``alpha`` and can score higher at a large ``alpha``.
    - ``data_range`` is the ``max_val`` of :func:`~kornia.metrics.ssim`: it sets :math:`C_1` and :math:`C_2` and
      divides the L1 term; pixel values are not rescaled. ``data_range=255.0`` on 8-bit images gives the loss of
      the same images divided by 255 at the default ``data_range=1.0``.
    - The defaults follow [3]: ``alpha=0.025``, as in [2], and ``compensation=200``, which neither [1] nor [2]
      applies; [1] sets :math:`\alpha = 0.84`. The default ``reduction='mean'`` averages the ``(B, H, W)``
      map, whose channels are already averaged.
    - The two images must have the same ``(C, H, W)`` shape. Their batch sizes must match, or one of them
      must be 1, and that image is then compared with every image of the other batch.
    - Integer and bool images count as the dtype of the Gaussian masks: float32, unless the module was moved to
      another floating dtype. The images are filtered in the promoted dtype of the two images and the masks, with
      float16 and bfloat16 raised to float32 and autocast disabled on CPU, CUDA and MPS. The loss is returned in
      the promoted dtype of the two images, so two integer images give a loss in the mask dtype.

Args:
    sigmas: Gaussian sigma of each scale; the last entry is the coarsest.
    data_range: range :math:`L` of the images.
    K: constants :math:`(k_1, k_2)` of :math:`C_1 = (k_1 L)^2` and :math:`C_2 = (k_2 L)^2`.
    alpha: weight of the MS-SSIM term; the L1 term gets :math:`1 - \alpha`.
    compensation: factor :math:`c` that scales the whole loss.
    reduction: ``'mean'`` (default) averages the loss, ``'sum'`` adds it, ``'none'`` keeps one value per pixel.

Shape:
    - Input1: ``(B, C, H, W)``.
    - Input2: ``(B, C, H, W)``.
    - Output: ``(B, H, W)`` or scalar if reduction is set to ``'mean'`` or ``'sum'``.

See Also:
    - :class:`~kornia.losses.SSIMLoss`: one scale and no L1 term, as ``(1 - SSIM) / 2``;
      :func:`~kornia.losses.ssim_loss` is its one-call form.

Examples:
    >>> input1 = torch.rand(1, 3, 5, 5)
    >>> input2 = torch.rand(1, 3, 5, 5)
    >>> criterion = kornia.losses.MS_SSIMLoss()
    >>> loss = criterion(input1, input2)

c               ó4   € V ^8„  d   QhRRRRRRRRRRR	R
RR/# )é   ÚsigmaszSequence[float]Ú
data_rangeÚfloatÚKztuple[float, float]ÚalphaÚcompensationÚ	reductionÚstrÚreturnÚNone© )Úformats   "ÚQC:\Ai_Coding\apps\studio\ComfyUI\.venv\Lib\site-packages\kornia\losses\ms_ssim.pyÚ__annotate__ÚMS_SSIMLoss.__annotate__j   sY   € ÷ Dñ DàðDð ðDð ð	Dð
 ðDð ðDð ðDð 
ñDó    c           	     	óV  <€ \         S
V `  4        W n        V^ ,          V,          ^,          V n        V^,          V,          ^,          V n        \        ^VR,          ,          4      V n        V Uu. uF  p\        V4      NK  	  upV n        W@n	        WPn
        W`n        \        V4      V n        ^V P                  ,          ^,           p\        P                  ! V Uu. uF  qpP!                  W‡4      NK  	  up4      P#                  ^4      p	V P%                  RV	RR7       R# u upi u upi )r   Ú_g_masksF)Ú
persistentNéÿÿÿÿ)ÚsuperÚ__init__ÚDRÚC1ÚC2ÚintÚpadr   r   r   r   r   ÚlenÚ
num_scalesÚtorchÚstackÚ_fspecial_gauss_2dÚ	unsqueezeÚregister_buffer)Úselfr   r   r   r   r   r   ÚsigmaÚfilter_sizeÚg_masksÚ	__class__s   &&&&&&&   €r   r"   ÚMS_SSIMLoss.__init__j   só   ø€ ô 	‰ÑÔØ#ŒØ˜A�$ Õ+°Õ1ˆŒØ˜A�$ Õ+°Õ1ˆŒÜ�q˜6 "�:•~Ó&ˆŒÙ17Ó8±¨”u˜U–|±Ñ8ˆŒØ!Œ
Ø#/ÔØ'Œä" 6›{ˆŒð ˜$Ÿ(™(•l QÕ&ˆÜ—+’+ÑX^Ó_ÑX^Èu×6Ñ6°{ÖJÑX^Ñ_Ó`×jÑjÐklÓmˆð 	×Ñ˜Z¨¸UÐÖCùò 9ùò `s   Á0D!ÃD&c               ó8   € V ^8„  d   QhRRRRRRRRR	R
RR
RR
RR/# )r   Ú
state_dictzdict[str, torch.Tensor]Úprefixr   Úlocal_metadataúdict[str, Any]ÚstrictÚboolÚmissing_keysz	list[str]Úunexpected_keysÚ
error_msgsr   r   r   )r   s   "r   r   r   ‡   sZ   € ÷ 
ñ 
à+ð
ð ð
ð 'ð	
ð
 ð
ð  ð
ð #ð
ð ð
ð 
ñ
r   c           	     	ó^   <€ VP                  VR ,           R4       \        SV `	  WW4WVV4       R# )r   N)Úpopr!   Ú_load_from_state_dict)	r/   r6   r7   r8   r:   r<   r=   r>   r3   s	   &&&&&&&&€r   rA   Ú!MS_SSIMLoss._load_from_state_dict‡   s/   ø€ ð 	�‰�v 
Õ*¨DÔ1Ü‰Ñ%Ø ¸ÐWaö	
r   c               ó    € V ^8„  d   QhRRRR/# )r   Ústater9   r   r   r   )r   s   "r   r   r   ™   s   € ÷ ñ  .ð °Tñ r   c                	óZ   <€ \         SV `  V4       R V P                  9  d
   . V n        R# R# )r   N)r!   Ú__setstate__Ú__dict__r   )r/   rD   r3   s   &&€r   rF   ÚMS_SSIMLoss.__setstate__™   s(   ø€ Ü‰Ñ˜UÔ#Ø˜4Ÿ=™=Ô(àˆDŽKñ )r   c          
     ó,   € V ^8„  d   QhRRRRRRRRR	R
/# ©r   Úsizer&   r0   r   ÚdevicezOptional[torch.device]ÚdtypezOptional[torch.dtype]r   útorch.Tensorr   )r   s   "r   r   r   Ÿ   s4   € ÷ ñ ØðØ %ðØ/EðØUjðà	ñr   c                ó  € \         P                  ! WVR7      pWQ^,          ,          p\         P                  ! V^,          ) ^V^,          ,          ,          4      pWfP                  4       ,          pVP	                  R4      # )zÙCreate 1-D gauss kernel.

Args:
    size: the size of gauss kernel.
    sigma: sigma of normal distribution.
    device: device to store the result on.
    dtype: dtype of the result.

Returns:
    1D kernel (size).

)rL   rM   r    )r*   ÚarangeÚexpÚsumÚreshape)r/   rK   r0   rL   rM   ÚcoordsÚgs   &&&&&  r   Ú_fspecial_gauss_1dÚMS_SSIMLoss._fspecial_gauss_1dŸ   s\   € ô —’˜d¸Ô?ˆØ˜!•)ÕˆÜ�IŠI˜ �	�l a¨%°­(¥lÕ3Ó4ˆØ	�U‰U‹W�ˆØ�y‰y˜‹}Ðr   c          
     ó,   € V ^8„  d   QhRRRRRRRRR	R
/# rJ   r   )r   s   "r   r   r   ´   s4   € ÷ 7ñ 7Øð7Ø %ð7Ø/Eð7ØUjð7à	ñ7r   c                óR   € V P                  WW44      p\        P                  ! WU4      # )zàCreate 2-D gauss kernel.

Args:
    size: the size of gauss kernel.
    sigma: sigma of normal distribution.
    device: device to store the result on.
    dtype: dtype of the result.

Returns:
    2D kernel (size x size).

)rV   r*   Úouter)r/   rK   r0   rL   rM   Úgaussian_vecs   &&&&& r   r,   ÚMS_SSIMLoss._fspecial_gauss_2d´   s%   € ð ×.Ñ.¨t¸FÓJˆÜ�{Š{˜<Ó6Ð6r   c               ó$   € V ^8„  d   QhRRRRRR/# )r   Úimg1rN   Úimg2r   r   )r   s   "r   r   r   Æ   s&   € ÷ P%ñ P%˜Lð P%°ð P%Àñ P%r   c                óH  € \        V\        P                  4      '       g   \        R\	        V4       24      h\        V\        P                  4      '       g   \        R\	        V4       24      h\        VP                  4      ^8X  g   \        RVP                   24      h\        VP                  4      ^8X  g   \        RVP                   24      hVP                  ^ ,          VP                  ^ ,          8H  ;'       g5    VP                  ^ ,          ^8H  ;'       g    VP                  ^ ,          ^8H  pVP                  R,          VP                  R,          8w  g	   V'       g'   \        RVP                   RVP                   R24      hV P                  P                  pVP                  4       '       g   VP                  4       '       d<   \        P                  ! VP                  VP                  4      pTpV P                  pEM¿VP                  4       '       d   VP                  MTpVP                  4       '       d   VP                  MTp	\        P                  ! W‰4      p\        P                  ! WT4      pV\        P                  \        P                  39   d   \        P                   pV\        P"                  8X  d©   \        V P$                  4      ^ 8”  d�   ^V P&                  ,          ^,           p
V P                  P(                  p\        P*                  ! V P$                   Uu. uF#  qÀP-                  W¬V\        P"                  4      NK%  	  up4      P/                  ^4      pMYV P                  P1                  V4      pV\        P                  \        P                  39   d   WwP3                  RR	R
7      ,          pVP1                  V4      pVP1                  V4      pVP                  R,          p\        P4                  P7                  \        P                  V4      P9                  V^^^4      pVP(                  P                  R8X  d=   \        P:                  ! RRR7      ;_uu_ 4        V P=                  WV4      pRRR4       MÀVP(                  P                  R8X  d=   \        P:                  ! RRR7      ;_uu_ 4        V P=                  WV4      pRRR4       MiVP(                  P                  R8X  d=   \        P:                  ! RRR7      ;_uu_ 4        V P=                  WV4      pRRR4       MV P=                  WV4      pXP1                  V4      # u upi   + '       g   i     L&; i  + '       g   i     L9; i  + '       g   i     LL; i)z¿Compute MS_SSIM loss.

Args:
    img1: the predicted image with shape ``(B, C, H, W)``.
    img2: the target image with a shape of ``(B, C, H, W)``.

Returns:
    Estimated MS-SSIM_L1 loss.

z&Input type is not a torch.Tensor. Got z'Output type is not a torch.Tensor. Got z,Invalid img1 shape, we expect BxCxHxW. Got: z,Invalid img2 shape, we expect BxCxHxW. Got: :é   NNzNInput and target must have the same shape, except for a batch size of 1. Got: z and Ú.T)ÚdimÚkeepdimÚcpuF)Údevice_typeÚenabledNÚcudaÚmps)éþÿÿÿr    éýÿÿÿ)Ú
isinstancer*   ÚTensorÚ	TypeErrorÚtyper(   ÚshapeÚ
ValueErrorr   r   rM   Ú
is_complexÚpromote_typesÚis_floating_pointÚfloat16Úbfloat16Úfloat32Úfloat64r   r'   rL   r+   r,   r-   ÚtorR   ÚjitÚannotateÚrepeatÚautocastÚ_compute_loss)r/   r^   r_   Ú
same_batchÚ
mask_dtypeÚoutput_dtypeÚcompute_dtyper2   Údtype1Údtype2rK   rL   r0   ÚCHÚlosss   &&&            r   ÚforwardÚMS_SSIMLoss.forwardÆ   s  € ô ˜$¤§¡×-Ò-ÜÐDÄTÈ$ÃZÀLÐQÓRÐRä˜$¤§¡×-Ò-ÜÐEÄdÈ4ÃjÀ\ÐRÓSÐSä�4—:‘:‹ !Ô#ÜÐKÈDÏJÉJÈ<ÐXÓYÐYä�4—:‘:‹ !Ô#ÜÐKÈDÏJÉJÈ<ÐXÓYÐYð —Z‘Z •] d§j¡j°¥mÑ3×_Ð_°t·z±zÀ!µ}ÈÑ7I×_Ð_ÈTÏZÉZÐXYÍ]Ð^_ÑM_ˆ
Ø�:‰:�b�>˜TŸZ™Z¨�^Ô+·:ÜðØŸ
™
�| 5¨¯©¨°Að7óð ð
 —]‘]×(Ñ(ˆ
Ø�?‰?×Ò §¡× 1Ò 1Ü ×.Ò.¨t¯z©z¸4¿:¹:ÓFˆLØ(ˆMØ—m‘mŠGð $(×#9Ñ#9×#;Ò#;�T—Z’ZÀˆFØ#'×#9Ñ#9×#;Ò#;�T—Z’ZÀˆFÜ ×.Ò.¨vÓ>ˆLô "×/Ò/°ÓIˆMØ¤§¡´·±Ð ?Ô?Ü %§¡�Ø¤§¡Ô-´#°d·k±kÓ2BÀQÔ2Fà˜4Ÿ8™8•| aÕ'�ØŸ™×-Ñ-�ÜŸ+š+Ø^b×^iÒ^iÓjÑ^iÐUZ×,Ñ,¨T¸&Ä%Ç-Á-ÖPÑ^iÑjóç‘)˜A“,ñ ð Ÿ-™-×*Ñ*¨=Ó9�Ø¤%§-¡-´·±Ð!@Ô@ð &¯©¸È$¨Ó(OÕO�Gà�w‰w�}Ó%ˆØ�w‰w�}Ó%ˆà—*‘*˜R•.ˆô —)‘)×$Ñ$¤U§\¡\°7Ó;×BÑBÀ2ÀqÈ!ÈQÓOˆà�;‰;×Ñ˜uÔ$Ü—’¨E¸5×AÖAØ×)Ñ)¨$°gÓ>�÷ BÐAà�[‰[×Ñ Ô'Ü—’¨F¸E×BÖBØ×)Ñ)¨$°gÓ>�÷ CÐBà�[‰[×Ñ Ô&Ü—’¨E¸5×AÖAØ×)Ñ)¨$°gÓ>�÷ BÐAð ×%Ñ% d°'Ó:ˆDØ�w‰w�|Ó$Ð$ùò9 k÷$ B×Aú÷ C×Bú÷ B×Aús*   Ì0)U&Ñ9U+ÓU>Ô'VÕ+U;	Õ>V	ÖV!	c               ó(   € V ^8„  d   QhRRRRRRRR/# )r   r^   rN   r_   r2   r   r   )r   s   "r   r   r     s)   € ÷ *ñ * ,ð *°lð *È\ð *Ð^jñ *r   c                	ó   € VP                   R	,          pV P                  p\        P                  ! WW@P                  R7      p\        P                  ! W#W@P                  R7      pWf,          pWw,          p	Wg,          p
\        P                  ! W,          W4V P                  R7      V,
          p\        P                  ! W",          W4V P                  R7      V	,
          p\        P                  ! W,          W4V P                  R7      V
,
          p^V
,          V P
                  ,           W‰,           V P
                  ,           ,          p^V,          V P                  ,           W¼,           V P                  ,           ,          pVRV^,
          RV13,          pVP                  ^WE.4      P                  ^R7      p^VV,          P                  ^R7      ,
          pW,
          P                  4       p\        P                  ! VW5^,
          RV1,          W@P                  R7      P                  ^4      pV P                  V,          ^V P                  ,
          V,          V P                  ,          ,           pV P                  V,          pV P                  R8X  d   \        P                  ! V4      pV# V P                  R8X  d   \        P                   ! V4      pV# V P                  R8X  d    V# \#        RV P                   24      h)
é   )ÚgroupsÚpadding:NNNN)rc   ÚmeanrR   ÚnonezInvalid reduction mode: rk   )rp   r)   ÚFÚconv2dr'   r$   r%   Ú	unflattenÚprodrŽ   Úabsr   r#   r   r   r*   rR   ÚNotImplementedError)r/   r^   r_   r2   r…   ÚSÚmuxÚmuyÚmux2Úmuy2ÚmuxyÚsigmax2Úsigmay2ÚsigmaxyÚlcÚcsÚlMÚPIcsÚloss_ms_ssimÚloss_l1Úgaussian_l1r†   s   &&&&                  r   r~   ÚMS_SSIMLoss._compute_loss  s?  € Ø—*‘*˜R•.ˆØ—‘ˆä�hŠh�t¨R¿¹ÔBˆÜ�hŠh�t¨R¿¹ÔBˆØ�yˆØ�yˆØ�yˆä—(’(˜4�;¨ÀDÇHÁHÔMÐPTÕTˆÜ—(’(˜4�;¨ÀDÇHÁHÔMÐPTÕTˆÜ—(’(˜4�;¨ÀDÇHÁHÔMÐPTÕTˆà�$�h˜Ÿ™Õ  T¥[°4·7±7Õ%:Õ;ˆØ�'�k˜DŸG™GÕ#¨Õ(9¸D¿G¹GÕ(CÕDˆà��1�q•5�:˜A�:�ÕˆØ�|‰|˜A ˜wÓ'×,Ñ,°Ð,Ó3ˆð ˜B �I×+Ñ+°Ð+Ó2Õ2ˆð •;×#Ñ#Ó%ˆô —h’h˜w¨°Aµ°
¸°
Õ(;ÀB×PXÑPXÔY×^Ñ^Ð_`Óaˆð �z‰z˜LÕ(¨A°·
±
­N¸kÕ+IÈDÏGÉGÕ+SÕSˆØ× Ñ  4Õ'ˆà�>‰>˜VÔ#Ü—:’:˜dÓ#ˆDð ˆð �^‰^˜uÔ$Ü—9’9˜T“?ˆDð
 ˆð	 �^‰^˜vÔ%Øð ˆô &Ð(@ÀÇÁÐ@PÐ&QÓRÐRr   )	r$   r%   r#   r   r   r)   r'   r   r   ))g      à?ç      ð?g       @g      @g       @r§   )g{®Gáz„?g¸…ëQ¸ž?gš™™™™™™?g      i@rŽ   )NN)Ú__name__Ú
__module__Ú__qualname__Ú__firstlineno__Ú__doc__r"   rA   rF   rV   r,   r‡   r~   Ú__static_attributes__Ú__classcell__)r3   s   @r   r
   r
       sE   ø† ñG÷RDò D÷:
ð 
÷$ð ÷÷*7õ$P%÷d*ó *r   r
   )Ú
__future__r   Útypingr   r   r   r*   Útorch.nn.functionalr   Ú
functionalr�   Úkornia.core.exceptionsr   ÚModuler
   r   r   r   Ú<module>rµ      s1   ðõ$ #ç *Ñ *ã ß Ð Ý å -ôb�"—)‘)ö br   