
    <h                       S SK JrJrJrJrJr  S SKrS SKJr  S SKJ	r	  SSK
JrJrJr  SSKJr  SSKJr  SS	KJr  SS
KJr  SSKJrJr  SSKJrJr  SSKJrJr  SSKJ r   SSK!J"r"J#r#J$r$J%r%  SSK&J'r'J(r(  SSK)J*r*  \(" 5       (       a  S SK+J,r,  S SK-J.r.J/r/  OSr,\'" 5       (       a	  S SK0J1r1J2r2  OSu  r2r1\%Rf                  " \45      r5 " S S\SS9r6 " S S\5      r7 " S S\Rp                  5      r9S r:S \Rv                  S!\<S"\Rv                  4S# jr= SHS$\Rp                  S%\Rv                  S&\Rv                  S'\Rv                  S(\\Rv                     S)\>S*\>S+\ \"   4S, jjr?SIS- jr@ " S. S/\Rp                  5      rA " S0 S1\R                  Rp                  5      rBS2\Rv                  S3\<4S4 jrCS5 rDS6 rE\F" \,\1\245      rGS7 rH " S8 S9\Rp                  5      rI " S: S;\Rp                  5      rJ\" S<5       " S= S>\Rp                  5      5       rK " S? S@\5      rL\# " SA SB\5      5       rM\# " SC SD\M5      5       rN\# " SE SF\M\5      5       rO/ SGQrPg)J    )AnyCallableOptional	TypedDictUnionN)nn)ACT2FN   )CacheDynamicCacheDynamicLayer)GenerationMixin)use_kernel_forward_from_hub)AttentionMaskConverter)GradientCheckpointingLayer)BaseModelOutputWithPastCausalLMOutputWithPast)ROPE_INIT_FUNCTIONSdynamic_rope_update)ALL_ATTENTION_FUNCTIONSPreTrainedModel)Unpack)TransformersKwargsauto_docstringcan_return_tuplelogging)is_causal_conv1d_availableis_mamba_2_ssm_available   )BambaConfig)selective_state_update)mamba_chunk_scan_combined mamba_split_conv1d_scan_combined)causal_conv1d_fncausal_conv1d_updateNNc                       \ rS rSr% Sr\R                  \S'   \R                  \S'   \\S'   \\S'   \R                  \S'   Sr
g	)
BambaFlashAttentionKwargs?   aR  
Keyword arguments for advanced Flash Attention, causal-conv1d, and mamba_ssm kernel usage.
Use cases include padding-free training and fewer `torch.compile` graph breaks.

