
    ^j                         d Z ddlmZmZmZmZmZ ddlZddlmZ ddl	m
Z
 ddlmZ ddlmZ d	 Z G d
 dej                         Z G d dej                         Zy)z Selective Kernel Convolution/Attention

Paper: Selective Kernel Networks (https://arxiv.org/abs/1903.06586)

Hacked together by / Copyright 2020 Ross Wightman
    )ListOptionalTupleTypeUnionN)nn   )ConvNormAct)make_divisible)_assertc                 n    t        | t        t        f      r| D ]  }t        |      c S  | dk\  r| dz  sJ y )N      )
isinstancelisttuple_kernel_valid)kkis     g/var/www/ramen.bs-engineer-server.com/venv/lib/python3.12/site-packages/timm/layers/selective_kernel.pyr   r      s?    !dE]# 	%B $$	%6a!ee    c                        e Zd Zddej                  ej
                  ddfdedededeej                     deej                     f
 fd	Z	d
 Z
 xZS )SelectiveKernelAttnr       Nchannels	num_pathsattn_channels	act_layer
norm_layerc                     ||d}t         	|           || _        t        j                  ||fddd|| _         ||fi || _         |d      | _        t        j                  |||z  fddd|| _        y)z| Selective Kernel Attention Module

        Selective Kernel attention mechanism factored out into its own module.

        devicedtyper	   F)kernel_sizebiasT)inplaceN)	super__init__r   r   Conv2d	fc_reducebnact	fc_select)
selfr   r   r   r   r   r"   r#   dd	__class__s
            r   r(   zSelectiveKernelAttn.__init__   s     /"8]\PU\Y[\]1b1T*=(Y2FhTU\aheghr   c                    t        |j                  d   | j                  k(  d       |j                  d      j	                  dd      }| j                  |      }| j                  |      }| j                  |      }| j                  |      }|j                  \  }}}}|j                  || j                  || j                  z  ||      }t        j                  |d      }|S )Nr	    )r   r   T)keepdimdim)r   shaper   summeanr*   r+   r,   r-   viewtorchsoftmax)r.   xBCHWs         r   forwardzSelectiveKernelAttn.forward0   s    
dnn,b1EE!HMM&$M/NN1GGAJHHQKNN1WW
1aFF1dnna4>>&91a@MM!#r   )__name__
__module____qualname__r   ReLUBatchNorm2dintr   Moduler(   rA   __classcell__r0   s   @r   r   r      so     !#)+*,..ii i 	i
 BIIi RYYi.
r   r   c            !       B    e Zd Zddddddddddej                  ej
                  ddddfdedee   deeee	e   f      d	ed
edede
dee   dedededeej                     deej                     deeej                        deeej                        f fdZd Z xZS )SelectiveKernelNr	   g      ?   Tin_channelsout_channelsr$   stridedilationgroupsrd_ratiord_channels
rd_divisorkeep_3x3split_inputr   r   aa_layer
drop_layerc                    ||d}t         |           |xs |}|xs ddg}t        |       t        |t              s|gdz  }|
r(|D cg c]  }||dz
  z  dz   }}dgt        |      z  }n|gt        |      z  }t        |      | _        || _        || _        || _	        | j                  r#|| j                  z  dk(  sJ || j                  z  }t        ||      }t        d||||||d|}t        j                  t        ||      D cg c]  \  }}t        ||f||d| c}}      | _        |xs t#        ||z  |		      }t%        || j                  |fi || _        y
c c}w c c}}w )a:   Selective Kernel Convolution Module

        As described in Selective Kernel Networks (https://arxiv.org/abs/1903.06586) with some modifications.

        Largest change is the input split, which divides the input channels across each convolution path, this can
        be viewed as a grouping of sorts, but the output channel counts expand to the module level value. This keeps
        the parameter count from ballooning when the convolutions themselves don't have groups, but still provides
        a noteworthy increase in performance over similar param count models without this attention layer. -Ross W

        Args:
            in_channels:  module input (feature) channel count
            out_channels:  module output (feature) channel count
            kernel_size: kernel size for each convolution branch
            stride: stride for convolutions
            dilation: dilation for module as a whole, impacts dilation of each branch
            groups: number of groups for each branch
            rd_ratio: reduction factor for attention features
            keep_3x3: keep all branch convolution kernels as 3x3, changing larger kernels for dilations
            split_input: split input channels evenly across each convolution branch, keeps param count lower,
                can be viewed as grouping by path, output expands to module out_channels count
            act_layer: activation layer to use
            norm_layer: batchnorm/norm layer to use
            aa_layer: anti-aliasing module
            drop_layer: spatial drop module in convs (drop block, etc)
        r!   r      r   r	   r   )rP   rR   r   r   rX   rY   )r$   rQ   )divisorN )r'   r(   r   r   r   lenr   rN   rO   rW   mindictr   
ModuleListzipr
   pathsr   r   attn)r.   rN   rO   r$   rP   rQ   rR   rS   rT   rU   rV   rW   r   r   rX   rY   r"   r#   r/   r   conv_kwargsdr   r0   s                          r   r(   zSelectiveKernel.__init__?   s   Z /#2{!+aVk"+t,&-!+K9DEAAE*a/EHE#K 00K zC$44H[)&(&/1444%7K\6* <&I**<8:< ]]K2$41 \\q1\P[\$4 5
 $b~lX6MWa'b'dnnmZWYZ	+ F $4s   
E&E+
c                    | j                   r_t        j                  || j                  | j                  z  d      }t        | j                        D cg c]  \  }} |||          }}}n| j                  D cg c]
  } ||       }}t        j                  |d      }| j                  |      }||z  }t        j                  |d      }|S c c}}w c c}w )Nr	   r4   )
rW   r:   splitrN   r   	enumeraterc   stackrd   r7   )r.   r<   x_splitiopx_pathsx_attns          r   rA   zSelectiveKernel.forward   s    kk!T%5%5%GKG3<TZZ3HI%!Rr'!*~IGI'+zz2r!u2G2KKQ'1JIIaQ J2s   C:C)rB   rC   rD   r   rE   rF   rG   r   r   r   floatboolr   rH   r(   rA   rI   rJ   s   @r   rL   rL   =   s@   
 +/;?#)-! $)+)+2648%J[J[ #3-J[ "%T#Y"78	J[
 J[ J[ J[ J[ "#J[ J[ J[ J[ BIIJ[ RYYJ[ tBII/J[  !bii1!J[X
r   rL   )__doc__typingr   r   r   r   r   r:   r   conv_bn_actr
   helpersr   trace_utilsr   r   rH   r   rL   r]   r   r   <module>rw      sI    6 5   $ #  "")) "JXbii Xr   