
    qi                        d dl Z d dlmZ d dlmZ d dlZd dlmZ ddlmZ	 ddl
mZ ddlmZ dd	lmZ dd
lmZ ddlmZ ddlmZmZ ddlmZ ddlmZmZ ddlmZ ddlmZm Z  ddl!m"Z"m#Z#m$Z$ ddl%m&Z&m'Z'm(Z(m)Z)m*Z*m+Z+m,Z,m-Z-m.Z.m/Z/ ddl0m1Z1 dZ2 ejf                  e4      Z5 G d dej                  jl                        Z7 G d de.      Z8 G d de*      Z9 G d de      Z: G d d e&      Z; G d! d"ejl                        Z< G d# d$ejl                        Z= G d% d&e'      Z> G d' d(e,      Z? G d) d*e+      Z@ G d+ d,e      ZA G d- d.e-eA      ZB G d/ d0e(      ZC G d1 d2e)      ZDg d3ZEy)4    N)Callable)cycle)nn   )initialization)ACT2FN)lazy_load_kernel)create_causal_mask)FlashAttentionKwargs)BaseModelOutputWithPast)ALL_ATTENTION_FUNCTIONSPreTrainedModel)Unpack)is_torchdynamo_compilinglogging)resolve_internal_import   )LlamaRotaryEmbeddingapply_rotary_pos_emb)pad_tensor_by_sizereshape_into_chunkssegment_sum)
ZambaAttentionZambaAttentionDecoderLayerZambaForCausalLMZambaForSequenceClassificationZambaHybridDynamicCacheZambaHybridLayerZambaMambaDecoderLayer
ZambaModelZambaRMSNormeager_attention_forward   )Zamba2ConfigzZyphra/Zamba2-2.7Bc                   (     e Zd Zd fd	ZddZ xZS )Zamba2RMSNormGatedc                     t         |           t        j                  t	        j
                  |            | _        || _        || _        y N)	super__init__r   	Parametertorchonesweightvariance_epsilon
group_size)selfhidden_sizer0   eps	__class__s       [/opt/pipecat/venv/lib/python3.12/site-packages/transformers/models/zamba2/modular_zamba2.pyr*   zZamba2RMSNormGated.__init__7   s6    ll5::k#:; #$    c                 b   |j                   }|j                  t        j                        }|?|t        j
                  j                  |j                  t        j                              z  }|j                  ^ }}|| j                  z  } |j                  g ||| j                   }|j                  d      j                  dd      }|t        j                  || j                  z         z  } |j                  g ||| j                  z   }| j                  |j                  |      z  S )Nr   T)keepdim)dtypetor,   float32r   
functionalsilushaper0   viewpowmeanrsqrtr/   r.   )	r1   hidden_statesgateinput_dtypeprefix_dimslast_dimgroup_counthidden_states_groupvariances	            r5   forwardzZamba2RMSNormGated.forward=   s   #))%((7)BMM,>,>twwu}}?U,VVM!.!4!4h$//10m00\+\{\DOO\&**1-222t2D1EKK4K`K`@`4aa0+00]+]{T__?\]{{]--k:::r6   )gư>r(   )__name__
__module____qualname__r*   rL   __classcell__r4   s   @r5   r&   r&   6   s    %;r6   r&   c                       e Zd Zy)Zamba2RMSNormNrM   rN   rO    r6   r5   rS   rS   K       r6   rS   c            
           e Zd ZdZej
                  dfdededej                  de	dz  fdZ
ded	ej                  d
ej                  dej                  fdZd Zddedz  defdZd
ej                  dedeeef   fdZy)Zamba2HybridDynamicCachea  
    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config
batch_sizer:   devicec           	      .   || _         |j                  | _        d| _        t        |j                  |j
                  z        | _        |j                  | _        |j                  | _
        |j                  | _        g | _        i | _        i | _        i | _        i | _        i | _        t%        |j&                        D ]  }t)        j*                  || j                  d|j,                  z  |j                  z  z   | j                  ||      | j                   |<   t)        j*                  || j                  |j.                  | j                  ||      | j"                  |<   | j                  |   dk(  s| j                  j1                  |        t%        |j&                        D cg c]  }t)        j2                  g g|z  |       c}| _        t%        |j&                        D cg c]  }t)        j2                  g g|z  |       c}| _        y c c}w c c}w )NFr   r[   r:   hybridr[   )r:   layers_block_typehas_previous_stateintmamba_expandr2   intermediate_sizemamba_d_statessm_state_sizemamba_d_convconv_kernel_sizen_mamba_headstransformer_layers_modules_parameters_buffersconv_states
ssm_statesrangenum_hidden_layersr,   zerosmamba_ngroupsmamba_headdimappendtensor	key_cachevalue_cache)r1   rY   rZ   r:   r[   i_s          r5   r*   z!Zamba2HybridDynamicCache.__init__]   s    
!'!9!9"'!$V%8%86;M;M%M!N$22 & 3 3#11"$v//0 	2A"'++&&V-A-A)AFDXDX)XX%%#DQ "'D..0D0DdFYFYbhpu"DOOA %%a(H4''..q1	2 SXX^XpXpRqrQ%,,tj'8HrTYZ`ZrZrTstqELL"
):6Jt sts   !"H""H	layer_idxnew_conv_statecache_positionreturnc                 T   | j                   |   }|j                  d| j                  dz
        }|j                  dd      }|j	                  |j
                        |d d d d |f<   | j                   |   j                          | j                   |xx   |z  cc<   | j                   |   S )Nr   r#   r8   shiftsdims)rn   clamprh   rollr;   r[   zero_)r1   r{   r|   r}   
