
    <h                        S r SSKJrJrJr  SSKrSSK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JrJrJrJr  SSKJrJrJrJr  S	S
KJr  S	SKJr  S	SKJrJr  S	SK J!r!  S	SK"J#r#  S	SK$J%r%J&r&J'r'  S	SK(J)r)J*r*  SSK+J,r,  \*" 5       (       a  SSK-J.r.  SSK/J0r0J1r1  OSr.\)" 5       (       a	  SSK2J3r3J4r4  OSu  r4r3\5" \.\3\445      r6\'Rn                  " \85      r9 " S S\SS9r: " S S\5      r " S S\5      r;S4S jr< " S  S!\5      r= " S" S#\5      r>S$ r? " S% S&\R                  5      rA " S' S(\5      rB " S) S*\5      rC " S+ S,\5      rD\% " S- S.\!5      5       rE\% " S/ S0\E5      5       rF " S1 S2\5      rG/ S3QrHg)5zPyTorch Bamba model.    )Optional	TypedDictUnionN)nn)ACT2FN) HybridMambaAttentionDynamicCacheJambaAttentionDecoderLayer)LlamaAttentionLlamaForCausalLMLlamaMLPLlamaRMSNormLlamaRotaryEmbeddingrotate_half)MambaRMSNormGatedpad_tensor_by_sizereshape_into_chunkssegment_sum   )DynamicLayer)AttentionMaskConverter)BaseModelOutputWithPastCausalLMOutputWithPast)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	)
BambaFlashAttentionKwargsL   aR  
Keyword arguments for advanced Flash Attention, causal-conv1d, and mamba_ssm kernel usage.
Use cases include padding-free training and fewer `torch.compile` graph breaks.

Attributes:
    cu_seq_lens_q (`torch.LongTensor`)
        Gets cumulative sequence length for query state.
    cu_seq_lens_k (`torch.LongTensor`)
        Gets cumulative sequence length for key state.
    max_length_q (`int`):
        Maximum sequence length for query state.
    max_length_k (`int`):
        Maximum sequence length for key state.
    seq_idx (`torch.IntTensor):
        Index of each packed sequence.
cu_seq_lens_qcu_seq_lens_kmax_length_qmax_length_kseq_idx N)__name__
__module____qualname____firstlineno____doc__torch
LongTensor__annotations__int	IntTensor__static_attributes__r/       _/var/www/html/shao/venv/lib/python3.13/site-packages/transformers/models/bamba/modular_bamba.pyr(   r(   L   s7    " ######__r;   r(   F)totalc                   B    \ rS rSrSr\R                  S4S\4S jjrSr	g)r   f   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                 T   [         R                  " [        S9  UR                  U l        SU l        UR
                  nUR                  n/ U l        / U l        / U l	        [        UR                  5       GH%  nU R                  U   S:X  a  U =R                  [        R                  " UUR                  UR                  -  SUR                   -  U-  -   UUUS9/-  sl        U =R                  [        R                  " UUR"                  UR$                  UUUS9/-  sl        M  U =R                  [        R&                  " / /U-  US9/-  sl        U =R                  [        R&                  " / /U-  US9/-  sl        U R                  R)                  U5        GM(     [        UR                  5       Vs/ sH  n[        R&                  " / /U-  US9PM     snU l        [        UR                  5       Vs/ sH  n[        R&                  " / /U-  US9PM     snU l        g s  snf s  snf )N)layer_classesFmamba   devicedtyperF   )r   __init__r   layers_block_typehas_previous_statemamba_d_convmamba_d_stateconv_states
ssm_statestransformer_layersrangenum_hidden_layersr5   zerosmamba_expandhidden_sizemamba_n_groupsmamba_n_headsmamba_d_headtensorappend	key_cachevalue_cache)	selfr@   
batch_sizerG   rF   conv_kernel_sizessm_state_sizei_s	            r<   rI   )HybridMambaAttentionDynamicCache.__init__t   s   (11M!'!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   4"H 5"H%)rN   rK   r[   rJ   rO   rP   r\   )
r0   r1   r2   r3   r4   r5   float16r!   rI   r:   r/   r;   r<   r   r   f   s(     ?DmmTX %u{ %u %ur;   r   c                       \ rS rSrSrg)BambaRotaryEmbedding   r/   Nr0   r1   r2   r3   r:   r/   r;   r<   rf   rf          r;   rf   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.
.Ndim)	unsqueezeshaper   r5   cat)qkcossinposition_idsunsqueeze_dim
rotary_dimq_rotq_passk_rotk_passq_embedk_embeds                r<   apply_rotary_pos_embr~      s    , --
&C
--
&C 2Jc;J;&'3
+;)<6c;J;&'3
+;)<6 {{51C78G{{51C78G ii)r2Gii)r2Gr;   c                       \ rS rSrSrg)BambaAttention   r/   Nrh   r/   r;   r<   r   r      ri   r;   r   c                       \ rS rSrSrg)BambaRMSNormGated   r/   Nrh   r/   r;   r<   r   r      ri   r;   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   )ro   rG   to)hidden_statesattention_maskrG   s      r<   apply_mask_to_padding_statesr      s_     !n&:&:1&=&AnFZFZ[\F]`aFa##&1d
)CCGGNr;   c                     ^  \ rS rSrSrS\S\4U 4S jjr    SS\R                  S\
\   S\
\R                     S	\
\R                     S
\
\R                     4
S jjr   SS\
\   S\
\R                     S	\
\R                     4S jjr    SS\
\   S\
\R                     S	\
\R                     S
\
\R                     4S jjrSrU =r$ )
BambaMixer   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@   	layer_idxc           	        > [         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 )N        infgMbP?g?rD   r    )in_channelsout_channelsbiaskernel_sizegroupspadding)r   Tepsa  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)6superrI   rW   	num_headsrU   rM   r`   rL   r_   r8   rT   intermediate_sizer   mamba_conv_biasuse_conv_bias
hidden_act
activationr   actmamba_proj_biasuse_biasrms_norm_epslayer_norm_epsilonrV   n_groupsrX   head_dimmamba_chunk_size
chunk_sizefloattime_step_limittime_step_mintime_step_maxconv_dimr   Conv1dconv1dLinearin_proj	Parameterr5   onesdt_biasarangelogA_log_no_weight_decayr   normDout_projis_fast_path_availableloggerwarning_once)r]   r@   r   projection_sizeA	__class__s        r<   rI   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_paramscache_positionr   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   rk   rl   .rG   T)zr   dt_softplusr   r   dt_limitF)r   r   r.   r   rmsnorm_weightrmsnorm_epsoutproj_weightoutproj_biasheaddimngroupsnorm_before_gatereturn_final_statesrD   )siluswish)xweightr   r   r.   )r   r   r   r.   r   r   r   )/r   r   ro   r   r`   rK   rN   r   rO   squeezesplitr   r   r   r&   r   r   r   r   r5   expr   r   expandr   r   float32r   r   viewr"   r   r   r   trainingr$   r   variance_epsilon	transposer   
functionalpadr_   copy_r   r%   r#   )r]   r   r   r   r   r.   projected_statesr^   seq_lenrb   groups_time_state_sizeuse_precomputed_statesgatehidden_states_B_CdtBCr   r   r   hidden_states_reshapedoutdt_limit_kwargshidden_states_B_C_transposedrN   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 )Nrk   rl   r    r   )shiftsdimsrH   rD   .).N).NNr   rE   )rm   output_sizer      )r    r   )9ro   rG   r   r   r   r   r   r   rK   rN   r   rO   rollr   rF   r   r   r5   sumr   r   r   r   r   r   r   r   r_   r   r   r`   r   r   r   r   r   r   softplusclampr   r   reshape
contiguousr   bmmr   repeat_interleaver   r   r   permutecumsumr   
zeros_likerp   r   r   )5r]   input_statesr   r   r   r^   r   rb   rG   r   r   r   r   r   rN   r   r   r   r   r   cache_devicer   dAdBdBxrO   ssm_states_reshaped
C_reshapedyr   pad_size
D_residualtA_cumsumLG_intermediateGM_intermediateMY_diagdecay_statesB_decaystatesprevious_statesdecay_chunk
new_statesr   state_decay_outC_times_statesstate_decay_out_permutedY_offr   contextualized_statess5                                                        r<   torch_forwardBambaMixer.torch_forward  s1    ".!3!3
Q"" 4LQ<<5&6&<&<''GR '= '
#
 $ &//&1& ((8>>qA&&t~~6<<Q? & d*& q!A% 	 "7C7O7OPTP^P^7_7d7dlnuw7d7xL$$T^^4ARSTVWYZSZA[A^A^_k_w_wx|  yG  yG  `H  `O  `O  BPL$$T^^4Q2X> '224>>BEET[[M_M_MfMfEgK %		kk0088;;! !!$58H8H$H! $): ; '/@/J/J1a/P, mm//03H3HKgKmKmnpKq3qst2u ((8>>{K $5F5P5PQRTU5V)WX[]e^e]eXe)f)p)pqrtu)v w89J[#kk##T]]T5H5H%H$--Z^ZmZmJmn
