
    qi;                       d dl Z d dlmZ d dlmZ d dlmZmZ d dlZd dlm	Z	 d dl
mZmZ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 ddlmZ ddlm Z  ddl!m"Z"m#Z#m$Z$ ddl%m&Z&m'Z' ddl(m)Z)m*Z* ddl+m,Z, ddl-m.Z.m/Z/m0Z0 ddl1m2Z2 ddl3m4Z4 ddl5m6Z6  e0jn                  e8      Z9 G d dej                  jt                        Z; G d de	jt                        Z< G d d      Z= G d  d!e	jt                        Z>d"ej~                  d#e@d$ej~                  fd%ZA	 dMd&e	jt                  d'ej~                  d(ej~                  d)ej~                  d*ej~                  dz  d+eBd,eBfd-ZCd. ZD ed/      dNd0       ZE G d1 d2e	jt                        ZFd3ej~                  d4e@fd5ZGd6 ZHd7 ZI G d8 d9e	jt                        ZJ G d: d;e	jt                        ZK G d< d=e	jt                        ZL G d> d?e       ZM G d@ dAe       ZN G dB dCe*      ZOe. G dD dEeO             ZP G dF dGeOe      ZQ e.dHI       G dJ dKeO             ZRg dLZSy)O    N)Callable)cycle)AnyOptional)nn)BCEWithLogitsLossCrossEntropyLossMSELoss   )initialization)ACT2FN)Cache)GenerationMixin)use_kernel_func_from_hub)lazy_load_kernel)create_causal_mask)FlashAttentionKwargs)GradientCheckpointingLayer)BaseModelOutputWithPastCausalLMOutputWithPast SequenceClassifierOutputWithPast)ROPE_INIT_FUNCTIONSdynamic_rope_update)ALL_ATTENTION_FUNCTIONSPreTrainedModel)Unpack)auto_docstringis_torchdynamo_compilinglogging)maybe_autocast)resolve_internal_import   )Zamba2Configc                   (     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_sizer/   eps	__class__s       \/opt/pipecat/venv/lib/python3.12/site-packages/transformers/models/zamba2/modeling_zamba2.pyr)   zZamba2RMSNormGated.__init__5   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 N   T)keepdim)dtypetor+   float32r   
functionalsilushaper/   viewpowmeanrsqrtr.   r-   )	r0   hidden_statesgateinput_dtypeprefix_dimslast_dimgroup_counthidden_states_groupvariances	            r4   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:::r5   gư>r'   )__name__
__module____qualname__r)   rM   __classcell__r3   s   @r4   r%   r%   4   s    %;r5   r%   c                   h     e Zd Zddeddf fdZdej                  dej                  fdZd Z xZ	S )	Zamba2RMSNormr2   returnNc                     t         |           t        j                  t	        j
                  |            | _        || _        y)z<
        Zamba2RMSNorm is equivalent to T5LayerNorm
        N)r(   r)   r   r*   r+   r,   r-   r.   )r0   r1   r2   r3   s      r4   r)   zZamba2RMSNorm.__init__J   s1     	ll5::k#:; #r5   rE   c                 "   |j                   }|j                  t        j                        }|j	                  d      j                  dd      }|t        j                  || j                  z         z  }| j                  |j                  |      z  S r7   )	r;   r<   r+   r=   rB   rC   rD   r.   r-   )r0   rE   rG   rL   s       r4   rM   zZamba2RMSNorm.forwardR   sy    #))%((7 $$Q',,R,>%Ht?T?T4T(UU{{]--k:::r5   c                 ^    t        | j                  j                         d| j                   S )Nz, eps=)tupler-   r@   r.   r0   s    r4   