conv_states        r5   update_conv_statez*Zamba2HybridDynamicCache.update_conv_state}   s     %%i0
'--a1F1F1JK__BR_8
+9+<+<Z=N=N+O
1a'(#))+#z1#	**r6   c                 l    | j                   j                          | j                  j                          y r(   )rn   r   ro   )r1   s    r5   resetzZamba2HybridDynamicCache.reset   s$     r6   c                     || j                   vr| j                   d   n|}t        | j                        |k  s | j                  |   j                         dk(  ry| j                  |   j                  d   S )zYReturns the sequence length of the cached states. A layer index can be optionally passed.r   )rj   lenrw   numelr?   )r1   r{   s     r5   get_seq_lengthz'Zamba2HybridDynamicCache.get_seq_length   sl     3<4CZCZ2ZD++A.`i	t~~)+t~~i/H/N/N/PTU/U~~i(..r22r6   c                 T    d}|j                   d   }| j                  |      |z   }||fS )zDReturn the length and offset of the cache, used to generate the maskr   )r?   r   )r1   r}   r{   	kv_offsetquery_length	kv_lengths         r5   get_mask_sizesz'Zamba2HybridDynamicCache.get_mask_sizes   s7    	%++A.''	2\A	)##r6   )r   )rM   rN   rO   __doc__r,   float16r$   rb   r:   strr*   Tensor
LongTensorr   r   r   tupler   rU   r6   r5   rX   rX   O   s     KP--nru"u03u<AKKuadgkaku@
+
+.3ll
+LQL\L\
+	
+ 3d
 33 3$U\\ $c $eTWY\T\o $r6   rX   c                       e Zd Zy)Zamba2RotaryEmbeddingNrT   rU   r6   r5   r   r      rV   r6   r   c                   F    e Zd ZdZ	 	 	 ddededz  dedz  dedz  f fdZ	 	 	 ddej                  ded	ej                  dz  d
e	dz  de
ej                  ej                  f   dz  dee   de
ej                  ej                  dz  e
ej                     dz  f   fdZ xZS )Zamba2AttentionaZ  
    Multi-headed attention from 'Attention Is All You Need' paper.

    Adapted from transformers.models.mistral.modeling_mistral.MistralAttention:
    The input dimension here is attention_hidden_size = 2 * hidden_size, and head_dim = attention_hidden_size // num_heads.
    The extra factor of 2 comes from the input being the concatenation of original_hidden_states with the output of the previous (mamba) layer
    (see fig. 2 in https://huggingface.co/papers/2405.16712).
    Additionally, replaced
    attn_weights = torch.matmul(query_states, key_states.transpose(2, 3)) / math.sqrt(self.head_dim) with
    attn_weights = torch.matmul(query_states, key_states.transpose(2, 3)) / math.sqrt(self.head_dim/2)
    Finally, this attention layer contributes to tied transformer blocks aimed to increasing compute without increasing model size. Because this
    layer is tied, un-tied adapters (formally the same as LoRA but used in the base model) modules are added to the q, k, v projectors to increase
    expressivity with a small memory overhead (see Fig. 2 of https://huggingface.co/papers/2411.15242).
    NrY   r{   num_fwd_mem_blocksblock_idc           	         t         |   ||       || _        |j                  | _        || _        |j                  rt        j                  g       | _	        t        j                  g       | _
        t        j                  g       | _        t        | j                        D ]  }||j                  z  |k(  r{t        j                  t        j                  | j                   | j"                  j$                  d      t        j                  | j"                  j$                  | j                   d            }t        j                  t        j                  | j                   | j"                  j$                  d      t        j                  | j"                  j$                  | j                   d            }t        j                  t        j                  | j                   | j"                  j$                  d      t        j                  | j"                  j$                  | j                   d            }n<t        j&                         }t        j&                         }t        j&                         }| j                  j)                  |       | j                  j)                  |       | j                  j)                  |       ! t+        | j                        D 	
ci c]  \  }	}
|
|	
 c}
}	| _        y c c}
}	w )NFbias)r)   r*   r   hybrid_layer_idslayer_block_mapr   use_shared_attention_adapterr   
ModuleListlinear_q_adapter_listlinear_k_adapter_listlinear_v_adapter_listrp   num_mem_blocks
SequentialLinearattention_hidden_sizerY   adapter_rankIdentityru   	enumerate	layer_dic)r1   rY   r{   r   r   ry   linear_q_adapterlinear_k_adapterlinear_v_adapterindexvaluer4   s              r5   r*   zZamba2Attention.__init__   s#    	+"4%66 ..)+r):D&)+r):D&)+r):D&4223 Dv,,,8')}}		$"<"<dkk>V>V]bc		$++":":D<V<V]bc($ (*}}		$"<"<dkk>V>V]bc		$++":":D<V<V]bc($ (*}}		$"<"<dkk>V>V]bc		$++":":D<V<V]bc($
 (*{{}$'){{}$'){{}$**112BC**112BC**112BC)D, <ETEYEY;Z[<5%%,[[s   K2rD   attention_maskpast_key_valuesposition_embeddingskwargsr~   c                    |j                   d d }g |d| j                  }| j                  |      }	| j                  |      }
| j	                  |      }| j
                  j                  rW| j                  |   }|	 | j                  |   |      z   }	|
 | j                  |   |      z   }
| | j                  |   |      z   }|	j                  |      j                  dd      }	|
j                  |      j                  dd      }
|j                  |      j                  dd      }| j
                  j                  r|\  }}t        |	|
||      \  }	}
||j                  |
||      \  }
}t!        j"                  | j
                  j$                  t&              } || |	|
||f| j(                  sdn| j*                  | j,                  d|\  }} |j.                  g |d j1                         }| j3                  |      }||fS )Nr8   r#   r   g        )dropoutscaling)r?   head_dimq_projk_projv_projrY   r   r   r   r   r   r@   	transposeuse_mem_roper   updater   get_interface_attn_implementationr"   trainingattention_dropoutr   reshape
contiguouso_proj)r1   rD   r{   r   r   r   r   input_shapehidden_shapequery_states
key_statesvalue_statesadapter_layer_idxcossinattention_interfaceattn_outputattn_weightss                     r5   rL   zZamba2Attention.forward   s    $))#2.88b8$--8{{=1[[/
{{=1;;33 $y 9'*W$*D*DEV*WXe*ffL#&Sd&@&@AR&STa&bbJ'*W$*D*DEV*WXe*ffL#((6@@AF__\2<<QB
#((6@@AF;;##*HC';L*VY[^'_$L*&'6'='=j,Xa'b$J(?(M(MKK,,.E)
 %8	%
  $}}C$2H2HLL	%
 	%
!\ *k));;;;FFHkk+.L((r6   )NNN)rM   rN   rO   r   r$   rb   r*   r,   r   rX   r   r   r   rL   rP   rQ   s   @r5   r   r      s    $ !%)-#'\'\ :'\  $J	'\
 *'\Z /3;?HL1)||1) 1) t+	1)
 2D81) #5<<#=>E1) -.1) 
u||U\\D0%2E2LL	M1)r6   r   c                        e Zd ZdZddededz  f fdZ	 	 ddej                  de	dz  dej                  dz  fd	Z
dde	dz  dej                  dz  fd
Z	 	 dde	dz  dej                  dz  fdZ xZS )Zamba2MambaMixeru  
    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)
    NrY   r{   c           	         t         |           || _        |j                  | _        |j                  | _        |j                  | _        t        |j                  | j                  z        | _
        || _        |j                  | _        d| _        t        j                         | _        |j"                  | _        |j$                  | _        |j(                  | _        | j                  j,                  | _        |j0                  | _        |j2                  | _        |j4                  | _        |j6                  | _        | j                  d| j&                  z  | j
                  z  z   | _        t        j:                  | j8                  | j8                  d|j                  | j8                  |j                  dz
        | _        | j                  | j8                  z   | j.                  z   }t        j>                  | j                  ||j@                        | _!        t        jD                  tG        jH                  | j.                              | _%        tG        jL                  d| j.                  dz         }t        jD                  tG        jN                  |            | _(        tS        | j                  | j                  | j&                  z  d      | _*        t        jD                  tG        jH                  | j.                              | _+        t        j>                  | j                  | j                  |j@                        | _,        t[        d	      }t]        |d
d       a/t]        |dd       a0t[        d      }tc        |d      a2tc        |d      a3tc        |d      a4tk        td        tf        th        t`        t^        f      a6tl        stn        jq                  d       y y )Nr>   r   Tr#   )in_channelsout_channelsr   kernel_sizegroupspaddingr   gh㈵>)r0   r3   zcausal-conv1dcausal_conv1d_updatecausal_conv1d_fnz	mamba-ssmz8ops.triton.selective_state_update.selective_state_update)chained_pathz1ops.triton.ssd_combined.mamba_chunk_scan_combinedz8ops.triton.ssd_combined.mamba_split_conv1d_scan_combineda  The fast path is not available because one of `(selective_state_update, causal_conv1d_fn, causal_conv1d_update)` is None. Falling back to the naive implementation. To install follow https://github.com/state-spaces/mamba/#installation and https://github.com/Dao-AILab/causal-conv1d)9r)   r*   rY   r2   re   rf   rg   rh   rb   rc   rd   r{   use_conv_bias
activationr   SiLUactuse_mem_eff_pathrs   n_groupsrt   r   ri   	num_heads
chunk_sizetime_step_limittime_step_mintime_step_maxconv_dimConv1dconv1dr   add_bias_linearin_projr+   r,   r-   dt_biasarangelogA_logr&   normDout_projr	   getattrr   r   r   selective_state_updatemamba_chunk_scan_combined mamba_split_conv1d_scan_combinedallis_fast_path_availableloggerwarning_once)r1   rY   r{   projection_sizeAcausal_conv1d	mamba_ssmr4   s          r5   r*   zZamba2MambaMixer.__init__  s   !--$22 & 3 3!$V%8%84;K;K%K!L"#11 779 & 7 7,,,,22 ++%55#11#11..T]]1BTEXEX1XXii++==''!+
 004==@4>>Qyy''
 ||EJJt~~$>? LLDNNQ./\\%))A,/
