o
    Zhj                     @   s  d Z ddlZddlmZmZmZ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& ddl'm(Z(m)Z) ddl*m+Z+m,Z, ddl-m.Z. e, rddl/m0Z0m1Z1 ddl2m3Z3 nd\Z3Z1Z0e+ rddl4m5Z5m6Z6 nd\Z6Z5e7e3e1e5e6e0fZ8e)9e:Z;G dd dej<Z=e&>e= de
j?de@de
j?fddZAG d d! d!eZB	"dCd#ej<d$e
j?d%e
j?d&e
j?d'ee
j? d(eCd)eCfd*d+ZDG d,d- d-ej<ZEG d.d/ d/ej<ZFG d0d1 d1ej<ZGG d2d3 d3ej<ZHG d4d5 d5ej<ZIG d6d7 d7ej<ZJe(G d8d9 d9e"ZKe(G d:d; d;eKZLG d<d= d=eKeZMe(d>d?G d@dA dAeKZNg dBZOdS )DzPyTorch Zamba model.    N)AnyCallableDictListOptionalTupleUnion)nn)BCEWithLogitsLossCrossEntropyLossMSELoss   )ACT2FN)CacheDynamicCache)GenerationMixin)AttentionMaskConverter)FlashAttentionKwargs)BaseModelOutputWithPastCausalLMOutputWithPast SequenceClassifierOutputWithPast)ALL_ATTENTION_FUNCTIONSPreTrainedModel)Unpack)ALL_LAYERNORM_LAYERS)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__ W/var/www/auris/lib/python3.10/site-packages/transformers/models/zamba/modeling_zamba.pyr*   A   s   

zZambaRMSNorm.__init__c                 C   sJ   |j }|tj}|djddd}|t|| j  }| j|| S )N   T)Zkeepdim)	dtypetor,   float32powmeanZrsqrtr/   r.   )r0   hidden_statesZinput_dtypeZvariancer5   r5   r6   forwardI   s
   zZambaRMSNorm.forwardc                 C   s   t | jj d| j S )Nz, eps=)tupler.   shaper/   r0   r5   r5   r6   
extra_reprP   s   zZambaRMSNorm.extra_repr)r(   )__name__
__module____qualname__r*   r?   rC   __classcell__r5   r5   r3   r6   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_dimr5   r5   r6   	repeat_kvX   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devicer9   hybridc                        g | ]}t jg g  d qS rS   r,   Ztensor.0_
batch_sizerS   r5   r6   
<listcomp>        z4ZambaHybridDynamicCache.__init__.<locals>.<listcomp>c                    rU   rV   rX   rY   r\   r5   r6   r^      r_   )r9   layers_block_typehas_previous_statemamba_expandr1   intermediate_sizemamba_d_statessm_state_sizemamba_d_convconv_kernel_sizen_mamba_headsconv_states
ssm_statestransformer_layersZ_modules_parameters_buffersrangenum_hidden_layersr,   zerosappend	key_cachevalue_cache)r0   configr]   r9   rS   iZcache_shaper5   r\   r6   r*   r   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 )Nr8   r   r7   dim)rr   rA   rs   r,   cat)r0   rv   rw   rx   ry   r5   r5   r6   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)	rn   lenrr   rS   Zindex_selectr:   rs   ri   rj   )r0   r~   rx   rS   r5   r5   r6   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   )rk   r   rr   rA   )r0   rx   r5   r5   r6   get_seq_length   s   z&ZambaHybridDynamicCache.get_seq_lengthc                 C      t dNz@ZambaHybridDynamicCache does not have a legacy cache equivalent.NotImplementedErrorrB   r5   r5   r6   to_legacy_cache      z'ZambaHybridDynamicCache.to_legacy_cachepast_key_valuesr   c                 C   r   r   r   )clsr   r5   r5   r6   from_legacy_cache   s   z)ZambaHybridDynamicCache.from_legacy_cacheN)r   )rD   rE   rF   __doc__r,   Zfloat16r*   Tensorintr   r   strr   r   r}   
LongTensorr   r   r   classmethodFloatTensorr   r5   r5   r5   r6   rQ   d   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 )Nr7   r   r   r8   )r{   r9   )ptrainingr   )rP   num_key_value_groupsr,   matmul	transposerA   r	   
functionalZsoftmaxr;   r:   r9   r   r   
contiguous)r   r   r   r   r   r   r   kwargsrv   rw   attn_weightscausal_maskattn_outputr5   r5   r6   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 )ZambaAttentiona9  
    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://arxiv.org/pdf/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)
    rt   rx   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 )Nr7         TFbias)r)   r*   rt   rx   attention_hidden_sizeZattention_head_dimrO   Znum_attention_headsrM   r   Zmax_position_embeddingsr   Z	is_causalattention_dropoutr	   Linearq_projk_projv_projr1   o_projr0   rt   rx   r3   r5   r6   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rb| j	j