extra_reprzZamba2RMSNorm.extra_reprY   s*    ))*+6$2G2G1HIIr5   rN   )
rO   rP   rQ   floatr)   r+   TensorrM   r\   rR   rS   s   @r4   rU   rU   I   s7    $ $$ $;U\\ ;ell ;Jr5   rU   c                      e Zd ZdZdZej                  dfdededej                  de
dz  fdZd	 Z	 dd
ej                  dej                  dedee
ef   dz  deej                  ej                  f   f
dZdej$                  f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dedej                  dej$                  dej                  fdZ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)`.
    FN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 )NFr8   rc   r;   hybridrc   )r;   layers_block_typehas_previous_stateintmamba_expandr1   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)r0   ra   rb   r;   rc   i_s          r4   r)   z!Zamba2HybridDynamicCache.__init__m   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c                 ,    t        | j                        S r'   )lenr   r[   s    r4   __len__z Zamba2HybridDynamicCache.__len__   s    4>>""r5   
key_statesvalue_states	layer_idxcache_kwargsrV   c                    | j                   |   j                  d   dk(  r|| j                   |<   || j                  |<   nft        j                  | j                   |   |gd      | j                   |<   t        j                  | j                  |   |gd      | j                  |<   | j                   |   | j                  |   fS )Nr9   r   r8   dim)r   r@   r   r+   cat)r0   r   r   r   r   s        r4   updatezZamba2HybridDynamicCache.update   s     >>)$**2.!3(2DNN9%*6DY'(-		4>>)3Lj2Y_`(aDNN9%*/))T5E5Ei5PR^4_ef*gDY'~~i($*:*:9*EEEr5   beam_idxc                    | j                         dkD  rvt        t        | j                              D ]S  }| j                  |   j                  }| j                  |   j                  d|j                  |            | j                  |<   | j                  |   j                  }| j                  |   j                  d|j                  |            | j                  |<   | j                  |   j                  }| j                  |   j                  d|j                  |            | j                  |<   | j                  |   j                  }| j                  |   j                  d|j                  |            | j                  |<   V yy)zDReorders the cache for beam search, given the selected beam indices.r   N)
get_seq_lengthrx   r   r   rc   index_selectr<   r   rv   rw   )r0   r   r   rc   s       r4   reorder_cachez&Zamba2HybridDynamicCache.reorder_cache   s[    1$"3t~~#67 	m		299,0NN9,E,R,RSTV^VaVabhVi,jy))))4;;.2.>.>y.I.V.VWXZbZeZeflZm.n  +)))4;;.2.>.>y.I.V.VWXZbZeZeflZm.n  +3::-1__Y-G-T-TUVX`XcXcdjXk-l	*	m %r5   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   )rr   r   r   numelr@   )r0   r   s     r4   r   z'Zamba2HybridDynamicCache.get_seq_length   sl     3<4CZCZ2ZD++A.`i	t~~)+t~~i/H/N/N/PTU/U~~i(..r22r5   cache_positionc                 T    d}|j                   d   }| j                  |      |z   }||fS )zDReturn the length and offset of the cache, used to generate the maskr   )r@   r   )r0   r   r   	kv_offsetquery_length	kv_lengths         r4   get_mask_sizesz'Zamba2HybridDynamicCache.get_mask_sizes   s7    	%++A.''	2\A	)##r5   new_conv_statec                 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"   r9   shiftsdims)rv   clamprp   rollr<   rc   zero_)r0   r   r   r   
conv_states        r4   update_conv_statez*Zamba2HybridDynamicCache.update_conv_state   s     %%i0
'--a1F1F1JK__BR_8
+9+<+<Z=N=N+O
1a'(#))+#z1#	**r5   c                 l    | j                   j                          | j                  j                          y r'   )rv   r   rw   r[   s    r4   resetzZamba2HybridDynamicCache.reset   s$     r5   r'   )r   )rO   rP   rQ   __doc__is_compileabler+   float16r#   rj   r;   strr)   r   r^   dictr   rZ   r   
LongTensorr   r   r   r   r    r5   r4   r`   r`   ]   sI    N KP--nru"u03u<AKKuadgkaku@# /3FLLF llF 	F
 38nt+F 
u||U\\)	*F"me&6&6 m3d
 33 3$U\\ $c $eTWY\T\o $