&""t/E/E/V\`
	 ejj89		$"8"8$:J:JQWQgQgh )9&}6LdS"=2DdK %[1	!8$^"
 %<$W%
! ,C$^,
(
 "%&)0 $"
 &> &r6   rD   cache_paramsr   c                    |j                   \  }}}| j                  | j                  z  }d| j                  z  d| j                  z  | j                  z  z   | j                  z   }|4|j
                  r'| j                  |j                  d            }	|	j                   d   |z
  dz  }
|
|
| j                  | j                  | j                  g}t        j                  |	|d      \  }}}}}t        ||j                  | j                     | j                  j                  j                  d      | j                  j                   | j"                        }t        j                  || j                  ||gd      \  }}}t        j$                  | j&                  j)                                }|d d d df   d d d d d f   j+                  d| j,                  | j                        j/                  t        j0                        }|d d d d d f   j+                  dd| j,                        }| j2                  d d d df   j+                  d| j,                        }| j4                  d d d df   j+                  d| j,                        }|j7                  || j                  |j                   d   | j                  z        }|j7                  || j                  |j                   d   | j                  z        }|j7                  || j                  | j,                        }t9        |j:                  | j                     ||||||d |d
      }|j7                  || j                  | j,                  z        }| j=                  ||      }| j?                  |      d d d df   }|S |Bt        j@                  |dk(        s*|jB                  }||d d d d d f   z  j/                  |      }| j                  |      }t        j$                  | j&                  j)                                }| jD                  i nd	| jD                  i}|t        j@                  |dk(        }nd}| jF                  r| jH                  r||rtK        || j                  j                  j                  d      | j                  j                   | j2                  |f| j4                  | jL                  d | j"                  | j<                  j                  | j<                  jN                  | j>                  j                  | j>                  j                   | j,                  | j                  d
dd|\  }}|S t        j                  || j                  | j                  | j                  gd      \  }}}|v|jQ                  dd      }tR        jT                  jW                  || jX                  |j                   d   z
  df      }|j                  | j                     j[                  |       t\        | j"                  dvrJ| j_                  | j                  |jQ                  dd            jQ                  dd      d d d |f         }nyt]        |jQ                  dd      | j                  j                  j                  d      | j                  j                   | j"                        jQ                  dd      d d d |f   }t        j                  || j                  ||gd      \  }}}|Bt        j@                  |dk(        s*|jB                  }||d d d d d f   z  j/                  |      }ta        |j7                  ||d| j,                        |||j7                  ||| j                  d      |j7                  ||| j                  d      f| jL                  | j4                  d d d| j2                  dd|\  }}|*|(|j:                  | j                     j[                  |       |j7                  ||d      }| j=                  ||      }| j?                  |      }|S )Nr   r#   r8   dim.r:   T)zr   dt_softplusdt_limitF)r   r   seq_idxr   rmsnorm_weightrmsnorm_epsoutproj_weightoutproj_biasheaddimngroupsnorm_before_gatereturn_final_statesr   )r>   swish)xr.   r   r   )r   r   r
  r  r  r   r  )1r?   r   rf   rd   r   ra   r   squeezer   r,   splitr   rn   r{   r   r.   r   r   expr   floatexpandr   r;   r<   r   r   r@   r   ro   r   r   r   r:   r   r   r   r   r   r/   r   r   r=   padrh   copy_r   r   r   )r1   rD   r  r   rZ   seq_lenrz   groups_time_state_sized_to_removein_projected_statesd_mlpsplit_projection_dimrE   hidden_states_B_CdtBCr  r   r   hidden_states_reshapedoutr:   projected_statesdt_limit_kwargsinput_not_masked	ssm_state	time_stephidden_states_B_C_tr   scan_outputs                                  r5   cuda_kernels_forwardz%Zamba2MambaMixer.cuda_kernels_forwardq  sv    "/!4!4
GQ!%1D1D!D$0001t}}3DtGZGZ3ZZ]a]k]kk #(G(G"&,,}/D/DQ/G"H(..r2[@QFE$)5$2H2H$--Y]YgYg#h 05<OQekm0n-Aq$)2 4!((8""**1-  ! #(++!'')?AWX#M1a
 4::++-..A!T3,1d
+222t}}dFYFYZ]]didqdq]rAAq$J&&r2t}}=Bll1dC<077DMMJGq$|$++B>Az4==!''!*2MNAz4==!''!*2MNA%2%7%7
DNNTXTaTa%b"2''7& M *..z4>>DMM;YZM IImT:M--.q$|<Cz 
u )%))Na<O2P%++!.1d
1K!K O OPU V#||M:4::++-..A$($8$8$@bzSWSgSgFhO)#(99^q-@#A #' $$<;OTd!A$KK&&..q1KK$$LL" ff# ##'99#3#3 $		 : :#'==#7#7!%!3!3 MM MM%*(,#"$ &%"YX 
m 6;[[$++T]]DNNK62'  +*;*E*Ea*K'!#!2!2+d.C.CFYF_F_`bFc.cef-g"J !,,T^^<BB:N#+tFW/W(,$5$?$?1$EFPPQRTUVWXZb[bZbWbc)% )9+55a;#{{1199!<![[--#'??	)
  i1oa'k)3% ',kk%++-CE[\'#q!
 "-eiiRS@S6T)//E%2^Aq$J5O%O$S$STY$ZM)B!&&z7BNFF:wrBFF:wrB*  $ff (, LL $* &*&Y (\-E ++DNN;AA)L)..z7BG"iiT:mmK0
r6   c                    |j                   \  }}}|j                  }|-|j                  r!| j                  |j	                  d            }n1|||d d d d d f   z  j                  |      }| j                  |      }|j                   d   d| j                  z  z
  d| j                  z  | j                  z  z
  | j                  z
  dz  }	|j                  |	|	| j                  | j                  | j                  gd      \  }}}
}}|_|j                  | j                     j                         }|j                  |j                        }|j                  r1|
j!                  d      }
|j"                  | j                     }t%        j&                  |dd      }|j(                  dk(  r|d d dd d f   n||d d d d df<   |j"                  | j                     j+                  |       t%        j,                  |j                  |j                        | j.                  j0                  d d dd d f   z  d      }| j2                  r|| j.                  j4                  z  }| j7                  |      j                  |      d d d df   }nj|j9                  dd      }t:        j<                  j?                  || j@                  |j                   d   z
  df      }|j"                  | j                     j+                  |       | j7                  | j/                  |      j9                  dd            d d d |d d f   }||j                  }||d d d d d f   z  j                  |      }nt%        jB                  || j                  | jD                  | j                  f|j                  |	      }| j7                  | j/                  |j9                  dd            dd |f   j9                  dd            }t%        j                  || j                  | j                  | j                  z  | j                  | j                  z  gd      \  }}}t%        jF                  | jH                  jK                                }|t|j                  rg|j(                  dk(  r