dkr\|ddr\td nt| j	j
 }|| ||	|
|f| jsnd	n| j| jd
|\}}|jg |dR   }| |}||fS )Nr8   r   r7   eagersdpaoutput_attentionsFz`torch.nn.functional.scaled_dot_product_attention` does not support `output_attentions=True`. Falling back to eager attention. This warning can be removed using the argument `attn_implementation="eager"` when loading the model.r   )r   r   )rA   rO   r   viewr   r   r   r}   r   rt   _attn_implementationgetloggerwarning_oncer   r   r   r   rK   r   r   )r0   r>   rx   r   r   r   Zinput_shapeZhidden_shapeZquery_statesrv   rw   Zattention_interfacer   r   r5   r5   r6   r?      s:   

zZambaAttention.forwardr   )rD   rE   rF   r   r    r   r*   r,   r   r   rQ   r   r   r   r?   rG   r5   r5   r3   r6   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`.
    rt   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   )Zin_channelsZout_channelsr   Zkernel_sizegroupspaddingr7   r   g      ?r9   r8   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*   rt   rx   r1   rd   re   rf   rg   rb   rc   mamba_dt_ranktime_step_rankrh   mamba_head_dimZmamba_conv_biasuse_conv_biasZmamba_proj_biasZuse_biasr	   Conv1dconv1dZhidden_mamba_act
activationr   actZuse_mamba_kernelsuse_fast_kernelsr   in_projr+   r,   rp   x_proj_weightdt_proj_weightdt_proj_biasaranger;   rJ   r   logrK   A_logr-   Dout_projis_fast_path_availabler   r   )r0   rt   rx   Ar3   r5   r6   r*   5  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   r7   r8   rz   r   )r   r   rR   .T)Zdt_softplus)Zdelta_softplusZreturn_last_state)/rA   ra   r   r   r   chunksqueezer   rK   rh   r   r.   sizer%   ri   rx   r   r   	unsqueezer,   allr	   r   padrg   copy_r$   r   r   splitr   re   r   expr   floatr   emptyrS   r9   rn   r#   rj   r   r|   r"   r   )r0   r>   r   r   r]   seq_lenr[   Zuse_precomputed_statesprojected_statesgateZconv_weightsri   ssm_parameters	time_stepBCdiscrete_time_stepr   Ztime_proj_biasscan_outputsnZscan_outputs_	ssm_stateZ
ssm_state_contextualized_statesr5   r5   r6   cuda_kernels_forwardt  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   r7   r8   rz   r   )Zshiftsdims.rR   r   )4rA   r9   r   r   r   r   r   r   rK   rh   
isinstancerQ   rj   rx   r   cloner:   rS   ra   ri   r,   Zrollsumr   r.   r   r   r   r   r   r	   r   r   rg   rp   r   re   r   r   r   r   r   Zsoftplusr   r   r   rn   r   rq   stackr   r   )r0   Zinput_statesr   r   r]   r   r[   r9   r   r>   r   	use_cacher   Z
conv_stater   r   r   r   r   r   Z
discrete_AZ
discrete_BZdeltaB_ur   ru   Zscan_outputr   r5   r5   r6   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   )r0   r>   r   r   r5   r5   r6   r?   2  s   zZambaMambaMixer.forwardr&   )rD   rE   rF   r   r    r*   r,   r   rQ   r   r   r?   rG   r5   r5   r3   r6   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*   rt   r1   rc   r	   r   	gate_projup_proj	down_projr   Z
hidden_actact_fnr0   rt   r3   r5   r6   r*   @  s   
zZambaMLP.__init__c                 C   s$   |  | | || | }|S r   )r   r   r   r   )r0   xr   r5   r5   r6   r?   J  s    zZambaMLP.forward)rD   rE   rF   r*   r?   rG   r5   r5   r3   r6   r   ?  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 )ZambaAttentionDecoderLayerNrt   rx   c                    sH   t    t||| _t|| _t|j|jd| _	t|j
|jd| _d S )Nr2   )r)   r*   r   	self_attnr   feed_forwardr'   r   rms_norm_epsinput_layernormr1   pre_ff_layernormr   r3   r5   r6   r*   P  s
   

z#ZambaAttentionDecoderLayer.__init__Fr>   original_hidden_statesr   r   r   r   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://arxiv.org/pdf/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.
        r8   rz   )r>   rx   r   r   r   r   Nr5   )r,   Zconcatenater  r  r  r  )r0   r>   r  rx   r   r   r   r   r   self_attn_weightsoutputsr5   r5   r6   r?   X  s$   





z"ZambaAttentionDecoderLayer.forwardr   NNFF)rD   rE   rF   r    r   r   r*   r,   r   rQ   boolr   r   r   r   r?   rG   r5   r5   r3   r6   r   O  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 )ZambaMambaDecoderLayerrt   rx   c                    s4   t    t||d| _t|j|jd| _|| _d S )N)rt   rx   r  )	r)   r*   r   mambar'   r1   r  r  rx   r   r3   r5   r6   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  r  )r0   r>   r  rx   r   r   r   r   r   r  r  r   Zresidualr  r	  r5   r5   r6   r?     s"   


zZambaMambaDecoderLayer.forward)	NNNNNFFNN)rD   rE   rF   r    r   r*   r,   r   r   rQ   r  r   r   r   r?   rG   r5   r5   r3   r6   r    sD    		
r  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linearr  c                    s    t    || _|| _|| _d S r   )r)   r*   r  r  mamba_decoder)r0   r  r  r  r3   r5   r6   r*     s   

zZambaHybridLayer.__init__NFr>   r  rx   r   r   r   r   r   r  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  rx   r   r   r   r   r  r   r   )r  r   r   r   r   r  r7   N)r  r  r  )r0   r>   r  rx   r   r   r   r   r   r  layer_outputsr  r  r5   r5   r6   r?     s4   

zZambaHybridLayer.forward)NNNNNFFN)rD   rE   rF   r   r	   r   r  r*   r,   r   r   r   rQ   r  r   r   r   r?   rG   r5   r5   r3   r6   r    s>    		
r  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   r  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   r8   ).rt   Zinitializer_ranger   r	   r   r   r.   dataZnormal_r   Zzero_	Embeddingpadding_idxr'   Zfill_r   r   r   initZuniform_r   rb   r1   rh   r,   r   Zrandmathr   Ztime_step_maxZtime_step_minclampZtime_step_floorexpm1r   r   r   re   r;   rJ   rc   r   r   rK   r   r   )r0   r   r  Zdt_init_stdr   dtZinv_dtr   r5   r5   r6   _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.
        )r$  r%  flash_attention_2r   )r)   _check_and_enable_flash_attn_2r   )r   rt   r"  r#  r$  r%  r3   r5   r6   r'  F  s   
z3ZambaPreTrainedModel._check_and_enable_flash_attn_2r
  )rD   rE   rF   r    Zconfig_classZbase_model_prefixZsupports_gradient_checkpointingZ_no_split_modulesZ_skip_keys_device_placementZ_supports_flash_attn_2Z_supports_sdpaZ_supports_cache_classZ_is_statefulr!  r   r   r,   r9   r   r   r   r   r  r'  rG   r5   r5   r3   r6   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
    rt   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 )Nr  )rx   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 r5   r5   )rZ   r   Zprefix_namer5   r6   r^     s    z'ZambaModel.__init__.<locals>.<listcomp>r  )r)   r*   pad_token_idr  
vocab_sizer	   r  r1   embed_tokensr   r`   rn   ro   rq   r  r   rt   iter_tied_weights_keys	enumerater  nextZ
ModuleListlayersr   r'   r  final_layernormgradient_checkpointing	post_init)
r0   rt   blockZmamba_layersZlinear_layersru   r2  Zlayer_idZ
layer_typeZ	tied_keysr3   r*  r6   r*   h  s>   zZambaModel.__init__c                 C      | j S r   r-  rB   r5   r5   r6   get_input_embeddings     zZambaModel.get_input_embeddingsc                 C   
   || _ d S r   r8  r0   r   r5   r5   r6   set_input_embeddings     
