o
    Zhl                     @   s  d Z ddlZddlmZmZmZmZmZ ddlZddl	m
  mZ ddlZddlm
Z
 ddlmZ ddlmZmZ ddlmZ dd	lmZ dd
lmZmZ ddlmZmZ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( e r~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Z6			dCdeej7eej7 df dee8 deej7 deej7e8f fddZ9G dd de
j:Z;d ej7d!e8dej7fd"d#Z<G d$d% d%eZ=G d&d' d'e
j:Z>G d(d) d)e>Z?G d*d+ d+e>Z@e>e?e@d,ZAG d-d. d.e
j:ZBG d/d0 d0e
j:ZCG d1d2 d2e
j:ZDG d3d4 d4e
j:ZEG d5d6 d6e
j:ZFe!G d7d8 d8eZGeEeFd9ZHe!G d:d; d;eGZIG d<d= d=eGeZJe!d>d?G d@dA dAeGZKg dBZLdS )DzPyTorch Jamba model.    N)AnyDictOptionalTupleUnion)nn   )ACT2FN)CacheDynamicCache)GenerationMixin)AttentionMaskConverter)!flash_attn_supports_top_left_maskis_flash_attn_available)MoeCausalLMOutputWithPastMoeModelOutputWithPast SequenceClassifierOutputWithPast)PreTrainedModel)auto_docstringcan_return_tuplelogging)is_causal_conv1d_availableis_mamba_ssm_available   )JambaConfig)_flash_attention_forward)mamba_inner_fnselective_scan_fn)selective_state_update)NNN)causal_conv1d_fncausal_conv1d_updateNN   router_logitsnum_expertsattention_maskreturnc                    s  | du s	t | tsdS t | tr#| d j tj fdd| D dd}tjjj|dd}tj||dd\}}tjj	||}|du rStj
| dd}	tj
|dd}
ng|j\}}|jd ||  }|dddddddf |||||fd|| }tj| | ddtj|dd }	|ddddddf ||||fd| }tj|| ddtj|dd }
t|	|
d }|| S )a  
    Computes auxiliary load balancing loss as in Switch Transformer - implemented in Pytorch.

    See Switch Transformer (https://arxiv.org/abs/2101.03961) for more details. This function implements the loss
    function presented in equations (4) - (6) of the paper. It aims at penalizing cases where the routing between
    experts is too unbalanced.

    Args:
        router_logits:
            Logits from the `router`, should be a tuple of model.config.num_hidden_layers tensors of
            shape [batch_size X sequence_length, num_experts].
        num_experts:
            Number of experts
        top_k:
            The number of experts to route per-token, can be also interpreted as the `top-k` routing
            parameter.
        attention_mask (`torch.Tensor`, *optional*):
            The attention_mask used in forward function
            shape [batch_size X sequence_length] if not None.

    Returns:
        The auxiliary loss.
    Nr   c                    s   g | ]}|  qS  )to).0Zlayer_routerZcompute_devicer'   W/var/www/auris/lib/python3.10/site-packages/transformers/models/jamba/modeling_jamba.py
<listcomp>e   s    z,load_balancing_loss_func.<locals>.<listcomp>dim)
isinstancetupledevicetorchcatr   
functionalsoftmaxtopkone_hotmeanfloatshapeexpandreshaper(   sum	unsqueeze)r#   r$   top_kr%   Zconcatenated_router_logitsrouting_weights_selected_expertsexpert_maskZtokens_per_expertZrouter_prob_per_expert
batch_sizesequence_lengthnum_hidden_layersZexpert_attention_maskZ router_per_expert_attention_maskZoverall_lossr'   r*   r+   load_balancing_loss_funcB   sB   



rH   c                       s.   e Zd Zd fdd	Zdd Zdd Z  ZS )	JambaRMSNormư>c                    s&   t    tt|| _|| _dS )z;
        JambaRMSNorm is equivalent to T5LayerNorm
        N)super__init__r   	Parameterr3   onesweightvariance_epsilon)selfhidden_sizeeps	__class__r'   r+   rL      s   

zJambaRMSNorm.__init__c                 C   sJ   |j }|tj}|djddd}|t|| j  }| j|| S )Nr"   r/   T)Zkeepdim)	dtyper(   r3   float32powr9   ZrsqrtrP   rO   )rQ   hidden_statesinput_dtypeZvariancer'   r'   r+   forward   s
   zJambaRMSNorm.forwardc                 C   s   t | jj d| j S )Nz, eps=)r1   rO   r;   rP   rQ   r'   r'   r+   
