Ë
    éÓ^j)#  ã                   ól  — d Z ddlZddlZddlmZmZmZmZ ddlZdddddœd	eej                     d
e
de
de
dedeeej                     ee
   eeef   f   fd„Zddœdej                  dede
dej                  fd„Zddœdej                  deeef   dee
   dede
dej                  fd„Z G d„ d«      Zy)uš  Variableâ€‘size Mixup / CutMix utilities for NaFlex data loaders.

This module provides:

* `mix_batch_variable_size` â€“ pixelâ€‘level Mixup/CutMix that operates on a
  list of images whose spatial sizes differ, mixing only their central overlap
  so no resizing is required.
* `pairwise_mixup_target` â€“ builds softâ€‘label targets that exactly match the
  perâ€‘sample pixel provenance produced by the mixer.
* `NaFlexMixup` â€“ a callable functor that wraps the two helpers and stores
  all augmentation hyperâ€‘parameters in one place, making it easy to plug into
  different dataset wrappers.

Hacked together by / Copyright 2025, Ross Wightman, Hugging Face
é    N)ÚDictÚListÚTupleÚUnionçš™™™™™é?ç      ð?ç      à?é   ©Úmixup_alphaÚcutmix_alphaÚswitch_probÚlocal_shuffleÚimgsr   r   r   r   Úreturnc                óÜ  ‡ — t        ‰ «      dk  rt        d«      ‚|dkD  r2|dkD  r-t        j                  d«      j	                  «       |k  }|r|n|}n|dkD  rd}|}n|dkD  rd}|}nt        d«      ‚t        j
                  j                  ||«      j                  «       j	                  «       }t        dt        d|«      «      }t        t        t        ‰ «      «      ˆ fd	„¬
«      }|dkD  r6t        dt        |«      |«      D ]  }	t        j                  ||	|	|z    «       Œ i }
t        |ddd…   |ddd…   «      D ]  \  }}||
|<   ||
|<   Œ t        ‰ «      dz  r|d   nd}dgt        ‰ «      z  }dgt        ‰ «      z  }t        t        ‰ «      «      D �]Ò  }||k(  r	‰ |   ||<   Œ|
|   }‰ |   ‰ |   }}|j                  \  }}}|j                  \  }}}||z  }t        ||«      t        ||«      }}||z  }||z
  dz  ||z
  dz  }}||z
  dz  ||z
  dz  } }|j!                  «       }|rÂt#        j$                  d|z
  «      }!t'        ||!z  «      t'        ||!z  «      }#}"|"|#z  }$t        j(                  d||"z
  «      }%t        j(                  d||#z
  «      }&||%z   ||&z   }(}'||%z   | |&z   }*})|dd…|)|)|"z   …|*|*|#z   …f   |dd…|'|'|"z   …|(|(|#z   …f<   |||<   d|$t+        |«      z  z
  }+|+||<   �ŒW|dd…|||z   …|||z   …f   },|dd…|||z   …| | |z   …f   }-|,j-                  |«      j/                  |-d|z
  ¬«      }.|.|dd…|||z   …|||z   …f<   |||<   ||z
  |z  ||z  |z  z   }+|+||<   �ŒÕ |||
fS )aO  Apply Mixup or CutMix on a batch of variable-sized images.

    Sorts images by aspect ratio and pairs neighboring samples. Only the mutual
    central overlap region of each pair is mixed.

    Args:
        imgs: List of transformed images shaped (C, H, W).
        mixup_alpha: Beta distribution alpha for Mixup. Set to 0 to disable.
        cutmix_alpha: Beta distribution alpha for CutMix. Set to 0 to disable.
        switch_prob: Probability of using CutMix when both modes are enabled.
        local_shuffle: Size of local windows for shuffling after aspect sorting.

    Returns:
        Tuple of (mixed_imgs, lam_list, pair_to) where:
            - mixed_imgs: List of mixed images
            - lam_list: Per-sample lambda values representing mixing degree
            - pair_to: Mapping i -> j of which sample was mixed with which
    é   z1Need at least two images to perform Mixup/CutMix.ç        © FTu=   Both mixup_alpha and cutmix_alpha are zero â€“ nothing to do.r   c                 óN   •— ‰|    j                   d   ‰|    j                   d   z  S )Nr   é   )Úshape)Úir   s    €úa/var/www/ramen.bs-engineer-server.com/venv/lib/python3.12/site-packages/timm/data/naflex_mixup.pyú<lambda>z)mix_batch_variable_size.<locals>.<lambda>E   s'   ø€ °4¸±7·=±=ÀÑ3CÀdÈ1ÁgÇmÁmÐTUÑFVÑ3V€ ó    )Úkeyr   r   Néÿÿÿÿ©Úalpha)ÚlenÚ
