
    ^j/)                         d Z ddl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  G d dej                        Z G d d	ej                        Z G d
 dej                        Z G d dej                        Zy)aH   Non-Local Attention Pooling Layers

A collection of global pooling layers that go beyond simple avg/max pooling.

LSEPool - LogSumExp pooling, a smooth approximation between avg and max pooling
SimPool - Attention-based pooling from 'Keep It SimPool' (ICCV 2023)

Based on implementations from:
* LSE Pooling: custom implementation by Bill Psomas
* SimPool: https://arxiv.org/abs/2309.06891 - 'Keep It SimPool: Who Said Supervised Transformers
    Suffer from Attention Deficit?' by Bill Psomas et al.

Hacked together by / Copyright 2024 Ross Wightman, original code by Bill Psomas
    )OptionalTypeUnionN   )use_fused_attnc                   t     e Zd ZdZ	 	 	 	 	 d	dededef fdZdej                  dej                  fdZ	 xZ
S )
	LsePlus2da  LogSumExp (LSE) Pooling for 2D inputs.

    A smooth approximation to max pooling that provides a learnable interpolation between
    average and max pooling. When r is large, LSE approaches max pooling; when r is small,
    it approaches average pooling.

    Implements: (1/r) * log((1/n) * sum(exp(r * (x - x_max)))) + x_max

    The x_max subtraction provides numerical stability.
    rr_learnableflattenc                     t         |           |r8t        j                  t	        j
                  |||            | _        || _        y| j                  dt	        j
                  |||             || _        y)z
        Args:
            r: Initial value of the pooling parameter. Higher = closer to max pooling.
            r_learnable: If True, r is a learnable parameter.
            flatten: If True, flatten spatial dims in output.
        devicedtyper
   N)	super__init__nn	Parametertorchtensorr
   register_bufferr   )selfr
   r   r   r   r   	__class__s         a/var/www/ramen.bs-engineer-server.com/venv/lib/python3.12/site-packages/timm/layers/other_pool.pyr   zLsePlus2d.__init__$   s_     	\\%,,qu"MNDF    ell1V5&QR    xreturnc                 ,   t        j                  |d      }t        j                  | j                  ||z
  z        }|j                  dd      }|d| j                  z  t        j                  |      z  z   }| j                  r|j                  d      }|S )Nr   )      Tdimkeepdim      ?)Fadaptive_max_pool2dr   expr
   meanlogr   r   r   x_maxexp_xsum_expouts         r   forwardzLsePlus2d.forward9   sz    %%a+		$&&AI./***6sTVV|uyy'999<<++a.C
r   )      $@TTNN__name__
__module____qualname____doc__floatboolr   r   Tensorr/   __classcell__r   s   @r   r	   r	      sU    	  $   	* %,, r   r	   c                   n     e Zd ZdZ	 	 	 	 ddedef fdZdej                  dej                  fdZ	 xZ
S )		LsePlus1da  LogSumExp (LSE) Pooling for sequence (NLC) inputs.

    A smooth approximation to max pooling that provides a learnable interpolation between
    average and max pooling. When r is large, LSE approaches max pooling; when r is small,
    it approaches average pooling.
    r
   r   c                     t         |           |r1t        j                  t	        j
                  |||            | _        y| j                  dt	        j
                  |||             y)z
        Args:
            r: Initial value of the pooling parameter. Higher = closer to max pooling.
            r_learnable: If True, r is a learnable parameter.
        r   r
   N)r   r   r   r   r   r   r
   r   )r   r
   r   r   r   r   s        r   r   zLsePlus1d.__init__K   sM     	\\%,,qu"MNDF  ell1V5&QRr   r   r   c                    |j                  dd      j                  }t        j                  | j                  ||z
  z        }|j                  dd      }|d| j                  z  t        j                  |      z  z   }|j                  d      S )Nr   Tr!   r$   )maxvaluesr   r'   r
   r(   r)   squeezer*   s         r   r/   zLsePlus1d.forward]   su    !T*11		$&&AI./**D*1sTVV|uyy'999{{1~r   )r0   TNNr1   r:   s   @r   r<   r<   C   sK      $SS S$ %,, r   r<   c                        e Zd ZU dZej
                  j                  e   ed<   	 	 	 	 	 	 	 dde	de	dedede
e   de
eej                        f fd	Zd
ej                   dej                   fdZ xZS )	SimPool2dab  SimPool: Simple Attention-Based Pooling for 2D (NCHW) inputs.

    From 'Keep It SimPool: Who Said Supervised Transformers Suffer from Attention Deficit?'
    https://arxiv.org/abs/2309.06891

    Uses GAP as query initialization and applies cross-attention between the GAP query
    and spatial features to produce a weighted pooled representation.
    
fused_attnr"   	num_headsqkv_biasqk_normgamma
norm_layerc	                 F   t         
|           ||d}	||z  dk(  sJ d       || _        ||z  | _        | j                  dz  | _        || _        t               | _        |xs t        j                  } ||fi |	| _
        t        j                  ||fd|i|	| _        t        j                  ||fd|i|	| _        |r1 || j                  fi |	| _         || j                  fi |	| _        yt        j                          | _        t        j                          | _        y)a  
        Args:
            dim: Input feature dimension (number of channels).
            num_heads: Number of attention heads.
            qkv_bias: If True, add bias to query and key projections.
            qk_norm: If True, apply normalization to queries and keys.
            gamma: If provided, apply power normalization to values with this exponent.
            norm_layer: Normalization layer for patches and optionally qk_norm.
            flatten: If True, flatten output to (B, C).
        r   r   "dim must be divisible by num_heads      biasNr   r   rE   head_dimscalerH   r   rD   r   	LayerNormnormLinearqkq_normk_normIdentityr   r"   rE   rF   rG   rH   rI   r   r   ddr   s             r   r   zSimPool2d.__init__q   s   * 	/Y!#I%II#"y(]]d*

(*/2<<
s)b)	39(9b939(9b9$T]]9b9DK$T]]9b9DK++-DK++-DKr   r   r   c                 4   |j                   \  }}}}||z  }|j                  d      j                  dd      }|j                  dd      }| j	                  |      }| j                  |      j                  |d| j                  | j                        j                  dd      }| j                  |      j                  ||| j                  | j                        j                  dd      }	|j                  ||| j                  | j                        j                  dd      }
| j                  |      | j                  |	      }	}| j                  |
j                  dd      }|
|z
  dz   }| j                  r1t        j                   ||	|j#                  | j                              }nR|| j$                  z  |	j                  dd      z  }|j'                  d      }||j#                  | j                        z  }|j#                  d	| j                  z        }n]| j                  rt        j                   ||	|
      }n9|| j$                  z  |	j                  dd      z  }|j'                  d      }||