+
+.3ll
+LQL\L\
+	
+ r5   r`   c                        e Zd ZU ej                  ed<   ddef fdZe	 	 	 ddedz  de	d   de
dz  ded	ef   fd
       Z ej                         ed               Z xZS )Zamba2RotaryEmbeddinginv_freqNra   c                    t         |           |j                  | _        |j                  | _        || _        | j
                  j                  d   | _        | j                  }| j                  dk7  rt        | j                     } || j
                  |      \  }| _
        | j                  d|d       | j                  d|j                         d       y )N	rope_typedefaultr   F)
persistentoriginal_inv_freq)r(   r)   max_position_embeddingsmax_seq_len_cachedoriginal_max_seq_lenra   rope_parametersr   compute_default_rope_parametersr   attention_scalingregister_bufferclone)r0   ra   rc   rope_init_fnr   r3   s        r4   r)   zZamba2RotaryEmbedding.__init__   s    "("@"@$*$B$B!44[A!%!E!E>>Y&.t~~>L+7V+L($(ZeD0(..2BuUr5   rc   ztorch.deviceseq_lenrV   ztorch.Tensorc                    | j                   d   }t        | dd      xs | j                  | j                  z  }d}d|t	        j
                  d|dt        j                        j                  |t        j                        |z  z  z  }||fS )	a  
        Computes the inverse frequencies according to the original RoPE implementation
        Args:
            config ([`~transformers.PreTrainedConfig`]):
                The model configuration.
            device (`torch.device`):
                The device to use for initialization of the inverse frequencies.
            seq_len (`int`, *optional*):
                The current sequence length. Unused for this type of RoPE.
        Returns:
            Tuple of (`torch.Tensor`, `float`), containing the inverse frequencies for the RoPE embeddings and the
            post-processing scaling factor applied to the computed cos/sin (unused in this type of RoPE).
        
rope_thetahead_dimNg      ?r   r8   r;   re   )	r   getattrr1   num_attention_headsr+   arangeint64r<   r]   )ra   rc   r   baser   attention_factorr   s          r4   r   z5Zamba2RotaryEmbedding.compute_default_rope_parameters   s    & %%l3fj$/c63E3EIcIc3c U\\!S!5;;?BB&X]XcXcBdgjjk
 )))r5   c                 N   | j                   d d d d f   j                         j                  |j                  d   dd      j	                  |j
                        }|d d d d d f   j                         }t        |j
                  j                  t              r/|j
                  j                  dk7  r|j
                  j                  nd}t        |d      5  |j                         |j                         z  j                  dd      }t        j                  ||fd	      }|j                         | j                  z  }|j                         | j                  z  }	d d d        j	                  |j                   
      	j	                  |j                   
      fS # 1 sw Y   AxY w)Nr   r9   r"   mpscpuF)device_typeenabledr8   r   r   )r   r]   expandr@   r<   rc   
isinstancetyper   r    	transposer+   r   cosr   sinr;   )
r0   xposition_idsinv_freq_expandedposition_ids_expandedr   freqsembr   r   s
             r4   rM   zZamba2RotaryEmbedding.forward   sR    !MM$4-8>>@GGHZHZ[\H]_acdehhijiqiqr ,QaZ 8 > > @'1!((--'E!((--[`J`ahhmmfkUC 	5&,,.1F1L1L1NNYYZ[]^_E))UEN3C'')d444C'')d444C		5 vvAGGv$cff177f&;;;	5 	5s   BFF$r'   NNN)rO   rP   rQ   r+   r^   __annotations__r#   r)   staticmethodr   rj   rZ   r]   r   no_gradr   rM   rR   rS   s   @r4   r   r      s    llV| V  &*+/"*t#*(* t* 
~u$	%	* *: U]]_<  <r5   r   rE   n_reprV   c                     | j                   \  }}}}|dk(  r| S | dddddddddf   j                  |||||      } | j                  |||z  ||      S )z
    This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
    num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
    r"   N)r@   r   reshape)rE   r   batchnum_key_value_headsslenr   s         r4   	repeat_kvr     so    
 2?1D1D.Ehz!!Qa"23::5BUW\^bdlmM  (;e(CT8TTr5   modulequerykeyvalueattention_maskscalingdropoutc                    t        || j                        }t        || j                        }	t        j                  ||j	                  dd            |z  }
||
|z   }
t
        j                  j                  |
dt        j                        j                  |j                        }
t
        j                  j                  |
|| j                        }
t        j                  |
|	      }|j	                  dd      j                         }||
fS )Nr8   r   r9   )r   r;   )ptrainingr"   )r   num_key_value_groupsr+   matmulr   r   r>   softmaxr=   r<   r;   r   r   
contiguous)r   r   r   r   r   r   r   kwargsr   r   attn_weightsattn_outputs               r4   eager_attention_forwardr     s     3 ; ;<JUF$?$?@L<<z';';Aq'ABWLL!#n4==((2U]](SVVW\WbWbcL==((6??([L,,|\:K''1-88:K$$r5   c                     | dd| j                   d   dz  f   }| d| j                   d   dz  df   }t        j                  | |fd      S )z*Rotates half the hidden dims of the input..Nr9   r8   r   )r@   r+   r   )r   x1x2s      r4   rotate_halfr   5  sZ    	
3"!''"+"""	#B	
3q ""	#B99rc2YB''r5   rotary_pos_embc                     |j                  |      }|j                  |      }| |z  t        |       |z  z   }||z  t        |      |z  z   }||fS )a  Applies Rotary Position Embedding to the query and key tensors.

    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.
        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.
    )	unsqueezer   )qkr   r   unsqueeze_dimq_embedk_embeds          r4   apply_rotary_pos_embr  <  sY    & --
&C
--
&C3w;q>C/0G3w;q>C/0GGr5   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).
    Nra   r   num_fwd_mem_blocksblock_idc           	         t         |           || _        || _        |j                  | _        |j
                  | _        |j                  |j                  z  | _	        |j                  | _
        | j                  dz  dz  | _        d| _        |j                  | _        t        j                  |j                  |j                  | j                  z  d      | _        t        j                  |j                  |j                  | j                  z  d      | _        t        j                  |j                  |j                  | j                  z  d      | _        t        j                  |j                  | j                  z  |j&                  d      | _        || _        |j,                  | _        || _        |j2                  rt        j4                  g       | _        t        j4                  g       | _        t        j4                  g       | _        t=        | j*                        D ]  }||j>                  z  |k(  r{t        j@                  t        j                  | j                  | j                  jB                  d      t        j                  | j                  jB                  | j                  d            }t        j@                  t        j                  | j                  | j                  jB                  d      t        j                  | j                  jB                  | j                  d            }t        j@                  t        j                  | j                  | j                  jB                  d      t        j                  | j                  jB                  | j                  d            }n<t        jD                         }t        jD                         }t        jD                         }| j6                  jG                  |       | j8                  jG                  |       | j:                  jG                  |       ! tI        | j.                        D 	
ci c]  \  }	}
|
|	
 c}
}	| _%        y c c}
}	w )Nr8   g      TFbias)&r(   r)   ra   r   attention_hidden_sizeattention_head_dimr   r   r   r   r   r   	is_causalattention_dropoutr   Linearq_projk_projv_projr1   o_projr	  hybrid_layer_idslayer_block_mapr
  use_shared_attention_adapter
ModuleListlinear_q_adapter_listlinear_k_adapter_listlinear_v_adapter_listrx   num_mem_blocks
Sequentialadapter_rankIdentityr}   	enumerate	layer_dic)r0   ra   r   r	  r
  r   linear_q_adapterlinear_k_adapterlinear_v_adapterindexr   r3   s              r4   r)   zZamba2Attention.__init__f  sJ    	"%+%A%A"11$*$>$>&B\B\$\!'-'E'E$)d2!'!9!9ii < <f>X>X[_[h[h>hotuii < <f>X>X[_[h[h>hotuii < <f>X>X[_[h[h>hotuii : :T]] JFL^L^ejk"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   Q6rE   r   past_key_valuesposition_embeddingsr   rV   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 )Nr9   r"   r8           )r   r   )r@   r   r  r  r  ra   r  r#  r  r  r  rA   r   use_mem_roper  r   r   get_interface_attn_implementationr   r   r  r   r   r   r  )r0   rE   r   r   r(  r)  r   input_shapehidden_shapequery_statesr   r   adapter_layer_idxr   r   attention_interfacer   r   s                     r4   rM   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((r5   r   )rO   rP   rQ   r   r#   rj   r)   r+   r^   r`   rZ   r   r   rM   rR   rS   s   @r4   r  r  V  s    $ !%)-#6\6\ :6\  $J	6\
 *6\x /3;?HL1)||1) 1) t+	1)
 2D81) #5<<#=>E1) -.1) 
