o
    ei                     @   s  d dl mZ d dlmZ d dlZd dlmZ ddlmZ ddl	m
Z
 ddlmZ dd	lmZ dd
lmZmZ ddlmZmZ ddlmZmZ ddlmZ ddlmZmZ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+ ddl,m-Z- e.e/Z0G dd de%Z1G dd dZ2G dd de$Z3G dd dej4Z5G dd  d e(Z6G d!d" d"e*Z7G d#d$ d$ej4Z8G d%d& d&eZ9G d'd( d(eZ:e9e:d)Z;G d*d+ d+eZ<eG d,d- d-e<Z=G d.d/ d/e+Z>G d0d1 d1ee<Z?g d2Z@dS )3    )Callable)AnyN)nn   )initialization)ACT2FN)lazy_load_kernel)create_causal_mask) GenericForSequenceClassificationGradientCheckpointingLayer)MoeCausalLMOutputWithPastMoeModelOutputWithPast)ALL_ATTENTION_FUNCTIONSPreTrainedModel)Unpack)TransformersKwargsauto_docstringlogging)merge_with_config_defaults)OutputRecordercapture_outputs   )LlamaAttentionLlamaRMSNormeager_attention_forward)
MistralMLP)MixtralExpertsMixtralForCausalLM   )JambaConfigc                   @      e Zd ZdS )JambaRMSNormN__name__
__module____qualname__ r&   r&   e/home/ubuntu/transcripts/venv/lib/python3.10/site-packages/transformers/models/jamba/modular_jamba.pyr!   -       r!   c                   @   s   e Zd ZdZdZejdfddZdd Zdd	 Z		dd
ej
dej
dedeeef dB deej
ej
f f
ddZdejfddZdej
dedeeef fddZddedB defddZd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)`.
    FNc           	   
      s&  || _ |j| _d| _|j|j }|j}|j}g | _g | _g | _	t
|jD ]P}| j| dkrN|  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devicedtyper,   c                        g | ]}t jg g  d qS r.   torchtensor.0_
batch_sizer,   r&   r'   
<listcomp>X        z=HybridMambaAttentionDynamicCache.__init__.<locals>.<listcomp>c                    r/   r0   r1   r4   r7   r&   r'   r9   Y   r:   )r-   layers_block_typehas_previous_statemamba_expandhidden_sizemamba_d_statemamba_d_convconv_states
ssm_statestransformer_layersrangenum_hidden_layersr2   zerosr3   append	key_cachevalue_cache)	selfconfigr8   r-   r,   intermediate_sizessm_state_sizeconv_kernel_sizeir&   r7   r'   __init__A   s,   
   z)HybridMambaAttentionDynamicCache.__init__c                 C   s
   t | jS N)lenrH   )rJ   r&   r&   r'   __len__[   s   
z(HybridMambaAttentionDynamicCache.__len__c                 C   s   | j | | j| fS rQ   )rH   rI   rJ   	layer_idxr&   r&   r'   __getitem__^   s   z,HybridMambaAttentionDynamicCache.__getitem__
key_statesvalue_statesrU   cache_kwargsreturnc                 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   dim)rH   shaperI   r2   cat)rJ   rW   rX   rU   rY   r&   r&   r'   updatea   s   
z'HybridMambaAttentionDynamicCache.updatebeam_idxc                 C   s   |   dkrdtt| jD ]X}| j| j}| j| d||| j|< | j| j}| j| d||| j|< | j| j}| j| d||| j|< | j	| j}| j	| d||| j	|< qdS dS )zDReorders the cache for beam search, given the selected beam indices.r   N)
get_seq_lengthrD   rR   rH   r,   index_selecttorI   rA   rB   )rJ   ra   rU   r,   r&   r&   r'   reorder_cacher   s    z.HybridMambaAttentionDynamicCache.reorder_cachecache_positionc                 C   s$   d}|j d }| || }||fS )zDReturn the length and offset of the cache, used to generate the maskr   )r^   rb   )rJ   rf   rU   	kv_offsetquery_length	kv_lengthr&   r&   r'   get_mask_sizes   s   
z/HybridMambaAttentionDynamicCache.get_mask_sizesr   c                 C   sN   || j vr
| j d n|}t| j|ks| j| jd dkrdS | j| jd S )zYReturns the sequence length of the cached states. A layer index can be optionally passed.r   r[   )rC   rR   rH   r^   rT   r&   r&   r'   rb      s   "z/HybridMambaAttentionDynamicCache.get_seq_lengthrQ   )r   )r#   r$   r%   __doc__is_compileabler2   float16rP   rS   rV   Tensorintdictstrr   tupler`   
LongTensorre   rj   rb   r&   r&   r&   r'   r)   1   s*    
 r)   c                       sv   e Zd Zdedef fddZ			ddejdejdB dedB d	ej	dB d
