o
    wi%                     @   s  d Z ddlZddlmZmZmZmZ ddl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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! ddl"m#Z#m$Z$ ddl%m&Z&m'Z' ddl(m)Z) e' rddl*m+Z+m,Z, ddl-m.Z. nd\Z.Z,Z+e& rddl/m0Z0m1Z1 nd\Z1Z0e2e.e,e0e1e+fZ3e$4e5Z6G dd de	j7Z8dej9de:dej9fddZ;G dd  d eZ<	!dBd"e	j7d#ej9d$ej9d%ej9d&eej9 d'e=d(e=fd)d*Z>G d+d, d,e	j7Z?G d-d. d.e	j7Z@G d/d0 d0e	j7ZAG d1d2 d2e	j7ZBG d3d4 d4e	j7ZCG d5d6 d6e	j7ZDe#G d7d8 d8eZEe#G d9d: d:eEZFG d;d< d<eEeZGe#d=d>G d?d@ d@eEZHg dAZIdS )CzPyTorch Zamba model.    N)AnyCallableOptionalUnion)nn)BCEWithLogitsLossCrossEntropyLossMSELoss   )ACT2FN)CacheDynamicCache)GenerationMixin)AttentionMaskConverter)FlashAttentionKwargs)BaseModelOutputWithPastCausalLMOutputWithPast SequenceClassifierOutputWithPast)ALL_ATTENTION_FUNCTIONSPreTrainedModel)Unpack)auto_docstringlogging)is_causal_conv1d_availableis_mamba_ssm_available   )ZambaConfig)mamba_inner_fnselective_scan_fn)selective_state_update)NNN)causal_conv1d_fncausal_conv1d_updateNNc                       s.   e Zd Zd fdd	Zdd Zdd Z  ZS )	ZambaRMSNormư>c                    s&   t    tt|| _|| _dS )z;
        ZambaRMSNorm is equivalent to T5LayerNorm
        N)super__init__r   	Parametertorchonesweightvariance_epsilon)selfhidden_sizeeps	__class__ e/home/ubuntu/sommelier/.venv/lib/python3.10/site-packages/transformers/models/zamba/modeling_zamba.pyr&   @   s   

zZambaRMSNorm.__init__c                 C   sJ   |j }|tj}|djddd}|t|| j  }| j|| S )N   T)keepdim)	dtypetor(   float32powmeanrsqrtr+   r*   )r,   hidden_statesinput_dtypevariancer1   r1   r2   forwardH   s
   zZambaRMSNorm.forwardc                 C   s   t | jj d| j S )Nz, eps=)tupler*   shaper+   r,   r1   r1   r2   
extra_reprO   s   zZambaRMSNorm.extra_repr)r$   )__name__
__module____qualname__r&   r?   rC   __classcell__r1   r1   r/   r2   r#   ?   s    r#   r<   n_repreturnc                 C   s^   | j \}}}}|dkr| S | dddddddddf |||||} | ||| ||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)rA   expandreshape)r<   rH   batchnum_key_value_headsslenhead_dimr1   r1   r2   	repeat_kvT   s
   0rP   c                   @   s   e Zd ZdZejdfddZ	ddejdejdede	e
eef  d	eejejf f
d
dZdejfddZdde	e d	efddZd	eeej eej f fddZedde	eeej   d	dfddZdS )ZambaHybridDynamicCachea  
    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)`.
    Nc              
      s  || _ |j| _d| _|j|j | _|j| _|j| _	|j
| _
g | _g | _g | _i | _i | _i | _t|jD ];}|  jtj | j| j	|dg7  _ | j
| j| j
 | jf}|  jtj||dg7  _| j| dkro| j| q4 fddt|jD | _ fddt|jD | _d S )NFdevicer6   hybridc                        g | ]}t jg g  d qS rS   r(   tensor.0_
batch_sizerS   r1   r2   
<listcomp>        z4ZambaHybridDynamicCache.__init__.<locals>.<listcomp>c                    rU   rV   rX   rZ   r]   r1   r2   r_      r`   )r6   layers_block_typehas_previous_statemamba_expandr-   intermediate_sizemamba_d_statessm_state_sizemamba_d_convconv_kernel_sizen_mamba_headsconv_states
ssm_statestransformer_layers_modules_parameters_buffersrangenum_hidden_layersr(   zerosappend	key_cachevalue_cache)r,   configr^   r6   rS   icache_shaper1   r]   r2   r&   n   s8   
 z ZambaHybridDynamicCache.__init__