|d d d df   n|d d dd d f   d d d df   }|j9                  dd      jM                  ||j                   d   | jD                        }| jN                  d
   jM                  | jN                  j                   d   | jD                        }t$        j:                  j<                  jQ                  ||j                  |j                        z         }t%        jR                  || jT                        }|d   jM                  | j                  | jD                  | j                        j                  t$        jV                        }t%        jF                  |d
   |z        }|jY                  || j                  d      dd d d f   }|jM                  || j                  | j                  | j                  z  |j                   d         j[                         }|jY                  |d|j                   d         }|d
   |dd d d f   z  }|jY                  |d| jD                        }||d
   z  }|j                  | j                     j+                  |j                  | j                     |z  |z          |jY                  || j                  d      dd d d f   }|jM                  || j                  | j                  | j                  z  |j                   d         j[                         }|jY                  |d|j                   d         }|j                  | j                     j                  |j                        }|j]                  || j                  z  | jD                  | j                        }|j]                  || j                  z  | j                  d      }t%        j^                  ||      }|j]                  || j                  | jD                        }| j`                  d
   jM                  | j`                  j                   d   | jD                        }|||z  z   j                  |j                        }|jY                  |d      d d d df   }n4t:        j<                  jQ                  || jN                  z         }t%        jR                  || jT                        }|jY                  ||d| jD                        jK                         }|jY                  ||d| j                        jK                         }|jY                  ||d| j                        jK                         }|jc                  | j                  | j                  z  d| j                        }|jc                  | j                  | j                  z  d| j                        }| jd                  || jd                  z  z
  | jd                  z  }| j`                  d
   tg        ||      z  }||d
   z  }|j                  |j                        |z  }||||fD cg c]  }ti        ||| jd                         c}\  }}}}|jk                  dddd      }t%        jl                  |d      }t%        jF                  to        |            }|d d d d d d d d d d d f   |d d d d d d d d d d d f   z  } | j-                  d      }!|!d
   |jk                  ddddd      d
   z  }"|"j-                  d      }#|#d
   |d d d d d f   z  j-                  d      }$t%        jF                  |d d d d d d dd f   |z
        }%||%jk                  dddd      d
   z  }&|&jk                  ddddd      d
   |jk                  ddddd      dd d d f   z  j-                  d      jk                  ddddd      }'|.|j                  r"|j                  | j                     d d d df   }(nt%        jp                  |'d d d df         }(t%        jr                  |(|'gd      }'t%        jF                  to        t:        j<                  j?                  |d d d d d d df   d                  })|'jk                  ddddd      }*|)d   |*d d d d d df   z  j-                  d      }+|+jk                  ddddd      },|,d d d df   |,d d df   }}'t%        jF                  |      }-|dd d d f   |'d d d d d df   z  }.|-jk                  dddd      }/|.j-                  d      |/d
   z  }0|$|0z   }|jY                  |d| j                  | jD                        }||z   }|dkD  r|d d d |d d d d f   }|jY                  ||d      }|*|(|j                  | j                     j+                  |       | ju                  ||
      }1| jw                  |1j                  |            }2|2S c c}w )Nr#   r8   r   r  r   r   r   .r]   ).N).NNr	  )r  output_size   )r#   r   )<r?   r:   ra   r   r  r;   rd   r   rf   r   r  r   ro   r{   cloner[   	unsqueezern   r,   r   ndimr  sumr   r.   r   r   r   r   r   r=   r  rh   rr   r   r  r   r  r  r   softplusr   r   r<   r   r   r@   bmmr   repeat_interleaver   r   r   permutecumsumr   
zeros_likecatr   r   )3r1   input_statesr  r   rZ   r  rz   r:   r+  r#  rE   rD   r&  r.  r   r'  r(  r  r   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_contractionstatesprevious_statesdecay_chunkstates_permutedresult
new_statesstate_decay_outC_times_statesstate_decay_out_permutedY_offr1  contextualized_statess3                                                      r5   torch_forwardzZamba2MambaMixer.torch_forward  sY   !-!3!3
GQ""#(G(G#||L,@,@,CD) ,~aDj/I IMMeT#||L9!''+a$2H2H.HH1t}}K\_c_r_rKrrtx  uC  uC  C  HI  I(8(>(>t55t~~V\^ )? )
%1dM2
 #$//?EEGI!]%9%9:I..~~a()55dnnE
"ZZ
2BG
ANASASWXAX}Q1W'=^k
1a8$((8>>zJ %		*--8H8O8O*PSWS^S^SeSefgijlmfmSn*ntv w%%!T[[%5%55M $ 7 : :5 A!T3, O - 7 7! <]]..!**]-@-@-DDaH
 ((8>>zJ $])C)M)MaPQ)R STUW_X_W_abTb c!-)//E%2^Aq$J5O%O$S$STY$ZMT^^T]]D<O<OP$++5I !HHT[[1H1HA1N%OPSU]V]U]P]%^%h%hijlm%noM#kk-$:P:PRVR_R_bfbubuRuw{  xE  xE  HL  H[  H[  x[  :\  bd  eq!YYtzz'')**#(G(G &(WW\AtSL!r!Q'{1dC<7PBa#**:rxx|T]]SBll9-44T\\5G5G5JDMMZG$$--b7::bhh3G.GHBR!3!34B/"))$..$--I\I\]``glgtgt`uA2i=1,-B
 		*dmmR8dAFAT]]DNNdmm4SUVU\U\]_U`allnA		*b!''"+6AI3a<0B *11*b$--PM}Y//C ##DNN399''7"<sB 		*dmmR8dAFAT]]DNNdmm4SUVU\U\]_U`allnA		*b!''"+6A &00@CCAGGLJ",//*t~~2Mt}}^b^q^q"r
