
    fTh                     4   S r SSKJr  SSKJrJrJrJr  SSK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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!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-J.r.  SSK/J0r0  \-" 5       (       a   \." 5       (       a  SSK1J2r2  SSK3J4r4J5r5  OSr2\," 5       (       a	  SSK6J7r7J8r8  OSu  r8r7\9" \2\7\845      r:\*Rv                  " \<5      r= " S S\SS9r> " S S\R~                  5      r? " S S\5      r@S4S jrA " S  S!\5      rB " S" S#\5      rCS$ rD " S% S&\
R                  5      rF " S' S(\5      rG " S) S*\5      rH " S+ S,\5      rI\( " S- S.\$5      5       rJ\( " S/ S0\J5      5       rK " S1 S2\5      rL/ S3QrMg)5zPyTorch Bamba model.    )partial)OptionalTuple	TypedDictUnionN)nn)ACT2FN)JambaAttentionDecoderLayer)LlamaAttentionLlamaForCausalLMLlamaMLPLlamaRMSNormLlamaRotaryEmbeddingrotate_half)MambaRMSNormGatedpad_tensor_by_sizereshape_into_chunkssegment_sum   )AttentionMaskConverter)BaseModelOutputWithPastCausalLMOutputWithPast)PreTrainedModel)Unpack)auto_docstringcan_return_tuplelogging)is_causal_conv1d_availableis_flash_attn_2_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	)
BambaFlashAttentionKwargsP   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__r0       _/var/www/auris/envauris/lib/python3.13/site-packages/transformers/models/bamba/modular_bamba.pyr)   r)   P   s7    " ######__r<   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
$ ) HybridMambaAttentionDynamicCachej   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rG   )super__init__layers_block_typehas_previous_statemamba_d_convmamba_d_stateconv_states
ssm_statestransformer_layersrangenum_hidden_layersr6   zerosmamba_expandhidden_sizemamba_n_groupsmamba_n_headsmamba_d_headtensorappend	key_cachevalue_cache)
selfrB   
batch_sizerH   rG   conv_kernel_sizessm_state_sizei_	__class__s
            r=   rK   )HybridMambaAttentionDynamicCache.__init__x   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 )rP   rM   r]   rL   rQ   rR   r^   )r1   r2   r3   r4   r5   r6   float16r"   rK   r;   __classcell__re   s   @r=   r@   r@   j   s)     ?DmmTX %u{ %u %ur<   r@   c                       \ rS rSrSrg)BambaRotaryEmbedding   r0   Nr1   r2   r3   r4   r;   r0   r<   r=   rk   rk          r<   rk   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   r6   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   r0   Nrm   r0   r<   r=   r   r      rn   r<   r   c                       \ rS rSrSrg)BambaRMSNormGated   r0   Nrm   r0   r<   r=   r   r      rn   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   )rt   rH   to)hidden_statesattention_maskrH   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
rB   	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?rE   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)6rJ   rK   rY   	num_headsrW   rO   rb   rN   ra   r9   rV   intermediate_sizer   mamba_conv_biasuse_conv_bias
hidden_act
activationr	   actmamba_proj_biasuse_biasrms_norm_epslayer_norm_epsilonrX   n_groupsrZ   head_dimmamba_chunk_size
chunk_sizefloattime_step_limittime_step_mintime_step_maxconv_dimr   Conv1dconv1dLinearin_proj	Parameterr6   onesdt_biasarangelogA_log_no_weight_decayr   normDout_projis_fast_path_availableloggerwarning_once)r_   rB   r   projection_sizeAre   s        r=   rK   BambaMixer.__init__   s   --!--$22 & 3 3!$V%8%84;K;K%K!L"#33 ++&++,.."("5"5--++ 11 !$U5\2" ..T]]1BTEXEX1XXii''--==))A-
 004==@4>>Qyy
 ||EJJt~~$>? LLDNNQ./\\%))A,/
&*

#%d&<&<$BYBYZ	ejj89"&		$"8"8$:J:JQUQ^Q^_%%>  fgr<   r   cache_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   rp   rq   .rH   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_statesrE   )siluswish)xweightr   r   r/   )r   r   r   r/   r   r   r   )/r   r   rt   r   rb   rM   rP   r   rQ   squeezesplitr   r   r   r'   r   r   r   r   r6   expr   r   expandr   r   float32r   r   viewr#   r   r   r   trainingr%   r   variance_epsilon	transposer   
functionalpadra   copy_r   r&   r$   )r_   r   r   r   r   r/   projected_statesr`   seq_lenrd   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_transposedrP   scan_output	ssm_states                              r=   cuda_kernels_forwardBambaMixer.cuda_kernels_forward2  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.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 )Nrp   rq   r!   r   )shiftsdimsrI   rE   .).N).NNr   rF   )rr   output_sizer      )r!   r   T)9rt   rH   r   r   r   r   r   r   rM   rP   r   rQ   rollr   rG   r   r   r6   sumr   r   r   r   r   r   r   r   ra   r   r   rb   r   r   r   r   r   r   softplusclampr   r   reshape
contiguousr   bmmr   repeat_interleaver   r   r   permutecumsumr   
zeros_likeru   r   r   )5r_   input_statesr   r   r   r`   r   rd   rH   r   r   r   r   r   rP   r   r   r   r   r   cache_devicer   dAdBdBxrQ   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  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   )r   r   r   rG   typer   NotImplementedErrorrH   rt   r   r$  )r_   r   r   r   r   r/   kwargsrH   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   ra   r   r   rW   r   r   r   r   r   r   r   r   rb   r   r   r   r   r   )NNNN)NNN)r1   r2   r3   r4   r5   r"   r9   rK   r6   Tensorr   r@   r7   r:   r   r$  r+  r;   rh   ri   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	_
 !._ %//*_ _r<   r   c                       \ rS rSrSrg)BambaMLPi  r0   Nrm   r0   r<   r=   r/  r/    rn   r<   r/  c                       \ rS rSrSrg)BambaRMSNormi  r0   Nrm   r0   r<   r=   r1  r1    rn   r<   r1  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  rB   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!   rD   )rB   r   	attentionzInvalid layer_type)