z  }|j                  dd      j                  ||      }|S )
Nr   r   Tr!   ư>r"   r$   )shaper   	transposer(   rR   rT   reshaperE   rO   rU   rV   rW   rH   aminrD   r%   scaled_dot_product_attentionpowrP   softmax)r   r   BCHWNrT   x_normrU   vv_min	v_shiftedattn_outattnr.   s                   r   r/   zSimPool2d.forward   s*   WW
1aE IIaL""1a( FFq$F' 1 FF1IaDNNDMMBLLQPQRFF6N""1aGQQRSUVWNN1a?II!QO{{1~t{{1~1::!FFr4F0EE	D(I99!Q	djj@YZDJJ!++b"*==|||+)--

";;,,sTZZ/0C44Q1=DJJ!++b"*==|||+Qh mmAq!))!Q/
r   r   FFNNNNr2   r3   r4   r5   r   jitFinalr7   __annotations__intr   r6   r   r   Moduler   r8   r/   r9   r:   s   @r   rC   rC   f   s     		%%
 "!%)48'('( '( 	'(
 '( E?'( !bii1'(R) )%,, )r   rC   c                        e Zd ZU dZej
                  j                  e   ed<   	 	 	 	 	 	 	 dde	de	dedede
e   de
eej                        f fd	Zd
ej                   dej                   fdZ xZS )	SimPool1daf  SimPool: Simple Attention-Based Pooling for sequence (NLC) inputs.

    From 'Keep It SimPool: Who Said Supervised Transformers Suffer from Attention Deficit?'
    https://arxiv.org/abs/2309.06891

    Uses GAP as query initialization and applies cross-attention between the GAP query
    and sequence tokens to produce a weighted pooled representation.
    rD   r"   rE   rF   rG   rH   rI   c	                 F   t         
|           ||d}	||z  dk(  sJ d       || _        ||z  | _        | j                  dz  | _        || _        t               | _        |xs t        j                  } ||fi |	| _
        t        j                  ||fd|i|	| _        t        j                  ||fd|i|	| _        |r1 || j                  fi |	| _         || j                  fi |	| _        yt        j                          | _        t        j                          | _        y)a  
        Args:
            dim: Input feature dimension.
            num_heads: Number of attention heads.
            qkv_bias: If True, add bias to query and key projections.
            qk_norm: If True, apply normalization to queries and keys.
            gamma: If provided, apply power normalization to values with this exponent.
            norm_layer: Normalization layer for tokens and optionally qk_norm.
        r   r   rK   rL   rM   NrN   rY   s             r   r   zSimPool1d.__init__   s   ( 	/Y!#I%II#"y(]]d*

(*/2<<
s)b)	39(9b939(9b9$T]]9b9DK$T]]9b9DK++-DK++-DKr   r   r   c                    |j                   \  }}}|j                  dd      }| j                  |      }| j                  |      j	                  |d| j
                  | j                        j                  dd      }| j                  |      j	                  ||| j
                  | j                        j                  dd      }|j	                  ||| j
                  | j                        j                  dd      }| j                  |      | j                  |      }}| j                  |j                  dd      }	||	z
  dz   }
| j                  r1t        j                  |||
j!                  | j                              }nR|| j"                  z  |j                  dd      z  }|j%                  d      }||
j!                  | j                        z  }|j!                  d	| j                  z        }n]| j                  rt        j                  |||      }n9|| j"                  z  |j                  dd      z  }|j%                  d      }||z  }|j                  dd      j	                  ||      }|S )
Nr   Tr!   r   r\   r]   r^   r_   r$   )r`   r(   rR   rT   rb   rE   rO   ra   rU   rV   rW   rH   rc   rD   r%   rd   re   rP   rf   )r   r   rg   rk   rh   rT   rl   rU   rm   rn   ro   rp   rq   r.   s                 r   r/   zSimPool1d.forward   s   ''1a FFq$F' 1 FF1IaDNNDMMBLLQPQRFF6N""1aGQQRSUVWNN1a?II!QO{{1~t{{1~1::!FFr4F0EE	D(I99!Q	djj@YZDJJ!++b"*==|||+)--

";;,,sTZZ/0C44Q1=DJJ!++b"*==|||+Qh mmAq!))!Q/
r   rr   rs   r:   s   @r   rz   rz      s     		%%
 "!%)48&(&( &( 	&(
 &( E?&( !bii1&(P% %%,, %r   rz   )r5   typingr   r   r   r   torch.nnr   torch.nn.functional
functionalr%   configr   rx   r	   r<   rC   rz    r   r   <module>r      sh    ) (     "(		 (V 		  F]		 ]@X		 Xr   