key_statesvalue_states	layer_idxcache_kwargsrI   c                 C   sz   | j | jd dkr|| j |< || j|< ntj| j | |gdd| j |< tj| j| |gdd| j|< | j | | j| fS )Nr4   r   r3   dim)rt   rA   ru   r(   cat)r,   ry   rz   r{   r|   r1   r1   r2   update   s   
zZambaHybridDynamicCache.updatebeam_idxc                 C   s   t t| jD ]V}| j| j}| j| d||| j|< | j| j}| j| d||| j|< | j| j}| j| d||| j|< | j| j}| j| d||| j|< qdS )zDReorders the cache for beam search, given the selected beam indices.r   N)	rp   lenrt   rS   index_selectr7   ru   rj   rk   )r,   r   r{   rS   r1   r1   r2   reorder_cache   s    z%ZambaHybridDynamicCache.reorder_cacher   c                 C   s:   || j vr
| j d n|}t| j|krdS | j| jd S )zYReturns the sequence length of the cached states. A layer index can be optionally passed.r   )rl   r   rt   rA   )r,   r{   r1   r1   r2   get_seq_length   s   z&ZambaHybridDynamicCache.get_seq_lengthc                 C      t dNz@ZambaHybridDynamicCache does not have a legacy cache equivalent.NotImplementedErrorrB   r1   r1   r2   to_legacy_cache      z'ZambaHybridDynamicCache.to_legacy_cachepast_key_valuesr   c                 C   r   r   r   )clsr   r1   r1   r2   from_legacy_cache   s   z)ZambaHybridDynamicCache.from_legacy_cacheN)r   )rD   rE   rF   __doc__r(   float16r&   Tensorintr   dictstrr   r@   r   
LongTensorr   r   r   classmethodFloatTensorr   r1   r1   r1   r2   rQ   `   s(    %
"(rQ           modulequerykeyvalueattention_maskscalingdropoutc                 K   s   t || j}t || j}	t||dd| }
|d ur3|d d d d d d d |jd f }|
| }
tjj|
dtj	d
|j}
tjj|
|| jd}
t|
|	}|dd }||
fS )Nr3   r
   r   r4   )r~   r6   )ptrainingr   )rP   num_key_value_groupsr(   matmul	transposerA   r   
functionalsoftmaxr8   r7   r6   r   r   
contiguous)r   r   r   r   r   r   r   kwargsry   rz   attn_weightscausal_maskattn_outputr1   r1   r2   eager_attention_forward   s   
&r   c                       s|   e Zd ZdZdedef fddZ	ddejdede	ej d	e	e
 d
ee deeje	ej e	eej  f fddZ  ZS )ZambaAttentionaA  
    Multi-headed attention from 'Attention Is All You Need' paper. Modified to use sliding window attention: Longformer
    and "Generating Long Sequences with Sparse Transformers".

    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)
    rv   r{   c                    s   t    || _|| _|j| _|j| _|j|j | _	|j
| _
| jd d | _d| _|j| _tj|j|j| j dd| _tj|j|j| j dd| _tj|j|j| j dd| _tj|j| j |jdd| _d S )Nr3         TFbias)r%   r&   rv   r{   attention_hidden_sizeattention_head_dimrO   num_attention_headsrM   r   max_position_embeddingsr   	is_causalattention_dropoutr   Linearq_projk_projv_projr-   o_projr,   rv   r{   r/   r1   r2   r&      s   
 zZambaAttention.__init__Nr<   r   past_key_valuer   rI   c                 K   s   |j d d }g |d| jR }| ||dd}| ||dd}	| ||dd}
|d urB||	|
|\}	}
t}| j	j
dkrPt| j	j
 }|| ||	|
|f| js\dn| j| jd|\}}|jg |dR   }| |}||fS )Nr4   r   r3   eagerr   )r   r   )rA   rO   r   viewr   r   r   r   r   rv   _attn_implementationr   r   r   r   rK   r   r   )r,   r<   r{   r   r   r   input_shapehidden_shapequery_statesry   rz   attention_interfacer   r   r1   r1   r2   r?      s2   

zZambaAttention.forwardr   )rD   rE   rF   r   r   r   r&   r(   r   r   rQ   r   r   r@   r?   rG   r1   r1   r/   r2   r      s"    r   c                       s^   e Zd ZdZdef fddZ	ddejdefdd	Z	ddefd
dZ
ddefddZ  ZS )ZambaMambaMixeruE  
    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)

    This module differs from `transformers.models.mamba.modeling_mamba.MambaMixer` in two ways:
    - Added multi-head: the output of `self.in_proj` is split into `self.n_mamba_heads` heads, and each head
    undergoes an independent forward pass, identical to the original `MambaMixer`, up until the pre-activations of
    `self.out_proj`. The pre-activations, coming from different mamba heads, are then concatenated and fed into `self.out_proj`.
    rv   c                    s  t    || _|| _|j| _|j| _|j| _|j	|j | _
|j| _|j| _| j
| j | _|j| _|j| _tj| j
| j
| j| j| j
| jd d| _|j| _t|j | _|j| _tj| j| j
d | jd| _tt | j| j| jd  | j| _!tt | j| j| jd d | jd  | _"tt | j| j| _#tj$d| jd tj%dd d d f }|&| j
d' }tt(|)| j| jd| _*tt+| j| j| _,tj| j
| j| jd| _-t.st/0d d S d S )	Nr   )in_channelsout_channelsr   kernel_sizegroupspaddingr3   r   g      ?r6   r4   ap  The fast path is not available because on of `(selective_state_update, selective_scan_fn, causal_conv1d_fn, causal_conv1d_update, mamba_inner_fn)` is None. To install follow https://github.com/state-spaces/mamba/#installation and https://github.com/Dao-AILab/causal-conv1d. If you want to use the naive implementation, set `use_mamba_kernels=False` in the model config)1r%   r&   rv   r{   r-   re   rf   rg   rh   rc   rd   mamba_dt_ranktime_step_rankri   mamba_head_dimmamba_conv_biasuse_conv_biasmamba_proj_biasuse_biasr   Conv1dconv1dhidden_mamba_act
activationr   actuse_mamba_kernelsuse_fast_kernelsr   in_projr'   r(   rr   x_proj_weightdt_proj_weightdt_proj_biasaranger8   rJ   r   logrK   A_logr)   Dout_projis_fast_path_availableloggerwarning_once)r,   rv   r{   Ar/   r1   r2   r&   +  sb   
	$ zZambaMambaMixer.__init__Nr<   cache_paramsc                 C   s  |j \}}}|d uo|jo|dk}| |dd}||dd|jddd\}}	|d }|	d}	|	|| j	d|dd}	| j
j| j
jd| j
jd}
|rnt|d|j| j |
| j
j| j}|d}nK|d urt|dks||d }|d urtj|| j|j d  df}|j| j | t||
| j
j| jd}|d urt|dks||d }|d| j	| j|dd}| jd d d d d d d f | dd}tj|| j| j| jgdd\}}}| j d d d f |dd }t!| j"#  }| j$d ur| j$# nd }tj%|d|f|j&|j'd}|rtt(| j	D ]K}t)|j*| j d d |f ||d	df ||d	df || ||d d df ||d d df | j+| |	|d	df || d
d
d}tj,||fdd}q'nntj%|d| j| jf|j&|j'd}t(| j	D ]E}t-|| || || || dd|| dd| j+| # |	| || d
d
d
\}}tj,||fdd }tj,||dfdd}q|d ur|d ur|j*| j | | .|dd}|S )Nr   r3   r4   r}   r   )r   r   rR   .T)dt_softplus)delta_softplusreturn_last_state)/rA   rb   r   r   r   chunksqueezer   rK   ri   r   r*   sizer!   rj   r{   r   r   	unsqueezer(   allr   r   padrh   copy_r    r   r   splitr   rf   r   expr   floatr   emptyrS   r6   rp   r   rk   r   r   r   r   )r,   r<   r   r   r^   seq_lenr\   use_precomputed_statesprojected_statesgateconv_weightsrj   ssm_parameters	time_stepBCdiscrete_time_stepr   time_proj_biasscan_outputsnscan_outputs_	ssm_state
ssm_state_contextualized_statesr1   r1   r2   cuda_kernels_forwardh  s   
$
*
z$ZambaMambaMixer.cuda_kernels_forwardc              
   C   s  |j \}}}|j}| |dd}||dd|jddd\}	}
|	d }	|
d}
|
|| j	d|dd}
t
|t}|r+|j| j j d |kr+| jrZ|j| j  }n|j| j }||	j}|jr|dkr|j| j j d |kr|j| j }tj|ddd}|	d d d d df |d d d d df< ||j| j< tj|| jjd d dd d f  dd}	| jr|	| jj7 }	| |	|d}	n|d urt|dks|	|d d |	j d  d f d }	tj |	| j!|	j d  df}||j| j< | | |	dd |f }	|d ur*t|dks*|	|d d |	j d  d f d }	nFtj"|| j	| j#| j$f|	j|d}|d urOt|dksO|	|d }	| | |	dd |f }	|d urqt|dksq|	|d }	|	d| j	| j#|dd}	| j%d d d d d d d f |	 dd	}tj&|| j'| j$| j$gdd\}}}| j(d d d f |dd	 | j)d d d d d d f  }tj*|}t+| j,-  }t+|d d d d d d d d f |d d d d d d d d d f  }|d d d d d d d d d f |d d d d d d d d d f -  }||	d d d d d d d d d f -  }g }t.|D ]\}|d d d d d d |d d f dd| |d d d d d d |d d f dd }t/|dd||d d d d |d d f d}|0|d d d d d d df  q2tj1|dd}||	| j2d d d d d d f   }|| |
 }|r||j| j< | 3|dd|d|dd}|S )
Nr   r3   r4   r}   r   )shiftsdims.rR   r   )4rA   r6   r   r   r   r   r   r   rK   ri   
isinstancerQ   rk   r{   r   cloner7   rS   rb   rj   r(   rollsumr   r*   r   r   r   r   r   r   r   r   rh   rr   r   rf   r   r   r   r   r   softplusr   r   r   rp   r   rs   stackr   r   )r,   input_statesr   r   r^   r   r\   r6   r   r<   r   	use_cacher  
conv_stater   r   r   r   r  r   
discrete_A
discrete_BdeltaB_ur  rw   scan_outputr  r1   r1   r2   slow_forward  s   

((&&* FH*X8&"zZambaMambaMixer.slow_forwardc                 C   s@   | j rtrd| jjjvrtd| j|||dS | j|||dS )NcudazFast Mamba kernels are not available. Make sure to they are installed and that the mamba module is on a CUDA device. lease run 'pip install causal-conv1d>=1.2.0' and 'pip install mamba-ssm', or set use_mamba_kernels=False in the model's config.)r   )r   r   r   rS   type
ValueErrorr	  r  )r,   r<   r   r   r1   r1   r2   r?   &  s   zZambaMambaMixer.forwardr"   )rD   rE   rF   r   r   r&   r(   r   rQ   r	  r  r?   rG   r1   r1   r/   r2   r     s    >
a]r   c                       s$   e Zd Z fddZdd Z  ZS )ZambaMLPc                    sr   t    || _|j| _|j| _tj| j| jdd| _tj| j| jdd| _tj| j| jdd| _	t
|j | _d S NFr   )r%   r&   rv   r-   rd   r   r   	gate_projup_proj	down_projr   
hidden_actact_fnr,   rv   r/   r1   r2   r&   4  s   
zZambaMLP.__init__c                 C   s$   |  | | || | }|S r   )r!  r#  r  r   )r,   xr!  r1   r1   r2   r?   >  s    zZambaMLP.forward)rD   rE   rF   r&   r?   rG   r1   r1   r/   r2   r  3  s    
r  c                       s   e Zd Zddedee f fddZ				ddejdejded	eej d
ee	 dee
 dee
 dee deejeeejejf  f fddZ  ZS )ZambaAttentionDecoderLayerNrv   r{   c                    sH   t    t||| _t|| _t|j|jd| _	t|j
|jd| _d S )Nr.   )r%   r&   r   	self_attnr  feed_forwardr#   r   rms_norm_epsinput_layernormr-   pre_ff_layernormr   r/   r1   r2   r&   D  s
   

z#ZambaAttentionDecoderLayer.__init__Fr<   original_hidden_statesr   r   output_attentionsr  r   rI   c              	   K   sj   t j||gdd}| |}| jd||||||d|\}}	| |}| |}|f}
|r3|
|	f7 }
|
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).
            layer_idx (`int`): layer_idx in the forward pass. Used to distinguish Zamba's tied transformer layers.
            attention_mask (`torch.FloatTensor`, *optional*): attention mask of size
                `(batch, sequence_length)` where padding elements are indicated by 0.
            past_key_value (`ZambaHybridDynamicCache`, *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.
        r4   r}   )r<   r{   r   r   r.  r  Nr1   )r(   concatenater+  r(  r,  r)  )r,   r<   r-  r{   r   r   r.  r  r   self_attn_weightsoutputsr1   r1   r2   r?   L  s$   





z"ZambaAttentionDecoderLayer.forwardr   NNFF)rD   rE   rF   r   r   r   r&   r(   r   rQ   boolr   r   r@   r   r?   rG   r1   r1   r/   r2   r&  C  s2    	
r&  c                       s   e Zd Zdedef fddZ									ddejdeej dee d	eej d
eej dee	 dee
 dee
 deej deej deejeeejejf  f fddZ  ZS )ZambaMambaDecoderLayerrv   r{   c                    s4   t    t||d| _t|j|jd| _|| _d S )N)rv   r{   r'  )	r%   r&   r   mambar#   r-   r*  r+  r{   r   r/   r1   r2   r&     s   

zZambaMambaDecoderLayer.__init__NFr<   r-  r   r   r   r.  r  cache_positiontransformer_hidden_statesrI   c                 K   sd   |}|
dur
||
 n|}|  |}| j|||d}d}|| }|f}|r)||f7 }|r0||f7 }|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_value (`ZambaHybridDynamicCache`, *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)r<   r   r   )r+  r5  )r,   r<   r-  r{   r   r   r   r.  r  r6  r7  r   residualr0  r1  r1   r1   r2   r?     s"   


zZambaMambaDecoderLayer.forward)	NNNNNFFNN)rD   rE   rF   r   r   r&   r(   r   r   rQ   r3  r   r@   r   r?   rG   r1   r1   r/   r2   r4    sD    		
r4  c                       s   e Zd Zdedejdef fddZ								ddej	d	e
ej	 d
e
e de
ej	 de
ej	 de
e de
e de
e de
ej deeje
eejejf  f fddZ  ZS )ZambaHybridLayershared_transflinearr5  c                    s    t    || _|| _|| _d S r   )r%   r&   r:  r;  mamba_decoder)r,   r:  r;  r5  r/   r1   r2   r&     s   

zZambaHybridLayer.__init__NFr<   r-  r{   r   r   r   r.  r  r6  rI   c
              
   C   sp   | j ||||||||	d}
|
d }|r|
d }| |}| j|||||||	d}
|r6|
d |f|
dd  }
|
S )a  
        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_value (`ZambaHybridDynamicCache`, *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.
        )r-  r{   r   r   r.  r  r6  r   r   )r7  r   r   r.  r  r6  r3   N)r:  r;  r<  )r,   r<   r-  r{   r   r   r   r.  r  r6  layer_outputsr7  r0  r1   r1   r2   r?     s4   

zZambaHybridLayer.forward)NNNNNFFN)rD   rE   rF   r&  r   r   r4  r&   r(   r   r   r   rQ   r3  r   r@   r   r?   rG   r1   r1   r/   r2   r9    s>    		
r9  c                       s   e Zd ZeZdZdZddgZdZdZ	dZ
dZdZdd Zee						dd
eej deeeeeef f  dedef fddZ  ZS )ZambaPreTrainedModelmodelTr&  r4  r   Fc                 C   s  | j j}t|tjtjfr%|jjjd|d |j	d ur#|j	j
  d S d S t|tjrF|jjjd|d |jd urD|jj|j 
  d S d S t|trT|jjd d S t|tr|jjjd|d | j jd }tj|j| | | j j| j j | j j }tt| j j|t| j jt| j j  t| j j j| j j d}|tt!|   }|j"j#| tj$d|j%d tj&dd d d f }|'|j(d) }|j*j#t|+|j|j,d |j-jd d S d S )	Nr   )r:   stdg      ?r   )minr   r   r4   ).rv   initializer_ranger  r   r   r   r*   datanormal_r   zero_	Embeddingpadding_idxr#   fill_r   r   r   inituniform_r   rc   r-   ri   r(   r   randmathr   time_step_maxtime_step_minclamptime_step_floorexpm1r   r   r   rf   r8   rJ   rd   r   r   rK   r   r   )r,   r   r@  dt_init_stdr   dtinv_dtr   r1   r1   r2   _init_weights  sD   



$"z"ZambaPreTrainedModel._init_weightsNtorch_dtype
device_maphard_check_onlycheck_device_mapc                    s.   t  j|||||d}|s|jdkrd|_|S )z
        Overloads `PreTrainedModel._check_and_enable_flash_attn_2` so as to DISABLE Flash Attention 2 by default on Zamba models.
        Flash attention 2 is currently not supported in the HuggingFace implementation of Zamba v1.
        )rX  rY  flash_attention_2r   )r%   _check_and_enable_flash_attn_2r   )r   rv   rV  rW  rX  rY  r/   r1   r2   r[  :  s   
z3ZambaPreTrainedModel._check_and_enable_flash_attn_2r2  )rD   rE   rF   r   config_classbase_model_prefixsupports_gradient_checkpointing_no_split_modules_skip_keys_device_placement_supports_flash_attn_2_supports_sdpa_supports_cache_class_is_statefulrU  r   r   r(   r6   r   r   r   r   r3  r[  rG   r1   r1   r/   r2   r>    s4     r>  c                       s   e Zd ZdZdef fddZdd Zdd Ze																				dd
e	e
j de	e
j de	e
j de	e de	e
j de	e de	e de	e de	e de	e
j deeef fddZdd Z  ZS )
ZambaModelz
    Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`ZambaDecoderLayer`]

    Args:
        config: ZambaConfig
    rv   c           
         s  t  | |j| _|j| _t|j|j| j| _t	|}g }g }|j
| _
t|jD ]2}|j
| dkr=|t||d q*|j
| dkr\|tj| jj| jjdd |t||d q*t|}t|}g }g | _t| j
D ]6\}}|dkrd| d g d}	g | j fd	d
|	D | _|t|t|t| qo|t| qot|| _|j| _t|j|jd| _d| _|   d S )Nr5  )r{   rT   Fr   zlayers..)	z%shared_transf.self_attn.q_proj.weightz%shared_transf.self_attn.k_proj.weightz%shared_transf.self_attn.v_proj.weightz%shared_transf.self_attn.o_proj.weightz+shared_transf.feed_forward.gate_proj.weightz)shared_transf.feed_forward.up_proj.weightz+shared_transf.feed_forward.down_proj.weightz$shared_transf.input_layernorm.weightz%shared_transf.pre_ff_layernorm.weightc                    s   g | ]} | qS r1   r1   )r[   r   prefix_namer1   r2   r_   ~  s    z'ZambaModel.__init__.<locals>.<listcomp>r'  )r%   r&   pad_token_idrG  
vocab_sizer   rF  r-   embed_tokensr&  ra   rp   rq   rs   r4  r   rv   iter_tied_weights_keys	enumerater9  next
ModuleListlayersr   r#   r*  final_layernormgradient_checkpointing	post_init)
r,   rv   blockmamba_layerslinear_layersrw   rq  layer_id
layer_type	tied_keysr/   rg  r2   r&   \  s>   zZambaModel.__init__c                 C      | j S r   rk  rB   r1   r1   r2   get_input_embeddings     zZambaModel.get_input_embeddingsc                 C   
   || _ d S r   r|  r,   r   r1   r1   r2   set_input_embeddings     
zZambaModel.set_input_embeddingsN	input_idsr   position_idsr   inputs_embedsr  r.  output_hidden_statesreturn_dictr6  rI   c                 C   s  |d ur|n| j j}|d ur|n| j j}|d ur|n| j j}|	d ur$|	n| j j}	|d u |d uA r4td| jrC| jrC|rCt	d d}|d u rL| 
|}|}t|}|r^|d u r^t	d |
d u rmtj|jd |jd}
|d u rv|
d}| |||
}|rdnd }|rdnd }t| jD ]A\}}|r||f7 }| jr| jr| |j|||||||||

}n||||||||||
d		}|d }|r|d d ur||d f7 }q| |}|r||f7 }|r|jsd
|_t||r|nd ||d}|	r|S | 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`.Fz{Zamba requires an initialized `ZambaHybridDynamicCache` to return a cache. None was provided, so no cache will be returned.r   rW   r   r1   )r-  r{   r   r   r   r.  r  r6  T)last_hidden_stater   r<   
attentions)rv   r.  r  r  use_return_dictr  rs  r   r   r   rk  r(   r  r   rA   rS   r   _update_causal_maskrn  rq  _gradient_checkpointing_func__call__rr  rb   r   to_tuple)r,   r  r   r  r   r  r  r.  r  r  r6  r<   r-  r   all_hidden_statesall_self_attnsr{   layerr=  outputr1   r1   r2   r?     s   







zZambaModel.forwardc                 C   sv  | j jdkr|d urd|v r|S d S |j|j}}t|j}|jd }|d d }tj||f|||d}	|dkr@tj	|	dd}	|	tj
||d|ddk9 }	|	d d d d d d f |jd ddd}	|d ur|	 }	| d	kr|jd }
|	d
d |
f d|d d d d d d f d }|	d
d |
f |||	d
d |
f< | j jdkr|d ur|jjdv rt|	|}	|	S )NrZ  r   r   r4   )
fill_valuer6   rS   )diagonalrW   r   r3   .sdpa)r  xpunpu)rv   r   r6   rS   r(   finforA  rA   fulltriur   rK   rJ   r  r~   eqmasked_fillr  r   _unmask_unattended)r,   r   input_tensorr6  r6   rS   	min_dtypesequence_lengthtarget_lengthr   mask_lengthpadding_maskr1   r1   r2   r     s0   
*
4$zZambaModel._update_causal_mask
NNNNNNNNNN)rD   rE   rF   r   r   r&   r}  r  r   r   r(   r   r   rQ   r   r3  r   r@   r   r?   r  rG   r1   r1   r/   r2   re  S  sP    /	

nre  c                       s  e Zd Zdef fddZdd Zdd Zdd	 Zd
d Zdd Z	dd Z
e												d$deej deej deej dee deej deej dee dee dee dee deej deeejf deeef fdd Z						!d%d"d#Z  ZS )&ZambaForCausalLMrv   c                    sP   t  | t|| _dg| jj| _|j| _tj|j|jdd| _	| 
  d S )Nzlm_head.weightFr   )r%   r&   re  r?  rm  rj  r   r   r-   lm_headrt  r$  r/   r1   r2   r&   &  s   