extra_repr   s   zJambaRMSNorm.extra_repr)rJ   )__name__
__module____qualname__rL   r[   r]   __classcell__r'   r'   rT   r+   rI      s    rI   rY   n_repc                 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)r;   r<   r=   )rY   rb   batchnum_key_value_headsslenhead_dimr'   r'   r+   	repeat_kv   s
   0rg   c                       s   e Zd ZdZejdf 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  ZS ) HybridMambaAttentionDynamicCachea  
    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           	   
      s0  t    || _|j| _d| _|j|j }|j}|j}g | _	g | _
g | _t|jD ]P}| j| dkrS|  j	tj |||dg7  _	|  j
tj |||dg7  _
q)|  j	tjg g  dg7  _	|  j
tjg g  dg7  _
| j| q) fddt|jD | _ fddt|jD | _d S )NFmambar2   rV   r2   c                        g | ]}t jg g  d qS rk   r3   tensorr)   rB   rE   r2   r'   r+   r,           z=HybridMambaAttentionDynamicCache.__init__.<locals>.<listcomp>c                    rl   rm   rn   rp   rq   r'   r+   r,      rr   )rK   rL   rV   layers_block_typehas_previous_statemamba_expandrR   mamba_d_statemamba_d_convconv_states
ssm_statestransformer_layersrangerG   r3   zerosro   append	key_cachevalue_cache)	rQ   configrE   rV   r2   intermediate_sizessm_state_sizeconv_kernel_sizeirT   rq   r+   rL      s.   

   z)HybridMambaAttentionDynamicCache.__init__