zZambaModel.set_input_embeddingsN	input_idsr   position_idsr   inputs_embedsr   r   output_hidden_statesreturn_dictr  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   r5   )r  rx   r   r   r   r   r   r  T)Zlast_hidden_stater   r>   
attentions)rt   r   rB  r   use_return_dictr   r4  r   r   r   r-  r,   r   r   rA   rS   r   _update_causal_maskr0  r2  Z_gradient_checkpointing_func__call__r3  ra   r   Zto_tuple)r0   r?  r   r@  r   rA  r   r   rB  rC  r  r>   r  r   Zall_hidden_statesZall_self_attnsrx   layerr  outputr5   r5   r6   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 )Nr&  r   r   r8   )Z
fill_valuer9   rS   )ZdiagonalrW   r   r7   .r   )r   ZxpuZnpu)rt   r   r9   rS   r,   Zfinfor  rA   fullZtriur   rK   rJ   r   r{   eqZmasked_fillr   r   Z_unmask_unattended)r0   r   Zinput_tensorr  r9   rS   Z	min_dtypeZsequence_lengthZtarget_lengthr   Zmask_lengthZpadding_maskr5   r5   r6   rF    s0   
*
4$zZambaModel._update_causal_mask
NNNNNNNNNN)rD   rE   rF   r   r    r*   r9  r=  r   r   r,   r   r   rQ   r   r  r   r   r   r?   rF  rG   r5   r5   r3   r6   r(  _  sP    /	

nr(  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 )&ZambaForCausalLMrt   c                    sP   t  | t|| _dg| jj| _|j| _tj|j|jdd| _	| 
  d S )Nzlm_head.weightFr   )r)   r*   r(  r  r/  r,  r	   r   r1   lm_headr5  r   r3   r5   r6   r*   2  s   
zZambaForCausalLM.__init__c                 C      | j jS r   r  r-  rB   r5   r5   r6   r9  <  r   z%ZambaForCausalLM.get_input_embeddingsc                 C      || j _d S r   rP  r<  r5   r5   r6   r=  ?     z%ZambaForCausalLM.set_input_embeddingsc                 C   r7  r   rN  rB   r5   r5   r6   get_output_embeddingsB  r:  z&ZambaForCausalLM.get_output_embeddingsc                 C   r;  r   rS  )r0   Znew_embeddingsr5   r5   r6   set_output_embeddingsE  r>  z&ZambaForCausalLM.set_output_embeddingsc                 C   r;  r   r  )r0   decoderr5   r5   r6   set_decoderH  r>  zZambaForCausalLM.set_decoderc                 C   r7  r   rV  rB   r5   r5   r6   get_decoderK  r:  zZambaForCausalLM.get_decoderNr   r?  r   r@  r   rA  labelsr   r   rB  rC  r  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   rA  r   r   rB  r  rC  r   r   losslogitsr   r>   rD  )rt   r   rB  rE  r  r   r   slicerN  Zloss_functionr,  r   r   r>   rD  )r0   r?  r   r@  r   rA  rZ  r   r   rB  rC  r  r[  Zloss_kwargsr	  r>   Zslice_indicesr^  r]  rI  r5   r5   r6   r?   N  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 )Nr8   r   r   )r9   rS   rA  r?  )r@  r   r   r   r[  r  )rA   rQ   rt   r9   rS   longZcumsumZmasked_fill_r   r}   Znum_logits_to_keep)r0   r?  r   r   rA  r  r@  r   r   Zempty_past_kvZmodel_inputsr5   r5   r6   prepare_inputs_for_generation  s:   