zZambaForCausalLM.__init__c                 C      | j jS r   r?  rk  rB   r1   r1   r2   r}  0  r   z%ZambaForCausalLM.get_input_embeddingsc                 C      || j _d S r   r  r  r1   r1   r2   r  3     z%ZambaForCausalLM.set_input_embeddingsc                 C   r{  r   r  rB   r1   r1   r2   get_output_embeddings6  r~  z&ZambaForCausalLM.get_output_embeddingsc                 C   r  r   r  )r,   new_embeddingsr1   r1   r2   set_output_embeddings9  r  z&ZambaForCausalLM.set_output_embeddingsc                 C   r  r   r?  )r,   decoderr1   r1   r2   set_decoder<  r  zZambaForCausalLM.set_decoderc                 C   r{  r   r  rB   r1   r1   r2   get_decoder?  r~  zZambaForCausalLM.get_decoderNr   r  r   r  r   r  labelsr  r.  r  r  r6  logits_to_keeprI   c                 K   s   |dur|n| j j}|	dur|	n| j j}	|
dur|
n| j j}
| j||||||||	||
d
}|d }t|tr<t| dn|}| |dd|ddf }d}|dur^| j	||| j
fi |}|
st|f|dd  }|durr|f| S |S t|||j|j|jdS )ah  
        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, ZambaForCausalLM

        >>> model = ZambaForCausalLM.from_pretrained("Zyphra/Zamba-7B-v1")
        >>> tokenizer = AutoTokenizer.from_pretrained("Zyphra/Zamba-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  r6  r  r   r   losslogitsr   r<   r  )rv   r.  r  r  r?  r  r   slicer  loss_functionrj  r   r   r<   r  )r,   r  r   r  r   r  r  r  r.  r  r  r6  r  loss_kwargsr1  r<   slice_indicesr  r  r  r1   r1   r2   r?   B  s@   (zZambaForCausalLM.forwardTc              	   K   s  |d u }	|	s5|d us|d |j d kr"|d d |j d  d f }n!|j d |j d kr4|d d |f }nt| j|j d | j| jd}|d url|d u rl| dd }||dkd |	sl|d d |j d  d f }|d urw|	rwd|i}