q! YYtzz'')**!'224>>BIIL Aq!GQc\*Ba#**:xx|T]]SBll9-44T\\5G5G5JDMMZG$$--b7::bhh3G.GHBR!5!5a!8$:N:Nq:QRB/"))$..$--I\I\]``glgtgt`uA))ByMA-.22,2GB
 		*mmR8dAFA]]DNNdmm4SUVU\U\]_U`allnA		*b!''"+6AI3a<0B *11*b$--PMi0044L4IC ##DNN399''7"<sB 		*mmR8dAFA]]DNNdmm4SUVU\U\]_U`allnA		*b!''"+6A &00@CC188[\[b[bCcJ",//*~~2Mt}}^b^q^q"r
^^ ;T=P=PRSTJ		-z:Az>>4==AA y!((a$--HA]Q&&**1773A 		*b)!T3,7A ''\\(9:BR!5!5a!8$:N:Nq:QRB)11*r4==Y__aM		*r43F3FGMMOA		*r43F3FGMMOA##DNNdmm$CX\XfXf#gA##DNNdmm$CX\XfXf#gA'OO*CCtVH	*-?x-XXJ *ByM9M](()B.A cpqrtuwxay%zay\]&9!Xt&Way%z"M1a 		!Q1%A||A2.H 		+a.)A q!Qa23a1dAq!8K6LLN""r"*A y\AIIaAq!,DY,OON""r"*A 	l]1a:%>>CCCJF !99XaArsl%;h%FGL,..q"b!<YGGGc4l+mI.FFKKPQKRF &"."9"9$.."I!TSV,"W"Z"Zbhbobo"Z"p"'"2"26!RaR%="AYY8a@F))K0A0A(1aQRTV;BWY_0`$abK%//15K%o61dC9PPUUZ[U\J *1crc6 2Jq"u4EIF $ii1OT1oq!T30GGN'6'>'>q!Q'J$#''+.Fy.QQE A		*b$..$--HAJA!|a'1a'(		*r2A $)A''7==iHii4(
 !%knnU.C D$$G &{s    u?c                 ~   [         (       aA  SU R                  R                  R                  R                  ;   a  U R                  XX4U5      $ Ub  [        S5      eUR                  nUbC  UR                  S   S:  a0  UR                  S   S:  a  XS S 2S S 2S 4   -  R                  U5      nU R                  XX45      $ )Ncudaz\`seq_idx` support requires fast path support. Please install `mamba_ssm` and `causal_conv1d`r    r   )r   r   r   rF   typer   NotImplementedErrorrG   ro   r   r!  )r]   r   r   r   r   r.   kwargsrG   s           r<   forwardBambaMixer.forward  s     "!f0C0C0J0J0O0O&O,,].jqrr%n  ##%.*>*>q*AA*E.J^J^_`JadeJe*Aq$J-GGKKERM!!-~^^r;   )r   r   r   r   r   r   r   r_   r   r   rU   r   r   r   r   r   r   r   r   r`   r   r   r   r   r   )NNNN)NNN)r0   r1   r2   r3   r4   r!   r8   rI   r5   Tensorr   r   r6   r9   r   r!  r(  r:   __classcell__r   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L% ?@L% !!1!12	L%
 !.L%d DH5915-1_ ?@_ !!1!12	_
 !._ %//*_ _r;   r   c                       \ rS rSrSrg)BambaMLPi  r/   Nrh   r/   r;   r<   r.  r.    ri   r;   r.  c                       \ rS rSrSrg)BambaRMSNormi  r/   Nrh   r/   r;   r<   r0  r0    ri   r;   r0  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         U ?SnUS:X  a  [        OS nU" U5      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    rC   )r@   r   	attentionzInvalid layer_type)