e
e deejejdB f fddZ  ZS )JambaAttentionrK   rU   c                    s   t  || 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 NFbias)superrP   r   Linearr>   num_attention_headshead_dimq_projnum_key_value_headsk_projv_projo_proj)rJ   rK   rU   	__class__r&   r'   rP      s
    zJambaAttention.__init__Nhidden_statesattention_maskpast_key_valuesrf   kwargsrZ   c                 K   s   |j d d }g |d| jR }| ||dd}| ||dd}	| ||dd}
|d urF||	|
| jd|i\}	}
t	
| jjt}|| ||	|
|f| jsZdn| j| jd|\}}|jg |dR   }| |}||fS )Nr[   r   r   rf           )dropoutscaling)r^   r|   r}   view	transposer   r   r`   rU   r   get_interfacerK   _attn_implementationr   trainingattention_dropoutr   reshape
contiguousr   )rJ   r   r   r   rf   r   input_shapehidden_shapequery_statesrW   rX   attention_interfaceattn_outputattn_weightsr&   r&   r'   forward   s6   

zJambaAttention.forwardNNN)r#   r$   r%   r   rp   rP   r2   ro   r)   rt   r   r   rs   r   __classcell__r&   r&   r   r'   ru      s$    
ru   c                       s   e Zd ZdZdef fddZ		ddejdedB dej	dB fd	d
Z
ddedB dej	dB fddZ		ddedB dej	dB 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)
    rK   c                    s  t    || _|| _|j| _|j| _|j| _|j	|j | _
|j| _|j| _|j| _tj| j
| j
| j| j| j
| jd d| _|j| _t|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+d	}t,|d
d a-t,|dd a.t+d}t,|dd a/t,|dd a0t,|dd a1t2t/t1t.t-t0fa3t3st45d d S d S )Nr   )in_channelsout_channelsrx   kernel_sizegroupspaddingr   rw   FTr[   epszcausal-conv1dcausal_conv1d_updatecausal_conv1d_fnz	mamba-ssmselective_state_updatemamba_inner_fnselective_scan_fna  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.)6ry   rP   rK   rU   r>   r?   rM   r@   rN   r=   rL   mamba_dt_ranktime_step_rankmamba_conv_biasuse_conv_biasmamba_proj_biasuse_biasr   Conv1dconv1d
hidden_act
activationr   actrz   in_projx_projdt_projr2   arangeexpandr   	ParameterlogA_logonesDout_projr!   rms_norm_epsdt_layernormb_layernormc_layernormr   getattrr   r   r   r   r   allis_fast_path_availableloggerwarning_once)rJ   rK   rU   Acausal_conv1d	mamba_ssmr   r&   r'   rP      s\   
	 zJambaMambaMixer.__init__Nr   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)dt_softplus)delta_softplusreturn_last_state)*r^   r<   rA   rU   rB   r   r   chunk	unsqueezer   weightr   sizer   squeezerx   r   r   
functionalpadrN   copy_r   r   r2   splitr   rM   r   r   r   r   datano_grad
zeros_likeexpr   floatr   r   r   r   )rJ   r   r   r   r8   seq_lenr6   use_precomputed_statesprojected_statesgateconv_weightsrA   ssm_parameters	time_stepBCtime_proj_biasdiscrete_time_stepr   scan_outputs	ssm_statecontextualized_statesr&   r&   r'   cuda_kernels_forward	  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[   )shiftsdims.r+   )0r^   r-   r   r   r   r   
isinstancer)   rB   rU   r   clonerd   r,   r<   rA   r2   rollsumr   r   r   rx   r   r   r   r   rN   rF   rL   rM   r   r   r   r   r   r   r   softplusr   r   r   rD   matmulrG   stackr   r   )rJ   input_statesr   r   r8   r   r6   r-   r   r   r   	use_cacher   
conv_stater   r   r   r   r   r   
discrete_A
discrete_BdeltaB_ur   rO   scan_outputr   r&   r&   r'   slow_forwardt  sx   
((



:<$<* zJambaMambaMixer.slow_forwardc                 C   sR   | j jrtrd| jjjjvrtd d| j _| j jr"| 	|||S | 
|||S )NcudazFast Mamba kernels are not available. Make sure that they are installed and that the mamba module is on a CUDA device. Turning off the fast path `config.use_mamba_kernels=False` and falling back to the slow path.F)rK   use_mamba_kernelsr   r   r   r,   typer   r   r   r   )rJ   r   r   r   r&   r&   r'   r     s   zJambaMambaMixer.forward)NN)r#   r$   r%   rl   r   rP   r2   ro   r)   rt   r   r   r   r   r&   r&   r   r'   r      s(    D
kXr   c                   @   r    )JambaMLPNr"   r&   r&   r&   r'   r     r(   r   c                   @   r    )JambaExpertsNr"   r&   r&   r&   r'   r    r(   r  c                       sD   e Zd ZdZdef fddZdd Zdejdej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.
    rK   c                    sN   t    |j| _|j| _|j| _|j| _t	j
| j| jdd| _t|| _d S rv   )ry   rP   r>   
hidden_dimrL   ffn_dimnum_expertsnum_experts_per_toktop_kr   rz   routerr  expertsrJ   rK   r   r&   r'   rP     s   
zJambaSparseMoeBlock.__init__c                 C   s<   t jjj|dt jd}t j|| jdd\}}|||jfS )Nr[   )r]   r-   r\   )	r2   r   r   softmaxr   topkr  rd   r-   )rJ   r   router_logitsrouting_weightstop_k_weightstop_k_indexr&   r&   r'   route_tokens_to_experts  s   z+JambaSparseMoeBlock.route_tokens_to_expertsr   rZ   c                 C   sR   |j \}}}|d|}| |}| ||\}}| |||}||||}|S )Nr[   )r^   r   r  r  r	  r   )rJ   r   r8   sequence_lengthr  r  r  r  r&   r&   r'   r     s   
zJambaSparseMoeBlock.forward)r#   r$   r%   rl   r   rP   r  r2   ro   r   r   r&   r&   r   r'   r    s
    
r  c                       s~   e Zd Zdedef fddZ					ddejdejdB d	ejdB d
e	dB de
dB dejdB dee dejfddZ  ZS )JambaAttentionDecoderLayerrK   rU   c                    sl   t    |jr|j| nd}t||| _|dkrtnt}||| _t|j	|j
d| _t|j	|j
d| _d S )Nr   r   )ry   rP   layers_num_expertsru   	self_attnr  r   feed_forwardr!   r>   r   input_layernormpre_ff_layernormrJ   rK   rU   r  ffn_layer_classr   r&   r'   rP     s   

z#JambaAttentionDecoderLayer.__init__NFr   r   position_idsr   r   rf   r   rZ   c           
   	   K   s\   |}|  |}| jd||||||d|\}}	|| }|}| |}| |}|| }|S )N)r   r   r  r   r   rf   r&   )r  r  r  r  )
rJ   r   r   r  r   r   rf   r   residualr6   r&   r&   r'   r     s$   


	

z"JambaAttentionDecoderLayer.forward)NNNFN)r#   r$   r%   r   rp   rP   r2   ro   rt   r)   boolr   r   FloatTensorr   r   r&   r&   r   r'   r    s0    	r  c                       sh   e Zd Zdedef fddZ			ddejdejdB dejdB d	e	dB d
e
e dejfddZ  ZS )JambaMambaDecoderLayerrK   rU   c                    sn   t    |jr|j| nd}t||d| _|dkrtnt}||| _t|j	|j
d| _t|j	|j
d| _d S )Nr   )rK   rU   r   )ry   rP   r  r   r*   r  r   r  r!   r>   r   r  r  r  r   r&   r'   rP   4  s   

zJambaMambaDecoderLayer.__init__Nr   r   r  r   r   rZ   c                 K   sJ   |}|  |}| j|||d}|| }|}| |}| |}|| }|S )N)r   r   r   )r  r*   r  r  )rJ   r   r   r  r   r   r  r&   r&   r'   r   =  s   


zJambaMambaDecoderLayer.forwardr   )r#   r$   r%   r   rp   rP   r2   ro   rt   r)   r   r   r  r   r   r&   r&   r   r'   r  3  s$    r  )	attentionr*   c                       sh   e Zd ZU eed< dZdZddgZdZdZ	dZ
dZeegeeejddd	Ze  fd
dZ  ZS )JambaPreTrainedModelrK   modelTr  r  r   r  )
layer_name)r   
attentionsr  c                    s   t  | t|tr5td|jd d d d f }||jd	 }t
|jt| t
|j d S t|trRt
j|jd| jjd t
j|jd| jjd d S d S )Nr   r[   r   )meanstd)ry   _init_weightsr   r   r2   r   rM   r   rL   r   initr   r   r   ones_r   r  normal_gate_up_projrK   initializer_range	down_proj)rJ   moduler   r   r&   r'   r'  f  s   

z"JambaPreTrainedModel._init_weights)r#   r$   r%   r   __annotations__base_model_prefixsupports_gradient_checkpointing_no_split_modules_skip_keys_device_placement_supports_flash_attn_supports_sdpa_is_statefulr  r  ru   r   r   rz   _can_record_outputsr2   r   r'  r   r&   r&   r   r'   r!  W  s   
 r!  c                       s   e Zd Zdef fddZeee							ddej	dB dej
dB dej	dB dedB d	ejdB d
edB dej	dB dee defddZdd Z  ZS )
JambaModelrK   c                    s   t  | |j| _|j| _t|j|j| j| _g }t	|j
D ]}t|j|  }||||d q t|| _t|j|jd| _d| _|   d S )N)rU   r   F)ry   rP   pad_token_idpadding_idx
vocab_sizer   	Embeddingr>   embed_tokensrD   rE   ALL_DECODER_LAYER_TYPESr;   rG   
ModuleListlayersr!   r   final_layernormgradient_checkpointing	post_init)rJ   rK   decoder_layersrO   layer_classr   r&   r'   rP   u  s   zJambaModel.__init__N	input_idsr   r  r   inputs_embedsr   rf   r   rZ   c              	   K   s"  |d u |d uA rt d|d u r| |}|r)|d u r)t| j|jd |j|jd}|d u rE|d ur5| nd}	tj	|	|	|jd  |jd}|d u rN|
d}t| j|||||d}
| ||}|}| jD ]}t|trm|n|
}||f|||||d|}qd| |}|r|jsd|_t||d	S )
Nz:You must specify exactly one of input_ids or inputs_embedsr   )rK   r8   r-   r,   r   r.   )rK   rG  r   rf   r   r  )r   r  r   r   rf   T)last_hidden_stater   )
ValueErrorr=  r)   rK   r^   r-   r,   rb   r2   r   r   r	   _update_mamba_maskr@  r   r  rA  r<   r   )rJ   rF  r   r  r   rG  r   rf   r   past_seen_tokenscausal_mask
mamba_maskr   decoder_layer
layer_maskr&   r&   r'   r     s`   