u||U\\D0%2E2LL	M1)r5   r  input_tensorpad_sizec                     t        | j                        dk(  r
ddddd|ddfnddd|ddf}t        j                  j                  j                  | |dd      S )z
    Padding x tensor with `pad_size` on the seq_len dim (dim=1)

    Assumes that we only have tensors of either size 4 or 3
       r   constant)moder   )r   r@   r+   r   r>   pad)r4  r5  	pad_shapes      r4   pad_tensor_by_sizer<    sf     47|7I7I3Ja3OAq!Q!Q/VWYZ\]_gijlmUnI88""<ST"UUr5   c                    t        | |      } t        | j                        dk(  r.| j                  | j                  d   d|| j                  d         S | j                  | j                  d   d|| j                  d   | j                  d         S )z
    Padding input_tensor with `pad_size` on the seq_len dim (dim=1) and
    simultaneously splitting it into chunk sequences.

    Assumes that we only have tensors of either size 4 or 3
    r   r   r9   r8   )r<  r   r@   r   )r4  r5  
chunk_sizes      r4   reshape_into_chunksr?    s     &lH=L
<!###L$6$6q$92z<K]K]^_K`aa ##q!2z<3E3Ea3H,J\J\]^J_
 	
r5   c                 "   | j                  d      } | d   j                  g | j                         | } t        j                  t        j                  ||| j
                  t        j                        d      }| j                  | d      } t        j                  | d      }t        j                  t        j                  ||| j
                  t        j                        d      }|j                  | t        j                         }|S )zo
    More stable segment sum calculation. Uses cumulative sums and masking instead of direct subtractions.
    r9   .Nre   )diagonalr   r   r   )