T^^ ;T=P=PRSTJ		-z:Az4>>4==AA y!((a$--HA]Q&&**1773A 		*b)!T3,7A ''T\\(9:BR!3!34B)11*gr4==Y__aM		*gD4G4GHNNPA		*gr43F3FGMMOA##DNNdmm$CX\XfXf#gA##DNNdmm$CX\XfXf#gA'DOO*CCtVH	*-?x-XXJ *ByM9M](()B.A cpqrtuwxay%z\]&9!Xt&W%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CAFF !99XaArsl%;h%FGL"#l&:&:1aA&Fy&Q"Q)11!Q1a@K}OdOdefhiklnoqrOstwy}  @A  uA  PB  B  G  G  LM  G  N  V  V  WX  Z[  ]^  `a  cd  eF'L,K,K"."9"9$.."I!TSV,"W"'"2"26!RaR%="AYY8a@F))K0A0A(1aQRTV;BWY_0`$abK$nnQ1a;O!/2_Q4QT_5UUZZ_`ZaF1aA6J *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'(		*gr2A$)A''7==iHii4(
 !%knnU.C D$$I &{s   yc                     t         rId| j                  j                  j                  j                  v rt               s| j                  |||      S | j                  |||      S )Ncuda)r   r   r.   r[   typer   r2  r_  )r1   rD   r  r   s       r5   rL   zZamba2MambaMixer.forward  sT     "f0C0C0J0J0O0O&OXpXr,,]L.YY!!-~NNr6   r(   NN)rM   rN   rO   r   r$   rb   r*   r,   r   rX   r2  r_  rL   rP   rQ   s   @r5   r   r     s    Y| Yd
 Y| 9=.2	T||T /5T t+	Tn%8PSW8W %nsnznz  ~B  oB %J 9=.2		O /5	O t+		Or6   r   c                   8     e Zd Zddededz  f fdZddZ xZS )	Zamba2MLPNrY   r   c           	          t         	|           || _        |j                  | _        |j                  | _        || _        || _        t        j                  | j                  d| j                  z  |j                        | _
        t        j                  | j                  | j                  |j                        | _        t        |j                     | _        t        j                  g       | _        t#        | j
                        D ]  }||j$                  z  |k(  rt        j&                  t        j                  | j                  j                  | j                  j(                  d      t        j                  | j                  j(                  d| j                  z  d            }nt        j*                         }| j                   j-                  |        |j.                  }t1        |      D ci c]  \  }}||
 c}}| _        yc c}}w )aQ  
        This MLP layer contributes to tied transformer blocks aimed to increasing compute without increasing model size. Because this layer
        is tied, un-tied adapter modules (formally same as LoRA, but used in the base model) are added to the up and gate projectors to increase expressivity with a small memory overhead.
        r   r   FN)r)   r*   rY   r2   rd   r   r   r   r   r   gate_up_proj	down_projr   
