
    ^jc                        d Z ddlmZ ddlmZ ddlmZmZmZm	Z	 ddl
Z
ddlmZ ddlmc mZ ddlmZ ddlmZ  G d	 d
ej&                        Zdededej&                  f   fdZdedej&                  f   fdZdedej&                  f   defdZdddej2                  ddfdedee   dededeeej&                        deej&                     fdZy)z
BlurPool layer inspired by
 - Kornia's Max_BlurPool2d
 - Making Convolutional Networks Shift-Invariant Again :cite:`zhang2019shiftinvar`

Hacked together by Chris Ha and Ross Wightman
    )partial)comb)CallableOptionalTypeUnionN   )get_padding)	LayerTypec                        e Zd ZdZ	 	 	 	 	 	 ddee   dedededdf
 fdZdd	Zdd
Z	de
j                  de
j                  fdZddZ xZS )
BlurPool2da  Creates a module that computes blurs and downsample a given feature map.
    See :cite:`zhang2019shiftinvar` for more details.
    Corresponds to the Downsample class, which does blurring and subsampling

    Args:
        channels = Number of input channels
        filt_size (int): binomial filter size for blurring. currently supports 3 (default) and 5.
        stride (int): downsampling filter stride

    Returns:
        torch.Tensor: the transformed tensor.
    Nchannels	filt_sizestridepad_modereturnc                    t         |           |dkD  sJ || _        || _        || _        || _        t        ||d      gdz  | _        |xs dd||f}| j                  dt        j                  |||      d       | j                          y )Nr	   )dilation   filtdevicedtypeF)
persistent)super__init__r   r   r   r   r
   paddingregister_buffertorchemptyreset_parameters)	selfr   r   r   r   r   r   
filt_shape	__class__s	           `/var/www/ramen.bs-engineer-server.com/venv/lib/python3.12/site-packages/timm/layers/blur_pool.pyr   zBlurPool2d.__init__!   s     	1}} " #IvBCaG m!Q	9=
VU[[FRW%Xejk 	    c                 $    | j                          y)zInitialize buffers.N_init_buffersr"   s    r%   r!   zBlurPool2d.reset_parameters9       r&   c           	         t        j                  t        | j                        D cg c]  }t	        | j                  dz
  |       c}dt         j
                        d| j                  dz
  z  z  }|dddf   |dddf   z  ddddddf   }| j                  |j                  | j                  ddd      }| j                  j                  |       yc c}w )z.Compute and fill non-persistent buffer values.r	   cpur      N)
r   tensorranger   r   float32r   repeatr   copy_)r"   kcoeffsblur_filters       r%   r)   zBlurPool2d._init_buffers=   s     272GHQT$..1$a(H--
 4>>A%&	(
 aga8$a:JK==$%,,T]]Aq!DK		$ Is    Cxc                 l   t        j                  || j                  | j                        }| j                  B|j
                  d   }| j                  j                  |d| j                  | j                        }n| j                  }| j                  }t        j                  ||| j                  |      S )N)moder	   )r   groups)Fpadr   r   r   shaper   expandr   conv2dr   )r"   r7   r   weights       r%   forwardzBlurPool2d.forwardJ   s    EE!T\\6== wwqzHYY%%h4>>4>>RF}}HYYFxx6$++hGGr&   c                 $    | j                          y)z"Initialize non-persistent buffers.Nr(   r*   s    r%   init_non_persistent_buffersz&BlurPool2d.init_non_persistent_buffersT   r+   r&   )N   r.   reflectNN)r   N)__name__
__module____qualname____doc__r   intstrr   r!   r)   r   TensorrA   rC   __classcell__)r$   s   @r%   r   r      s     '+% sm    	 
   
 0%H H%,, Hr&   r   aa_layerr   .c                    t        | t              rs| j                         j                  dd      j                  dd      }|dv rt        j
                  S |dv rt        S |dk(  rt        t        d      S t        d	|  d
      | S )z6Map string shorthands to callables (class or partial)._ -)avgavgpool)blurblurpoolblurpcconstant)r   zUnknown anti-aliasing layer (z).)	
isinstancerK   lowerreplacenn	AvgPool2dr   r   AssertionError)rN   keys     r%   _normalize_aa_layerr`   Y   s    (C nn&&sB/77R@$$<<&&(?:
;;<XJbIJJOr&   layer_callablec                 b    t        | t              r| j                  S t        | t              r| S dS )z?Return the class behind a callable (unwrap partial), else None.N)rY   r   functype)ra   s    r%   _underlying_clsre   h   s,    .'*"""'=>G4Gr&   c                 l    t        |       }	 t        |t              S # t        $ r Y yt        $ r Y yw xY w)z2True if callable is BlurPool2d or a partial of it.F)re   
issubclassr   	TypeError	Exception)ra   clss     r%   _is_blurpoolrk   o   s;    
.
)C#z**  s    	333r.   Tr   r   enablenoopc                    | r|s| |       S dS t        |       } ||d}t        |       r@t        | t              r| j                  r| j                  ni }d|vr|||d<   d|vr|||d<   	  | di |S # t
        $ r  | |      cY S w xY w)zE Anti-aliasing factory that supports strings, classes, and partials. N)r   r   r   r    )r`   rk   rY   r   keywordsrh   )	rN   r   r   rl   rm   r   r   call_kwargsexisting_kws	            r%   	create_aars   z   s     6)tv3t3 #8,H  (6:K H+5h+HXM^M^h''df;&6+=$*K!+%%*;#(K  &+&&   s   ,A4 4BB)rI   	functoolsr   mathr   typingr   r   r   r   r   torch.nnr\   torch.nn.functional
functionalr;   r   r
   r   Moduler   r`   re   boolrk   IdentityrJ   rs   ro   r&   r%   <module>r}      s     2 2       B BJ) bii0H HHS"))^$< H#ryy.!9 d  #'*,++! ! 3-!  !  	! 
 tBII'!  bii! r&   