
    RЦi)#                     x   S r SSKrSSKrSSKJrJrJrJr  SSKrSSSSS.S	\\R                     S
\
S\
S\
S\S\\\R                     \\
   \\\4   4   4S jjrSS.S\R                  S\S\
S\R                  4S jjrSS.S\R                  S\\\4   S\\
   S\S\
S\R                  4S jjr " S S5      rg)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 5      S:  a  [        S5      eUS:  a9  US:  a3  [        R                  " S5      R	                  5       U:  nU(       a  UOUnO!US:  a  SnUnOUS:  a  SnUnO[        S5      e[        R
                  R                  Xf5      R                  5       R	                  5       n[        S[        SU5      5      n[        [        [        T 5      5      U 4S	 jS
9nUS:  a7  [        S[        U5      U5       H  n	[        R                  " XX-    5        M     0 n
[        USSS2   USSS2   5       H  u  pXU'   XU'   M     [        T 5      S-  (       a  US   OSnS/[        T 5      -  nS/[        T 5      -  n[        [        T 5      5       GH  nUU:X  a
  T U   UU'   M  U
U   nT U   T U   nnUR                  u  nnnUR                  u  nnnUU-  n[        UU5      [        UU5      nnUU-  nUU-
  S-  UU-
  S-  nnUU-
  S-  UU-
  S-  n nUR!                  5       nU(       a  ["        R$                  " SU-
  5      n!['        UU!-  5      ['        UU!-  5      n#n"U"U#-  n$[        R(                  " SUU"-
  5      n%[        R(                  " SUU#-
  5      n&UU%-   UU&-   n(n'UU%-   U U&-   n*n)USS2U)U)U"-   2U*U*U#-   24   USS2U'U'U"-   2U(U(U#-   24'   UUU'   SU$[+        U5      -  -
  n+U+UU'   GMb  USS2UUU-   2UUU-   24   n,USS2UUU-   2U U U-   24   n-U,R-                  U5      R/                  U-SU-
  S9n.U.USS2UUU-   2UUU-   24'   UUU'   UU-
  U-  UU-  U-  -   n+U+UU'   GM     XU
4$ )a  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   > TU    R                   S   TU    R                   S   -  $ )Nr      )shape)ir   s    U/var/www/html/ai-image-ml/venv/lib/python3.13/site-packages/timm/data/naflex_mixup.py<lambda>)mix_batch_variable_size.<locals>.<lambda>E   s%    47==3Cd1gmmTUFV3V    )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_sizera      s   4 4y1}LMM S\C/ZZ^((*[8
 *	s	
		
XYY!!&&u4;;=BBDG#s3()G 5T#)VWEq1c%j-8ENN5u'<=> 9 !GE#A#Jadd,

 - t9q=eBidG&*Vc$i%7J ECI-H3t9< GJqMAJa$q'BHH	2rHH	2rG	 Rc"bkBBwbQbQvbQbQvXXZ		#-0Ii(#b9n*=BBwHNN1b2g.ENN1b2g.E$D$D68D$)OTSWZ\S\_9\6]Bq$r	/4?23JqM(U9-="==M'HQK E%"*,fVb[.@@AGE%"*,fVb[.@@AGkk'*//sW}/MG:ABq%
"F6B;$667JqM&5BW|E[^gEggM'HQKW Z ((r   r   )	smoothingtargetsnum_classesrb   c                    X!-  nSU-
  U-   n[         R                  " U R                  S5      U4U[         R                  U R                  S9nUR                  SU R                  S5      U5        U$ )Nr   r   )dtypedevicer   )r$   fullsizefloat32rg   scatter_	unsqueeze)rc   rd   rb   off_valon_valy_onehots         r   smoothed_sparse_targetrp      sm     %G9_w&Fzz	a+&mm~~	H a**1-v6Or   r=   rB   c                    [        XUS9nUR                  5       n UR                  5        H/  u  pgX&   nX   R                  U5      R	                  XW   SU-
  S9  M1     U $ )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.
rd   rb   r   r    )rp   r1   itemsmul_r8   )	rc   r=   rB   rd   rb   ro   r   rC   lams	            r   pairwise_mixup_targetrv      sa    ( &gR[\HnnGk
!!(+S3Y!?   Nr   c                       \ rS rSrSrSSSSSSS.S	\S
\S\S\S\S\S\SS4S jjrS\\	R                     S\	R                  S\\\	R                     \\	R                     4   4S jrSrg)NaFlexMixup   z<Callable wrapper that combines mixing and target generation.r   r   r	   r
   r   )r   r   r   probr   label_smoothingrd   r   r   r   rz   r   r{   r   Nc                X    Xl         X l        X0l        X@l        XPl        X`l        Xpl        g)u  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)rd   r   r   r   rz   r   rb   )selfrd   r   r   r   rz   r   r{   s           r   __init__NaFlexMixup.__init__   s,    , '&(&	*(r   r   rc   c                    [        U[        R                  5      (       d  [        R                  " U5      n[        R                  " 5       U R
                  :  a0  [        X R                  U R                  S9nXR                  S5      4$ [        UU R                  U R                  U R                  U R                  S9u  p4n[        UUUU R                  U R                  S9nX2R                  S5      4$ )ui  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.
rr   r   r   )
isinstancer$   Tensortensorr.   rz   rp   rd   rb   unbindra   r   r   r   r   rv   )r}   r   rc   rA   rB   r=   s         r   __call__NaFlexMixup.__call__   s     '5<<00ll7+G==?TYY&,WBRBR^b^l^lmG***(?((**((,,)
%
g (((nn
 >>!,,,r   )r   r   r   rd   rz   rb   r   )__name__
__module____qualname____firstlineno____doc__r4   r6   r~   r   r$   r   r   r   __static_attributes__r   r   r   rx   rx      s    F "%"%!$!"%() ) 	)
  ) ) ) ) #) 
)<%-u||$%- \\%- 
tELL!4#55	6	%-r   rx   )r   r2   r.   typingr   r   r   r   r$   r   r6   r4   ra   rp   rv   rx   r   r   r   <module>r      s4     + +  !! j)5<< j) j) 	j)
 j) j) 4tE{DcN:;j)b 	  	
 \\2 c3h u+
   \\:F- F-r   