
    ^j3/                        d dl 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dlmZ g d	Zej                   j"                  e
dd
ej$                  deej$                     fd              Zej                   j"                  e
	 	 ddedej$                  deej$                     dedeej$                     f
d              Z G d dej.                        Z G d dej.                        Zy)    )FinalOptionalTypeN)nn)
functional   )register_notrace_function)use_fused_attn)apply_rot_embed_cat)	AttentionAttentionRopemaybe_add_maskresolve_self_attn_maskscores	attn_maskc                     || S | |z   S N )r   r   s     `/var/www/ramen.bs-engineer-server.com/venv/lib/python3.12/site-packages/timm/layers/attention.pyr   r      s     &6>FY,>>    seq_lenattn	is_causalreturnc                 .   |r.|j                  | | ft        d            j                  d      }|S |d }|S |j                  t        j
                  k(  r?t	        j                  ||j                        }|j                  | t        d             |S |}|S )Nz-infr   )dtype)new_fullfloattriu_r   torchbool
zeros_likemasked_fill_)r   r   r   r   	attn_biass        r   r   r      s     MM7G"4eFmDJJ1M	  
		  
EJJ	&$$YdjjA		z5=9  	r   c                       e Zd ZU dZee   ed<   	 	 	 	 	 	 	 	 	 	 	 	 	 ddededee   dee   ded	ed
ededede	de	dee
ej                        ddf fdZ	 	 ddej                  deej                     dedej                  fdZ xZS )r   a  Standard Multi-head Self Attention module with QKV projection.

    This module implements the standard multi-head attention mechanism used in transformers.
    It supports both the fused attention implementation (scaled_dot_product_attention) for
    efficiency when available, and a manual implementation otherwise. The module includes
    options for QK normalization, attention dropout, and projection dropout.
    
fused_attnNdim	num_headsattn_head_dimdim_outqkv_biasqk_norm
scale_norm	proj_biasgated	attn_drop	proj_drop
norm_layerr   c                 6   t         |           ||d}|xs |}|}|||z  dk(  sJ d       ||z  }|s|r	|J d       || _        || _        ||z  | _        |dz  | _        t               | _        t        j                  || j                  dz  fd|i|| _
        |r	 ||fi |nt        j                         | _        |r	 ||fi |nt        j                         | _        t        j                  |
      | _        |r || j                  fi |nt        j                         | _        |	r#t        j                  || j                  fd|i|nd| _        t        j                  | j                  |fd|i|| _        t        j                  |      | _        y)	a  Initialize the Attention module.

        Args:
            dim: Input dimension of the token embeddings.
            num_heads: Number of attention heads.
            attn_head_dim: Dimension of each attention head. If None, computed as dim // num_heads.
            dim_out: Output dimension. If None, same as dim.
            qkv_bias: Whether to use bias in the query, key, value projections.
            qk_norm: Whether to apply normalization to query and key vectors.
            scale_norm: Whether to apply normalization to attention output before projection.
            proj_bias: Whether to use bias in the output projection.
            gated: Apply an elementwise sigmoid gate to the attention output (anti attention-sink, GenLIP-style).
            attn_drop: Dropout rate applied to the attention weights.
            proj_drop: Dropout rate applied after the output projection.
            norm_layer: Normalization layer constructor for QK normalization if enabled.
        devicer   Nr   $dim should be divisible by num_heads<norm_layer must be provided if qk_norm or scale_norm is True         bias)super__init__r(   head_dimattn_dimscaler
   r&   r   LinearqkvIdentityq_normk_normDropoutr0   normgateprojr1   )selfr'   r(   r)   r*   r+   r,   r-   r.   r/   r0   r1   r2   r5   r   ddr=   	__class__s                    r   r<   zAttention.__init__5   sw   B 	/.S ?a'O)OO'i'Hj)i+ii)" !H,%
(*99S$--!"3I(IbI4;j0R04;j0R0I.7AJt}}33r{{}	JOBIIc4==FxF2FUY	IIdmmWK9KK	I.r   xr   r   c                    |j                   \  }}}| j                  | j                  |      j                         nd }| j                  |      j	                  ||d| j
                  | j                        j                  ddddd      }|j                  d      \  }	}
}| j                  |	      | j                  |
      }
}	| j                  r>t        j                  |	|
||| j                  r| j                  j                   nd|      }nf|	| j"                  z  }	|	|
j%                  dd	      z  }t'        ||||      }t)        ||      }|j+                  d	
      }| j                  |      }||z  }|j%                  dd      j	                  ||| j,                        }| j/                  |      }|||z  }| j1                  |      }| j3                  |      }|S )Nr9      r   r              r   	dropout_pr   r'   )shaperG   sigmoidrA   reshaper(   r=   permuteunbindrC   rD   r&   Fscaled_dot_product_attentiontrainingr0   pr?   	transposer   r   softmaxr>   rF   rH   r1   )rI   rL   r   r   BNCrG   rA   qkvr   r$   s                 r   forwardzAttention.forwardo   s    ''1a)-)>tyy|##%Dhhqk!!!Q4>>4==IQQRSUVXY[\^_`**Q-1a{{1~t{{1~1??..1a#.2mm$..**#	A DJJAq{{2r**D.q$	9MI!$	2D<<B<'D>>$'DqAKK1%%aDMM:IIaLDAIIaLNN1r   )   NNFFFTFrP   rP   NNNNF)__name__
__module____qualname____doc__r   r!   __annotations__intr   r   r   r   Moduler<   r    Tensorrg   __classcell__rK   s   @r   r   r   +   s    d
 +/%)"!$"!!488/8/ 8/ $C=	8/
 c]8/ 8/ 8/ 8/ 8/ 8/ 8/ 8/ !bii18/  
!8/z 15#	"||"  -" 	"
 
"r   r   c                   2    e Zd ZU dZej
                  j                  e   ed<   	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 dde	de	de
e	   dedede	d	ed
ede
e	   deej                     dededededef fdZ	 	 	 dde
ej                      de
ej                      defdZ xZS )r   z A Self Attention module with ROPE support.

    Includes options for:
     * QK normalization option
     * Attention output (scale) normalization
     * Fused or unfused QKV projection support
    r&   r'   r(   r*   r+   	qkv_fusednum_prefix_tokensr0   r1   r)   r2   r,   r-   r.   rotate_halfr/   c                    t         |           ||d}|xs |}|	}|||z  dk(  sJ d       ||z  }|s|r	|
J d       || _        || _        ||z  | _        |dz  | _        || _        t               | _        || _	        |rAt        j                  || j                  dz  fd|i|| _        dx| _        x| _        | _        nd| _        t        j                  || j                  fd|i|| _        t        j                  || j                  fd|i|| _        t        j                  || j                  fd|i|| _        |r	 |
|fi |nt        j                          | _        |r	 |
|fi |nt        j                          | _        t        j&                  |      | _        |r |
| j                  fi |nt        j                          | _        |r#t        j                  || j                  fd|i|nd| _        t        j                  | j                  |fd|i|| _        t        j&                  |      | _        y)	a  Initialize the Attention module.

        Args:
            dim: Input dimension of the token embeddings
            num_heads: Number of attention heads
            dim_out: Output dimension. If None, same as dim.
            qkv_bias: Whether to add a bias term to the query, key, and value projections
            qkv_fused: Whether to use fused QKV projection (single linear) or separate projections
            num_prefix_tokens: Number of reg/cls tokens at the beginning of the sequence that
                should not have position embeddings applied
            attn_drop: Dropout rate for attention weights
            proj_drop: Dropout rate for the output projection
            attn_head_dim: Dimension of each attention head. If None, computed as dim // num_heads.
            norm_layer: Normalization layer constructor to use for QK and scale normalization
            qk_norm: Enable normalization of query (Q) and key (K) vectors with norm_layer
            scale_norm: Enable normalization (scaling) of attention output with norm_layer
            proj_bias: Whether to use bias in the output projection
            rotate_half: Use 'half' ROPE layout instead of default 'interleaved'
        r4   Nr   r6   r7   r8   r9   r:   )r;   r<   r(   r=   r>   r?   rv   r
   r&   rw   r   r@   rA   q_projk_projv_projrB   rC   rD   rE   r0   rF   rG   rH   r1   )rI   r'   r(   r*   r+   ru   rv   r0   r1   r)   r2   r,   r-   r.   rw   r/   r5   r   rJ   r=   rK   s                       r   r<   zAttentionRope.__init__   s   N 	/.S ?a'O)OO'i'H)i+ii)"  9,%