hidden_actact_fnr   gate_up_proj_adapter_listrp   r   r   r   r   ru   r   r   r   )
r1   rY   r   r   ry   gate_up_proj_adapterr   r   r   r4   s
            r5   r*   zZamba2MLP.__init__  s   
 	!--!'!9!9"4 IId&6&6D<R<R8RY_YoYop4#9#94;K;KRXRhRhiV../)+r):&t../ 	HA6(((H4')}}IIdkk55t{{7O7OV[\IIdkk66D<R<R8RY^_($
 (*{{}$**112FG	H !11;D_;UV<5%%,VVs   3H
c                     | j                  |      }| j                  |   }| | j                  |   |      z   }t        j                  |dd      }| j                  |d         |d   z  }| j                  |      }|S )Nr   r8   r  r   r#   )rg  r   rk  r,   chunkrj  rh  )r1   hidden_stater{   gate_up_stateoutputs        r5   rL   zZamba2MLP.forward  s    )),7NN9-	%(Q(F(Fy(QR^(__M1"={{=#34}Q7GG-r6   rc  r(   )rM   rN   rO   r$   rb   r*   rL   rP   rQ   s   @r5   re  re    s%    W| WPSVZPZ W<r6   re  c                   4    e Zd Zddededz  dedz  f fdZ	 	 	 	 ddej                  dej                  dedej                  dz  d	edz  d
e	dz  dej                  dz  dee   deej                  eej                  ej                  f   dz  f   fdZ xZS )Zamba2AttentionDecoderLayerNrY   r   r{   c                     || _         t        |j                        }t        |   ||       t        |d||      | _        t        |||      | _        y )Nr8   )r{   r   r   )r   r   )	r   r   r   r)   r*   r   	self_attnre  feed_forward)r1   rY   r   r{   num_gsr4   s        r5   r*   z$Zamba2AttentionDecoderLayer.__init__  sO     V,,-+(2RXckl%fRZ[r6   rD   original_hidden_statesr   r   output_attentionsr   r   r~   c           
          t        j                  ||gd      }| j                  |      } | j                  d||||||d|\  }}	| j	                  |      }| j                  ||      }|f}