sizer   r+   trilr,   rc   boolmasked_fillcumsuminf)r4  r>  masktensor_segsums       r4   segment_sumrK    s     ""2&J 2<	*11S<3D3D3FS
SL::ejjZ@S@S[`[e[efqstD++TE15LLL26M ::ejjZ@S@S[`[e[efqrsD!--teeiiZ@Mr5   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)
    Nra   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?   r8   Tr"   )in_channelsout_channelsr  kernel_sizegroupspaddingr  gh㈵>)r/   r2   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)   ra   r1   rm   rn   ro   rp   rj   rk   rl   r   use_conv_bias
activationr   SiLUactuse_mem_eff_pathr{   n_groupsr|   r   rq   	num_headsr>  time_step_limittime_step_mintime_step_maxconv_dimConv1dconv1dr  add_bias_linearin_projr*   r+   r,   dt_biasr   logA_logr%   normDout_projr   r   rT  rU  r!   selective_state_updatemamba_chunk_scan_combined mamba_split_conv1d_scan_combinedallis_fast_path_availableloggerwarning_once)r0   ra   r   projection_sizeAcausal_conv1d	mamba_ssmr3   s          r4   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 $"
 &> &r5   rE   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 )Nr8   r"   r9   r   .r   T)zrf  dt_softplusdt_limitF)rj  r>  seq_idxrX  rmsnorm_weightrmsnorm_epsoutproj_weightoutproj_biasheaddimngroupsnorm_before_gatereturn_final_statesr   )r?   swish)r   r-   r  rX  )r>  rj  ry  r|  r  rf  rz  )1r@   r\  rn   rl   r]  ri   re  squeezera  r+   splitrT  rv   r   rc  r-   r  rX  exprh  r]   r   r   r<   r=   rf  rj  rA   rl  rw   ri  rk  ro  r;   r^  r[  r   rn  r>  r.   r   r   r>   r:  rp   copy_rU  rZ  rm  )r0   rE   rw  r   rb   r   r   groups_time_state_sized_to_removein_projected_statesd_mlpsplit_projection_dimrF   hidden_states_B_CdtBCrt  rf  rj  hidden_states_reshapedoutr;   projected_statesdt_limit_kwargsinput_not_masked	ssm_state	time_stephidden_states_B_C_tr   scan_outputs                                  r4   cuda_kernels_forwardz%Zamba2MambaMixer.cuda_kernels_forwardk  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
r5   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"   r9   r8   r   r   r   r   .re   rA  ).NNr   )r   output_sizer7  )r"   r   )<r@   r;   ri   re  r  r<   rl   r\  rn   r]  r  ra  rw   r   r   rc   r   rv   r+   r   ndimr  sumrc  r-   rW  r  rZ  r   r   r>   r:  rp   rz   r   r  rh  r]   r   rf  softplusr   r_  r=   r   r   rA   bmmrj  repeat_interleaver>  r<  r?  permuterG  rK  
zeros_liker   ri  rk  )3r0   input_statesrw  r   rb   r   r   r;   r  r  rF   rE   r  r  r   r  r  rt  rf  dAdBdBxrw   ssm_states_reshaped
C_reshapedyrj  r5  
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_offr  contextualized_statess3                                                      r4   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)rp  re  r-   rc   r   r   r  r  )r0   rE   rw  r   s       r4   rM   zZamba2MambaMixer.forward  sT     "f0C0C0J0J0O0O&OXpXr,,]L.YY!!-~NNr5   r'   NN)rO   rP   rQ   r   r#   rj   r)   r+   r^   r`   r  r  rM   rR   rS   s   @r4   rM  rM    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r5   rM  c                   8     e Zd Zddededz  f fdZddZ xZS )	Zamba2MLPNra   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.
        r8   r  FN)r(   r)   ra   r1   rl   r	  r
  r   r  rd  gate_up_proj	down_projr   
hidden_actact_fnr  gate_up_proj_adapter_listrx   r  r  r   r!  r}   r  r"  r#  )
r0   ra   r	  r
  r   gate_up_proj_adapterr  r'  r   r3   s
            r4   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 )Nr8   r9   r   r   r"   )r  r#  r  r+   chunkr  r  )r0   hidden_stater   gate_up_stateoutputs        r4   rM   zZamba2MLP.forward  s    )),7NN9-	%(Q(F(Fy(QR^(__M1"={{=#34}Q7GG-r5   r  r'   )rO   rP   rQ   r#   rj   r)   rM   rR   rS   s   @r4   r  r    s%    W| WPSVZPZ W<r5   r  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 )Zamba2AttentionDecoderLayerNra   r
  r   c                 @   t         |           || _        t        |j                        }t        |d||      | _        t        |||      | _        t        |j                  |j                        | _        t        |j                  |j                        | _        y )Nr9   )r   r	  r
  )r	  r
  r2   )r(   r)   r
  r   r  r  	self_attnr  feed_forwardrU   r  rms_norm_epsinput_layernormr1   pre_ff_layernorm)r0   ra   r
  r   num_gsr3   s        r4   r)   z$Zamba2AttentionDecoderLayer.__init__  s     V,,-(2RXckl%fRZ[,V-I-IvObObc -f.@.@fFYFY Zr5   rE   original_hidden_statesr   r(  output_attentionsr)  r   rV   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.
        r9   r   )rE   r   r   r(  r  r)  r   )r+   concatenater  r  r  r  )r0   rE   r  r   r   r(  r  r)  r   self_attn_weightsoutputss              r4   rM   z#Zamba2AttentionDecoderLayer.forward  s    > ))=:P*QWYZ,,];+94>> ,
')+/ 3,
 ,
