Ë
    éÓ^jü"  ã                   ó<  — d Z ddlmZmZ ddlZddlmZ ddlmc mZ	 	 	 	 	 	 	 	 ddej                  dedededed	ed
edefd„Z G d„ dej                  «      Zddededefd„Z G d„ dej                  «      Z	 ddedeeee   f   dedeee   eee      f   fd„Zy)a>   DropBlock, DropPath

PyTorch implementations of DropBlock and DropPath (Stochastic Depth) regularization layers.

Papers:
DropBlock: A regularization method for convolutional networks (https://arxiv.org/abs/1810.12890)

Deep Networks with Stochastic Depth (https://arxiv.org/abs/1603.09382)

Code:
DropBlock impl inspired by two Tensorflow impl that I liked:
 - https://github.com/tensorflow/tpu/blob/master/models/official/resnet/resnet_model.py#L74
 - https://github.com/clovaai/assembled-cnn/blob/master/nets/blocks.py

Hacked together by / Copyright 2020 Ross Wightman
é    )ÚListÚUnionNÚxÚ	drop_probÚ
block_sizeÚgamma_scaleÚ
with_noiseÚinplaceÚcouple_channelsÚscale_by_keepc           	      óæ  — | j                   \  }}	}
}t        ||
«      t        ||«      }}t        ||z  |
z  |z  «      t        ||z  «      z  t        |
|z
  dz   ||z
  dz   z  «      z  }||rdn|	|
|f}t        j                  «       5  t        j
                  || j                  | j                  ¬«      j                  |«      }t        j                  |||fd|dz  |dz  f¬«      }|dz  dk(  s|dz  dk(  r|d|dz   dz  d…|dz   dz  d…f   }d|z
  }ddd«       |rt        j                  «       5  t        j                  «      j                  «       }|j                  «       ddd«       |r"| j                  «      j                  «       | S | z  z   } | S |r•t        j                  «       5  j                  «       |j!                  t        j"                  ¬	«      j%                  «       j'                  d
«      z  }|j                  |j!                  | j                  «      «       ddd«       |r| j                  «       | S | z  } | S # 1 sw Y   �Œ>xY w# 1 sw Y   Œ÷xY w# 1 sw Y   Œ>xY w)a   DropBlock. See https://arxiv.org/pdf/1810.12890.pdf

    DropBlock with an experimental gaussian noise option.

    Args:
        x: Input tensor of shape (B, C, H, W).
        drop_prob: Probability of dropping a block.
        block_size: Size of the block to drop.
        gamma_scale: Scale factor for the drop probability.
        with_noise: If True, add gaussian noise to dropped regions instead of zeros.
        inplace: If True, perform operation in-place.
        couple_channels: If True, all channels share the same drop mask (per the original paper).
            If False, each channel gets an independent mask.
        scale_by_keep: If True, scale kept activations to maintain expected values.

    Returns:
        Tensor with dropped blocks, same shape as input.
    é   )ÚdtypeÚdeviceé   )Úkernel_sizeÚstrideÚpaddingr   .Nç      ð?)r   gH¯¼šò×z>)ÚshapeÚminÚfloatÚtorchÚno_gradÚemptyr   r   Ú
bernoulli_ÚFÚ
max_pool2dÚ
empty_likeÚnormal_Úmul_Úadd_ÚnumelÚtoÚfloat32ÚsumÚadd)r   r   r   r   r	   r
   r   r   ÚBÚCÚHÚWÚkhÚkwÚgammaÚnoise_shapeÚ