key_statesvalue_states	layer_idxcache_kwargsr&   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 )Nr/   r   r"   r-   )r~   r;   r   r3   r4   )rQ   r   r   r   r   r'   r'   r+   update   s   
z'HybridMambaAttentionDynamicCache.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)	r{   lenr~   r2   Zindex_selectr(   r   rx   ry   )rQ   r   r   r2   r'   r'   r+   reorder_cache   s    z.HybridMambaAttentionDynamicCache.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   )rz   r   r~   r;   )rQ   r   r'   r'   r+   get_seq_length   s   z/HybridMambaAttentionDynamicCache.get_seq_lengthc                 C      t dNzIHybridMambaAttentionDynamicCache does not have a legacy cache equivalent.NotImplementedErrorr\   r'   r'   r+   to_legacy_cache     z0HybridMambaAttentionDynamicCache.to_legacy_cachepast_key_valuesr   c                 C   r   r   r   )clsr   r'   r'   r+   from_legacy_cache
  s   z2HybridMambaAttentionDynamicCache.from_legacy_cacheN)r   )r^   r_   r`   __doc__r3   Zfloat16rL   Tensorintr   r   strr   r   r   
LongTensorr   r   r   classmethodFloatTensorr   ra   r'   r'   rT   r+   rh      s(     
",rh   c                       s   e Zd ZdZddedee f fddZ						ddej	d	eej	 d
eej
 dee dededeej
 deej	eej	 eeej	  f fddZ  ZS )JambaAttentionz
    Multi-headed attention from 'Attention Is All You Need' paper. Modified to use sliding window attention: Longformer
    and "Generating Long Sequences with Sparse Transformers".
    Nr   r   c                    s  t    || _|| _|d u rtd| jj d |j| _|j	| _
| j| j
 | _|j| _| j
| j | _d| _|j| _| j| j
 | jkrQtd| j d| j
 d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 )	NzInstantiating z without passing a `layer_idx` is not recommended and will lead to errors during the forward call if caching is used. Please make sure to provide a `layer_idx` when creating this class.Tz?hidden_size must be divisible by num_heads (got `hidden_size`: z and `num_heads`: z).Fbias)rK   rL   r   r   loggerwarning_oncerU   r^   rR   Znum_attention_heads	num_headsrf   rd   num_key_value_groups	is_causalattention_dropout
ValueErrorr   Linearq_projk_projv_projo_proj)rQ   r   r   rT   r'   r+   rL     s0   

 zJambaAttention.__init__FrY   r%   position_idspast_key_valueoutput_attentions	use_cachecache_positionr&   c                 C   s  |  \}}	}
| |}| |}| |}|||	| j| jdd}|||	| j| jdd}|||	| j| jdd}|d urN|	||| j
\}}t|| j}t|| j}t||ddt| j }|d ur|d d d d d d d |jd f }|| }tjj|dtjd|j}tjj|| j| jd}t||}|  || j|	| jfkrtd|| j|	| jf d	|   |dd }|||	| j}| |}|sd }|||fS )
Nr   r"   r   r   r/   r.   rV   )ptrainingz `attn_output` should be of size z	, but is ) sizer   r   r   viewr   rf   	transposerd   r   r   rg   r   r3   matmulmathsqrtr;   r   r5   r6   rW   r(   rV   dropoutr   r   r   
contiguousr=   rR   r   )rQ   rY   r%   r   r   r   r   r   bszq_lenrB   query_statesr   r   attn_weightscausal_maskattn_outputr'   r'   r+   r[   3  s<   



 &

zJambaAttention.forwardr   NNNFFN)r^   r_   r`   r   r   r   r   rL   r3   r   r   rh   boolr   r[   ra   r'   r'   rT   r+   r     s4     	r   c                       sl   e Zd ZdZ fddZ						ddejdeej deej d	ee	 d
e
de
deej fddZ  ZS )JambaFlashAttention2aF  
    Jamba flash attention module. This module inherits from `JambaAttention` as the weights of the module stays
    untouched. The only required change would be on the forward pass where it needs to correctly call the public API of
    flash attention and deal with padding tokens in case the input contains any of them.
    c                    s   t  j|i | t | _d S r   )rK   rL   r   _flash_attn_uses_top_left_mask)rQ   argskwargsrT   r'   r+   rL   r  s   zJambaFlashAttention2.__init__NFrY   r%   r   r   r   r   r   c                 K   s  |  \}	}
}| |}| |}| |}||	|
| j| j}||	|
| j| jdd}||	|
| j| jdd}|d urJ|	||| j
\}}t|| j}t|| j}| js[dn| j}|j}|tjkrt rot }nt| jdrz| jj}n| jjj}td| d ||}||}||}|dd}|dd}t|||||
|t| jdd | j| jd	}||	|
| j ! }| "|}|sd }|||fS )	Nr   r"           _pre_quantization_dtypezThe input hidden states seems to be silently casted in float32, this might be related to the fact you have upcasted embedding or layer norm layers in float32. We will cast back the input in .sliding_window)r   r   r   Zuse_top_left_mask)#r   r   r   r   r   r   rf   rd   r   r   r   rg   r   r   r   rV   r3   rW   Zis_autocast_enabledZget_autocast_gpu_dtypehasattrr   r   rO   r   r   r(   r   getattrr   r   r=   rR   r   r   )rQ   rY   r%   r   r   r   r   r   r   r   r   rB   r   r   r   Zdropout_raterZ   Ztarget_dtyper   r   r'   r'   r+   r[   z  sZ   











zJambaFlashAttention2.forwardr   )r^   r_   r`   r   rL   r3   r   r   r   rh   r   r[   ra   r'   r'   rT   r+   r   k  s0    r   c                       s   e Zd ZdZ						ddejdeej deej dee de	d	e	d
eej de
ejeej ee
ej  f f fddZ  ZS )JambaSdpaAttentionz
    Jamba attention module using torch.nn.functional.scaled_dot_product_attention. This module inherits from
    `JambaAttention` as the weights of the module stays untouched. The only changes are on the forward pass to adapt to
    SDPA API.
    NFrY   r%   r   r   r   r   r   r&   c                    s  |rt d t j||||||dS | \}}	}
| |}| |}| |}|||	| j	| j
dd}|||	| j| j
dd}|||	| j| j
dd}|d ura|||| j\}}t|| j}t|| j}|}|d ur|d d d d d d d |jd f }|jjdkr|d ur| }| }| }| jr|d u r|	dkrdnd}tjjj||||| jr| jnd	|d
}|dd }|||	| j}| |}|d |fS )Na  JambaModel is using JambaSdpaAttention, but `torch.nn.functional.scaled_dot_product_attention` does not support `output_attentions=True`. Falling back to the manual attention implementation, but specifying the manual implementation will be required from Transformers version v5.0.0 onwards. This warning can be removed using the argument `attn_implementation="eager"` when loading the model.)rY   r%   r   r   r   r   r   r"   r   cudaTFr   )Z	attn_maskZ	dropout_pr   )r   r   rK   r[   r   r   r   r   r   r   rf   r   rd   r   r   rg   r   r;   r2   typer   r   r3   r   r5   Zscaled_dot_product_attentionr   r   rR   r   )rQ   rY   r%   r   r   r   r   r   r   r   rB   r   r   r   r   r   r   rT   r'   r+   r[     sV   
	


&	

zJambaSdpaAttention.forwardr   )r^   r_   r`   r   r3   r   r   r   rh   r   r   r[   ra   r'   r'   rT   r+   r     s2    
	r   )eagerflash_attention_2sdpac                       s   e Zd ZdZdef fddZ		ddejdede	ej
 fd	d