(( --m<))-C ")++Gr5   r  )NNFN)rO   rP   rQ   r#   rj   r)   r+   r^   r`   rE  r   r   r   rZ   FloatTensorrM   rR   rS   s   @r4   r  r    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r5   r  c                       e Zd Zde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j                  dz  deej                  eej                  ej                  f   dz  f   fdZ xZS )Zamba2MambaDecoderLayerra   r   c                     t         |           t        ||      | _        t	        |j
                  |j                        | _        || _        y )N)ra   r   r  )	r(   r)   rM  mambarU   r1   r  r  r   )r0   ra   r   r3   s      r4   r)   z Zamba2MambaDecoderLayer.__init__;  s>    %VyI
,V-?-?VEXEXY"r5   NrE   r  r   causal_maskr(  r  	use_cacher   r   transformer_hidden_statesrV   c                     |}|||z   n|}| j                  |      }| j                  |||      }d}||z   }|f}|r||fz  }|r||fz  }|S )a  
        Args:
            hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
            attention_mask (`torch.FloatTensor`, *optional*): attention mask of size
                `(batch, sequence_length)` where padding elements are indicated by 0.
            past_key_values (`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`).
            cache_position (`torch.LongTensor` of shape `(sequence_length)`, *optional*):
                Indices depicting the position of the input sequence tokens in the sequence.
        N)rE   rw  r   )r  r  )r0   rE   r  r   r   r  r(  r  r  r   r   r  r   residualr  r  s                   r4   rM   zZamba2MambaDecoderLayer.forwardA  s    > !
 :S9^M55dq 	 ,,];

'() # 
 ! !=0 ")++G))Gr5   )
NNNNNFFNNN)rO   rP   rQ   r#   rj   r)   r+   r^   r`   rE  r   rZ   r  rM   rR   rS   s   @r4   r  r  :  s,   #| # # 7; $.2+/;?).!&26049=;||; !&t 3; :	;
 t+; \\D(; 2D8;  $;; $;; ((4/; &&-; $)<<$#6; 
u  %(9(95;L;L(L"MPT"TT	U;r5   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                 L    t         |           || _        || _        || _        y r'   )r(   r)   r  mamba_decoderr  )r0   r  r  r  r3   s       r4   r)   zZamba2HybridLayer.__init__  s'     	""4r5   NrE   r  r   r   r  r(  r  r  r)  r   rV   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.
        )r  r   r   r(  r  r)  r   r   r"   )r  r   r(  r  r  r)  r8   N)r  r  r  )r0   rE   r  r   r   r  r(  r  r  r)  r   layer_outputsr  r  s                 r4   rM   zZamba2HybridLayer.forward  s    B //#9&+/ 3% 0 	
 %2!$4! -a 0$(KK0I$J!**&?)+/ 3 + 
 *1-/@AMRSRTDUUMr5   )	NNNNNFFNN)rO   rP   rQ   r  r   r  r  r)   r+   r^   rj   r`   rE  r   rZ   r  rM   rR   rS   s   @r4   r  r    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@r5   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 )Zamba2PreTrainedModelra   modelTr  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_weightsr   rM  r+   r  randra   rq   mathrg  r`  r_  r   time_step_floorexpm1initr  rf  r   r]  rh  ones_rj  )r0   r   r  inv_dtrt  r3   s        r4   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  0r5   )rO   rP   rQ   r#   r   base_model_prefixsupports_gradient_checkpointing_no_split_modules_skip_keys_device_placement_supports_flash_attn_supports_flex_attn_supports_sdpa_is_statefulr+   r   r  rR   rS   s   @r4   r  r    sW    &*#68QR"3NLU]]_! !r5   r  c                   (    e Zd ZdZdef fdZe	 	 	 	 	 	 	 	 	 	 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d Z xZS )Zamba2Modelzh
    Model consisting of *config.num_hidden_layers* layers.

    Args:
        config: Zamba2Config
    ra   c                 L   t         |   |       || _        |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)   ra   pad_token_idpadding_idx