r   rI   	self_attnr.  feed_forwardr3  r   rC   r   
ValueError)r]   r@   r   r3  num_expertsffn_layer_classr   s         r<   rI   BambaDecoderLayer.__init__  sl    N&1Q&6(D+F3$ #6GDJ;&+F>DN122r;   r   r   ru   past_key_valueoutput_attentions	use_cacher   position_embeddingsr'  returnc	                 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.
rC   )r   r   r   r   Nr5  )r   r   ru   r<  r=  r>  r   r?  r/   )input_layernormr3  rC   r6  pre_ff_layernormr7  )r]   r   r   ru   r<  r=  r>  r   r?  r'  residualself_attn_weightsoutputss                r<   r(  BambaDecoderLayer.forward  s    D !,,]; ??g% JJ ++--	
 M !%__+/3~~ 
0+-)-"3#-$7
0 
0,M !0 !--m<))-8 0 ")++Gr;   )r7  r3  rC   r6  )rC   )NNNFFNN)r0   r1   r2   r3   r!   r8   strrI   r5   r*  r   r6   r   booltupler   r(   FloatTensorr(  r:   r+  r,  s   @r<   r2  r2    s*   3{ 3s 3 3 3( 2637EI,1$)59KOK||K !.K u//0	K
 !!ABK $D>K D>K !!1!12K &eELL%,,,F&GHK 23K 