ValueErrorÚtorchÚrandÚitemÚdistributionsÚBetaÚsampleÚmaxÚminÚsortedÚrangeÚrandomÚshuffleÚzipr   ÚcloneÚmathÚsqrtÚintÚrandintÚfloatÚmulÚadd_)/r   r   r   r   r   Ú
use_cutmixr    Úlam_rawÚorderÚstartÚpair_toÚaÚbÚodd_oneÚ
mixed_imgsÚlam_listr   ÚjÚxiÚxjÚ_ÚhiÚwiÚhjÚwjÚ	dest_areaÚohÚowÚoverlap_areaÚtop_iÚleft_iÚtop_jÚleft_jÚ	cut_ratioÚchÚcwÚcut_areaÚy_offÚx_offÚyl_iÚxl_iÚyl_jÚxl_jÚcorrected_lamÚpatch_iÚpatch_jÚblendeds/   `                                              r   Úmix_batch_variable_sizer`      s  ø€ ô4 ˆ4ƒy�1‚}ÜÐLÓMÐMð �SÒ˜\¨CÒ/Ü—Z‘Z “^×(Ñ(Ó*¨[Ñ8ˆ
Ù *‘°‰Ø	�sÒ	Øˆ
Ø‰Ø	˜Ò	Øˆ
Ø‰äÐXÓYÐYä×!Ñ!×&Ñ& u¨eÓ4×;Ñ;Ó=×BÑBÓD€GÜ�#”s˜3 Ó(Ó)€Gô ”5œ˜T›Ó#Ó)VÔW€EØ�qÒÜ˜1œc %›j¨-Ó8ò 	?ˆEÜ�N‰N˜5  u¨}Ñ'<Ð=Õ>ð	?ð !€GÜ�E™#˜A˜#‘J  a d¨ d¡Ó,ò ‰ˆˆ1Øˆ�‰
Øˆ�Š
ðô ˜t›9 qš=ˆe�BŠi¨d€Gà&* V¬c°$«iÑ%7€JØ ˜E¤C¨£IÑ-€Hä”3�t“9Óó +(ˆØ�Š<Ø  ™GˆJ�q‰MØà�A‰JˆØ�a‘˜$˜q™'ˆBˆØ—H‘H‰	ˆˆ2ˆrØ—H‘H‰	ˆˆ2ˆrØ˜‘Gˆ	ô �R˜“œc " b›kˆBˆØ˜B‘wˆØ˜b™ Q™¨¨b©°Q©ˆvˆØ˜b™ Q™¨¨b©°Q©ˆvˆà�X‰X‹ZˆÙäŸ	™	 #¨¡-Ó0ˆIÜ˜˜i™Ó(¬#¨b°9©nÓ*=�ˆBØ˜B‘wˆHÜ—N‘N 1 b¨2¡gÓ.ˆEÜ—N‘N 1 b¨2¡gÓ.ˆEà ™¨°©�$ˆDØ ™¨°©�$ˆDØ68º¸DÀ$ÈÁ)¸OÈTÐSWÐZ\ÑS\È_Ð9\Ñ6]ˆBŠq�$˜˜r™	�/ 4¨°© ?Ð2Ñ3ØˆJ�q‰Mà (¬U°9Ó-=Ñ"=Ñ=ˆMØ'ˆH�Q‹Kð š˜E %¨"¡*Ð,¨f°V¸b±[Ð.@Ð@ÑAˆGØš˜E %¨"¡*Ð,¨f°V¸b±[Ð.@Ð@ÑAˆGà—k‘k 'Ó*×/Ñ/°¸sÀW¹}Ð/ÓMˆGØ:AˆBŠq�%˜ ™
Ð" F¨6°B©;Ð$6Ð6Ñ7ØˆJ�q‰Mà&¨Ñ5¸ÑBÀWÈ|ÑE[Ð^gÑEgÑgˆMØ'ˆH�Q‹KðW+(ðZ �x Ð(Ð(r   r   )Ú	smoothingÚtargetsÚnum_classesra   c                óè   — ||z  }d|z
  |z   }t        j                  | j                  d«      |f|t         j                  | j                  ¬«      }|j                  d| j                  d«      |«       |S )Nr   r   )ÚdtypeÚdevicer   )r#   ÚfullÚsizeÚfloat32rf   Úscatter_Ú	unsqueeze)rb   rc   ra   Úoff_valÚon_valÚy_onehots         r   Úsmoothed_sparse_targetro   „   so   € ð ˜+Ñ%€GØ�9‰_˜wÑ&€Fä�z‰zØ	�‰�a‹˜+Ð&ØÜ�m‰mØ�~‰~ô	€Hð ×Ñ�a˜×*Ñ*¨1Ó-¨vÔ6Ø€Or   r<   rA   c                óÒ   — t        | ||¬«      }|j                  «       } |j                  «       D ]5  \  }}||   }| |   j                  |«      j	                  ||   d|z
  ¬«       Œ7 | S )u  Create soft targets that match the pixelâ€‘level mixing performed.

    Args:
        targets: (B,) tensor of integer class indices.
        pair_to: Mapping of sample index to its mixed partner as returned by mix_batch_variable_size().
        lam_list: Perâ€‘sample fractions of own pixels, also from the mixer.
        num_classes: Total number of classes in the dataset.
        smoothing: Labelâ€‘smoothing value in the range [0, 1).

    Returns:
        Tensor of shape (B, num_classes) whose rows sum to 1.
    ©rc   ra   r   r   )ro   r0   ÚitemsÚmul_r7   )	rb   r<   rA   rc   ra   rn   r   rB   Úlams	            r   Úpairwise_mixup_targetru   —   sr   € ô( & g¸;ÐR[Ô\€HØ�n‰nÓ€GØ—‘“ò @‰ˆˆ1Ø�q‰kˆØ�‰
�‰˜Ó×!Ñ! (¨1¡+°S¸3±YÐ!Õ?ð@ð €Nr   c                   óÈ   — e Zd ZdZdddddddœded	ed
edededededdfd„Zdeej                     dej                  de
eej                     eej                     f   fd„Zy)ÚNaFlexMixupz<Callable wrapper that combines mixing and target generation.r   r   r	   r
   r   )r   r   r   Úprobr   Úlabel_smoothingrc   r   r   r   rx   r   ry   r   Nc                óf   — || _         || _        || _        || _        || _        || _        || _        y)u4  Configure the augmentation.

        Args:
            num_classes: Total number of classes.
            mixup_alpha: Beta Î± for Mixup. 0 disables Mixup.
            cutmix_alpha: Beta Î± for CutMix. 0 disables CutMix.
            switch_prob: Probability of selecting CutMix when both modes are enabled.
            prob: Probability of applying any mixing per batch.
            local_shuffle: Window size used to shuffle images after aspect sorting so pairings vary between epochs.
            smoothing: Labelâ€‘smoothing value. 0 disables smoothing.
        N)rc   r   r   r   rx   r   ra   )Úselfrc   r   r   r   rx   r   ry   s           r   Ú__init__zNaFlexMixup.__init__·   s:   € ð, 'ˆÔØ&ˆÔØ(ˆÔØ&ˆÔØˆŒ	Ø*ˆÔØ(ˆ�r   r   rb   c                 óò  — t        |t        j                  «      st        j                  |«      }t	        j                  «       | j
                  kD  r5t        || j                  | j                  ¬«      }||j                  d«      fS t        || j                  | j                  | j                  | j                  ¬«      \  }}}t        |||| j                  | j                  ¬«      }||j                  d«      fS )u¡  Apply the augmentation and generate matching targets.

        Args:
            imgs: List of already transformed images shaped (C, H, W).
            targets: Hard labels with shape (B,).

        Returns:
            mixed_imgs: List of mixed images in the same order and shapes as the input.
            targets: Softâ€‘label tensor shaped (B, num_classes) suitable for crossâ€‘entropy with soft targets.
        rq   r   r   )Ú