Zddede	ej
 fddZ		ddede	ej
 fddZ  ZS )JambaMambaMixeru  
    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)
    r   c                    s  t    || _|| _|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j| j
| j| jd  dd| _tj| j| j
dd| _td| jd d d d f }| | j
d! }t"t#|| _$t"t%| j
| _&tj| j
| j| jd| _'t(| j|j)d| _*t(| j|j)d| _+t(| j|j)d| _,t-st./d	 d S d S )
Nr   )Zin_channelsZout_channelsr   Zkernel_sizegroupspaddingr"   r   FTr/   rS   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)0rK   rL   r   r   rR   rv   r   rw   r   ru   r   Zmamba_dt_ranktime_step_rankZmamba_conv_biasuse_conv_biasZmamba_proj_biasZuse_biasr   Conv1dconv1d
hidden_act
activationr	   actZuse_mamba_kernelsuse_fast_kernelsr   in_projx_projdt_projr3   aranger<   r   rM   logA_logrN   Dout_projrI   rms_norm_epsdt_layernormb_layernormc_layernormis_fast_path_availabler   r   )rQ   r   r   ArT   r'   r+   rL   -  sJ   
	 zJambaMambaMixer.__init__NrY   cache_paramsr%   c                 C   s  |j \}}}|d uo*|jo*|dko*|j| j j d |j| j j d   ko(|kn  }| |dd}|jddd\}}	|d urH||d }| j	j
| j	j
d| j	j
d}
|rtt|d|j| j |
| j	j| j}|d}n'|d urtj|| j|j d  df}|j| j | t||
| j	j| jd}|d ur||d }| |dd}tj|| j| j| jgdd\}}}| |}| |}| |}| jjj }t!  t"| jjj | jj_ W d    n1 sw   Y  | |dd}t!  || jj_ W d    n	1 sw   Y  t#| j$%  }|d ur(|% nd }|rVt&|j| j |d |d ||d d df |d d df | j'|	d |dd	
d}n.t(||||dd|dd| j'% |	|ddd

\}}|d ur|d ur|j| j | | )|dd}|S )Nr   r   r"   r-   r/   )r   ).r   T)Zdt_softplus)Zdelta_softplusZreturn_last_state)*r;   rt   rx   r   ry   r   r   chunkr?   r   rO   r   r   r    Zsqueezer   r   r   r5   padr   copy_r   r   r3   splitr   r   r   r   r   r   dataZno_gradZ
zeros_likeexpr   r:   r   r   r   r   )rQ   rY   r   r%   rE   seq_lenrB   Zuse_precomputed_statesprojected_statesgateZconv_weightsrx   ssm_parameters	time_stepBCZtime_proj_biasdiscrete_time_stepr   scan_outputs	ssm_statecontextualized_statesr'   r'   r+   cuda_kernels_forwarda  s   	$










z$JambaMambaMixer.cuda_kernels_forwardc              	   C   s  |j \}}}|j}| |dd}|jddd\}	}
|d ur&|	|d }	t|t}|r|j| j	 j d |kr| j
rD|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@tj|	| j|	j d  df}||j| j	< | | |	dd |f }	ntj|| j| jf|	j|d}| | |	dd |f }	|d ur|	|d }	| |	dd}tj || j!| j| jgdd\}}}| "|}| #|}| $|}| %|}tj&|dd}t'| j()  }t'|d d d d d d f |d d d d d d d f  }|d d d d d d d f |d d d d d d d f )  }||	d d d d d d d f )  }g }t*|D ]D}|d d d d |d d f | |d d d d |d d f  }t+|||d d |d d f d}|,|d d d d df  qtj-|dd}||	| j.d d d d f   }|| |
 }|r||j| j	< | /|dd}|S )	Nr   r"   r-   r   r/   )Zshiftsdims.rj   )0r;   rV   r   r   r   r?   r0   rh   ry   r   r   cloner(   r2   rt   rx   r3   Zrollr>   r   rO   r   r   r   r   r5   r   r   r|   r   r   r   r   r   r   r   r   r   Zsoftplusr   r   r:   r{   r   r}   stackr   r   )rQ   Zinput_statesr   r%   rE   r   rB   rV   r   rY   r   r   r  Z