u  (51B1BEDUDU1U+V"WW	XK Kr;   r2  c                   R   ^  \ rS rSr% \\S'   SrSrS/rSr	Sr
SrSrU 4S jrSrU =r$ )	BambaPreTrainedModeli&  r@   modelTr2  past_key_valuesc                 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_weights
isinstancer   r   datafill_r5   r   r   r   r   r   )r]   moduler   s     r<   rQ  "BambaPreTrainedModel._init_weights2  s{    f%fj))NN%%c* %		%,,q&:J:JQ:N*O PFLLHHMM$ *r;   r/   )r0   r1   r2   r3   r!   r7   base_model_prefixsupports_gradient_checkpointing_no_split_modules_skip_keys_device_placement_supports_flash_attn_supports_sdpa_is_statefulrQ  r:   r+  r,  s   @r<   rM  rM  &  s>    &*#,-"3NL% %r;   rM  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$ )
BambaModeli:  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   r3  r   )r@   F)r   rI   pad_token_idpadding_idx
vocab_sizer   	EmbeddingrU   embed_tokensrQ   rR   rZ   r2  rJ   
ModuleListlayers_attn_implementationr0  r   final_layernormrf   
rotary_embgradient_checkpointing	post_init)r]   r@   decoder_layersra   r   s       r<   rI   BambaModel.__init__<  s     !.. ++LL):):F<N<NPTP`P`av//0A!!"3FTZTlTlmnTo"pq 1mmN3$*$?$?!+F,>,>FDWDWX.f=&+#r;   	input_idsr   ru   rO  inputs_embedsr>  r=  output_hidden_statesr   r'  r@  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    rH   r   r/   rC   )r   ru   r<  r=  r>  r   r?  T)last_hidden_staterO  r   
attentions)r@   r=  rq  r>  r8  rk  r   r   r   re  r5   r   ro   rF   rn   _update_causal_mask_update_mamba_maskrj  rg  r3  ri  rK   r   )r]   ro  r   ru   rO  rp  r>  r=  rq  r   r'  r   causal_mask
mamba_maskr?  all_hidden_statesall_self_attnsdecoder_layer
layer_masklayer_outputs
next_caches                        r<   r(  BambaModel.forwardO  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;   input_tensorc           	         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)rp  past_key_values_lengthis_trainingr    rk   )sequence_lengthtarget_lengthrG   r   r^   )r$  xpunpu)r@   rh  get_seq_lengthr   _ignore_causal_mask_sdpar   rG   ro   rR  r5   r*  5_prepare_4d_causal_attention_mask_with_cache_positionrF   r%  finfomin_unmask_unattended)r]   r   r  r   rO  r=  past_seen_tokensrG   r  r  rw  	min_dtypes               r<   ru  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  rG   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_valuerG   rF   r    )diagonalrH   rk   r   )rm   r5   r  r  fullrF   triur   r   r   clonero   r   masked_fill)r   r  r  rG   r   r^   r'  rw  r  mask_lengthpadding_attention_maskpadding_masks               r<   r  @BambaModel._prepare_4d_causal_attention_mask_with_cache_position  s   < %.*<*<*>!*C(K, ) E*..I** 0Y\j\q\qK !##jjqA5<<>S>STWeWmWmnprsWtttK%dD!Q&67>>z1bRTUK))//1,2226*8D$9I*Jn]^`dfgim]mNn*nq?*+Q.*"U) '  +1aL[L+@ADZZ+q05@Aq,;,AV5W5c5c 6Aq!\k\12 r;   c                 b    UnUS   S:  d!  Ub   [         R                  " US:H  5      (       a  SnU$ )zV
No need for zeroing states when
    1. Cached forward
    2. Attending to all inputs
r   Nr    )r5   all)r]   r   r   rx  s       r<   rv  BambaModel._update_mamba_mask'  s:     $
!q ^%?EIIn`aNaDbDbJr;   )rh  re  ri  rk  rg  rb  rj  rc  )	NNNNNNNNN)r0   r1   r2   r3   r!   rI   r   r   r   r5   r6   r*  r   rK  rI  r   r(   r   r(  ru  staticmethodr8   rG   r  rv  r:   r+  r,  s   @r<   r_  r_  :  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                   d  ^  \ rS rS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r      SS jrSrU =r$ )BambaForCausalLMi3  c                 f   > [         TU ]  U5        UR                  U l        U R                  5         g )N)r   rI   z_loss_coefficientrl  )r]   r@   r   s     r<   rI   BambaForCausalLM.__init__4  s*     "(";"; 	r;   ro  r   ru   rO  rp  labelsr>  r=  rq  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 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)	ro  r   ru   rO  rp  r>  r=  rq  r   )logitsr  rc  r   rk   rl   r   rD   )lossr  rO  r   rt  r/   )r@   r=  rq  rN  rs  rR  r8   slicelm_headloss_functionrc  r  	logsumexpr   rG   powmeanr   rO  r   rt  )r]   ro  r   ru   rO  rp  r  r>  r=  rq  r   r  r'  rF  r   slice_indicesr  r  z_losss                      r<   r(  BambaForCausalLM.forward;  st   J 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
$ )Nrk   r    r   rH   rp  ro  )ru   rO  r>  r   r  r   )ro   r   r@   rG   rF   longr  masked_fill_r   updatenum_logits_to_keep)r]   ro  rO  r   rp  r   ru   r>  r'  empty_past_kvmodel_inputss              r<   prepare_inputs_for_generation.BambaForCausalLM.prepare_inputs_for_generation  sb    (4/ )!"%);;%a.*>*>q*A)A)C&CD	#~';';A'>>%a&78	>Y__Q/DKKO %,*>)..077;a?L%%n&91= +A	0B/B/D,DE $+];L')=)=)?@L ,#2&"0"&++"@"@"0		
 r;   )r  )NNNNNNNNNNr   )NNNNNT)r0   r1   r2   r3   rI   r   r5   r6   r*  r   rK  rI  r   r8   r   r(  r  r:   r+  r,  s   @r<   r  r  3  s2    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
` 8 8r;   r  )r_  r  rM  )Nr    )Ir4   typingr   r   r   r5   torch.utils.checkpointr   transformers.activationsr   (transformers.models.jamba.modeling_jambar   r	   (transformers.models.llama.modeling_llamar
   r   r   r   r   r   *transformers.models.mamba2.modeling_mamba2r   r   r   r   cache_utilsr   modeling_attn_mask_utilsr   modeling_outputsr   r   modeling_utilsr   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&   r  r   
get_loggerr0   r   r(   rf   r~   r   r   r   Moduler   r.  r0  r2  rM  r_  r  __all__r/   r;   r<   <module>r     s  (  - -    + q   ( > O - & 
 W , Rmm!DD-7**46FH\]^  
		H	%	 43u'G 3ul	/ 	
%P	^ 		) 	^_ ^_B	x 		< 	]2 ]@ %? % %& u% u upM' M` Er;   