vocab_sizer   	Embeddingr1   embed_tokensrh   
get_layerslayersr.  rU   r  final_layernormr,  use_long_contextrq  rr  r   
rotary_embgradient_checkpointing	post_initr0   ra   r3   s     r4   r)   zZamba2Model.__init__  s     !.. ++LL):):F<N<NPTP`P`a!'!9!9oo'$*$?$?!,V-?-?VEXEXY&&##{ 4F;DO&+# 	r5   N	input_idsr   r   r(  inputs_embedsr  r  output_hidden_statesreturn_dictr   rV   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;   rc   r   r"   rg   )ra   r  r   r   r(  r   )r   r   )r(  r  r  r)  r   T)last_hidden_stater(  rE   
attentions)ra   r  r  r  use_return_dict
ValueErrorr  r   rq  rr  r  r+   r   r@   r`   r;   rc   r   first_transformer_layer_idr   r   r   r  r"  r  r  ri   r   to_tuple)r0   r  r   r   r(  r  r  r  r  r  r   r   rE   r  rb   past_seen_tokensr  r)  all_hidden_statesall_self_attnsr   layerr  r  s                           r4   rM   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;&//*;;r5   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"  rf   zlayers.z.shared_transformer)r
  Fr  )_tied_weights_keysr'  r"  rh   r  ra   r   listr   r  r   nextr   r}   r  r   r  r1   r  r  )r0   r  unique_hybrid_blockslayer_id
layer_typemamba_layerprefix_patterntarget_patternr
  
attn_blocklinear_layers              r4   r  zZamba2Model.get_layersy  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$$r5   
NNNNNNNNNN)rO   rP   rQ   r   r#   r)   r   r+   r   r^   r`   r  rE  rZ   r   rM   r  rR   rS   s   @r4   r  r    s   | .  .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< m<^!%r5   r  c                       e Zd ZddiZdef fdZe	 	 	 	 	 	 	 	 	 	 	 	 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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j                  z  deez  fd       Z	 	 	 	 	 	 	 d fd	Z xZS )Zamba2ForCausalLMzlm_head.weightzmodel.embed_tokens.weightra   c                     t         |   |       t        |      | _        |j                  | _        t        j                  |j                  |j                  d      | _        | j                          y NFr  )
r(   r)   r  r  r  r   r  r1   lm_headr  r  s     r4   r)   zZamba2ForCausalLM.__init__  sU      (
 ++yy!3!3V5F5FUS 	r5   Nr  r   r   r(  r  labelsr  r  r  r  r   logits_to_keeprV   c                    ||n| j                   j                  }|	|	n| j                   j                  }	|
|
n| j                   j                  }
| j	                  ||||||||	||

      }|d   }t        |t              rt        | d      n|}| j                  |dd|ddf         }d}| | j                  ||| j                  fi |}|
s|f|dd z   }||f|z   S |S t        |||j                  |j                  |j                        S )al  
        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, Zamba2ForCausalLM

        >>> model = Zamba2ForCausalLM.from_pretrained("Zyphra/Zamba2-7B-v1")
        >>> tokenizer = AutoTokenizer.from_pretrained("Zyphra/Zamba2-7B-v1")

        >>> prompt = "Hey, are you conscious? Can you talk to me?"
        >>> inputs = tokenizer(prompt, return_tensors="pt")

        >>> # Generate
        >>> generate_ids = model.generate(inputs.input_ids, max_length=30)
        >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
        "Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you."
        ```N)
r  r   r   r(  r  r  r  r  r   r  r   r"   losslogitsr(  rE   r$  )ra   r  r  r%  r  r   rj   slicer>  loss_functionr  r   r(  rE   r$  )r0   r  r   r   r(  r  r?  r  r  r  r  r   r@  r   r  rE   slice_indicesrD  rC  r  s                       r4   rM   zZamba2ForCausalLM.forward  sL   P 2C1N-TXT_T_TqTq %9$D $++JjJj 	 &1%<k$++B]B] **)%+'/!5)#  
  
8B>SV8W~ot4]kmA}a,?@A%4%%ffdooPPDY,F'+'7D7V#CVC%#33!//))
 	
r5   c	                     |:t        | j                  |j                  d   | j                  | j                        }| j                  j
                  |	d<   t        |   |f|||||||d|	}
|
S )Nr   r!  r@  )r(  r   r  r   r   r  is_first_iteration)r`   ra   r@   r;   rc   num_logits_to_keepr(   prepare_inputs_for_generation)r0   r  r(  r   r  r   r   r  rI  r   model_inputsr3   s              r4   rK  z/Zamba2ForCausalLM.prepare_inputs_for_generation  s     "6Y__Q/tzz$++O $(;;#A#A w<

+)')%1

 

 r5   )NNNNNNNNNNNr   )NNNNNTF)rO   rP   rQ   r.  r#   r)   r   r+   r   r^   r`   r  rE  rj   rZ   r   rM   rK  rR   rS   s   @r4   r;  r;    sj   *,GH|   .2.204;?26*.!%)-,0#'26-.O