|r|
|	fz  }
|
S )a  
        Args:
            hidden_states (`torch.FloatTensor`): output of previous Mamba layer of shape `(batch, seq_len, embed_dim)`
            original_hidden_states (`torch.FloatTensor`): word embedding output of shape `(batch, seq_len, embed_dim)`.
                This is concatenated with `hidden_states` (which is the output of the previous (mamba) layer). The
                concatenated tensor is then used as input of the pre-attention RMSNorm
                (see fig. 2 in https://huggingface.co/papers/2405.16712).
            attention_mask (`torch.FloatTensor`, *optional*): attention mask of size
                `(batch, sequence_length)` where padding elements are indicated by 0.
            past_key_values (`Zamba2HybridDynamicCache`, *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`).
            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.
        r8   r  )rD   r{   r   r   ry  r   rU   )r,   concatenateinput_layernormru  pre_ff_layernormrv  )r1   rD   rx  r{   r   r   ry  r   r   self_attn_weightsoutputss              r5   rL   z#Zamba2AttentionDecoderLayer.forward  s    > ))=:P*QWYZ,,];+94>> ,
')+/ 3,
 ,
(( --m<))-C ")++Gr6   rc  )NNFN)rM   rN   rO   r$   rb   r*   r,   r   rX   boolr   r   r   r   FloatTensorrL   rP   rQ   s   @r5   rs  rs     s    \| \sTz \UX[_U_ \ /3;?).7;3||3 !&3 	3
 t+3 2D83  $;3 #--43 -.3 
u  %(9(95;L;L(L"MPT"TT	U3r6   rs  c                   (     e Zd Zdedef fdZ xZS )Zamba2MambaDecoderLayerrY   r{   c                     t         |   ||       t        ||      | _        t	        |j
                  |j                        | _        y )N)rY   r{   r3   )r)   r*   r   mambarS   r2   rms_norm_epsr|  )r1   rY   r{   r4   s      r5   r*   z Zamba2MambaDecoderLayer.__init__?  s;    +%VyI
,V-?-?VEXEXYr6   )rM   rN   rO   r$   rb   r*   rP   rQ   s   @r5   r  r  >  s    Z| Z Z Zr6   r  c                       e Zd Zdedej
                  def fdZ	 	 	 	 	 	 	 	 	 ddej                  dej                  dz  de
dz  d	ej                  dz  d
ej                  dz  dedz  dedz  dedz  dej                  dz  dej                  dz  deej                  eej                  ej                  f   dz  f   fdZ xZS )Zamba2HybridLayershared_transformerlinearr  c                 :    t         |   |||       | `|| _        y r(   )r)   r*   shared_transfr  )r1   r  r  r  r4   s       r5   r*   zZamba2HybridLayer.__init__F  s%     	+VU;"4r6   NrD   rx  r{   r   causal_maskr   ry  	use_cacher   position_idsr~   c           
          | j                  |||||||	|
      }|d   }|r|d   }| j                  |      }| j                  |||||||	      }|r|d   f|dd z   }|S )aY  
        Args:
            hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
            original_hidden_states (`torch.FloatTensor`): word embedding output that will be concatenated with
            hidden activations to form the input of the shared transformer layer.
            layer_idx (`int`): layer number.
            attention_mask (`torch.FloatTensor`, *optional*): attention mask of size
                `(batch, sequence_length)` where padding elements are indicated by 0.
            past_key_values (`Zamba2HybridDynamicCache`, *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`).
            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.
        )rx  r{   r   r   ry  r   r  r   r#   )transformer_hidden_statesr   r   ry  r  r   r   N)r  r  mamba_decoder)r1   rD   rx  r{   r   r  r   ry  r  r   r  layer_outputsr  r~  s                 r5   rL   zZamba2HybridLayer.forwardM  s    B //#9&+/ 3% 0 	
 %2!$4! -a 0$(KK0I$J!**&?)+/ 3 + 
 *1-/@AMRSRTDUUMr6   )	NNNNNFFNN)rM   rN   rO   rs  r   r   r  r*   r,   r   rb   rX   r  r   r   r  rL   rP   rQ   s   @r5   r  r  E  s0   5"=5GIyy5Yp5 7; $.2+/;?).!&7;04@||@ !&t 3@ :	@
 t+@ \\D(@ 2D8@  $;@ $;@ #--4@ &&-@ 
u  %(9(95;L;L(L"MPT"TT	U@r6   r  c                   v     e Zd ZU eed<   dZdZddgZdZdZ	dZ
dZdZ ej                          fd       Z xZS )Zamba2PreTrainedModelrY   modelTrs  r  r   c                    t         |   |       t        |t              rt	        j
                  t	        j                  | j                  j                        t        j                  | j                  j                        t        j                  | j                  j                        z
  z  t        j                  | j                  j                        z         j                  | j                  j                        }|t	        j                  t	        j                  |              z   }t!        j"                  |j$                  |       t	        j&                  d|j(                  dz         }t!        j"                  |j*                  t	        j                  |             t!        j,                  |j.                         y y )N)minr#   )r)   _init_weights
isinstancer   r,   r  randrY   ri   mathr   r   r   r   time_step_floorexpm1initr  r   r   r   r   ones_r   )r1   moduler&  inv_dtr  r4   s        r5   r  z#Zamba2PreTrainedModel._init_weights  s(   f%f./

4;;44588DKK556$++B[B[9\\^((4;;4456 e33e4	  %))U[["%5$566FJJv~~v.Q 0 01 45AJJv||UYYq\2JJvxx  0r6   )rM   rN   rO   r$   __annotations__base_model_prefixsupports_gradient_checkpointing_no_split_modules_skip_keys_device_placement_supports_flash_attn_supports_flex_attn_supports_sdpa_is_statefulr,   no_gradr  rP   rQ   s   @r5   r  r    sW    &*#68QR"3NLU]]_! !r6   r  c                      e Zd ZdZdefdZd Z	 	 	 	 	 	 	 	 	 	 ddej                  dz  dej                  dz  dej                  dz  d	e
dz  d
ej                  dz  dedz  dedz  dedz  dedz  dej                  dz  deez  fdZy)Zamba2Modelzh
    Model consisting of *config.num_hidden_layers* layers.

    Args:
        config: Zamba2Config
    rY   c                 X   t         j                  | |       || _        |j                  | _        |j
                  | _        t        j                  |j
                  |j                  | j                        | _	        |j                  | _
        | j                         | _        |j                  | _        t        |j                  |j                        | _        |j"                  r1|j$                  rt&        j)                  d       t+        |      | _        d| _        | j1                          y )Nr  ze`use_long_context` set to `True`: using rescaled `rope_theta` and extended `max_position_embeddings`.F)r  r*   rY   pad_token_idpadding_idx
vocab_sizer   	Embeddingr2   embed_tokensr`   
get_layerslayersr   rS   r  final_layernormr   use_long_contextr   r   r   
rotary_embgradient_checkpointing	post_init)r1   rY   s     r5   r*   zZamba2Model.__init__  s    &&tV4!.. ++LL):):F<N<NPTP`P`a!'!9!9oo'$*$?$?!,V-?-?VEXEXY&&##{ 4F;DO&+# 	r6   c                     g }i | _         d| _        g }t        | j                        D ]O  \  }}t	        | j
                  |      }|dk(  rd| d}t        |t              r"t        |      | j
                  j                  k\  rDt        |t              rt        |      }t        |      }| j                   j                  ||i       n|j                  |       || j
                  j                  z  }t        | j
                  |      }	t        j                   | j
                  j"                  | j
                  j"                  d      }