conv_stater   r   r   r   r   r   Z
discrete_AZ
discrete_BZdeltaB_ur   r   Zscan_outputr  r'   r'   r+   slow_forward  sx   
((



:<$<* zJambaMambaMixer.slow_forwardc                 C   s>   | j rtrd| jjjjvrtd| |||S | |||S )Nr   zsFast Mamba kernels are not available. Make sure to they are installed and that the mamba module is on a CUDA device)	r   r   r   rO   r2   r   r   r  r  )rQ   rY   r   r%   r'   r'   r+   r[   !  s   zJambaMambaMixer.forwardr!   )r^   r_   r`   r   r   rL   r3   r   rh   r   r   r  r  r[   ra   r'   r'   rT   r+   r   %  s(    7
kXr   c                       s$   e Zd Z fddZdd Z  ZS )JambaMLPc                    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   )rK   rL   r   rR   r   r   r   	gate_projup_proj	down_projr	   r   act_fnrQ   r   rT   r'   r+   rL   2  s   
zJambaMLP.__init__c                 C   s$   |  | | || | }|S r   )r  r  r
  r  )rQ   xr  r'   r'   r+   r[   <  s    zJambaMLP.forward)r^   r_   r`   rL   r[   ra   r'   r'   rT   r+   r  1  s    
r  c                       sF   e Zd ZdZdef fddZdejdeejejf fddZ	  Z
S )	JambaSparseMoeBlocka  
    This implementation is
    strictly equivalent to standard MoE with full capacity (no
    dropped tokens). It's faster since it formulates MoE operations
    in terms of block-sparse operations to accommodate imbalanced
    assignments of tokens to experts, whereas standard MoE either
    (1) drop tokens at the cost of reduced performance or (2) set
    capacity factor to number of experts and thus waste computation
    and memory on padding.
    r   c                    sd   t     j| _ j| _ j| _ j| _t	j
| j| jdd| _t	 fddt| jD | _d S )NFr   c                    s   g | ]}t  qS r'   )r  rp   r   r'   r+   r,   V  s    z0JambaSparseMoeBlock.__init__.<locals>.<listcomp>)rK   rL   rR   
hidden_dimr   Zffn_dimr$   num_experts_per_tokr@   r   r   router
ModuleListr{   expertsr  rT   r  r+   rL   N  s   
$zJambaSparseMoeBlock.__init__rY   r&   c                 C   s"  |j \}}}|d|}| |}tj|dtjd}tj|| jdd\}}|	|j
}tj|| |f|j
|jd}tjjj|| jdddd}	t| jD ]8}
| j|
 }t|	|
 \}}|j d dkreqM|d	|f d|}|||||d	f  }|d||	|j
 qM||||}||fS )
 r/   r   r   r-   )rV   r2   )Znum_classesr"   r   N)r;   r   r  Fr6   r3   r:   r7   r@   r(   rV   r|   r2   r   r5   r8   r$   Zpermuter{   r  wherer=   Z