z.ZambaForCausalLM.prepare_inputs_for_generation)NNNNNNNNNNNr   )NNNNNT)rD   rE   rF   r    r*   r9  r=  rT  rU  rX  rY  r   r   r,   r   r   rQ   r   r  r   r   r   r   r?   ra  rG   r5   r5   r3   r6   rM  1  sn    
	

TrM  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).
    )Z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_labelsr(  r  r/  r	   r   r1   scorer5  r   r3   r5   r6   r*     s   

z'ZambaForSequenceClassification.__init__c                 C   rO  r   rP  rB   r5   r5   r6   r9    r   z3ZambaForSequenceClassification.get_input_embeddingsc                 C   rQ  r   rP  r<  r5   r5   r6   r=    rR  z3ZambaForSequenceClassification.set_input_embeddingsNr?  r   r@  r   rA  rZ  r   r   rB  rC  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   rA  r   r   rB  rC  r   r   z=Cannot handle batch sizes > 1 if no padding token is defined.r8   rR   z will not detect padding tokens in `inputs_embeds`. Results may be unexpected if using padding tokens in conjunction with `inputs_embeds.`rW   Z
regressionZsingle_label_classificationZmulti_label_classificationr\  )rt   rE  r  rd  rA   r+  r   r:   rS   r,   Zint32r   Zargmaxr   r   r4   rD   Zproblem_typerc  r9   r`  r   r   r   r   r   r
   r   r   r>   rD  )r0   r?  r   r@  r   rA  rZ  r   r   rB  rC  Ztransformer_outputsr>   r^  r]   Zlast_non_pad_tokenZnon_pad_maskZtoken_indicesZpooled_logitsr]  Zloss_fctrI  r5   r5   r6   r?     sx   



"


z&ZambaForSequenceClassification.forwardrL  )rD   rE   rF   r*   r9  r=  r   r   r,   r   r   r   r   r   r   r  r   r   r?   rG   r5   r5   r3   r6   rb    sL    
	

rb  )rM  rb  r(  r  )r   )Pr   r  typingr   r   r   r   r   r   r   r,   Ztorch.utils.checkpointr	   Ztorch.nnr
   r   r   Zactivationsr   Zcache_utilsr   r   Z
generationr   Zmodeling_attn_mask_utilsr   Zmodeling_flash_attention_utilsr   Zmodeling_outputsr   r   r   Zmodeling_utilsr   r   Zprocessing_utilsr   Zpytorch_utilsr   utilsr   r   Zutils.import_utilsr   r   Zconfiguration_zambar    Z&mamba_ssm.ops.selective_scan_interfacer!   r"   Z+mamba_ssm.ops.triton.selective_state_updater#   Zcausal_conv1dr$   r%   r   r   Z
get_loggerrD   r   Moduler'   rq   r   r   rP   rQ   r   r   r   r   r   r   r  r  r  r(  rM  rb  __all__r5   r5   r5   r6   <module>   s   $


e
L  ?DHD R ,p