rJ   rK   	self_attnr/  feed_forwardr4  r   rD   r   
ValueError)r_   rB   r   r4  num_expertsffn_layer_classre   s         r=   rK   BambaDecoderLayer.__init__  sl    N&1Q&6(D+F3$ #6GDJ;&+F>DN122r<   r   r   rz   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.
rD   )r   r   r   r   Nr6  )r   r   rz   r=  r>  r?  r   r@  r0   )input_layernormr4  rD   r7  pre_ff_layernormr8  )r_   r   r   rz   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<   )r8  r4  rD   r7  )rD   )NNNFFNN)r1   r2   r3   r4   r"   r9   strrK   r6   r-  r   r7   r@   boolr   r   r)   FloatTensorr+  r;   rh   ri   s   @r=   r3  r3    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<   r3  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+  modelTr3  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   )meanstdg      ?r!   )rB   initializer_range
isinstancer   r   r   r   datanormal_r   zero_r   r1  fill_	Embeddingpadding_idxr   r   r6   r   r   r   r   r   )r_   modulerR  s      r=   _init_weights"BambaPreTrainedModel._init_weights7  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$ ,r<   r0   N)r1   r2   r3   r4   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\  r;   r0   r<   r=   rM  rM  +  s=    L&*#,-"3!N L%r<   rM  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$ )
BambaModeliI  rB   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   r4  r   )rB   F)rJ   rK   pad_token_idrZ  
vocab_sizer   rY  rW   embed_tokensrS   rT   r\   r3  rL   
ModuleListlayers_attn_implementationr1  r   final_layernormrk   
rotary_embgradient_checkpointing	post_init)r_   rB   decoder_layersrc   re   s       r=   rK   BambaModel.__init__K  s     !.. ++LL):):F<N<NPTP`P`av//0A!!"3FTZTlTlmnTo"pq 1mmN3$*$?$?!+F,>,>FDWDWX.f=&+#r<   c                     U R                   $ Nrl  )r_   s    r=   get_input_embeddingsBambaModel.get_input_embeddings^  s       r<   c                     Xl         g rw  rx  )r_   values     r=   set_input_embeddingsBambaModel.set_input_embeddingsa  s    !r<   	input_idsr   rz   rO  inputs_embedsr?  r>  output_hidden_statesr   r*  rA  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!   rI   r   r0   rD   )r   rz   r=  r>  r?  r   r@  T)last_hidden_staterO  r   
attentions)rB   r>  r  r?  r9  rr  r   r   r   rl  r6   r   rt   rG   rs   _update_causal_mask_update_mamba_maskrq  rn  r4  _gradient_checkpointing_funcr   __call__rp  rM   r   )r_   r  r   rz   rO  r  r?  r>  r  r   r*  r   causal_mask
mamba_maskr@  all_hidden_statesall_self_attnsdecoder_layer
layer_masklayer_outputs
next_caches                        r=   r+  BambaModel.forwardd  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
&+&+%	
 	
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)r  past_key_values_lengthis_trainingr!   rp   )sequence_lengthtarget_lengthrH   r   r`   )r'  xpunpu)rB   ro  get_seq_lengthr   _ignore_causal_mask_sdpar   rH   rt   rT  r6   r-  5_prepare_4d_causal_attention_mask_with_cache_positionrG   r(  finfomin_unmask_unattended)r_   r   r  r   rO  r>  past_seen_tokensrH   r  r  r  	min_dtypes               r=   r  BambaModel._update_causal_mask  sc    ;;++/BB)c^.C%%
 @O?Z?99;`a ;;++v5>O%>>*'7 MM	 ""&,,Q/ .%,,77   $!3a7 	 PP+')#))!, Q 
 KK,,6*%%**.DD%
 E*..I0CCK[Kr<   r  r  rH   r`   c                    U b  U R                  5       S:X  a  U nU$ [        R                  " U5      R                  n[        R                  " X4XUR
                  S9nUS:w  a  [        R                  " USS9nU[        R                  " X$R
                  S9UR                  SS5      :  -  nUSSSS2SS24   R                  USSS5      nU b  UR                  5       nU R                  S   n	U SS2SSSS24   U SS2SSS2S4   :H  SS2SS2U* S2SS24   R                  U5      n
USS2SS2SS2SU	24   U
-   nUS:H  nUSS2SS2SS2SU	24   R                  X5      USS2SS2SS2SU	24'   U$ )	a  
Creates a causal 4D mask of shape `(batch_size, 1, query_length, key_value_length)` from a 2D mask of shape
`(batch_size, key_value_length)`, or if the input `attention_mask` is already 4D, do nothing.

Args:
    attention_mask (`torch.Tensor`):
        A 2D attention mask of shape `(batch_size, key_value_length)` or a 4D attention mask of shape
        `(batch_size, 1, query_length, key_value_length)`.
    sequence_length (`int`):
        The sequence length being processed.
    target_length (`int`):
        The target length: when generating with static cache, the mask should be as long as the static cache,
        to account for the 0 padding, the part of the cache that is not filled yet.
    dtype (`torch.dtype`):
        The dtype to use for the 4D attention mask.
    cache_position (`torch.Tensor`):
        Indices depicting the position of the input sequence tokens in the sequence.
    batch_size (`torch.Tensor`):
        Batch size.
Nr   )
fill_valuerH   rG   r!   )diagonalrI   rp   r   )rr   r6   r  r  fullrG   triur   r   r   clonert   r   masked_fill)r   r  r  rH   r   r`   r*  r  r  mask_lengthpadding_attention_maskpadding_masks               r=   r  @BambaModel._prepare_4d_causal_attention_mask_with_cache_position  s   < %.*<*<*>!*C(K, ) E*..I** 0Y\j\q\qK !##jjqA5<<>S>STWeWmWmnprsWtttK%dD!Q&67>>z1bRTUK))//1,2226*8D$9I*Jn]^`dfgim]mNn*nq?*+Q.*"U) '  +1aL[L+@ADZZ+q05@Aq,;,AV5W5c5c 6Aq!\k\12 r<   c                 b    UnUS   S:  d!  Ub   [         R                  " US:H  5      (       a  SnU$ )zV
No need for zeroing states when
    1. Cached forward
    2. Attending to all inputs
r   Nr!   )r6   all)r_   r   r   r  s       r=   r  BambaModel._update_mamba_maskI  s:     $
!q ^%?EIIn`aNaDbDbJr<   )ro  rl  rp  rr  rn  rZ  rq  rk  )	NNNNNNNNN)r1   r2   r3   r4   r"   rK   ry  r}  r   r   r   r6   r7   r-  r@   rK  rJ  r   r)   r   r+  r  staticmethodr9   rH   r  r  r;   rh   ri   s   @r=   rh  rh  I  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	 	r<   rh  c                   ^  ^  \ 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U 4S jjjr      SS jrSrU =r$ )BambaForCausalLMiU  r  r   rz   rO  r  labelsr?  r>  r  r   logits_to_keeprA  c                 :   > [         TU ]  " UUUUUUUUU	U
U40 UD6$ )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."
```)rJ   r+  )r_   r  r   rz   rO  r  r  r?  r>  r  r   r  r*  re   s                r=   r+  BambaForCausalLM.forwardV  sB    J w 
 
 	
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
$ )Nrp   r!   r   rI   r  r  )rz   rO  r?  r   r  r   )rt   r@   rB   rH   rG   longr  masked_fill_r  updatenum_logits_to_keep)r_   r  rO  r   r  r   rz   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<   r0   )NNNNNNNNNNr   )NNNNNT)r1   r2   r3   r4   r   r6   r7   r-  r@   rK  rJ  r   r9   r   r+  r  r;   rh   ri   s   @r=   r  r  U  s%    151537FJ59-1$(,0/359342
E,,-2
 !.2
 u//0	2

 ""BC2
   1 122
 ))*2
 D>2
 $D>2
 'tn2
 !!1!122
 c5<</02
 
 2
 2
n 8 8r<   r  )rh  r  rM  )Nr!   )Nr5   	functoolsr   typingr   r   r   r   r6   torch.utils.checkpointr   (transformers.models.jamba.modeling_jambamodelsjambamodeling_jambatransformers.activationsr	   r
   (transformers.models.llama.modeling_llamar   r   r   r   r   r   *transformers.models.mamba2.modeling_mamba2r   r   r   r   modeling_attn_mask_utilsr   modeling_outputsr   r   modeling_utilsr   processing_utilsr   utilsr   r   r   utils.import_utilsr   r   r    configuration_bambar"   +mamba_ssm.ops.triton.selective_state_updater#   !mamba_ssm.ops.triton.ssd_combinedr$   r%   causal_conv1dr&   r'   r  r   
get_loggerr1   r   r)   r@   rk   r   r   r   r   Moduler   r/  r1  r3  rM  rh  r  __all__r0   r<   r=   <module>r     s  (   4 4    A A + O   ? O - & 
 r q , Rmm!DD-7**46FH\]^  
		H	%	 43u~'V'V 3ul	/ 	
%P	^ 		) 	__ __D	x 		< 	]2 ]@ %? % %: H% H HVm' m` Er<   