index_add_)rQ   rY   rE   rF   r  r#   rA   rC   Zfinal_hidden_statesrD   Z
expert_idxZexpert_layeridxZtop_xZcurrent_stateZcurrent_hidden_statesr'   r'   r+   r[   X  s(   

zJambaSparseMoeBlock.forward)r^   r_   r`   r   r   rL   r3   r   r   r[   ra   r'   r'   rT   r+   r  B  s    (
r  c                          e Zd Zdedef fddZ							ddej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jeeejejf  f fddZ  ZS )JambaAttentionDecoderLayerr   r   c                    sh   t    |j| }t|j ||| _|dkrtnt}||| _t	|j
|jd| _t	|j
|jd| _d S )Nr   r   )rK   rL   layers_num_expertsJAMBA_ATTENTION_CLASSES_attn_implementation	self_attnr  r  feed_forwardrI   rR   r   input_layernormpre_ff_layernormrQ   r   r   r$   Zffn_layer_classrT   r'   r+   rL     s   


z#JambaAttentionDecoderLayer.__init__NFrY   r%   r   r   r   output_router_logitsr   r   r&   c	              	   C   s   |}	|  |}| j|||||||d\}}
}|	| }|}	| |}| |}t|tr0|\}}n|d}}|	| }|f}|rC||
f7 }|rJ||f7 }|rQ||f7 }|S )  
        Args:
            hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
            attention_mask (`torch.FloatTensor`, *optional*): attention mask of size
                `(batch, sequence_length)` where padding elements are indicated by 0.
            past_key_value (`HybridMambaAttentionDynamicCache`, *optional*): cached past key and value projection states
            output_attentions (`bool`, *optional*):
                Whether or not to return the attentions tensors of all attention layers. See `attentions` under
                returned tensors for more detail.
            output_router_logits (`bool`, *optional*):
                Whether or not to return the logits of all the routers. They are useful for computing the router loss, and
                should not be returned during inference.
            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.
        )rY   r%   r   r   r   r   r   N)r"  r   r#  r!  r0   r1   )rQ   rY   r%   r   r   r   r%  r   r   residualself_attn_weightsZpresent_key_value
ff_outputsr#   outputsr'   r'   r+   r[     s6   








z"JambaAttentionDecoderLayer.forwardNNNFFFNr^   r_   r`   r   r   rL   r3   r   r   r   rh   r   r   r   r[   ra   r'   r'   rT   r+   r    8    	
r  c                       r  )JambaMambaDecoderLayerr   r   c                    sd   t    |j| }t||d| _|dkrtnt}||| _t|j	|j
d| _t|j	|j
d| _d S )N)r   r   r   r   )rK   rL   r  r   ri   r  r  r!  rI   rR   r   r"  r#  r$  rT   r'   r+   rL     s   


zJambaMambaDecoderLayer.__init__NFrY   r%   r   r   r   r%  r   r   r&   c	                 C   s   |}	|  |}| j|||d}d}
|	| }|}	| |}| |}t|tr+|\}}n|d}}|	| }|f}|r>||
f7 }|rE||f7 }|rL||f7 }|S )r&  )rY   r   r%   N)r"  ri   r#  r!  r0   r1   )rQ   rY   r%   r   r   r   r%  r   r   r'  r(  r)  r#   r*  r'   r'   r+   r[     s0   








zJambaMambaDecoderLayer.forwardr+  r,  r'   r'   rT   r+   r.    r-  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dS )	JambaPreTrainedModelmodelTr  r.  r   c                 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rtd|jd d d d f }||jd }|jjt| |jjd d S d S )Nr   )r9   stdg      ?r   r/   )r   Zinitializer_ranger0   r   r   r   rO   r   Znormal_r   Zzero_	Embeddingpadding_idxrI   Zfill_r   r3   r   r   r<   r   r   r   r   r   r   )rQ   moduler1  r   r'   r'   r+   _init_weights.  s&   



z"JambaPreTrainedModel._init_weightsN)r^   r_   r`   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_statefulr5  r'   r'   r'   r+   r/  "  s    r/  )Z	attentionri   c                       s   e Zd ZdZdef fddZdd Zdd Ze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fddZdd Zdd Z  ZS )
JambaModelz
    Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`JambaDecoderLayer`]

    Args:
        config: JambaConfig
    r   c                    s   t  | |j| _|j| _t|j|j| j| _g }t	|j
D ]}t|j|  }||||d q t|| _|j| _t|j|jd| _d| _|   d S )N)r   r   F)rK   rL   pad_token_idr3  
vocab_sizer   r2  rR   embed_tokensr{   rG   ALL_DECODER_LAYER_TYPESrs   r}   r  layersr  rI   r   final_layernormgradient_checkpointing	post_init)rQ   r   Zdecoder_layersr   Zlayer_classrT   r'   r+   rL   N  s   zJambaModel.__init__c                 C      | j S r   r9  r\   r'   r'   r+   get_input_embeddingsa     zJambaModel.get_input_embeddingsc                 C   
   || _ d S r   r@  rQ   valuer'   r'   r+   set_input_embeddingsd     