zJambaModel.forwardc                 C   s6   |}|dur|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
        Nr   r   )r2   r   )rJ   r   rf   rM  r&   r&   r'   rJ    s
   zJambaModel._update_mamba_mask)NNNNNNN)r#   r$   r%   r   rP   r   r   r   r2   rt   ro   r)   r  r  r   r   r   r   rJ  r   r&   r&   r   r'   r8  s  s@    	
Cr8  c                       s   e Zd Zdef fddZ										ddejdB dejdB dejdB d	edB d
ej	dB dejdB de
dB de
dB dejdB deejB dee def fddZ  ZS )JambaForCausalLMrK   c                    s   t  | |j| _d S rQ   )ry   rP   r  r
  r   r&   r'   rP     s   zJambaForCausalLM.__init__Nr   rF  r   r  r   rG  labelsr   output_router_logitsrf   logits_to_keepr   rZ   c              
      s$   t  j||||||||	|
f	i |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."
        ```)ry   r   )rJ   rF  r   r  r   rG  rQ  r   rR  rf   rS  r   r   r&   r'   r     s   $
zJambaForCausalLM.forward)
NNNNNNNNNr   )r#   r$   r%   r   rP   r2   rt   ro   r)   r  r  rp   r   r   r   r   r   r&   r&   r   r'   rP    sJ    	
rP  c                   @   r    )JambaForSequenceClassificationNr"   r&   r&   r&   r'   rT    r(   rT  )rP  rT  r8  r!  )Acollections.abcr   typingr   r2   r    r   r(  activationsr   integrationsr   masking_utilsr	   modeling_layersr
   r   modeling_outputsr   r   modeling_utilsr   r   processing_utilsr   utilsr   r   r   utils.genericr   utils.output_capturingr   r   llama.modeling_llamar   r   r   mistral.modeling_mistralr   mixtral.modeling_mixtralr   r   configuration_jambar   
get_loggerr#   r   r!   r)   ru   Moduler   r   r  r  r  r  r>  r!  r8  rP  rT  __all__r&   r&   r&   r'   <module>   sL   
_0   %(
!g7