
    bCi                       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  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%  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= SIS%\Rp                  S&\Rv                  S'\Rv                  S(\Rv                  S)\\Rv                     S*\>S+\>S,\\    4S- jjr?SJS. jr@ " S/ S0\Rp                  5      rA " S1 S2\R                  Rp                  5      rBS3\Rv                  S4\<4S5 jrCS6 rDS7 rE\F" \,\1\245      rGS8 rH " S9 S:\Rp                  5      rI " S; S<\Rp                  5      rJ\" S=5       " S> S?\Rp                  5      5       rK " S@ SA\5      rL\! " SB SC\5      5       rM\! " SD SE\M5      5       rN\! " SF SG\M\5      5       rO/ SHQrPg)K    )AnyCallableOptional	TypedDictUnionN)nn)ACT2FN   )Cache)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)deprecate_kwarg)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.       b/home/james-whalen/.local/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\R                  S4S\4S 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g) HybridMambaAttentionDynamicCacheY   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)`.
FNconfigc                 (   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 )NFmamba   devicedtyperE   )layers_block_typehas_previous_statemamba_d_convmamba_d_stateconv_states
ssm_statestransformer_layersrangenum_hidden_layersr4   zerosmamba_expandhidden_sizemamba_n_groupsmamba_n_headsmamba_d_headtensorappend	key_cachevalue_cache)	selfr@   
batch_sizerF   rE   conv_kernel_sizessm_state_sizei_s	            r;   __init__)HybridMambaAttentionDynamicCache.__init__i   s   !'!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   rC   dim)rY   shaperZ   r4   cat)r[   rc   rd   re   rf   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)	rO   lenrY   rE   index_selecttorZ   rL   rM   )r[   rp   re   rE   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   )rN   rr   rY   rl   )r[   re   s     r;   get_seq_length/HybridMambaAttentionDynamicCache.get_seq_length   sP     3<CZCZ2ZD++A.`i	t~~)+~~i(..r22r:   )rL   rI   rY   rH   rM   rN   rZ   N)r   )r/   r0   r1   r2   r3   is_compileabler4   float16r   ra   Tensorr7   r   dictstrr   tuplern   r5   ru   ry   r9   r.   r:   r;   r>   r>   Y   s     N>CmmTX $u{ $uV 26FLLF llF 	F
 tCH~.F 