zJambaModel.set_input_embeddingsN	input_idsr%   r   r   inputs_embedsr   r   output_hidden_statesr%  r   r&   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| 
|}|}|rY|d u rYt	d |
d u rhtj|jd |jd}
|d u rq|
d}| |||
}| ||
}|rdnd }|rdnd }|	rdnd }| jD ]U}t|tr|n|}|r||f7 }| jr| jr| |j||||||	||
	}n|||||||	||
d	}|d }|r|d d ur||d f7 }|	r|d
 d ur||d
 f7 }q| |}|r||f7 }|r|jsd|_|sd n|}t|||||dS )Nz:You must specify exactly one of input_ids or inputs_embedszX`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`.FzJamba requires an initialized `HybridMambaAttentionDynamicCache` to return a cache. None was provided, so no cache will be returned.r   rk   r   r'   )r%   r   r   r   r%  r   r   r/   T)last_hidden_stater   rY   
attentionsr#   )r   r   r%  rJ  r   r   r=  r   r   r   r9  r3   r   r;   r2   r?   _update_causal_mask_update_mamba_maskr;  r0   r.  Z_gradient_checkpointing_func__call__r<  rt   r   )rQ   rH  r%   r   r   rI  r   r   rJ  r%  r   rY   r   
mamba_maskZall_hidden_statesZall_self_attnsZall_router_logitsZdecoder_layerZ
layer_maskZlayer_outputsZ
next_cacher'   r'   r+   r[   g  s   






zJambaModel.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   r/   )Z
fill_valuerV   r2   )Zdiagonalrk   r   r"   .r   )r   ZxpuZnpu)r   r  rV   r2   r3   Zfinfominr;   fullZtriur   r=   r<   r  r.   eqZmasked_fillr   r   Z_unmask_unattended)rQ   r%   Zinput_tensorr   rV   r2   Z	min_dtyperF   Ztarget_lengthr   Zmask_lengthZpadding_maskr'   r'   r+   rM    s0   
*
4$zJambaModel._update_causal_maskc                 C   s.   |}|d dks|durt |dkrd}|S )zv
        No need for zeroing states when
            1. Cached forward
            2. Attending to all inputs
        r   Nr   )r3   all)rQ   r%   r   rP  r'   r'   r+   rN    s   "zJambaModel._update_mamba_mask)
NNNNNNNNNN)r^   r_   r`   r   r   rL   rA  rF  r   r   r   r3   r   r   rh   r   r   r   r[   rM  rN  ra   r'   r'   rT   r+   r6  E  sT    	
s#r6  c                       s  e Zd Zdg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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fd d!Z				"			#d'd$d%Z  ZS )(JambaForCausalLMzlm_head.weightr   c                    sX   t  | t|| _|j| _tj|j|jdd| _|j	| _	|j
| _
|j| _|   d S r	  )rK   rL   r6  r0  r8  r   r   rR   lm_headrouter_aux_loss_coefr$   r  r>  r  rT   r'   r+   rL     s   
zJambaForCausalLM.__init__c                 C      | j jS r   r0  r9  r\   r'   r'   r+   rA    r   z%JambaForCausalLM.get_input_embeddingsc                 C      || j _d S r   rY  rD  r'   r'   r+   rF       z%JambaForCausalLM.set_input_embeddingsc                 C   r?  r   rV  r\   r'   r'   r+   get_output_embeddings   rB  z&JambaForCausalLM.get_output_embeddingsc                 C   rC  r   r\  )rQ   Znew_embeddingsr'   r'   r+   set_output_embeddings#  rG  z&JambaForCausalLM.set_output_embeddingsc                 C   rC  r   r0  )rQ   decoderr'   r'   r+   set_decoder&  rG  zJambaForCausalLM.set_decoderc                 C   r?  r   r_  r\   r'   r'   r+   get_decoder)  rB  zJambaForCausalLM.get_decoderNr   rH  r%   r   r   rI  labelsr   r   rJ  r%  r   logits_to_keepr&   c                 K   s  |dur|n| j j}|
dur|
n| j j}
|	dur|	n| j j}	| j||||||||	|
|d
}|j}t|tr;t| dn|}| 	|dd|ddf }d}|dur]| j
||| jfi |}d}|
rzt|j| j| j|}|durz|| j||j 7 }t||||j|j|j|jdS )aj  
        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, JambaForCausalLM

        >>> model = JambaForCausalLM.from_pretrained("ai21labs/Jamba-v0.1")
        >>> tokenizer = AutoTokenizer.from_pretrained("ai21labs/Jamba-v0.1")

        >>> 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)
rH  r%   r   r   rI  r   r   rJ  r%  r   )lossaux_losslogitsr   rY   rL  r#   )r   r   r%  rJ  r0  rK  r0   r   slicerV  loss_functionr8  rH   r#   r$   r  rW  r(   r2   r   r   rY   rL  )rQ   rH  r%   r   r   rI  rc  r   r   rJ  r%  r   rd  Zloss_kwargsr*  rY   Zslice_indicesrg  re  rf  r'   r'   r+   r[   ,  sT   )zJambaForCausalLM.forwardFTc	              
   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 )Nr/   r   r   rk   rI  rH  )r   r   r   r%   r%  rd  r   )r;   rh   r   rV   r2   longZcumsumZmasked_fill_r   r   Znum_logits_to_keep)rQ   rH  r   r%   rI  r%  r   r   r   r   Zempty_past_kvZmodel_inputsr'   r'   r+   prepare_inputs_for_generation  s<   
z.JambaForCausalLM.prepare_inputs_for_generation)NNNNNNNNNNNr   )NNNFNNT)r^   r_   r`   Z_tied_weights_keysr   rL   rA  rF  r]  r^  ra  rb  r   r   r   r3   r   r   rh   r   r   r   r   r   r[   rk  ra   r'   r'   rT   r+   rU    st    	
^rU  a  
    The Jamba Model with a sequence classification head on top (linear layer).

    [`JambaForSequenceClassification`] 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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fddZ  ZS )JambaForSequenceClassificationc                    s@   t  | |j| _t|| _tj|j| jdd| _| 	  d S r	  )