block_maskÚ	keep_maskÚnoiseÚnormalize_scales                       ú[/var/www/ramen.bs-engineer-server.com/venv/lib/python3.12/site-packages/timm/layers/drop.pyÚdrop_block_2dr5      sb  € ð8 —‘�J€A€qˆ!ˆQÜ�˜QÓ¤ Z°Ó!3ˆ€Bô �+ 	Ñ)¨AÑ-°Ñ1Ó2´U¸2À¹7³^ÑCÄeÈQÐQSÉVÐVWÉZÐ\]Ð`bÑ\bÐefÑ\fÑLgÓFhÑh€Eð ™?‘a°°1°aÐ8€KÜ	�‰‹ñ $Ü—[‘[ °A·G±GÀAÇHÁHÔM×XÑXÐY^Ó_ˆ
ô —\‘\ØØ˜R˜ØØ˜1‘W˜b A™gÐ&ô	
ˆ
ð �‰6�QŠ;˜"˜q™& Aš+à# C¨"¨q©&°A©©¸¸a¹À1¹¹Ð$EÑFˆJà˜‘Oˆ	÷$ñ" Ü�]‰]‹_ñ 	#Ü×$Ñ$ YÓ/×7Ñ7Ó9ˆEØ�J‰J�zÔ"÷	#ñ Ø�F‰F�9Ó×"Ñ" 5Ô)ð €Hð �I‘ Ñ%ˆAð €Hñ Ü—‘“ñ <à"+§/¡/Ó"3°i·l±lÌÏÉ°lÓ6W×6[Ñ6[Ó6]×6aÑ6aÐbfÓ6gÑ"g�Ø—‘˜×1Ñ1°!·'±'Ó:Ô;÷<ñ
 Ø�F‰F�9Ôð €Hð �I‘ˆAà€H÷M$ñ $ú÷$	#ð 	#ú÷<ð <ús&   ÂBIÄ05IÆ1A9I'ÉIÉI$É'I0c                   óV   ‡ — e Zd ZdZ	 	 	 	 	 	 	 ddededededededefˆ fd	„Zd
„ Zˆ xZ	S )ÚDropBlock2daa   DropBlock. See https://arxiv.org/pdf/1810.12890.pdf

    Args:
        drop_prob: Probability of dropping a block.
        block_size: Size of the block to drop.
        gamma_scale: Scale factor for the drop probability.
        with_noise: If True, add gaussian noise to dropped regions instead of zeros.
        inplace: If True, perform operation in-place.
        couple_channels: If True, all channels share the same drop mask (per the original paper).
            If False, each channel gets an independent mask.
        scale_by_keep: If True, scale kept activations to maintain expected values.
    r   r   r   r	   r
   r   r   c                 óÖ   •— t         ‰| �  «        || _        || _        || _        || _        || _        || _        || _        ddh}	|D ]   }
|
|	vsŒdd l	}|j                  d|
› d�«       Œ" y )NÚ	batchwiseÚfastr   z/DropBlock2d() got unexpected keyword argument 'ú')ÚsuperÚ__init__r   r   r   r	   r
   r   r   ÚwarningsÚwarn)Úselfr   r   r   r	   r
   r   r   ÚkwargsÚdeprecated_argsÚkr>   Ú	__class__s               €r4   r=   zDropBlock2d.__init__t   s„   ø€ ô 	‰ÑÔØ"ˆŒØ&ˆÔØ$ˆŒØ$ˆŒØˆŒØ.ˆÔØ*ˆÔð '¨Ð/ˆØò 	VˆAØ˜Ò'ÛØ—‘Ð OÐPQÈsÐRSÐTÕUñ	Vó    c           
      óè   — | j                   r| j                  s|S t        || j                  | j                  | j                  | j
                  | j                  | j                  | j                  ¬«      S )N)r   r   r   r	   r
   r   r   )	Útrainingr   r5   r   r   r	   r
   r   r   ©r@   r   s     r4   ÚforwardzDropBlock2d.forward�   s[   € Ø�}Š} D§N¢NØˆHÜØØ—n‘nØ—‘Ø×(Ñ(Ø—‘Ø—L‘LØ ×0Ñ0Ø×,Ñ,ô	
ð 		
rE   ©gš™™™™™¹?é   r   FFTT)
Ú__name__Ú
__module__Ú__qualname__Ú__doc__r   ÚintÚboolr=   rI   Ú__classcell__©rD   s   @r4   r7   r7   f   su   ø„ ñð  #ØØ!$Ø$Ø!Ø$(Ø"&ñVàðVð ðVð ð	Vð
 ðVð ðVð "ðVð  õVö6
rE   r7   rG   c                 óÞ   — |dk(  s|s| S d|z
  }| j                   d   fd| j                  dz
  z  z   }| j                  |«      j                  |«      }|dkD  r|r|j	                  |«       | |z  S )a(  Drop paths (Stochastic Depth) per sample (when applied in main path of residual blocks).

    This is the same as the DropConnect impl I created for EfficientNet, etc networks, however,
    the original name is misleading as 'Drop Connect' is a different form of dropout in a separate paper...
    See discussion: https://github.com/tensorflow/tpu/issues/494#issuecomment-532968956 ... I've opted for
    changing the layer and argument names to 'drop path' rather than mix DropConnect as a layer name and use
    'survival rate' as the argument.

    ç        r   r   )r   )r   ÚndimÚ	new_emptyr   Údiv_)r   r   rG   r   Ú	keep_probr   Úrandom_tensors          r4   Ú	drop_pathr[   ž   sw   € ð �B‚™hØˆØ�I‘€IØ�W‰W�Q‰ZˆM˜D A§F¡F¨Q¡JÑ/Ñ/€EØ—K‘K Ó&×1Ñ1°)Ó<€MØ�3‚™=Ø×Ñ˜9Ô%Øˆ}ÑÐrE   c                   ó:   ‡ — e Zd ZdZddedefˆ fd„Zd„ Zd„ Zˆ xZ	S )ÚDropPathz^Drop paths (Stochastic Depth) per sample  (when applied in main path of residual blocks).
    r   r   c                 ó>   •— t         ‰| �  «        || _        || _        y ©N)r<   r=   r   r   )r@   r   r   rD   s      €r4   r=   zDropPath.__init__µ   s   ø€ Ü‰ÑÔØ"ˆŒØ*ˆÕrE   c                 óZ   — t        || j                  | j                  | j                  «      S r_   )r[   r   rG   r   rH   s     r4   rI   zDropPath.forwardº   s!   € Ü˜˜DŸN™N¨D¯M©M¸4×;MÑ;MÓNÐNrE   c                 ó6   — dt        | j                  d«      d›�S )Nz
drop_prob=é   z0.3f)Úroundr   )r@   s    r4   Ú
extra_reprzDropPath.extra_repr½   s   € ØœE $§.¡.°Ó3°DÐ9Ð:Ð:rE   )rU   T)
rL   rM   rN   rO   r   rQ   r=   rI   rd   rR   rS   s   @r4   r]   r]   ²   s&   ø„ ññ+ %ð +¸Tõ +ò
Oö;rE   r]   Údrop_path_rateÚdepthsÚ	stagewiseÚreturnc                 óÖ  — t        |t        «      rC|rt        d«      ‚t        j                  d| |d¬«      D �cg c]  }|j                  «       ‘Œ }}|S t        |«      }|rEt        j                  d| |d¬«      j                  |«      D �cg c]  }|j                  «       ‘Œ }}|S t        j                  d| |d¬«      D �cg c]  }|j                  «       ‘Œ }}|S c c}w c c}w c c}w )a   Generate drop path rates for stochastic depth.

    This function handles two common patterns for drop path rate scheduling:
    1. Per-block: Linear increase from 0 to drop_path_rate across all blocks
    2. Stage-wise: Linear increase across stages, with same rate within each stage

    Args:
        drop_path_rate: Maximum drop path rate (at the end).
        depths: Either a single int for total depth (per-block mode) or
                list of ints for depths per stage (stage-wise mode).
        stagewise: If True, use stage-wise pattern. If False, use per-block pattern.
                   When depths is a list, stagewise defaults to True.

    Returns:
        For per-block mode: List of drop rates, one per block.
        For stage-wise mode: List of lists, drop rates per stage.
    z;stagewise=True requires depths to be a list of stage depthsr   Úcpu)r   )	Ú
isinstancerP   Ú
ValueErrorr   ÚlinspaceÚitemr&   ÚsplitÚtolist)re   rf   rg   r   ÚdprÚtotal_depths         r4   Úcalculate_drop_path_ratesrs   Á   sÕ   € ô, �&œ#ÔáÜÐZÓ[Ð[Ü!&§¡°°>À6ÐRWÔ!XÖY˜Aˆq�v‰v�xÐYˆÐYØˆ
ô ˜&“kˆÙä',§~¡~°a¸ÈÐ]bÔ'c×'iÑ'iÐjpÓ'qÖr !�1—8‘8•:ÐrˆCÐrØˆJô &+§^¡^°A°~À{Ð[`Ô%aÖb �1—6‘6•8ÐbˆCÐbØˆJùò Zùò sùò cs   ¹CÂC!ÃC&rJ   )rU   FT)F)rO   Útypingr   r   r   Útorch.nnÚnnÚtorch.nn.functionalÚ
functionalr   ÚTensorr   rP   rQ   r5   ÚModuler7   r[   r]   rs   © rE   r4   ú<module>r|      s  ðñ÷  ã Ý ß Ð ð
 ØØ Ø ØØ $Ø"ñKØ�<‰<ðKàðKð ðKð ð	Kð
 ðKð ðKð ðKð óKô\5
�"—)‘)ô 5
ñp˜Eð °$ð Ètó ô(;ˆr�y‰yô ;ð$  ñ&Øð&à�c˜4 ™9�nÑ%ð&ð ð&ð ˆ4�‰;˜˜T %™[Ñ)Ð)Ñ*ô	&rE   