##d*O
 t+O
 &&-	O

 2D8O
 ((4/O
   4'O
 $;O
  $;O
 #TkO
 D[O
 ((4/O
 ell*O
 
'	'O
 O
h     r5   r;  a  
    The Zamba2 Model with a sequence classification head on top (linear layer).

    [`Zamba2ForSequenceClassification`] uses the last token in order to do the classification, as other causal models
    (e.g. GPT-2) do.

    Since it does classification on the last token, it requires to know the position of the last token. If a
    `pad_token_id` is defined in the configuration, it finds the last token that is not a padding token in each row. If
    no `pad_token_id` is defined, it simply takes the last value in each row of the batch. Since it cannot guess the
    padding tokens when `inputs_embeds` are passed instead of `input_ids`, it does the same (take the last value in
    each row of the batch).
    )custom_introc                       e Zd Z fdZe	 	 	 	 	 	 	 	 	 	 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j                  dz  d	e
dz  d
e
dz  de
dz  de
dz  deez  fd       Z xZS )Zamba2ForSequenceClassificationc                     t         |   |       |j                  | _        t        |      | _        t        j                  |j                  | j                  d      | _        | j                          y r=  )
r(   r)   
num_labelsr  r  r   r  r1   scorer  r  s     r4   r)   z(Zamba2ForSequenceClassification.__init__.  sS      ++ (
YYv114??O
 	r5   Nr  r   r   r(  r  r?  r  r  r  r  rV   c                    |
|
n| j                   j                  }
| j                  ||||||||	|
	      }|d   }| j                  |      }||j                  d   }n|j                  d   }| j                   j
                  |dk7  rt        d      | j                   j
                  d}n||| j                   j
                  k7  j                  |j                  t        j                        }t        j                  |j                  d   |j                  t        j                        }||z  j                  d      }n.d}t        j                  | j                  j                    d       |t        j                  ||j                  	      |f   }d}||j                  |j                        }| j                   j"                  | j$                  dk(  rd
| j                   _        nl| j$                  dkD  rL|j&                  t        j(                  k(  s|j&                  t        j*                  k(  rd| j                   _        nd| j                   _        | j                   j"                  d
k(  rIt-               }| j$                  dk(  r& ||j/                         |j/                               }n |||      }n| j                   j"                  dk(  r=t1               } ||j3                  d| j$                        |j3                  d            }n,| j                   j"                  dk(  rt5               } |||      }|
s|f|dd z   }||f|z   S |S t7        |||j8                  |j:                  |j<                        S )a  
        labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
            Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
            config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
            `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
        N)r   r   r(  r  r  r  r  r  r   r"   z=Cannot handle batch sizes > 1 if no padding token is defined.r9   re   z will not detect padding tokens in `inputs_embeds`. Results may be unexpected if using padding tokens in conjunction with `inputs_embeds.`rg   
regressionsingle_label_classificationmulti_label_classificationrB  )ra   r%  r  rR  r@   r  r&  r<   rc   r+   int32r   argmaxrq  rr  r3   rO   problem_typerQ  r;   longrj   r
   r  r	   rA   r   r   r(  rE   r$  )r0   r  r   r   r(  r  r?  r  r  r  r  r   transformer_outputsrE   rD  rb   last_non_pad_tokennon_pad_masktoken_indicespooled_logitsrC  loss_fctr  s                          r4   rM   z'Zamba2ForSequenceClassification.forward7  s   * &1%<k$++B]B]"jj)%+'/!5# ) 

 ,A.M* "+J&,,Q/J;;##+
a\]];;##+!#"%)A)AAEEfmmUZU`U`aL!LL)<V]]Z_ZeZefM"/,">!F!Fr!J!#>>**+ ,Z Z
 u||Jv}}MOaabYYv}}-F{{''/??a'/;DKK,__q(fllejj.HFLL\a\e\eLe/LDKK,/KDKK,{{''<7"9??a'#M$9$9$;V^^=MND#M6:D))-JJ+- 2 22t GUWY))-II,.v6#%(;AB(??F)-)9TGf$EvE/ /??-;;*55
 	
r5   r9  )rO   rP   rQ   r)   r   r+   r   r^   r   r  rE  rZ   r   rM   rR   rS   s   @r4   rO  rO    s     .2.204(,26*.!%)-,0#'\
##d*\
 t+\
 &&-	\

 \
 ((4/\
   4'\
 $;\
  $;\
 #Tk\
 D[\
 
1	1\
 \
r5   rO  )r;  rO  r  r  )r+  )r"   )Tr  collections.abcr   	itertoolsr   typingr   r   r+   r   torch.nnr   r	   r
    r   r  activationsr   cache_utilsr   
generationr   integrationsr   integrations.hub_kernelsr   masking_utilsr   modeling_flash_attention_utilsr   modeling_layersr   modeling_outputsr   r   r   modeling_rope_utilsr   r   modeling_utilsr   r   processing_utilsr   utilsr   r   r   utils.genericr    utils.import_utilsr!   configuration_zamba2r#   
get_loggerrO   rq  Moduler%   rU   r`   r   r^   rj   r   r]   r   r   r  r  r<  r?  rK  rM  r  r  r  r  r  r  r;  rO  __all__r   r5   r4   <module>ry     sX  *  $      A A & !   ) 4 8 / B 9 q q K F & F F + 9 . 
		H	%; ;*JBII J(o  o d><BII ><B	UU\\ 	U# 	U%,, 	U& %II%<<% 
% <<	%
 LL4'% % %2( *+ ,2y)bii y)~VU\\ VS V
((EOryy EOP'		 'T=")) =@B8 BJI2 IX!O !< p%' p% p%h~- ~B g
&; g
g
T kr5   