nd| i}
|
	||||| jj
|d |
S )Nr4   r   r   )r6   rS   r  r  )r  r   r  r   r  r6  )rA   rQ   rv   r6   rS   longcumsummasked_fill_r   r   num_logits_to_keep)r,   r  r   r   r  r6  r  r  r   empty_past_kvmodel_inputsr1   r1   r2   prepare_inputs_for_generation  s:   

z.ZambaForCausalLM.prepare_inputs_for_generation)NNNNNNNNNNNr   )NNNNNT)rD   rE   rF   r   r&   r}  r  r  r  r  r  r   r   r(   r   r   rQ   r   r3  r   r   r@   r   r?   r  rG   r1   r1   r/   r2   r  %  sn    
	

Tr  a  
    The Zamba Model with a sequence classification head on top (linear layer).

    [`ZambaForSequenceClassification`] 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                       s   e Zd Z fddZdd Zdd Ze										ddeej	 d	eej
 d
eej	 deeeeej f  deej deej	 dee dee dee dee deeef fddZ  ZS )ZambaForSequenceClassificationc                    sJ   t  | |j| _t|| _| jj| _tj|j| jdd| _	| 
  d S r  )r%   r&   
num_labelsre  r?  rm  r   r   r-   scorert  r$  r/   r1   r2   r&     s   

