
    fTh                       S SK Jr  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s  Js  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(  SSK)J*r*J+r+  SSK,J-r-  \+" 5       (       a  S SK.J/r/  S SK0J1r1J2r2  OSr/\*" 5       (       a	  S SK3J4r4J5r5  OSu  r5r4\(Rl                  " \75      r8 " S S\SS9r9 " S S\Rt                  5      r: " S S\	Rv                  5      r<S  r=S!\R|                  S"\?S#\R|                  4S$ jr@ SHS%\	Rv                  S&\R|                  S'\R|                  S(\R|                  S)\\R|                     S*\AS+\A4S, jjrBSIS- jrC " S. S/\	Rv                  5      rD " S0 S1\R                  Rv                  5      rES2\R|                  S3\?4S4 jrFS5 rGS6 rH\I" \/\4\545      rJS7 rK " S8 S9\	Rv                  5      rL " S: S;\	Rv                  5      rM\" S<5       " S= S>\	Rv                  5      5       rN " S? S@\	Rv                  5      rO\& " SA SB\"5      5       rP\& " SC SD\P5      5       rQ\& " SE SF\P\5      5       rR/ SGQrSg)J    )partial)CallableOptionalTuple	TypedDictUnionN)nn)ACT2FN   )Cache)GenerationMixin)use_kernel_forward_from_hub)AttentionMaskConverter)FlashAttentionKwargs)BaseModelOutputWithPastCausalLMOutputWithPast)ROPE_INIT_FUNCTIONSdynamic_rope_update)ALL_ATTENTION_FUNCTIONSPreTrainedModel)Unpack)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	)
BambaFlashAttentionKwargsA   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/auris/envauris/lib/python3.13/site-packages/transformers/models/bamba/modeling_bamba.pyr&   r&   A   s7    " ######__r9   r&   F)totalc                   P   ^  \ rS rSrSr\R                  S4S\4U 4S jjjrSr	U =r
$ ) HybridMambaAttentionDynamicCache[   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)`.
Nconfigc                 J  > [         T	U ]  XX45        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rD   )super__init__layers_block_typehas_previous_statemamba_d_convmamba_d_stateconv_states
ssm_statestransformer_layersrangenum_hidden_layersr3   zerosmamba_expandhidden_sizemamba_n_groupsmamba_n_headsmamba_d_headtensorappend	key_cachevalue_cache)
selfr?   
batch_sizerE   rD   conv_kernel_sizessm_state_sizei_	__class__s
            r:   rH   )HybridMambaAttentionDynamicCache.__init__i   s   U;!'!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 )rM   rJ   rZ   rI   rN   rO   r[   )r.   r/   r0   r1   r2   r3   float16r   rH   r8   __classcell__rb   s   @r:   r=   r=   [   s)     ?DmmTX %u{ %u %ur9   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   r?   c                   > [         TU ]  5         [        US5      (       aH  UR                  b;  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)rG   rH   hasattrrk   getrl   max_position_embeddingsmax_seq_len_cachedoriginal_max_seq_lenr?   r   rope_init_fnattention_scalingregister_bufferro   original_inv_freq)r\   r?   rD   ro   rb   s       r:   rH   BambaRotaryEmbedding.__init__   s    6>**v/B/B/N#0044[&BUBUBYBYZ`BabDN&DN"("@"@$*$B$B!/?+/+<+<T[[&+Q((ZeD!%r9   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   r   mpscpuF)device_typeenabledrB   dimrE   )ro   floatexpandshapetorD   
isinstancerm   strr3   autocast	transposecatcosrw   sinrE   )
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.)rw   r?   rt   ry   ru   rv   rl   N)r.   r/   r0   r1   r   rH   r3   no_gradr   r   r8   re   rf   s   @r:   rh   rh      s6    /{ / /" ]]_<  <r9   rh   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..Nr|   rB   r   )r   r3   r   )r   x1x2s      r:   rotate_halfr      sZ    	
3"!''"+"""	#B	
3q ""	#B99rc2YB''r9   hidden_statesn_repreturnc                     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)r   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Tr9   modulequerykeyvalueattention_maskscalingdropoutc                 @   [        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$ )NrB   r   r|   )r   rE   )ptrainingr   )r   num_key_value_groupsr3   matmulr   r   r	   
functionalsoftmaxfloat32r   rE   r   r   
contiguous)r   r   r   r   r   r   r   kwargs
key_statesvalue_states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$$r9   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.
r|   .Nr   )	unsqueezer   r   r3   r   )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r9   c                   F  ^  \ 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                     \\
\R                        4   4S jjrSrU =r$ )BambaAttentioni	  z=Multi-headed attention from 'Attention Is All You Need' paperr?   	layer_idxc                 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)rG   rH   r?   r   getattrrT   num_attention_headsr   r   r   r   attention_dropout	is_causalr	   Linearattention_biasq_projk_projv_projo_proj)r\   r?   r   rb   s      r:   rH   BambaAttention.__init__  sI   "
F4F4F&JdJd4de$*$>$>&B\B\$\!}}d*!'!9!9ii : :T]] JQWQfQf
 ii : :T]] JQWQfQf
 ii : :T]] JQWQfQf
 ii&&68J8JQWQfQf
r9   r   position_embeddingsr   past_key_valuecache_positionr   r   c                    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  ad  U R                  R                  S:X  a-  UR                  SS5      (       a  [        R                  S	5        O[         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$ )Nr|   r   rB   )r   r   r   eagersdpaoutput_attentionsFz`torch.nn.functional.scaled_dot_product_attention` does not support `output_attentions=True`. Falling back to eager attention. This warning can be removed using the argument `attn_implementation="eager"` when loading the model.        )r   r   )r   r   r   viewr   r   r   r   updater   r   r?   _attn_implementationrr   loggerwarning_oncer   r   r   r   r   r   r   )r\   r   r   r   r   r   r   input_shapehidden_shapequery_statesr   r   r   r   cache_kwargsattention_interfacer   r   s                     r:   r   BambaAttention.forward#  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{{//69fjjI\^c>d>d##L
 '>dkk>^>^&_#$7	%
  $}}C$2H2HLL	%
 	%
!\ "));;;;FFHkk+.L((r9   )r   r?   r   r   r   r   r   r   r   r   r   r$   )r.   r/   r0   r1   r2   r   r6   rH   r3   Tensorr   r   r   r4   r   r   r   r8   re   rf   s   @r:   r   r   	  s    G
{ 
s 
8 +/590)||0) #5<<#=>0) !.	0)
 !0) !!1!120) -.0) 
u||Xell3XeELL>Q5RR	S0) 0)r9   r   c                   6   ^  \ rS rSrSU 4S jjrSS jrSrU =r$ )BambaRMSNormGatediV  c                    > [         TU ]  5         [        R                  " [        R
                  " U5      5      U l        X l        g r   rG   rH   r	   	Parameterr3   onesweightvariance_epsilonr\   rT   epsrb   s      r:   rH   BambaRMSNormGated.__init__W  s-    ll5::k#:; #r9   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      -  $ NrB   r|   T)keepdim)rE   r   r3   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:::r9   r   r   gư>r   r.   r/   r0   r1   rH   r   r8   re   rf   s   @r:   r   r   V  s    $
	; 	;r9   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   )lenr   r3   r	   r   pad)r
  r  	pad_shapes      r:   pad_tensor_by_sizer  k  sd     47|7I7I3Ja3OAq!Q!Q/VWYZ\]_gijlmUnI88""<ST"UUr9   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   r|   rB   )r  r  r   r   )r
  r  
chunk_sizes      r:   reshape_into_chunksr  v  s     &l=L
<!###L$6$6q$92zK]K]^_K`aa ##q!2z3E3Ea3H,J\J\]^J_
 	
r9   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.
r|   .NrC   diagonalr   r   r   )
sizer   r3   trilr   rD   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r9   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   )r   rE   r   )r   r   rE   s      r:   apply_mask_to_padding_statesr%    s_     !n&:&:1&=&AnFZFZ[\F]`aFa##&1d
)CCGGNr9   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
r?   r   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?rB   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)6rG   rH   rV   	num_headsrT   rL   r_   rK   r^   r6   rS   intermediate_sizer   mamba_conv_biasuse_conv_bias
hidden_act
activationr
   actmamba_proj_biasuse_biasrms_norm_epslayer_norm_epsilonrU   n_groupsrW   r   mamba_chunk_sizer  r   time_step_limittime_step_mintime_step_maxconv_dimr	   Conv1dconv1dr   in_projr   r3   r   dt_biasarangelogA_log_no_weight_decayr   normDout_projis_fast_path_availabler   r   )r\   r?   r   projection_sizeArb   s        r:   rH   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gr9   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   r|   r   .r   T)zrC  dt_softplusr   r   dt_limitF)rI  r  r,   r4  rmsnorm_weightrmsnorm_epsoutproj_weightoutproj_biasheaddimngroupsnorm_before_gatereturn_final_statesrB   )r   swish)r   r   r   r4  r,   )r  rI  rQ  r,   r[  rC  rR  )/r%  rB  r   r:  r_   rJ   rM   r   rN   squeezesplitr0  r?  r/  r#   rA  r   r   r4  r3   exprF  r   r   r   r   r   rC  rI  r   r   rH  rJ  r<  r   r!   r  r   r   r	   r   r  r^   copy_r5  r"   r    )r\   r   rO  r   r   r,   projected_statesr]   seq_lenra   groups_time_state_sizeuse_precomputed_statesr  hidden_states_B_CdtBCrM  rC  rI  hidden_states_reshapedoutdt_limit_kwargshidden_states_B_C_transposedrM   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
r9   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.b2  Ub/  UR                  U R                     R9                  U.5        SUl        U Ro                  UU
5      n3U Rq                  U3R                  U5      5      n4U4$ s  sn f )Nr|   r   r   r   )shiftsdimsrF   rB   .r  ).NNr   rC   )r   output_sizer   r  r   )r   r   T)9r   rE   r%  rB  r^  r0  r?  r/  rJ   rM   r   rN   rollr   rD   rA  r   r3   sumr]  r2  r   r5  r   r	   r   r  r^   r`  r:  r_   r_  rF  r   r   r   rC  softplusclampr<  r   r   r   r   bmmrI  repeat_interleaver  r  r  permuter  r#  
zeros_liker   rH  rJ  )5r\   input_statesrO  r   r   r]   rb  ra   rE   ra  r  re  rf  rd  rM   rl  r   rg  rh  rM  cache_devicerC  dAdBdBxrN   ssm_states_reshaped
C_reshapedyrI  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_statesrn  state_decay_outC_times_statesstate_decay_out_permutedY_offrm  contextualized_statess5                                                        r:   torch_forwardBambaMixer.torch_forward  s9    ".!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 !99hq!Q|&<x&GIL,..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H26/ii4(
 !%knnU.C D$$I &{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   )rK  rB  r   rD   rm   ro  NotImplementedErrorrE   r   r   r  )r\   r   rO  r   r   r,   r   rE   s           r:   r   BambaMixer.forwardx  s     "!f0C0C0J0J0O0O&O,,].jqrr%n  ##%.*>*>q*AA*E.J^J^_`JadeJe*Aq$J-GGKKERM!!-~^^r9   )rF  rI  r5  r4  r  rA  r?  r^   rC  r   rT   rB  r0  r   r9  r:  rH  r/  rJ  r_   r<  r>  r=  r7  r2  )NNNN)NNN)r.   r/   r0   r1   r2   r   r6   rH   r3   r   r   r=   r4   r7   ro  r  r   r8   re   rf   s   @r:   r'  r'    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M% ?@M% !!1!12	M%
 !.M%f DH5915-1_ ?@_ !!1!12	_
 !._ %//*_ _r9   r'  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   )rG   rH   r?   rT   r0  r	   r   mlp_bias	gate_projup_proj	down_projr
   r3  act_fnr\   r?   rb   s     r:   rH   BambaMLP.__init__  s    !--!'!9!94#3#3T5K5KRXRaRabyy!1!143I3IPVP_P_`4#9#94;K;KRXRaRabV../r9   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	r9   )r  r?   r  r  rT   r0  r  r	  rf   s   @r:   r  r    s    0 r9   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:   rH   BambaRMSNorm.__init__  s/     	ll5::k#:; #r9   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   )	rE   r   r3   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:::r9   c                 ^    [        U R                  R                  5       SU R                   3$ )Nz, eps=)tupler   r   r   r\   s    r:   
extra_reprBambaRMSNorm.extra_repr  s*    ))*+6$2G2G1HIIr9   r  r  )	r.   r/   r0   r1   rH   r   r  r8   re   rf   s   @r:   r  r    s    $;J Jr9   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  r?   r   
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.  rA   )r?   r   	attentionzInvalid layer_type)rG   rH   r  feed_forwardr  rT   r8  input_layernormpre_ff_layernormr  r'  rA   r   	self_attn
ValueError)r\   r?   r   r  num_expertsffn_layer_classrb   s         r:   rH   BambaDecoderLayer.__init__  s    &1Q&6(D+F3+F,>,>FDWDWX ,V-?-?VEXEX Y$ #6GDJ;&+F>DN122r9   r   r   r   r   r   	use_cacher   r   r   r   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.
rA   )r   rO  r   r   Nr  )r   r   r   r   r   r  r   r   r-   )r  r  rA   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r9   )r  r  r  rA   r  r  )rA   )NNNFFNN)r.   r/   r0   r1   r   r6   r   rH   r3   r   r   r4   r=   r  r   r   r&   FloatTensorr   r8   re   rf   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r9   r  c                   @    \ rS rSr\rSrSrS/rSr	Sr
SrSrSrS rSrg)	BambaPreTrainedModeli  modelTr  past_key_valuesc                    U R                   R                  n[        U[        R                  [        R
                  45      (       aW  UR                  R                  R                  SUS9  UR                  b%  UR                  R                  R                  5         g g [        U[        [        45      (       a&  UR                  R                  R                  S5        g [        U[        R                  5      (       ad  UR                  R                  R                  SUS9  UR                  b2  UR                  R                  UR                     R                  5         g g [        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 )Nr   )r  stdg      ?r   )r?   initializer_ranger   r	   r   r@  r   datanormal_r   zero_r   r  fill_	Embeddingpadding_idxr'  rC  r3   rE  rD  r/  rF  rI  )r\   r   r  s      r:   _init_weights"BambaPreTrainedModel._init_weights   sc   kk++fryy"))455MM&&CS&9{{&  &&( '!2L ABBMM$$S)--MM&&CS&9!!-""6#5#56<<> .
++NN%%c* %		%,,q&:J:JQ:N*O PFLLHHMM$ ,r9   r-   N)r.   r/   r0   r1   r   config_classbase_model_prefixsupports_gradient_checkpointing_no_split_modules_skip_keys_device_placement_supports_flash_attn_2_supports_sdpa_supports_cache_class_is_statefulr  r8   r-   r9   r:   r  r    s=    L&*#,-"3!N L%r9   r  c                     ^  \ rS rSrS\4U 4S jjrS rS 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\R0                  S\R                  S\4S j5       rS rSrU =r$ )
BambaModeli2  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)r   r  r.  )r?   F)rG   rH   pad_token_idr  
vocab_sizer	   r  rT   embed_tokensrP   rQ   rY   r  rI   
ModuleListlayersr   r  r8  final_layernormrh   
rotary_embgradient_checkpointing	post_init)r\   r?   decoder_layersr`   rb   s       r:   rH   BambaModel.__init__4  s     !.. ++LL):):F<N<NPTP`P`av//0A!!"3FTZTlTlmnTo"pq 1mmN3$*$?$?!+F,>,>FDWDWX.f=&+#r9   c                     U R                   $ r   r  r  s    r:   get_input_embeddingsBambaModel.get_input_embeddingsG  s       r9   c                     Xl         g r   r  r\   r   s     r:   set_input_embeddingsBambaModel.set_input_embeddingsJ  s    !r9   	input_idsr   r   r  inputs_embedsr  r   output_hidden_statesr   r   r   c
                    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$                   H  nUR&                  S	:X  a  UOUnU(       a  X4-  nU R
                  (       a?  U R                  (       a.  U R)                  [+        UR,                  40 U
D6UUUUUUU	U5	      nOU" U4UUUUUU	US
.U
D6nUS   nU(       d  M  US   c  M  UUS   4-  nM     U R/                  U5      nU(       a  X4-  nU(       a  UR0                  (       d  SUl        U(       d  S OUn[3        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   rF   r   r-   rA   )r   r   r   r   r  r   r   T)last_hidden_stater  r   
attentions)r?   r   r  r  r  r  r   r   r   r  r3   rD  r   rD   r   _update_causal_mask_update_mamba_maskr  r  r  _gradient_checkpointing_funcr   __call__r  rJ   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.forwardM  s    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!**t}} $ A AM22=f=! #%"'
! !.!
!#-!-#2&7'#1(;
! 
! *!,M   #/"}Q'7&99NK )N ,,];  !11?#E#E15O.!*T
&+&+%	
 	
r9   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   r   )r  past_key_values_lengthis_trainingr   r|   )sequence_lengthtarget_lengthrE   r   r]   )r  xpunpu)r?   r   get_seq_lengthr   _ignore_causal_mask_sdpar   rE   r   r   r3   r   5_prepare_4d_causal_attention_mask_with_cache_positionrD   rm   finfomin_unmask_unattended)r\   r   r
  r   r  r   past_seen_tokensrE   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r9   r  r  rE   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_valuerE   rD   r   r  rF   r|   r   )r   r3   r  r  fullrD   triurD  r   r   cloner   r   r  )r   r  r  rE   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 r9   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   )r3   all)r\   r   r   r  s       r:   r   BambaModel._update_mamba_mask2  s:     $
!q ^%?EIIn`aNaDbDbJr9   )r   r  r  r  r  r  r  r  )	NNNNNNNNN)r.   r/   r0   r1   r   rH   r  r  r   r   r   r3   r4   r   r=   r  r  r   r&   r   r   r  staticmethodr6   rE   r  r   r8   re   rf   s   @r:   r  r  2  s   { &!"  151537FJ59$(,0/359m
E,,-m
 !.m
 u//0	m

 ""BCm
   1 12m
 D>m
 $D>m
 'tnm
 !!1!12m
 23m
 
!m
  m
^:: ll: 	:
 ::  :x 555 5 {{	5
 5 5 5n	 	r9   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
 r
S 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$ )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                  5         g )NFr   )
rG   rH   r  r  r  r	   r   rT   r+  r  r  s     r:   rH   BambaForCausalLM.__init__D  sU     '
 ++yy!3!3V5F5FUS 	r9   c                 .    U R                   R                  $ r   r  r  r  s    r:   r  %BambaForCausalLM.get_input_embeddingsM  s    zz&&&r9   c                 $    XR                   l        g r   r1  r  s     r:   r  %BambaForCausalLM.set_input_embeddingsP  s    "'

r9   c                     U R                   $ r   r+  r  s    r:   get_output_embeddings&BambaForCausalLM.get_output_embeddingsS  s    ||r9   c                     Xl         g r   r6  )r\   new_embeddingss     r:   set_output_embeddings&BambaForCausalLM.set_output_embeddingsV  s    %r9   c                     Xl         g r   r  )r\   decoders     r:   set_decoderBambaForCausalLM.set_decoderY  s    
r9   c                     U R                   $ r   r>  r  s    r:   get_decoderBambaForCausalLM.get_decoder\  s    zzr9   r  r   r   r  r  labelsr  r   r  r   logits_to_keepr   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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-  rE  r  )lossr-  r  r   r  r-   )r?   r   r  r  r  r   r6   slicer+  loss_functionr  r   r  r   r  )r\   r  r   r   r  r  rE  r  r   r  r   rF  r   r  r   slice_indicesr-  rH  s                     r:   r   BambaForCausalLM.forward_  s   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%#33!//))
 	
r9   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
$ )Nr|   r   r   rF   r  r  )r   r  r  r   rF  r   )r   r=   r?   rE   rD   longr  masked_fill_r   r   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		
 r9   )r+  r  r  )NNNNNNNNNNr   )NNNNNT)r.   r/   r0   r1   _tied_weights_keys_tp_plan_pp_planrH   r  r  r7  r;  r@  rC  r   r   r   r3   r4   r   r=   r  r  r   r6   r   r   rS  r8   re   rf   s   @r:   r*  r*  >  s   *+=)H_-z:;H'(&  151537FJ59-1$(,0/35934G
E,,-G
 !.G
 u//0	G

 ""BCG
   1 12G
 ))*G
 D>G
 $D>G
 'tnG
 !!1!12G
 c5<</0G
 
 G
  G
X 8 8r9   r*  )r  r*  r  )r   )Nr   )T	functoolsr   typingr   r   r   r   r   r3   r	   (transformers.models.jamba.modeling_jambamodelsjambamodeling_jambatransformers.activationsr
   cache_utilsr   
generationr   integrationsr   modeling_attn_mask_utilsr   modeling_flash_attention_utilsr   modeling_outputsr   r   modeling_rope_utilsr   r   modeling_utilsr   r   processing_utilsr   utilsr   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_loggerr.   r   r&   r=   Modulerh   r   r   r6   r   r   r   r   r   r   r  r  r#  r&  rK  r%  r'  r  r  r  r  r  r*  __all__r-   r9   r:   <module>rq     s  6  > >   A A +   ) 7 > B O K F & > > V , Rmm!DD-7** 
		H	%	 43u~'V'V 3ul<299 <D(	UU\\ 	U# 	U%,, 	U& %II%<<% 
% <<	%
 U\\*% % %6%PJ)RYY J)Z; ;*VU\\ VS V
(( 46FH\]^ __ __Dryy   Y'J299 J (J(]		 ]@ %? % %: H% H HV c+_ c cL Er9   