Attributes:
    cu_seq_lens_q (`torch.LongTensor`)
        Gets cumulative sequence length for query state.
    cu_seq_lens_k (`torch.LongTensor`)
        Gets cumulative sequence length for key state.
    max_length_q (`int`):
        Maximum sequence length for query state.
    max_length_k (`int`):
        Maximum sequence length for key state.
    seq_idx (`torch.IntTensor):
        Index of each packed sequence.
cu_seq_lens_qcu_seq_lens_kmax_length_qmax_length_kseq_idx N)__name__
__module____qualname____firstlineno____doc__torch
LongTensor__annotations__int	IntTensor__static_attributes__r/       `/var/www/html/shao/venv/lib/python3.13/site-packages/transformers/models/bamba/modeling_bamba.pyr(   r(   ?   s7    " ######__r;   r(   F)totalc                     ^  \ rS rSrSrSrSrSr\R                  S4S\
4U 4S jjjr SS\R                  S\R                  S	\S
\\\\4      S\\R                  \R                  4   4
S jjrS\R(                  4S jrSS	\\   S\4S jjrS\\\R                     \\R                     4   4S jr\SS\\\\R2                           SS4S jj5       rSrU =r$ ) HybridMambaAttentionDynamicCacheX   a|  
A dynamic cache that can handle both the attention cache (which has a seq_len dimension) and the mamba cache
(which has a constant shape regardless of seq_len).

This cache has two sets of lists of tensors: `key_cache` and `value_cache` for attention cache and `conv_states`
and `ssm_states` for mamba cache. Each of these lists has `num_layers` tensors. The expected shape for each tensor
For attention layers, `key_cache` and `value_cache` have a shape of `(batch_size, num_heads, seq_len, head_dim)`,
while `conv_states` and `ssm_states` have a shape of `(batch_size, 0)` (empty tensors).
For mamba layers, `key_cache` and `value_cache` have a shape of `(batch_size, 0)` (empty tensors),
while `conv_states` represents the convolution state and has a shape of `(batch_size, d_inner, d_conv)`,
and `ssm_states` represents the ssm state and has a shape of `(batch_size, d_inner, d_state)`.
NFconfigc                 H  > [         T	U ]  [        S9  UR                  U l        SU l        UR
                  nUR                  n/ U l        / U l        / U l	        [        UR                  5       GH%  nU R                  U   S:X  a  U =R                  [        R                  " UUR                  UR                  -  SUR                   -  U-  -   UUUS9/-  sl        U =R                  [        R                  " UUR"                  UR$                  UUUS9/-  sl        M  U =R                  [        R&                  " / /U-  US9/-  sl        U =R                  [        R&                  " / /U-  US9/-  sl        U R                  R)                  U5        GM(     [        UR                  5       Vs/ sH  n[        R&                  " / /U-  US9PM     snU l        [        UR                  5       Vs/ sH  n[        R&                  " / /U-  US9PM     snU l        g s  snf s  snf )N)layer_classesFmamba   devicedtyperG   )super__init__r   layers_block_typehas_previous_statemamba_d_convmamba_d_stateconv_states
ssm_statestransformer_layersrangenum_hidden_layersr5   zerosmamba_expandhidden_sizemamba_n_groupsmamba_n_headsmamba_d_headtensorappend	key_cachevalue_cache)
selfrA   
batch_sizerH   rG   conv_kernel_sizessm_state_sizei_	__class__s
            r<   rK   )HybridMambaAttentionDynamicCache.__init__j   s   |4!'!9!9"'!..--"$v//0A%%a(G3  KK",,v/A/AAAH]H]D]`nDnn(%#%   KK",,++&%#	$ 	   U\\2$2CF%S$TT ELL"
1B6$R#SS''..q11 14 SXX^XpXpRqrRqQ%,,tj'8HRqrTYZ`ZrZrTstTsqELL"
):6JTst sts   ."H/"H
key_statesvalue_states	layer_idxcache_kwargsreturnc                 |   U R                   U   R                  S   S:X  a  XR                   U'   X R                  U'   Ob[        R                  " U R                   U   U/SS9U R                   U'   [        R                  " U R                  U   U/SS9U R                  U'   U R                   U   U R                  U   4$ )Nr   rE   dim)r]   shaper^   r5   cat)r_   rg   rh   ri   rj   s        r<   update'HybridMambaAttentionDynamicCache.update   s     >>)$**2.!3(2NN9%*6Y'(-		4>>)3Lj2Y_`(aDNN9%*/))T5E5Ei5PR^4_ef*gDY'~~i($*:*:9*EEEr;   beam_idxc                    [        [        U R                  5      5       GHT  nU R                  U   R                  nU R                  U   R	                  SUR                  U5      5      U R                  U'   U R                  U   R                  nU R                  U   R	                  SUR                  U5      5      U R                  U'   U R                  U   R                  nU R                  U   R	                  SUR                  U5      5      U R                  U'   U R                  U   R                  nU R                  U   R	                  SUR                  U5      5      U R                  U'   GMW     g)zDReorders the cache for beam search, given the selected beam indices.r   N)	rS   lenr]   rG   index_selecttor^   rP   rQ   )r_   rt   ri   rG   s       r<   reorder_cache.HybridMambaAttentionDynamicCache.reorder_cache   s=   s4>>23I^^I.55F(,y(A(N(NqRZR]R]^dRe(fDNN9%%%i077F*.*:*:9*E*R*RSTV^VaVabhVi*jDY'%%i077F*.*:*:9*E*R*RSTV^VaVabhVi*jDY'__Y/66F)-)C)P)PQRT\T_T_`fTg)hDOOI& 4r;   c                     XR                   ;  a  U R                   S   OUn[        U R                  5      U::  a  gU R                  U   R                  S   $ )zYReturns the sequence length of the cached states. A layer index can be optionally passed.r   )rR   rv   r]   rp   )r_   ri   s     r<   get_seq_length/HybridMambaAttentionDynamicCache.get_seq_length   sP     3<CZCZ2ZD++A.`i	t~~)+~~i(..r22r;   c                     [        S5      eNzIHybridMambaAttentionDynamicCache does not have a legacy cache equivalent.NotImplementedErrorr_   s    r<   to_legacy_cache0HybridMambaAttentionDynamicCache.to_legacy_cache   s    !"mnnr;   past_key_valuesr   c                     [        S5      er   r   )clsr   s     r<   from_legacy_cache2HybridMambaAttentionDynamicCache.from_legacy_cache   s    !"mnnr;   )rP   rM   r]   rL   rQ   rR   r^   N)r   )r0   r1   r2   r3   r4   r]   r^   is_compileabler5   float16r    rK   Tensorr8   r   dictstrr   tuplerr   r6   ry   r}   r   classmethodFloatTensorr   r:   __classcell__re   s   @r<   r?   r?   X   s0    IKN>CmmTX %u{ %u %uX 26FLLF llF 	F
 tCH~.F 
u||U\\)	*F"ie&6&6 i3 3c 3ouU\\':E%,,<O'O!P o ouUEVEV?W9X0Y oes o or;   r?   c                   l   ^  \ rS rSrSS\4U 4S jjjr\R                  " 5       \S 5       5       r	Sr
U =r$ )BambaRotaryEmbedding   rA   c                   > [         TU ]  5         [        US5      (       aZ  [        UR                  [
        5      (       a;  UR                  R                  SUR                  R                  S5      5      U l        OSU l        UR                  U l	        UR                  U l
        Xl        [        U R                     U l        U R                  U R                  U5      u  o0l        U R                  SUSS9  U R                   U l        g )Nrope_scaling	rope_typetypedefaultinv_freqF)
persistent)rJ   rK   hasattr
isinstancer   r   getr   max_position_embeddingsmax_seq_len_cachedoriginal_max_seq_lenrA   r   rope_init_fnattention_scalingregister_bufferr   original_inv_freq)r_   rA   rG   r   re   s       r<   rK   BambaRotaryEmbedding.__init__   s    6>**z&:M:Mt/T/T#0044[&BUBUBYBYZ`BabDN&DN"("@"@$*$B$B!/?+/+<+<T[[&+Q((ZeD!%r;   c                 b   U R                   S S S 2S 4   R                  5       R                  UR                  S   SS5      R	                  UR
                  5      nUS S 2S S S 24   R                  5       n[        UR
                  R                  [        5      (       a0  UR
                  R                  S:w  a  UR
                  R                  OSn[        R                  " USS9   UR                  5       UR                  5       -  R                  SS5      n[        R                  " Xf4SS	9nUR                  5       U R                  -  nUR                  5       U R                  -  n	S S S 5        WR	                  UR                   S
9W	R	                  UR                   S
94$ ! , (       d  f       N@= f)Nr   rm   r   mpscpuF)device_typeenabledrE   rn   rH   )r   floatexpandrp   rx   rG   r   r   r   r5   autocast	transposerq   cosr   sinrH   )
r_   xposition_idsinv_freq_expandedposition_ids_expandedr   freqsembr   r   s
             r<   forwardBambaRotaryEmbedding.forward   sR    !MM$4-8>>@GGHZHZ[\H]_acdehhijiqiqr ,QaZ 8 > > @'1!((--'E'E!((--[`J`ahhmmfk^^UC&,,.1F1L1L1NNYYZ[]^_E))UN3C'')d444C'')d444C	 D vvAGGv$cff177f&;;; DCs   $BF  
F.)r   rA   r   r   r   r   r   r   )r0   r1   r2   r3   r    rK   r5   no_gradr   r   r:   r   r   s   @r<   r   r      s6    /{ / /" ]]_<  <r;   r   c                     U SSU R                   S   S-  24   nU SU R                   S   S-  S24   n[        R                  " U* U4SS9$ )z*Rotates half the hidden dims of the input..Nrm   rE   rn   )rp   r5   rq   )r   x1x2s      r<   rotate_halfr      sZ    	
3"!''"+"""	#B	
3q ""	#B99rc2YB''r;   hidden_statesn_reprk   c                     U R                   u  p#pEUS:X  a  U $ U SS2SS2SSS2SS24   R                  X#XU5      n U R                  X#U-  XE5      $ )z
This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
r   N)rp   r   reshape)r   r   batchnum_key_value_headsslenhead_dims         r<   	repeat_kvr      s_    
 2?1D1D.Ez!!Qa"23::5W\dlmM  e(CTTTr;   modulequerykeyvalueattention_maskscalingdropoutkwargsc                 @   [        X R                  5      n[        X0R                  5      n	[        R                  " XR	                  SS5      5      U-  n
Ub"  US S 2S S 2S S 2S UR
                  S   24   nX-   n
[        R                  R                  U
S[        R                  S9R                  UR                  5      n
[        R                  R                  XU R                  S9n
[        R                  " X5      nUR	                  SS5      R                  5       nX4$ )NrE   r
   r|   rm   )ro   rH   )ptrainingr   )r   num_key_value_groupsr5   matmulr   rp   r   
functionalsoftmaxfloat32rx   rH   r   r   
contiguous)r   r   r   r   r   r   r   r   rg   rh   attn_weightscausal_maskattn_outputs                r<   eager_attention_forwardr      s     3 ; ;<JU$?$?@L<<';';Aq'ABWLL!$Q1.D
0@0@0D.D%DE#1==((2U]](SVVW\WbWbcL==((6??([L,,|:K''1-88:K$$r;   c                 R   UR                  U5      nUR                  U5      nUR                  S   nU SSU24   U SUS24   pUSSU24   USUS24   pXr-  [        U5      U-  -   nX-  [        U	5      U-  -   n[        R                  " X/SS9n[        R                  " X/SS9nX4$ )a  Applies Rotary Position Embedding to the query and key tensors.

Removes the interleaving of cos and sin from GLM

Args:
    q (`torch.Tensor`): The query tensor.
    k (`torch.Tensor`): The key tensor.
    cos (`torch.Tensor`): The cosine part of the rotary embedding.
    sin (`torch.Tensor`): The sine part of the rotary embedding.
    position_ids (`torch.Tensor`, *optional*):
        Deprecated and unused.
    unsqueeze_dim (`int`, *optional*, defaults to 1):
        The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
        sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
        that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
        k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
        cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
        the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
Returns:
    `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
rm   .Nrn   )	unsqueezerp   r   r5   rq   )qkr   r   r   unsqueeze_dim
rotary_dimq_rotq_passk_rotk_passq_embedk_embeds                r<   apply_rotary_pos_embr     s    , --
&C
--
&C 2Jc;J;&'3
+;)<6c;J;&'3
+;)<6 {{51C78G{{51C78G ii)r2Gii)r2Gr;   c                     ^  \ rS rSrSrS\S\4U 4S jjr  SS\R                  S\
\R                  \R                  4   S\\R                     S	\\   S
\\R                     S\\   S\
\R                  \R                  4   4S jjrSrU =r$ )BambaAttentioni7  z=Multi-headed attention from 'Attention Is All You Need' paperrA   ri   c                 P  > [         TU ]  5         Xl        X l        [	        USUR
                  UR                  -  5      U l        UR                  UR                  -  U l	        U R                  S-  U l
        UR                  U l        SU l        [        R                  " UR
                  UR                  U R                  -  UR                  S9U l        [        R                  " UR
                  UR                  U R                  -  UR                  S9U l        [        R                  " UR
                  UR                  U R                  -  UR                  S9U l        [        R                  " UR                  U R                  -  UR
                  UR                  S9U l        g )Nr   g      Tbias)rJ   rK   rA   ri   getattrrW   num_attention_headsr   r   r   r   attention_dropout	is_causalr   Linearattention_biasq_projk_projv_projo_proj)r_   rA   ri   re   s      r<   rK   BambaAttention.__init__:  sI   "
F4F4F&JdJd4de$*$>$>&B\B\$\!}}d*!'!9!9ii : :T]] JQWQfQf
 ii : :T]] JQWQfQf
 ii : :T]] JQWQfQf
 ii&&68J8JQWQfQf
r;   r   position_embeddingsr   past_key_valuecache_positionr   rk   c                 4   UR                   S S n/ UQSPU R                  P7nU R                  U5      R                  U5      R	                  SS5      n	U R                  U5      R                  U5      R	                  SS5      n
U R                  U5      R                  U5      R	                  SS5      nUu  p[        XX5      u  pUb$  XUS.nUR                  XU R                  U5      u  p[        nU R                  R                  S:w  a  [        U R                  R                     nU" U U	U
UU4U R                  (       d  SOU R                  U R                   S.UD6u  nnUR"                  " / UQSP76 R%                  5       nU R'                  U5      nUU4$ )Nrm   r   rE   )r   r   r  eager        )r   r   )rp   r   r   viewr   r   r   r   rr   ri   r   rA   _attn_implementationr   r   r   r   r   r   r   )r_   r   r   r   r   r  r   input_shapehidden_shapequery_statesrg   rh   r   r   rj   attention_interfacer   r   s                     r<   r   BambaAttention.forwardQ  s    $))#2.88b8$--8{{=166|DNNqRST[[/44\BLLQPQR
{{=166|DNNqRST&#7RU#[ %#&nUL'5'<'<ZW[WeWegs't$J(?;;++w6"9$++:Z:Z"[$7	%
  $}}C$2H2HLL	%
 	%
!\ "));;;;FFHkk+.L((r;   )r   rA   r   r   r   ri   r   r   r   r   r   r&   )r0   r1   r2   r3   r4   r    r8   rK   r5   r   r   r   r   r6   r   r   r   r:   r   r   s   @r<   r   r   7  s    G
{ 
s 
8 +/59))||)) #5<<#=>)) !.	))
 !)) !!1!12)) +,)) 
u||U\\)	*)) ))r;   r   c                   6   ^  \ rS rSrSU 4S jjrSS jrSrU =r$ )BambaRMSNormGatedi}  c                    > [         TU ]  5         [        R                  " [        R
                  " U5      5      U l        X l        g r   rJ   rK   r   	Parameterr5   onesweightvariance_epsilonr_   rW   epsre   s      r<   rK   BambaRMSNormGated.__init__~  s-    ll5::k#:; #r;   c                    UR                   nUR                  [        R                  5      nUb?  U[        R
                  R                  UR                  [        R                  5      5      -  nUR                  S5      R                  SSS9nU[        R                  " X@R                  -   5      -  nU R                  UR                  U5      -  $ NrE   rm   T)keepdim)rH   rx   r5   r   r   r   silupowmeanrsqrtr  r  )r_   r   gateinput_dtypevariances        r<   r   BambaRMSNormGated.forward  s    #))%((7)BMM,>,>twwu}}?U,VVM $$Q',,R,>%H?T?T4T(UU{{]--k:::r;   r  r  gư>r   r0   r1   r2   r3   rK   r   r:   r   r   s   @r<   r  r  }  s    $
	; 	;r;   r  input_tensorpad_sizec                     [        U R                  5      S:X  a
  SSSSSUSS4OSSSUSS4n[        R                  R                  R                  XSSS9$ )zv
Padding x tensor with `pad_size` on the seq_len dim (dim=1)

Assumes that we only have tensors of either size 4 or 3
   r   constant)moder   )rv   rp   r5   r   r   pad)r%  r&  	pad_shapes      r<   pad_tensor_by_sizer-    sd     47|7I7I3Ja3OAq!Q!Q/VWYZ\]_gijlmUnI88""<ST"UUr;   c                    [        X5      n [        U R                  5      S:X  a-  U R                  U R                  S   SX R                  S   5      $ U R                  U R                  S   SX R                  S   U R                  S   5      $ )z
Padding input_tensor with `pad_size` on the seq_len dim (dim=1) and
simultaneously splitting it into chunk sequences.

Assumes that we only have tensors of either size 4 or 3
r
   r   rm   rE   )r-  rv   rp   r   )r%  r&  
chunk_sizes      r<   reshape_into_chunksr0    s     &l=L
<!###L$6$6q$92zK]K]^_K`aa ##q!2z3E3Ea3H,J\J\]^J_
 	
r;   c           	      
   U R                  S5      nU S   R                  " / U R                  5       QUP76 n [        R                  " [        R                  " XU R
                  [        R                  S9SS9nU R                  U) S5      n [        R                  " U SS9n[        R                  " [        R                  " XU R
                  [        R                  S9SS9nUR                  U) [        R                  * 5      nU$ )zg
More stable segment sum calculation. Uses cumulative sums and masking instead of direct subtractions.
rm   .NrF   diagonalr   r|   rn   )
sizer   r5   trilr  rG   boolmasked_fillcumsuminf)r%  r/  masktensor_segsums       r<   segment_sumr=    s     ""2&J  	*11S<3D3D3FS
SL::ejj@S@S[`[e[efqstD++TE15LLL26M ::ejj@S@S[`[e[efqrsD!--teeiiZ@Mr;   c                     UbO  UR                   S   S:  a<  UR                   S   S:  a)  U R                  nXSS2SS2S4   -  R                  U5      n U $ )ze
Tunes out the hidden states for padding tokens, see https://github.com/state-spaces/mamba/issues/66
Nr   r   )rp   rH   rx   )r   r   rH   s      r<   apply_mask_to_padding_statesr?    s_     !n&:&:1&=&AnFZFZ[\F]`aFa##&1d
)CCGGNr;   c                     ^  \ rS rSrSrS\S\4U 4S jjr    SS\R                  S\
\   S\
\R                     S	\
\R                     S
\
\R                     4
S jjr   SS\
\   S\
\R                     S	\
\R                     4S jjr    SS\
\   S\
\R                     S	\
\R                     S
\
\R                     4S jjrSrU =r$ )
BambaMixeri  u'  
Compute ∆, A, B, C, and D the state space parameters and compute the `contextualized_states`.
A, D are input independent (see Mamba paper [1] Section 3.5.2 "Interpretation of A" for why A isn't selective)
∆, B, C are input-dependent (this is a key difference between Mamba and the linear time invariant S4,
and is why Mamba is called **selective** state spaces)

The are a few differences between this and Mamba2Mixer:
- The variable use_precomputed_states is slightly different due to the HybridCache structure
- There's a few non-obvious bugs fixed with batching in the slow path that exist in main
- Some extra variables that our layer doesn't need have been removed
- We ported most of the refactors in https://github.com/huggingface/transformers/pull/35154, which is (as of Dec 18, 2024) unmerged
rA   ri   c           	        > [         TU ]  5         UR                  U l        UR                  U l        UR
                  U l        UR                  U l        [        UR                  U R                  -  5      U l        X l        UR                  U l        UR                  U l        ["        UR                     U l        UR&                  U l        UR*                  U l        UR.                  U l        UR2                  U l        UR6                  U l        S[;        S5      4U l        SU l        SU l         U R                  SU R0                  -  U R                  -  -   U l!        [D        RF                  " U RB                  U RB                  UR                  U R                  U RB                  U R                  S-
  S9U l$        U R                  U RB                  -   U R                  -   n[D        RJ                  " U R                  UU R(                  S9U l&        [D        RN                  " [P        RR                  " U R                  5      5      U l*        [P        RV                  " SU R                  S-   5      n[D        RN                  " [P        RX                  " U5      5      U l-        S	U RZ                  l.        [_        U R                  U R,                  S
9U l0        [D        RN                  " [P        RR                  " U R                  5      5      U l1        S	U Rb                  l.        [D        RJ                  " U R                  U R                  U R(                  S9U l2        [f        (       d  [h        Rk                  S5        g [h        Rk                  S5        g )Nr  r:  gMbP?g?rE   r   )in_channelsout_channelsr   kernel_sizegroupspaddingr   Tr  a  The fast path is not available because on of `(selective_state_update, causal_conv1d_fn, causal_conv1d_update)` is None. Falling back to the naive implementation. To install follow https://github.com/state-spaces/mamba/#installation and https://github.com/Dao-AILab/causal-conv1dzDThe fast path for Bamba will be used when running the model on a GPU)6rJ   rK   rY   	num_headsrW   rO   rb   rN   ra   r8   rV   intermediate_sizeri   mamba_conv_biasuse_conv_bias
hidden_act
activationr	   actmamba_proj_biasuse_biasrms_norm_epslayer_norm_epsilonrX   n_groupsrZ   r   mamba_chunk_sizer/  r   time_step_limittime_step_mintime_step_maxconv_dimr   Conv1dconv1dr   in_projr  r5   r  dt_biasarangelogA_log_no_weight_decayr  normDout_projis_fast_path_availableloggerwarning_once)r_   rA   ri   projection_sizeAre   s        r<   rK   BambaMixer.__init__  s   --!--$22 & 3 3!$V%8%84;K;K%K!L"#33 ++&++,.."("5"5--++ 11 !$U5\2" ..T]]1BTEXEX1XXii''--==))A-
 004==@4>>Qyy
 ||EJJt~~$>? LLDNNQ./\\%))A,/
&*

#%d&<&<$BYBYZ	ejj89"&		$"8"8$:J:JQUQ^Q^_%%>  fgr;   r   cache_paramsr  r   r.   c                 h   [        X5      nU R                  U5      nUR                  u  pxn	U R                  U R                  -  n
US L=(       a    UR
                  =(       a    US:H  =(       aw    UR                  U R                     R                  S   UR                  U R                     R                  S   s=:H  =(       a    U:H  Os  =(       a    US L=(       a    US   S:  nU(       Ga  UR                  S5      R                  U R                  U R                  U R                  /SS9u  pn[        UUR                  U R                     U R                  R                   R                  S5      U R                  R"                  U R$                  5      n[&        R                  " UU R                  X/SS9u  pn[&        R(                  " U R*                  R-                  5       5      * nUS S 2S S4   S S 2S S 2S 4   R/                  SU R0                  U R                  5      R3                  [&        R4                  S9nUS S 2S S 2S 4   R/                  SSU R0                  5      nU R6                  S S 2S S4   R/                  SU R0                  5      nU R8                  S S 2S S4   R/                  SU R0                  5      nUR;                  XpR                  UR                  S   U R                  -  5      nUR;                  XpR                  UR                  S   U R                  -  5      nUR;                  XpR                  U R0                  5      n[=        UR                  U R                     UUUUUUS USS9
nUR;                  XpR                  U R0                  -  5      nU R?                  X5      nU RA                  U5      S S 2S S4   nU$ [&        R(                  " U R*                  R-                  5       5      * nU RB                  S	[-        S
5      4:X  a  0 OSU RB                  0nU RD                  (       a  Uc  [G        UU R                  R                   R                  S5      U R                  R"                  U R6                  U4U R8                  U RH                  UU R$                  U R>                  R                   U R>                  RJ                  U R@                  R                   U R@                  R"                  U R0                  U R                  SSS.UD6nU$ UR                  U R                  U R                  U R                  /SS9u  pnUbv  URM                  SS5      n[N        RP                  RS                  UU RT                  UR                  S   -
  S45      nUR                  U R                     RW                  U5        U R$                  S;  aH  U RY                  U R                  URM                  SS5      5      SS U24   RM                  SS5      5      nOn[[        URM                  SS5      U R                  R                   R                  S5      U R                  R"                  U R$                  US9RM                  SS5      n[        X5      n[&        R                  " UU R                  X/SS9u  pn[]        UR;                  XxSU R0                  5      UUUR;                  XxU R                  S5      UR;                  XxU R                  S5      4U RH                  U R8                  S USU R6                  SS.UD6u  nnUb+  Ub(  UR                  U R                     RW                  U5        UR;                  XxS5      nU R?                  UU5      nU RA                  U5      nU$ )Nr   r   rm   rn   .r   T)zr]  dt_softplusr  r:  dt_limitF)rc  r/  r.   rN  rmsnorm_weightrmsnorm_epsoutproj_weightoutproj_biasheaddimngroupsnorm_before_gatereturn_final_statesrE   )r  swish)r   r  r   rN  r.   )r/  rc  rm  r.   rw  r]  rn  )/r?  r\  rp   rT  rb   rM   rP   ri   rQ   squeezesplitrJ  rY  rI  r%   r[  r  r   rN  r5   expr`  r   r   r   rx   r   r]  rc  r  r!   rb  rd  rV  r   r#   r/  r  r   r   r   r+  ra   copy_rO  r$   r"   )r_   r   rk  r  r   r.   projected_statesr`   seq_lenrd   groups_time_state_sizeuse_precomputed_statesr  hidden_states_B_CdtBCri  r]  rc  hidden_states_reshapedoutdt_limit_kwargshidden_states_B_C_transposedrP   scan_output	ssm_states                              r<   cuda_kernels_forwardBambaMixer.cuda_kernels_forward%  s    5]S<<6 "/!4!4
Q!%1D1D!D $ &//&1& ((8>>qA&&t~~6<<Q? & d*& q!A% 	 "*:*B*B1*E*K*K''GR +L +'DR
 !5!((8""**1-  ! #(++!'')?X#Ma 4::++-..A!T3,1d
+222t}}dFYFYZ]]didqdq]rAAq$J&&r2t}}=Bll1dC<077DMMJGq$|$++B>Az==!''!*2MNAz==!''!*2MNA%2%7%7
NNTXTaTa%b"2''7& M *..z>>DMM;YZM IIm:M --.q$|<C| 
w 4::++-..A$($8$8S%,<O$ObV`bfbvbvUwO }}!56$KK&&..q1KK$$LL ff####'99#3#3 $		 : :#'==#7#7!%!3!3 MM MM%*(-#$ &%l 
A /?.D.D++T]]DNNKQS /E /+  + 4E3N3NqRS3T0"$--"3"34..1M1S1STV1WWYZ[#K !,,T^^<BB;O??*;;(,$5$?$?1$EFsHWH}U__`acde)% )9+55a;#{{1199!<![[--#'?? ')  i1o & %AAR$c!&+kk%++-C\'#! *C!&&zBNFF:rBFF:rB*  $ff#(, LL $* &*&Y" (\-E ++DNN;AA)L)..zBG"iiT: mmK0
r;   c                    UR                   u  pVnUR                  n[        X5      nU R                  U5      n	U	R	                  U R
                  U R                  U R                  /SS9u  pnUS L=(       a    UR                  =(       a    US:H  =(       aw    UR                  U R                     R                   S   UR                  U R                     R                   S   s=:H  =(       a    U:H  Os  =(       a    US L=(       a    US   S:  nU(       GaT  UR                  U R                     R                  SSS9UR                  U R                  '   US S 2SS S 24   R                  UR                  U R                     R                  5      UR                  U R                     S S 2S S 2S4'   UR                  U R                     R                  U R                  R                   R                  S9n["        R$                  " XR                  R                   R'                  S5      -  SS9nU R(                  (       a  XR                  R*                  -   nU R-                  U5      nOUbu  UR/                  SS5      n[0        R2                  R5                  XR6                  UR                   S   -
  S45      nUR                  U R                     R9                  U5        U R-                  U R                  UR/                  SS5      5      SS U24   R/                  SS5      5      n[        X5      n["        R                  " UU R
                  U R:                  U R<                  -  U R:                  U R<                  -  /SS9u  nnn["        R>                  " U R@                  RC                  5       5      * nU(       Ga  UR                  U R                     R                  nUS S 2SS S 24   S S 2S S4   nUR/                  SS5      RE                  X\R                   S   U RF                  5      nU RH                  S	   RE                  U RH                  R                   S   U RF                  5      n["        R0                  R2                  RK                  UUR                  UR                  5      -   5      n["        RL                  " XRN                  S   U RN                  S   5      nUS
   RE                  U R                  U RF                  U R<                  5      R                  ["        RP                  S9n["        R>                  " US	   U-  5      R                  US9nURS                  XPR:                  S5      SS S S 24   nURE                  XPR:                  U R                  U R:                  -  UR                   S   5      RU                  5       nURS                  USUR                   S   5      nUS	   USS S S 24   -  nURS                  USU RF                  5      nUUS	   -  R                  US9nUR                  U R                     R9                  UR                  U R                     U-  U-   5        URS                  XPR:                  S5      SS S S 24   nURE                  XPR:                  U R                  U R:                  -  UR                   S   5      RU                  5       nURS                  USUR                   S   5      nUR                  U R                     R                  UR                  UR                  S9nURW                  XPR                  -  U RF                  U R<                  5      nURW                  XPR                  -  U R<                  S5      n["        RX                  " UU5      nURW                  XPR                  U RF                  5      nU RZ                  S	   RE                  U RZ                  R                   S   U RF                  5      nUUU-  -   R                  UR                  5      nURS                  US5      S S 2S S4   nGO[0        R2                  RK                  XRH                  -   5      n["        RL                  " XRN                  S   U RN                  S   5      nURS                  XVSU RF                  5      RC                  5       nURS                  XVSU R<                  5      RC                  5       nURS                  XVSU R<                  5      RC                  5       nUR]                  U R                  U R:                  -  SU R                  S9nUR]                  U R                  U R:                  -  SU R                  S9nU R^                  X`R^                  -  -
  U R^                  -  nU RZ                  S	   [a        UU5      -  nUUS	   -  nUR                  UR                  5      U-  nUUUU4 V s/ sH  n [c        U UU R^                  5      PM     sn u  nnnnURe                  SSSS5      n["        Rf                  " USS9n!["        R>                  " [i        U5      5      n"US S 2S S 2S S 2S S S 2S S 24   US S 2S S 2S S S 2S S 2S S 24   -  n#U#R%                  SS9n$U$S	   U"Re                  SSSSS5      S	   -  n%U%R%                  SS9n&U&S	   US S 2S S 2S 4   -  R%                  SS9n'["        R>                  " U!S S 2S S 2S S 2SS 24   U!-
  5      n(UU(Re                  SSSS5      S	   -  n)U)SS S S 24   US	   -  R%                  SS9n*U(       a9  UR                  U R                     S S 2S S4   R                  U*R                  S9n+O["        Rj                  " U*S S 2S S24   5      n+["        Rl                  " U+U*/SS9n*["        R>                  " [i        [0        R2                  R5                  U!S S 2S S 2S S 2S4   S5      5      5      n,U,R/                  SS5      n,U,S
   U*S S 2S S 2S S4   -  R%                  SS9n-U-S S 2S S24   U-S S 2S4   n.n*["        R>                  " U!5      n/USS S S 24   U*S S 2S S 2S S4   -  n0U/Re                  SSSS5      n1U0R%                  S5      U1S	   -  n2U'U2-   nURS                  USU R                  U RF                  5      nUU-   nUS:  a  US S 2S U2S S 2S S 24   nURS                  XVS5      nU.b+  Ub(  UR                  U R                     R9                  U.5        U Ro                  UU
5      n3U Rq                  U3R                  U5      5      n4U4$ s  sn f )Nrm   rn   r   r   )shiftsdimsrI   rE   .r2  ).NNr   rF   )ro   output_sizer
   r(  r|   )r   r   )9rp   rH   r?  r\  rz  rJ  rY  rI  rM   rP   ri   rQ   rollrx   rG   r[  r  r5   sumry  rL  r   rO  r   r   r   r+  ra   r|  rT  rb   r{  r`  r   r   r   r]  softplusclamprV  r   r   r   r  bmmrc  repeat_interleaver/  r-  r0  permuter9  r=  
zeros_likerq   rb  rd  )5r_   input_statesrk  r  r   r`   r~  rd   rH   r}  r  r  r  r  rP   r  r   r  r  ri  cache_devicer]  dAdBdBxrQ   ssm_states_reshaped
C_reshapedyrc  r&  
D_residualtA_cumsumLG_intermediateGM_intermediateMY_diagdecay_statesB_decaystatesprevious_statesdecay_chunk
new_statesr  state_decay_outC_times_statesstate_decay_out_permutedY_offr  contextualized_statess5                                                        r<   torch_forwardBambaMixer.torch_forward  s1    ".!3!3
Q"" 4LQ<<5&6&<&<''GR '= '
#
 $ &//&1& ((8>>qA&&t~~6<<Q? & d*& q!A% 	 "7C7O7OPTP^P^7_7d7dlnuw7d7xL$$T^^4ARSTVWYZSZA[A^A^_k_w_wx|  yG  yG  `H  `O  `O  BPL$$T^^4Q2X> '224>>BEET[[M_M_MfMfEgK %		kk0088;;! !!$58H8H$H! $): ; '/@/J/J1a/P, mm//03H3HKgKmKmnpKq3qst2u ((8>>{K $5F5P5PQRTU5V)WX[]e^e]eXe)f)p)pqrtu)v w89J[#kk##T]]T5H5H%H$--Z^ZmZmJmn
q! YYtzz'')**!'224>>BIIL Aq!GQc\*Ba#**:xx|T]]SBll9-44T\\5G5G5JDMMZG$$--b7::bhh3G.GHBR!5!5a!8$:N:Nq:QRB/"))$..$--I\I\]``glgtgt`uA))ByMA-.22,2GB
 		*mmR8dAFA]]DNNdmm4SUVU\U\]_U`allnA		*b!''"+6AI3a<0B *11*b$--PMi0044L4IC ##DNN399''7"<sB 		*mmR8dAFA]]DNNdmm4SUVU\U\]_U`allnA		*b!''"+6A &00@CC188[\[b[bCcJ",//*~~2Mt}}^b^q^q"r
^^ ;T=P=PRSTJ		-z:Az>>4==AA y!((a$--HA]Q&&**1773A 		*b)!T3,7A ''\\(9:BR!5!5a!8$:N:Nq:QRB)11*r4==Y__aM		*r43F3FGMMOA		*r43F3FGMMOA##DNNdmm$CX\XfXf#gA##DNNdmm$CX\XfXf#gA'OO*CCtVH	*-?x-XXJ *ByM9M](()B.A cpqrtuwxay%zay\]&9!Xt&Way%z"M1a 		!Q1%A||A2.H 		+a.)A q!Qa23a1dAq!8K6LLN""r"*A y\AIIaAq!,DY,OON""r"*A 	l]1a:%>>CCCJF !99XaArsl%;h%FGL,..q"b!<YGGGc4l+mI.FFKKPQKRF &"."9"9$.."I!TSV,"W"Z"Zbhbobo"Z"p"'"2"26!RaR%="AYY8a@F))K0A0A(1aQRTV;BWY_0`$abK%//15K%o61dC9PPUUZ[U\J *1crc6 2Jq"u4EIF $ii1OT1oq!T30GGN'6'>'>q!Q'J$#''+.Fy.QQE A		*b$..$--HAJA!|a'1a'(		*r2A $)A''7==iHii4(
 !%knnU.C D$$G &{s    u?c                 ~   [         (       aA  SU R                  R                  R                  R                  ;   a  U R                  XX4U5      $ Ub  [        S5      eUR                  nUbC  UR                  S   S:  a0  UR                  S   S:  a  XS S 2S S 2S 4   -  R                  U5      nU R                  XX45      $ )Ncudaz\`seq_idx` support requires fast path support. Please install `mamba_ssm` and `causal_conv1d`r   r   )re  r\  r  rG   r   r  r   rH   rp   rx   r  )r_   r   rk  r  r   r.   r   rH   s           r<   r   BambaMixer.forward  s     "!f0C0C0J0J0O0O&O,,].jqrr%n  ##%.*>*>q*AA*E.J^J^_`JadeJe*Aq$J-GGKKERM!!-~^^r;   )r`  rc  rO  rN  r/  r[  rY  ra   r]  r   rW   r\  rJ  ri   rS  rT  rb  rI  rd  rb   rV  rX  rW  rQ  rL  )NNNN)NNN)r0   r1   r2   r3   r4   r    r8   rK   r5   r   r   r?   r6   r9   r  r  r   r:   r   r   s   @r<   rA  rA    sO   Ah{ Ahs AhL DH5915-1g||g ?@g !!1!12	g
 !.g %//*gZ DH5915L% ?@L% !!1!12	L%
 !.L%d DH5915-1_ ?@_ !!1!12	_
 !._ %//*_ _r;   rA  c                   .   ^  \ rS rSrU 4S jrS rSrU =r$ )BambaMLPi  c                   > [         TU ]  5         Xl        UR                  U l        UR                  U l        [
        R                  " U R                  U R                  UR                  S9U l        [
        R                  " U R                  U R                  UR                  S9U l	        [
        R                  " U R                  U R                  UR                  S9U l
        [        UR                     U l        g )Nr   )rJ   rK   rA   rW   rJ  r   r   mlp_bias	gate_projup_proj	down_projr	   rM  act_fnr_   rA   re   s     r<   rK   BambaMLP.__init__  s    !--!'!9!94#3#3T5K5KRXRaRabyy!1!143I3IPVP_P_`4#9#94;K;KRXRaRabV../r;   c                     U R                  U R                  U R                  U5      5      U R                  U5      -  5      nU$ r   )r  r  r  r  )r_   r   r  s      r<   r   BambaMLP.forward  s6    NN4;;t~~a/@#ADLLQRO#ST	r;   )r  rA   r  r  rW   rJ  r  r$  r   s   @r<   r  r    s    0 r;   r  RMSNormc                   8   ^  \ rS rSrSU 4S jjrS rS rSrU =r$ )BambaRMSNormi  c                    > [         TU ]  5         [        R                  " [        R
                  " U5      5      U l        X l        g)z+
BambaRMSNorm is equivalent to T5LayerNorm
Nr  r  s      r<   rK   BambaRMSNorm.__init__  s/     	ll5::k#:; #r;   c                    UR                   nUR                  [        R                  5      nUR	                  S5      R                  SSS9nU[        R                  " X0R                  -   5      -  nU R                  UR                  U5      -  $ r  )	rH   rx   r5   r   r  r  r  r  r  )r_   r   r  r   s       r<   r   BambaRMSNorm.forward  sw    #))%((7 $$Q',,R,>%H?T?T4T(UU{{]--k:::r;   c                 ^    [        U R                  R                  5       SU R                   3$ )Nz, eps=)r   r  rp   r  r   s    r<   
extra_reprBambaRMSNorm.extra_repr  s*    ))*+6$2G2G1HIIr;   r"  r#  )	r0   r1   r2   r3   rK   r   r  r:   r   r   s   @r<   r  r    s    $;J Jr;   r  c                     ^  \ rS rSrSS\S\S\4U 4S jjjr       SS\R                  S\
\R                     S\
\R                     S	\
\   S
\
\   S\
\   S\
\R                     S\
\\R                  \R                  4      S\\   S\\R"                  \
\\R"                  \R"                  4      4   4S jjrSrU =r$ )BambaDecoderLayeri  rA   ri   
layer_typec                 `  > [         TU ]  5         SnUS:X  a  [        OS nU" U5      U l        [	        UR
                  UR                  S9U l        [	        UR
                  UR                  S9U l        X0l	        US:X  a  [        XS9U l        g US:X  a  [        X5      U l        g [        S5      e)Nr   rH  rD   )rA   ri   	attentionzInvalid layer_type)rJ   rK   r  feed_forwardr  rW   rR  input_layernormpre_ff_layernormr  rA  rD   r   	self_attn
ValueError)r_   rA   ri   r  num_expertsffn_layer_classre   s         r<   rK   BambaDecoderLayer.__init__  s    &1Q&6(D+F3+F,>,>FDWDWX ,V-?-?VEXEX Y$ #6GDJ;&+F>DN122r;   r   r   r   r   output_attentions	use_cacher  r   r   rk   c	                 R   Un
U R                  U5      nU R                  S:X  a  U R                  " SUUUUS.U	D6nSnO-U R                  S:X  a  U R                  " SUUUUUUUUS.U	D6u  pX-   nUn
U R	                  U5      nU R                  U5      nX-   nU4nU(       a  UW4-  nU$ )a[  
Args:
    hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
    attention_mask (`torch.FloatTensor`, *optional*): attention mask of size
        `(batch, sequence_length)` where padding elements are indicated by 0.
    past_key_value (`HybridMambaAttentionDynamicCache`, *optional*): cached past key and value projection states
    output_attentions (`bool`, *optional*):
        Whether or not to return the attentions tensors of all attention layers. See `attentions` under
        returned tensors for more detail.
    use_cache (`bool`, *optional*):
        If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
        (see `past_key_values`).
    cache_position (`torch.LongTensor` of shape `(sequence_length)`, *optional*):
        Indices depicting the position of the input sequence tokens in the sequence.
    position_embeddings (`tuple[torch.FloatTensor, torch.FloatTensor]`, *optional*):
        Tuple containing the cosine and sine positional embeddings of shape `(batch_size, seq_len, head_dim)`,
        with `head_dim` being the embedding dimension of each attention head.
    kwargs (`dict`, *optional*):
        Arbitrary kwargs. Can be used to provide `BambaFlashAttentionKwargs` for
        padding-free training and/or improve torch.compile performance.
rD   )r   rk  r  r   Nr  )r   r   r   r   r  r  r  r   r/   )r  r  rD   r  r  r  )r_   r   r   r   r   r  r  r  r   r   residualself_attn_weightsoutputss                r<   r   BambaDecoderLayer.forward  s    D !,,]; ??g% JJ ++--	
 M !%__+/3~~ 
0+-)-"3#-$7
0 
0,M !0 !--m<))-8 0 ")++Gr;   )r  r  r  rD   r  r  )rD   )NNNFFNN)r0   r1   r2   r3   r    r8   r   rK   r5   r   r   r6   r?   r7  r   r   r(   r   r   r:   r   r   s   @r<   r  r    s*   3{ 3s 3 3 3( 2637EI,1$)59KOK||K !.K u//0	K
 !!ABK $D>K D>K !!1!12K &eELL%,,,F&GHK 23K 
u  (51B1BEDUDU1U+V"WW	XK Kr;   r  c                   R   ^  \ rS rSr% \\S'   SrSrS/rSr	Sr
SrSrU 4S jrSrU =r$ )	BambaPreTrainedModeli:  rA   modelTr  r   c                 r  > [         TU ]  U5        [        U[        5      (       a  UR                  R
                  R                  S5        [        R                  " [        R                  " SUR                  S-   5      5      UR                  l        UR                  R
                  R                  S5        g g )Ng      ?r   )rJ   _init_weightsr   rA  r]  datafill_r5   r_  r^  rI  r`  rc  )r_   r   re   s     r<   r  "BambaPreTrainedModel._init_weightsF  s{    f%fj))NN%%c* %		%,,q&:J:JQ:N*O PFLLHHMM$ *r;   r/   )r0   r1   r2   r3   r    r7   base_model_prefixsupports_gradient_checkpointing_no_split_modules_skip_keys_device_placement_supports_flash_attn_supports_sdpa_is_statefulr  r:   r   r   s   @r<   r  r  :  s>    &*#,-"3NL% %r;   r  c                     ^  \ rS rSrS\4U 4S jjr\\         SS\\	R                     S\\	R                     S\\	R                     S\\   S\\	R                     S	\\   S
\\   S\\   S\\	R                     S\\   S\4S jj5       5       rS\	R                  S\	R                  S\	R                  S\S
\4
S jr\S\	R                  S\S\S\	R,                  S\	R                  S\4S j5       rS rSrU =r$ )
BambaModeliN  rA   c           	      N  > [         TU ]  U5        UR                  U l        UR                  U l        [
        R                  " UR                  UR                  U R                  5      U l        / n[        UR                  5       H)  nUR                  [        XUR                  U   S95        M+     [
        R                  " U5      U l        UR                   U l        [#        UR                  UR$                  S9U l        [)        US9U l        SU l        U R/                  5         g )N)ri   r  rH  )rA   F)rJ   rK   pad_token_idpadding_idx
vocab_sizer   	EmbeddingrW   embed_tokensrS   rT   r\   r  rL   
ModuleListlayersr  r  rR  final_layernormr   
rotary_embgradient_checkpointing	post_init)r_   rA   decoder_layersrc   re   s       r<   rK   BambaModel.__init__P  s     !.. ++LL):):F<N<NPTP`P`av//0A!!"3FTZTlTlmnTo"pq 1mmN3$*$?$?!+F,>,>FDWDWX.f=&+#r;   	input_idsr   r   r   inputs_embedsr  r  output_hidden_statesr  r   rk   c
                 H   Ub  UOU R                   R                  nUb  UOU R                   R                  nUb  UOU R                   R                  nUS L US L-  (       a  [	        S5      eU R
                  (       a/  U R                  (       a  U(       a  [        R                  S5        SnUc  U R                  U5      nUnU(       a  Uc  [        R                  S5        U	c,  [        R                  " UR                  S   UR                  S9n	Uc  U	R                  S5      nU R                  X%XU5      nU R!                  X)5      nU R#                  X5      nU(       a  SOS nU(       a  SOS nU R$                   HS  nUR&                  S	:X  a  UOUnU(       a  X4-  nU" U4UUUUUU	US
.U
D6nUS   nU(       d  MB  US   c  MJ  UUS   4-  nMU     U R)                  U5      nU(       a  X4-  nU(       a  UR*                  (       d  SUl        U(       d  S OUn[-        UUUUS9$ )Nz:You must specify exactly one of input_ids or inputs_embedszX`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`.FzBamba requires an initialized `HybridMambaAttentionDynamicCache` to return a cache. None was provided, so no cache will be returned.r   rI   r   r/   rD   )r   r   r   r  r  r  r   T)last_hidden_stater   r   
attentions)rA   r  r  r  r  r  r   rf  rg  r  r5   r^  rp   rG   r   _update_causal_mask_update_mamba_maskr  r  r  r  rM   r   )r_   r  r   r   r   r  r  r  r  r  r   r   r   
mamba_maskr   all_hidden_statesall_self_attnsdecoder_layer
layer_masklayer_outputs
next_caches                        r<   r   BambaModel.forwardc  sF    2C1N-TXT_T_TqTq$8$D $++JjJj 	 "+!6IDKK<Q<Q	-t";<YZZ&&4==Yj I  --i8M%0:
 !"\\-*=*=a*@I]I]^N)33A6L..>L]
 ,,^L
 #oomJ"6BD0d![[M'4'?'?7'JP[J#!%55!)
))."3#-$7
 
M *!,M   #/"}Q'7&99N1 )4 ,,];  !11?#E#E15O.!*T
&+&+%	
 	
r;   r%  c           	         U R                   R                  S:X  a  Ub  SU;   a  U$ g Ub  UR                  5       OSnU R                   R                  S:X  a.  U(       d'  [        R                  " UUUU R
                  S9(       a  g UR                  nUR                  S   n[        U[        R                  5      (       a  UR                  S   OXh-   S-   n	U R                  UUU	UUUR                  S   S9n
U R                   R                  S:X  aZ  UbW  UR                  R                  S	;   a=  U(       d6  [        R                  " U5      R                  n[        R                   " X5      n
U
$ )
Nflash_attention_2r  r   sdpa)r  past_key_values_lengthis_trainingr   rm   )sequence_lengthtarget_lengthrH   r  r`   )r  xpunpu)rA   r  r}   r   _ignore_causal_mask_sdpar   rH   rp   r   r5   r   5_prepare_4d_causal_attention_mask_with_cache_positionrG   r   finfomin_unmask_unattended)r_   r   r%  r  r   r  past_seen_tokensrH   r  r  r   	min_dtypes               r<   r	  BambaModel._update_causal_mask  sc    ;;++/BB)c^.C%%
 @O?Z?99;`a ;;++v5>O%>>*'7 MM	 ""&,,Q/ .%,,77   $!3a7 	 PP+')#))!, Q 
 KK,,6*%%**.DD%
 E*..I0CCK[Kr;   r  r  rH   r`   c                    U b  U R                  5       S:X  a  U nU$ [        R                  " U5      R                  n[        R                  " X4XUR
                  S9nUS:w  a  [        R                  " USS9nU[        R                  " X$R
                  S9UR                  SS5      :  -  nUSSSS2SS24   R                  USSS5      nU b  UR                  5       nU R                  S   n	U SS2SSSS24   U SS2SSS2S4   :H  SS2SS2U* S2SS24   R                  U5      n
USS2SS2SS2SU	24   U
-   nUS:H  nUSS2SS2SS2SU	24   R                  X5      USS2SS2SS2SU	24'   U$ )	a  
Creates a causal 4D mask of shape `(batch_size, 1, query_length, key_value_length)` from a 2D mask of shape
`(batch_size, key_value_length)`, or if the input `attention_mask` is already 4D, do nothing.

Args:
    attention_mask (`torch.Tensor`):
        A 2D attention mask of shape `(batch_size, key_value_length)` or a 4D attention mask of shape
        `(batch_size, 1, query_length, key_value_length)`.
    sequence_length (`int`):
        The sequence length being processed.
    target_length (`int`):
        The target length: when generating with static cache, the mask should be as long as the static cache,
        to account for the 0 padding, the part of the cache that is not filled yet.
    dtype (`torch.dtype`):
        The dtype to use for the 4D attention mask.
    cache_position (`torch.Tensor`):
        Indices depicting the position of the input sequence tokens in the sequence.
    batch_size (`torch.Tensor`):
        Batch size.
Nr(  )
fill_valuerH   rG   r   r3  rI   rm   r   )ro   r5   r  r  fullrG   triur^  r   r   clonerp   rx   r8  )r   r  r  rH   r  r`   r   r   r"  mask_lengthpadding_attention_maskpadding_masks               r<   r  @BambaModel._prepare_4d_causal_attention_mask_with_cache_position  s   < %.*<*<*>!*C(K, ) E*..I** 0Y\j\q\qK !##jjqA5<<>S>STWeWmWmnprsWtttK%dD!Q&67>>z1bRTUK))//1,2226*8D$9I*Jn]^`dfgim]mNn*nq?*+Q.*"U) '  +1aL[L+@ADZZ+q05@Aq,;,AV5W5c5c 6Aq!\k\12 r;   c                 b    UnUS   S:  d!  Ub   [         R                  " US:H  5      (       a  SnU$ )zV
No need for zeroing states when
    1. Cached forward
    2. Attending to all inputs
r   Nr   )r5   all)r_   r   r  r  s       r<   r
  BambaModel._update_mamba_mask;  s:     $
!q ^%?EIIn`aNaDbDbJr;   )r  r  r  r  r  r  r  r  )	NNNNNNNNN)r0   r1   r2   r3   r    rK   r   r   r   r5   r6   r   r?   r   r7  r   r(   r   r   r	  staticmethodr8   rH   r  r
  r:   r   r   s   @r<   r  r  N  s   { &  151537FJ59$(,0/359`
E,,-`
 !.`
 u//0	`

 ""BC`
   1 12`
 D>`
 $D>`
 'tn`
 !!1!12`
 23`
 
!`
  `
D:: ll: 	:
 ::  :x 555 5 {{	5
 5 5 5n	 	r;   r  c                     ^  \ rS rSrS/rSS0rSS/S/40rU 4S jrS rS	 r	\
\           SS
\\R                     S\\R                     S\\R                     S\\   S\\R"                     S\\R                     S\\   S\\   S\\   S\\R                     S\\\R                  4   S\4S jj5       5       r      SS jrSrU =r$ )BambaForCausalLMiG  zlm_head.weightlm_headcolwise_repr   logitsc                   > [         TU ]  U5        [        U5      U l        UR                  U l        [
        R                  " UR                  UR                  SS9U l        UR                  U l	        U R                  5         g )NFr   )rJ   rK   r  r  r  r   r   rW   r3  z_loss_coefficientr   r  s     r<   rK   BambaForCausalLM.__init__M  sc     '
 ++yy!3!3V5F5FUS"(";"; 	r;   c                     Xl         g r   r  )r_   decoders     r<   set_decoderBambaForCausalLM.set_decoderW  s    
r;   c                     U R                   $ r   r:  r   s    r<   get_decoderBambaForCausalLM.get_decoderZ  s    zzr;   r  r   r   r   r  labelsr  r  r  r  logits_to_keeprk   c                    Ub  UOU R                   R                  nU	b  U	OU R                   R                  n	U R                  " S
UUUUUUUU	U
S.	UD6nUR                  n[        U[        5      (       a  [        U* S5      OUnU R                  USS2USS24   5      nSnUb  U R                  " S
UX`R                   R                  S.UD6nU R                  S:  aU  UR                  SS9R                  UR                  S9R                  S5      R!                  5       nUU R                  U-  -   n[#        UUUR$                  UR&                  UR(                  S	9$ )a  
labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
    Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
    config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
    (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.

Example:

```python
>>> from transformers import AutoTokenizer, BambaForCausalLM

>>> model = BambaForCausalLM.from_pretrained("...")
>>> tokenizer = AutoTokenizer.from_pretrained("...")

>>> prompt = "Hey, are you conscious? Can you talk to me?"
>>> inputs = tokenizer(prompt, return_tensors="pt")

>>> # Generate
>>> generate_ids = model.generate(inputs.input_ids, max_length=30)
>>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
"Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you."
```N)	r  r   r   r   r  r  r  r  r  )r5  rA  r  r   rm   rn   r   rE   )lossr5  r   r   r  r/   )rA   r  r  r  r  r   r8   slicer3  loss_functionr  r7  	logsumexprx   rH   r  r  r   r   r   r  )r_   r  r   r   r   r  rA  r  r  r  r  rB  r   r  r   slice_indicesr5  rD  z_losss                      r<   r   BambaForCausalLM.forward]  st   N 2C1N-TXT_T_TqTq$8$D $++JjJj 	
 ,0:: ,
)%+'/!5),
 ,
  118B>SV8W8W~ot4]kmA}a,?@A%%pVF{{OeOepiopD&&*))b)1444::4FJJ1MRRTd55>>%#33!//))
 	
r;   c           	         US L n	U	(       d]  Uc  US   UR                   S   :  a  US S 2UR                   S   * S 24   nOaUR                   S   UR                   S   :w  a	  US S 2U4   nO7[        U R                  UR                   S   U R                  U R                  S9nUbZ  UcW  UR                  5       R                  S5      S-
  nUR                  US:H  S5        U	(       d  US S 2UR                   S   * S 24   nUb  U	(       a  SU0n
OSUR                  5       0n
U
R                  UUUUU R                  R                  US.5        U
$ )Nrm   r   r   rI   r  r  )r   r   r  r   rB  r  )rp   r?   rA   rH   rG   longr9  masked_fill_r   rr   num_logits_to_keep)r_   r  r   r   r  r  r   r  r   empty_past_kvmodel_inputss              r<   prepare_inputs_for_generation.BambaForCausalLM.prepare_inputs_for_generation  sb    (4/ )!"%);;%a.*>*>q*A)A)C&CD	#~';';A'>>%a&78	>Y__Q/DKKO %,*>)..077;a?L%%n&91= +A	0B/B/D,DE $+];L')=)=)?@L ,#2&"0"&++"@"@"0		
 r;   )r3  r  r  r7  )NNNNNNNNNNr   )NNNNNT)r0   r1   r2   r3   _tied_weights_keys_tp_plan_pp_planrK   r<  r?  r   r   r   r5   r6   r   r?   r   r7  r   r8   r   r   rQ  r:   r   r   s   @r<   r2  r2  G  s{   *+=)H_-z:;H  151537FJ59-1$(,0/35934K
E,,-K
 !.K
 u//0	K

 ""BCK
   1 12K
 ))*K
 D>K
 $D>K
 'tnK
 !!1!12K
 c5<</0K
 
 K
  K
` 8 8r;   r2  )r  r2  r  )r  )Nr   )Qtypingr   r   r   r   r   r5   r   transformers.activationsr	   cache_utilsr   r   r   
generationr   integrationsr   modeling_attn_mask_utilsr   modeling_layersr   modeling_outputsr   r   modeling_rope_utilsr   r   modeling_utilsr   r   processing_utilsr   utilsr   r   r   r   utils.import_utilsr   r   configuration_bambar    +mamba_ssm.ops.triton.selective_state_updater!   !mamba_ssm.ops.triton.ssd_combinedr"   r#   causal_conv1dr$   r%   
get_loggerr0   rf  r(   r?   Moduler   r   r   r8   r   r   r   r   r   r  r-  r0  r=  r.  re  r?  rA  r  r  r  r  r  r2  __all__r/   r;   r<   <module>rj     s  6 = <   + < < ) 7 > 9 O K F & R R V , Rmm!DD-7** 
		H	%	 2dou doN<299 <D(	UU\\ 	U# 	U%,, 	U& %II%<<% 
% <<	%
 U\\*% % % '(%6%PC)RYY C)L; ;*VU\\ VS V
(( 46FH\]^ ^_ ^_Bryy   Y'J299 J (J(]2 ]@ %? % %& u% u up \+_ \ \~ Er;   