z'ZambaForSequenceClassification.__init__c                 C   r  r   r  rB   r1   r1   r2   r}    r   z3ZambaForSequenceClassification.get_input_embeddingsc                 C   r  r   r  r  r1   r1   r2   r    r  z3ZambaForSequenceClassification.set_input_embeddingsNr  r   r  r   r  r  r  r.  r  r  rI   c                 C   sB  |
dur|
n| j j}
| j||||||||	|
d	}|d }| |}|dur+|jd }n|jd }| j jdu r>|dkr>td| j jdu rGd}n1|durl|| j jk|jt	j
}t	j|jd |jt	j
d}|| d}nd}t| jj d |t	j||jd	|f }d}|dur||j}| j jdu r| jdkrd
| j _n| jdkr|jt	jks|jt	jkrd| j _nd| j _| j jd
krt }| jdkr|| | }n+|||}n%| j jdkrt }||d| j|d}n| j jdkrt }|||}|
s|f|dd  }|dur|f| S |S t|||j|j|jd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.r4   rR   z will not detect padding tokens in `inputs_embeds`. Results may be unexpected if using padding tokens in conjunction with `inputs_embeds.`rW   
regressionsingle_label_classificationmulti_label_classificationr  )rv   r  r?  r  rA   ri  r  r7   rS   r(   int32r   argmaxr   r   r0   rD   problem_typer  r6   r  r   r	   r   r   r   r   r   r   r<   r  )r,   r  r   r  r   r  r  r  r.  r  r  transformer_outputsr<   r  r^   last_non_pad_tokennon_pad_masktoken_indicespooled_logitsr  loss_fctr  r1   r1   r2   r?     sx   



"


z&ZambaForSequenceClassification.forwardr  )rD   rE   rF   r&   r}  r  r   r   r(   r   r   r   r   listr   r3  r@   r   r?   rG   r1   r1   r/   r2   r    sL    
	

r  )r  r  re  r>  )r   )Jr   rL  typingr   r   r   r   r(   torch.utils.checkpointr   torch.nnr   r   r	   activationsr   cache_utilsr   r   
generationr   modeling_attn_mask_utilsr   modeling_flash_attention_utilsr   modeling_outputsr   r   r   modeling_utilsr   r   processing_utilsr   utilsr   r   utils.import_utilsr   r   configuration_zambar   &mamba_ssm.ops.selective_scan_interfacer   r   +mamba_ssm.ops.triton.selective_state_updater   causal_conv1dr    r!   r   r   
get_loggerrD   r   Moduler#   r   r   rP   rQ   r   r   r   r   r  r&  r4  r9  r>  re  r  r  __all__r1   r1   r1   r2   <module>   s   

e
F  ?DHD R ,p