rK   rL   Z
num_labelsr6  r0  r   r   rR   scorer>  r  rT   r'   r+   rL     s
   
z'JambaForSequenceClassification.__init__c                 C   rX  r   rY  r\   r'   r'   r+   rA    r   z3JambaForSequenceClassification.get_input_embeddingsc                 C   rZ  r   rY  rD  r'   r'   r+   rF    r[  z3JambaForSequenceClassification.set_input_embeddingsNrH  r%   r   r   rI  rc  r   r   rJ  r&   c
              
   C   s(  | j ||||||||	d}
|
j}| |}|dur|jd }n|jd }| jjdu r2|dkr2td| jjdu r;d}n1|dur`|| 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d
}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).
        )r%   r   r   rI  r   r   rJ  Nr   r   z=Cannot handle batch sizes > 1 if no padding token is defined.r/   rj   z will not detect padding tokens in `inputs_embeds`. Results may be unexpected if using padding tokens in conjunction with `inputs_embeds.`rk   )rg  rc  pooled_logitsr   )re  rg  r   rY   rL  )r0  rK  rm  r;   r   r7  r   r(   r2   r3   Zint32r   Zargmaxr   r   rU   r^   ri  r   r   rY   rL  )rQ   rH  r%   r   r   rI  rc  r   r   rJ  Ztransformer_outputsrY   rg  rE   Zlast_non_pad_tokenZnon_pad_maskZtoken_indicesrn  re  r'   r'   r+   r[     sL   


z&JambaForSequenceClassification.forward)	NNNNNNNNN)r^   r_   r`   rL   rA  rF  r   r   r   r3   r   r   r
   r   r   r   r[   ra   r'   r'   rT   r+   rl    sH    		
rl  )rU  rl  r6  r/  )Nr"   N)Mr   r   typingr   r   r   r   r   r3   Ztorch.nn.functionalr   r5   r  Ztorch.utils.checkpointZactivationsr	   Zcache_utilsr
   r   Z
generationr   Zmodeling_attn_mask_utilsr   Zmodeling_flash_attention_utilsr   r   Zmodeling_outputsr   r   r   Zmodeling_utilsr   utilsr   r   r   Zutils.import_utilsr   r   Zconfiguration_jambar   r   Z&mamba_ssm.ops.selective_scan_interfacer   r   Z+mamba_ssm.ops.triton.selective_state_updater   Zcausal_conv1dr   r    rT  r   Z
get_loggerr^   r   r   r   rH   ModulerI   rg   rh   r   r   r   r  r   r  r  r  r.  r/  r:  r6  rU  rl  __all__r'   r'   r'   r+   <module>   s   


UX[`S  ?RO
 G ;V