|j                  t%        |	|
|             ?|j                  |       R t        j&                  |      S )	Nr   r{   r^   zlayers.z.shared_transformer)r   Fr   )_tied_weights_keysfirst_transformer_layer_idr   r`   r  rY   r  listr   r   r   nextr   ru   rs  r   r   r2   r  r   )r1   r  unique_hybrid_blockslayer_id
layer_typemamba_layerprefix_patterntarget_patternr   
attn_blocklinear_layers              r5   r  zZamba2Model.get_layers  sQ   "$*+'!$-d.D.D$E 	+ Hj1$++RKX%#*8*4G!H ##7>/0DKK4N4NN!"6=/45I/J,%)*>%?N++22NN3ST )//?#dkk&@&@@8xX
!yy)@)@$++BYBY`ef/
L+VWk*5	+6 }}V$$r6   N	input_idsr   r  r   inputs_embedsr  ry  output_hidden_statesreturn_dictr}   r~   c                    ||n| j                   j                  }||n| j                   j                  }||n| j                   j                  }|	|	n| j                   j                  }	|d u |d uz  rt        d      | j                  r%| j                  r|rt        j                  d       d}|| j                  |      }|}t        j                  |      }|rO|M||j                  d   n|j                  d   }t        | j                   || j                  | j                         }|
R||j#                  | j$                        nd}t        j&                  |||j                  d   z   |j                         }
||
j)                  d      }t+        | j                   |||
||	      }| j-                  ||
      }|rdnd }|rdnd }t/        | j0                        D ]6  \  }}|r||fz  } |||||||||||
      }|d   }|s(|d   .||d   fz  }8 | j3                  |      }|r||fz  }||j4                  sd|_        t7        ||r|nd ||      }|	r|S |j9                         S )NzaYou cannot specify both input_ids and inputs_embeds at the same time, and must specify either onezX`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`.Fr   )r:   r[   r  r#   r_   )rY   r  r   r}   r   r  )r  rU   )r   ry  r  r   r  T)last_hidden_stater   rD   
attentions)rY   ry  r  r  use_return_dict
ValueErrorr  r   r   r   r  r,   r6  r?   rX   r:   r[   r   r  r   r7  r
   r  r   r  r  ra   r   to_tuple)r1   r  r   r  r   r  r  ry  r  r  r}   r   rD   rx  rZ   past_seen_tokensr  r   all_hidden_statesall_self_attnsr{   layerr  rq  s                           r5   rL   zZamba2Model.forward  s    2C1N-TXT_T_TqTq$8$D $++JjJj 	 "+!6IDKK<Q<Q	%0%<k$++B]B]-t";<s  &&4==Yj I  --i8M%!&]!; 0/8/D+-J]J]^_J`J6t{{JVZV`V`imitituO! #.  ..9X9X.Y 
 #\\ "2]5H5H5K"KTaThThN )33A6L(;;'))+%
 #oom,oW"6BD0d )$++ 6 	:Iu#!m%55!!& /"3#$7)M *!,M  #/"}Q'7&99N-	:0 ,,];  -!11&/Q/Q15O.(+/8Od+%	
 %v;&//*;;r6   )
NNNNNNNNNN)rM   rN   rO   r   r$   r*   r  r,   r   r   rX   r  r  r   r   rL   rU   r6   r5   r  r    s   | .!%J .2.204;?26!%)-,0#'26m<##d*m< t+m< &&-	m<
 2D8m< ((4/m< $;m<  $;m< #Tkm< D[m< ((4/m< 
(	(m<r6   r  c                       e Zd Zy)Zamba2ForCausalLMNrT   rU   r6   r5   r  r  `  rV   r6   r  c                       e Zd Zy)Zamba2ForSequenceClassificationNrT   rU   r6   r5   r  r  d  rV   r6   r  )r  r  r  r  )Fr  collections.abcr   	itertoolsr   r,   r    r   r  activationsr   integrations.hub_kernelsr	   masking_utilsr
   modeling_flash_attention_utilsr   modeling_outputsr   modeling_utilsr   r   processing_utilsr   utilsr   r   utils.import_utilsr   llama.modeling_llamar   r   mamba2.modeling_mamba2r   r   r   zamba.modeling_zambar   r   r   r   r   r   r   r    r!   r"   configuration_zamba2r$   _CONFIG_FOR_DOC
get_loggerrM   r   Moduler&   rS   rX   r   r   r   re  rs  r  r  r  r  r  r  __all__rU   r6   r5   <module>r     sH    $    & ! 8 / B 7 F & 6 9 M Y Y   / '			H	%; ;*	L 	K$6 K$\	0 	j)n j)ZEOryy EOP'		 'T;"< ;|Z4 ZH( HV!O !<o<*3 o<d	( 		&D 	r6   