!2(*&yydmma&7MhM"MDH6::DK:$+DH))CLXLLDK))CLXLLDK))CLXLLDK4;j0R04;j0R0I.7AJt}}33r{{}	JOBIIc4==FxF2FUY	IIdmmWK9KK	I.r   roper   r   c                    |j                   \  }}}| j                  | j                  |      j                         nd}| j                  c| j                  |      }	|	j	                  ||d| j
                  | j                        j                  ddddd      }	|	j                  d      \  }
}}n| j                  |      j	                  ||| j
                  | j                        j                  dd      }
| j                  |      j	                  ||| j
                  | j                        j                  dd      }| j                  |      j	                  ||| j
                  | j                        j                  dd      }| j                  |
      | j                  |      }}
|| j                  }t!        | dd      }t#        j$                  |
ddddd|ddf   t'        |
dddd|dddf   ||	      gd
      j)                  |      }
t#        j$                  |ddddd|ddf   t'        |dddd|dddf   ||	      gd
      j)                  |      }| j*                  r>t-        j.                  |
|||| j0                  r| j2                  j4                  nd|      }nf|
| j6                  z  }
|
|j                  dd      z  }t9        ||||      }t;        ||      }|j=                  d
      }| j3                  |      }||z  }|j                  dd      j	                  ||| j>                        }| jA                  |      }|||z  }| jC                  |      }| jE                  |      }|S )a  Forward pass for the attention module.

        Args:
            x: Input tensor of shape (batch_size, sequence_length, embedding_dim)
            rope: Rotary position embeddings tensor for position-aware attention
            attn_mask: Optional attention mask to apply during attention computation
            is_causal: If True, use causal (autoregressive) masking

        Returns:
            Tensor of shape (batch_size, sequence_length, dim_out)
        Nr9   rN   r   r   rO   rw   F)halfrU   rP   rQ   rS   rT   )#rV   rG   rW   rA   rX   r(   r=   rY   rZ   ry   r_   rz   r{   rC   rD   rv   getattrr    catr   type_asr&   r[   r\   r]   r0   r^   r?   r   r   r`   r>   rF   rH   r1   )rI   rL   r|   r   r   ra   rb   rc   rG   rA   rd   re   rf   nptr~   r   r$   s                    r   rg   zAttentionRope.forward   s   $ ''1a)-)>tyy|##%D88((1+C++aAt~~t}}EMMaQRTUWXZ[\CjjmGAq!A&&q!T^^T]]KUUVWYZ[AA&&q!T^^T]]KUUVWYZ[AA&&q!T^^T]]KUUVWYZ[A{{1~t{{1~1((C46D		1Q4C4]+-@1aq=AQSW^b-cdjklttuvwA		1Q4C4]+-@1aq=AQSW^b-cdjklttuvwA??..1a#.2mm$..**#	A DJJAq{{2r**D.q$	9MI!$	2D<<B<'D>>$'DqAKK1%%aDMM:IIaLDAIIaLNN1r   )rh   NTTr   rP   rP   NNFFTFFNN)NNF)rj   rk   rl   rm   r    jitr   r!   rn   ro   r   r   r   r   rp   r<   rq   rg   rr   rs   s   @r   r   r      sI    		%%
 %)!"%&!!+/*.!$" %%H/H/ H/ c]	H/
 H/ H/  #H/ H/ H/ $C=H/ RYYH/ H/ H/ H/ H/  !H/Z ,004#= 5<<(=  -	=
 =r   r   r   ri   )typingr   r   r   r    r   torch.nnr   r[   _fxr	   configr
   pos_embed_sincosr   __all__fxwraprq   r   ro   r!   r   rp   r   r   r   r   r   <module>r      s    ( (   $ * " 1 U ?5<< ?HU\\4J ?  ?  -1	ll ELL) 	
 ell  (f		 fRQBII Qr   