u||U\\)	*F"ie&6&6 i3 3c 3 3r:   r>   c                      ^  \ rS rSr% \R
                  \S'   SS\4U 4S jjjr\R                  " 5       \
S 5       5       rSrU =r$ )BambaRotaryEmbedding   inv_freqr@   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defaultr   F)
persistent)superra   hasattr
isinstancer   r   getr   max_position_embeddingsmax_seq_len_cachedoriginal_max_seq_lenr@   r   rope_init_fnattention_scalingregister_bufferr   original_inv_freq)r[   r@   rE   r   	__class__s       r;   ra   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   ri   r   mpscpuF)device_typeenabledrC   rj   rF   )r   floatexpandrl   rt   rE   r   r   r   r4   autocast	transposerm   cosr   sinrF   )
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   r@   r   r   r   r   r   r{   )r/   r0   r1   r2   r4   r~   r6   r   ra   no_gradr   r   r9   __classcell__r   s   @r;   r   r      s@    ll/{ / /" ]]_<  <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..Nri   rC   rj   )rl   r4   rm   )r   x1x2s      r;   rotate_halfr      sZ    	
3"!''"+"""	#B	
3q ""	#B99rc2YB''r:   hidden_statesn_reprg   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)rl   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$ )NrC   r
   rx   ri   )rk   rF   )ptrainingr   )r   num_key_value_groupsr4   matmulr   rl   r   
functionalsoftmaxfloat32rt   rF   r   r   
contiguous)r   r   r   r   r   r   r   r   rc   rd   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.
ri   .Nrj   )	unsqueezerl   r   r4   rm   )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                   4  ^  \ rS rSrSrS\S\4U 4S jjr\" SSSS	9  SS
\	R                  S\\	R                  \	R                  4   S\\	R                     S\\   S\\	R                     S\\   S\\	R                  \	R                  4   4S jj5       rSrU =r$ )BambaAttentioni0  z=Multi-headed attention from 'Attention Is All You Need' paperr@   re   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)r   ra   r@   re   getattrrS   num_attention_headsr   r   r   r   attention_dropout	is_causalr   Linearattention_biasq_projk_projv_projo_proj)r[   r@   re   r   s      r;   ra   BambaAttention.__init__3  sI   "
F4F4F&JdJd4de$*$>$>&B\B\$\!}}d*!'!9!9ii : :T]] JQWQfQf
 ii : :T]] JQWQfQf
 ii : :T]] JQWQfQf
 ii&&68J8JQWQfQf
r:   past_key_valuepast_key_values4.58new_nameversionr   position_embeddingsr   cache_positionr   rg   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$ )Nri   r   rC   )r   r   r   eager        )r   r   )rl   r   r   viewr   r   r   r   rn   re   r   r@   _attn_implementationr   r   r   r   r   r   r   )r[   r   r   r   r   r   r   input_shapehidden_shapequery_statesrc   rd   r   r   rf   attention_interfacer   r   s                     r;   r   BambaAttention.forwardJ  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'6'='=jX\XfXfht'u$J(?;;++w6"9$++:Z:Z"[$7	%
  $}}C$2H2HLL	%
 	%
!\ "));;;;FFHkk+.L((r:   )r   r@   r   r   r   re   r   r   r   r   r   r%   )r/   r0   r1   r2   r3   r   r7   ra   r   r4   r~   r   r   r   r5   r   r   r   r9   r   r   s   @r;   r   r   0  s    G
{ 
s 
. %0A6R ,059))||)) #5<<#=>)) !.	))
 "%)) !!1!12)) +,)) 
u||U\\)	*)) S))r:   r   c                   6   ^  \ rS rSrSU 4S jjrSS jrSrU =r$ )BambaRMSNormGatediw  c                    > [         TU ]  5         [        R                  " [        R
                  " U5      5      U l        X l        g r{   r   ra   r   	Parameterr4   onesweightvariance_epsilonr[   rS   epsr   s      r;   ra   BambaRMSNormGated.__init__x  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      -  $ NrC   ri   T)keepdim)rF   rt   r4   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{   r/   r0   r1   r2   ra   r   r9   r   r   s   @r;   r  r  w  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   )rr   rl   r4   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   ri   rC   )r"  rr   rl   r   )r  r  
chunk_sizes      r;   reshape_into_chunksr%    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.
ri   .NrD   diagonalr   rx   rj   )
sizer   r4   trilr  rE   boolmasked_fillcumsuminf)r  r$  masktensor_segsums       r;   segment_sumr2    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   )rl   rF   rt   )r   r   rF   s      r;   apply_mask_to_padding_statesr4    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 hybrid cache 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
r@   re   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-        []        U R                  U R,                  S	9U l/        [D        RN                  " [P        RR                  " U R                  5      5      U l0        [D        RJ                  " U R                  U R                  U R(                  S9U l1        [d        (       d  [f        Ri                  S
5        g [f        Ri                  S5        g )Nr   r/  gMbP?g?rC   r   )in_channelsout_channelsr   kernel_sizegroupspaddingr   r
  a  The fast path is not available because one 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)5r   ra   rU   	num_headsrS   rK   r^   rJ   r]   r7   rR   intermediate_sizere   mamba_conv_biasuse_conv_bias
hidden_act
activationr	   actmamba_proj_biasuse_biasrms_norm_epslayer_norm_epsilonrT   n_groupsrV   r   mamba_chunk_sizer$  r   time_step_limittime_step_mintime_step_maxconv_dimr   Conv1dconv1dr   in_projr  r4   r  dt_biasarangelogA_logr  normDout_projis_fast_path_availableloggerwarning_once)r[   r@   re   projection_sizeAr   s        r;   ra   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   ri   rj   .r   T)zrR  dt_softplusr   r/  dt_limitF)rW  r$  r-   rC  rmsnorm_weightrmsnorm_epsoutproj_weightoutproj_biasheaddimngroupsnorm_before_gatereturn_final_statesrC   )r  swish)r   r  r   rC  r-   )r$  rW  ra  r-   rk  rR  rb  )/r4  rQ  rl   rI  r^   rI   rL   re   rM   squeezesplitr?  rN  r>  r$   rP  r  r   rC  r4   exprU  r   r   r   rt   r   rR  rW  r   r    rV  rX  rK  r   r"   r$  r  r   r   r   r   r]   copy_rD  r#   r!   )r[   r   r_  r   r   r-   projected_statesr\   seq_lenr`   groups_time_state_sizeuse_precomputed_statesr  hidden_states_B_CdtBCr]  rR  rW  hidden_states_reshapedoutdt_limit_kwargshidden_states_B_C_transposedrL   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 )Nri   rj   r   r   )shiftsdimsrG   rC   .r'  ).NNr   rD   )rk   output_sizer
   r  rx   )r   r   )9rl   rF   r4  rQ  rn  r?  rN  r>  rI   rL   re   rM   rollrt   rE   rP  r  r4   sumrm  rA  r   rD  r   r   r   r   r]   rp  rI  r^   ro  rU  r   r   r   rR  softplusclamprK  r   r   r   r   bmmrW  repeat_interleaver$  r"  r%  permuter.  r2  
zeros_likerm   rV  rX  )5r[   input_statesr_  r   r   r\   rr  r`   rF   rq  r  ru  rv  rt  rL   r|  r   rw  rx  r]  cache_devicerR  dAdBdBxrM   ssm_states_reshaped
C_reshapedyrW  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   !v 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   )rY  rQ  r  rE   r   r  NotImplementedErrorrF   rl   rt   r  )r[   r   r_  r   r   r-   r   rF   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:   )rU  rW  rD  rC  r$  rP  rN  r]   rR  r   rS   rQ  r?  re   rH  rI  rV  r>  rX  r^   rK  rM  rL  rF  rA  )NNNN)NNN)r/   r0   r1   r2   r3   r   r7   ra   r4   r~   r   r>   r5   r8   r  r  r   r9   r   r   s   @r;   r6  r6    sL   ?h{ ?hs ?hH 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:   r6  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   )r   ra   r@   rS   r?  r   r   mlp_bias	gate_projup_proj	down_projr	   rB  act_fnr[   r@   r   s     r;   ra   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  r@   r  r  rS   r?  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;   ra   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  )	rF   rt   r4   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  rl   r  )r[   s    r;   
extra_reprBambaRMSNorm.extra_repr  s*    ))*+6$2G2G1HIIr:   r  r  )	r/   r0   r1   r2   ra   r   r  r9   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SS	9       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5       rSrU =r$ )BambaDecoderLayeri  r@   re   
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   r=  rB   )r@   re   	attentionzInvalid layer_type)r   ra   r  feed_forwardr  rS   rG  input_layernormpre_ff_layernormr  r6  rB   r   	self_attn
ValueError)r[   r@   re   r  num_expertsffn_layer_classr   s         r;   ra   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   r   r   r   output_attentions	use_cacher   r   r   rg   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_values (`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.
rB   )r   r_  r   r   Nr  )r   r   r   r   r  r  r   r   r.   )r  r  rB   r  r  r  )r[   r   r   r   r   r  r  r   r   r   residualself_attn_weightsoutputss                r;   r   BambaDecoderLayer.forward  s    F !,,]; ??g% JJ +,--	
 M !%__+/3~~ 
0+-) /"3#-$7
0 
0,M !0 !--m<))-8 0 ")++Gr:   )r  r  r  rB   r  r  )rB   )NNNFFNN)r/   r0   r1   r2   r   r7   r   ra   r   r4   r~   r   r5   r>   r,  r   r   r'   FloatTensorr   r9   r   r   s   @r;   r  r    s@   3{ 3s 3 3 3" %0A6R 2637FJ,1$)59KOK||K !.K u//0	K
 ""BC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 S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$ )	BambaPreTrainedModeli3  r@   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   )r   _init_weightsr   r6  rR  datafill_r4   rT  rS  r>  rU  rW  )r[   r   r   s     r;   r  "BambaPreTrainedModel._init_weights?  s{    f%fj))NN%%c* %		%,,q&:J:JQ:N*O PFLLHHMM$ *r:   r.   )r/   r0   r1   r2   r   r6   base_model_prefixsupports_gradient_checkpointing_no_split_modules_skip_keys_device_placement_supports_flash_attn_supports_sdpa_is_statefulr  r9   r   r   s   @r;   r  r  3  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$ )
BambaModeliG  r@   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)re   r  r=  )r@   F)r   ra   pad_token_idpadding_idx
vocab_sizer   	EmbeddingrS   embed_tokensrO   rP   rX   r  rH   
ModuleListlayersr   r  rG  final_layernormr   
rotary_embgradient_checkpointing	post_init)r[   r@   decoder_layersr_   r   s       r;   ra   BambaModel.__init__I  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   rg   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   rG   r   r.   rB   )r   r   r   r  r  r   r   T)last_hidden_stater   r   
attentions)r@   r  r  r  r  r  r   rZ  r[  r  r4   rS  rl   rE   r   _update_causal_mask_update_mamba_maskr  r  r  r  rI   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.forward\  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   ri   )sequence_lengthtarget_lengthrF   r   r\   )r  xpunpu)r@   r   ry   r   _ignore_causal_mask_sdpar   rF   rl   r   r4   r~   5_prepare_4d_causal_attention_mask_with_cache_positionrE   r   finfomin_unmask_unattended)r[   r   r  r   r   r  past_seen_tokensrF   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  rF   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_valuerF   rE   r   r(  rG   ri   r   )rk   r4   r  r  fullrE   triurS  r   r   clonerl   rt   r-  )r   r  r  rF   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   )r4   all)r[   r   r   r  s       r;   r   BambaModel._update_mamba_mask4  s:     $
!q ^%?EIIn`aNaDbDbJr:   )r   r  r  r  r  r  r  r  )	NNNNNNNNN)r/   r0   r1   r2   r   ra   r   r   r   r4   r5   r~   r>   r  r,  r   r'   r   r   r  staticmethodr7   rF   r  r   r9   r   r   s   @r;   r  r  G  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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$ )BambaForCausalLMi@  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   )r   ra   r  r  r  r   r   rS   r)  z_loss_coefficientr  r  s     r;   ra   BambaForCausalLM.__init__F  sc     '
 ++yy!3!3V5F5FUS"(";"; 	r:   r  r   r   r   r  labelsr  r  r  r   logits_to_keeprg   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   )r+  r/  r  r   ri   rj   r   rC   )lossr+  r   r   r  r.   )r@   r  r  r  r  r   r7   slicer)  loss_functionr  r-  	logsumexprt   rF   r  r  r   r   r   r  )r[   r  r   r   r   r  r/  r  r  r  r   r0  r   r  r   slice_indicesr+  r2  z_losss                      r;   r   BambaForCausalLM.forwardP  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R                  5        H  u  pX;  d  M  XU'   M     U
$ )Nri   r   r   rG   r  r  )r   r   r  r   r0  r   )rl   r>   r@   rF   rE   longr.  masked_fill_r   rn   num_logits_to_keepitems)r[   r  r   r   r  r   r   r  r   empty_past_kvmodel_inputsr   r   s                r;   prepare_inputs_for_generation.BambaForCausalLM.prepare_inputs_for_generation  s    (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		
 !,,.JC&$)S! ) r:   )r)  r  r  r-  )NNNNNNNNNNr   )NNNNNT)r/   r0   r1   r2   _tied_weights_keys_tp_plan_pp_planra   r   r   r   r4   r5   r~   r>   r  r,  r   r7   r   r   r@  r9   r   r   s   @r;   r(  r(  @  sq   *+=)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
` > >r:   r(  )r  r(  r  )r   )Nr   )Qtypingr   r   r   r   r   r4   r   transformers.activationsr	   cache_utilsr   
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.deprecationr   utils.import_utilsr   r   configuration_bambar   +mamba_ssm.ops.triton.selective_state_updater    !mamba_ssm.ops.triton.ssd_combinedr!   r"   causal_conv1dr#   r$   
get_loggerr/   rZ  r'   r>   Moduler   r   r~   r7   r   r   r   r   r   r  r"  r%  r2  r$  rY  r4  r6  r  r  r  r  r  r(  __all__r.   r:   r;   <module>rZ     s  6 = <   +   ) 7 > 9 O K F & R R 0 V , Rmm!DD-7** 
		H	%	 2Z3 Z3z!<299 !<H(	UU\\ 	U# 	U%,, 	U& %II%<<% 
% <<	%
 U\\*% % % '(%6%PD)RYY D)N; ;*VU\\ VS V
(( 46FH\]^ \_ \_~ryy   Y'J299 J (J(^2 ^B %? % %& u% u up \+_ \ \~ Er:   