isinstancer#   ÚTensorÚtensorr-   rx   ro   rc   ra   Úunbindr`   r   r   r   r   ru   )r{   r   rb   r@   rA   r<   s         r   Ú__call__zNaFlexMixup.__call__Õ   sÔ   € ô ˜'¤5§<¡<Ô0Ü—l‘l 7Ó+ˆGä�=‰=‹?˜TŸY™YÒ&Ü,¨WÀ$×BRÑBRÐ^b×^lÑ^lÔmˆGØ˜Ÿ™¨Ó*Ð*Ð*ä(?ØØ×(Ñ(Ø×*Ñ*Ø×(Ñ(Ø×,Ñ,ô)
Ñ%ˆ
�H˜gô (ØØØØ×(Ñ(Ø—n‘nô
ˆð ˜7Ÿ>™>¨!Ó,Ð,Ð,r   )Ú__name__Ú
__module__Ú__qualname__Ú__doc__r3   r5   r|   r   r#   r   r   r‚   r   r   r   rw   rw   ´   s¸   „ ÙFð "%Ø"%Ø!$ØØ!"Ø%(ò)ð ð)ð ð	)ð
  ð)ð ð)ð ð)ð ð)ð #ð)ð 
ó)ð<%-à�u—|‘|Ñ$ð%-ð —\‘\ð%-ð 
ˆt�E—L‘LÑ! 4¨¯©Ñ#5Ð5Ñ	6ô	%-r   rw   )r†   r1   r-   Útypingr   r   r   r   r#   r   r5   r3   r`   ro   ru   rw   r   r   r   ú<module>rˆ      s4  ðñó Û ß +Ó +ã ð !Ø!Ø Øòj)Ø�5—<‘<Ñ ðj)ð ðj)ð ð	j)ð
 ðj)ð ðj)ð ˆ4�—‘Ñ˜t E™{¨D°°c°©NÐ:Ñ;ój)ðb ò	Ø—‘ðð ðð ð	ð
 ‡\�\óð2 òØ—‘ðà�c˜3�h‘ðð �u‘+ðð
 ðð ðð ‡\�\ó÷:F-ò F-r   