o
    Zh                     @   s  d Z ddlZddlmZmZmZmZ ddlZddlZddlm	Z	 ddl
mZ 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mZ ddl m!Z! ddl"m#Z#m$Z$m%Z%m&Z& ddl'm(Z( e% rddl)m*Z* ddl+m,Z, e rddlm-Z- e&.e/Z0			d@deej1eej1 df dee2 deej1 deej1e2f fddZ3G dd de	j4Z5G dd de	j4Z6G d d! d!e	j4Z7G d"d# d#e	j4Z8G d$d% d%e	j4Z9G d&d' d'e	j4Z:d(d) Z;dAd*d+Z<G d,d- d-e	j4Z=G d.d/ d/e=Z>G d0d1 d1e=Z?e=e?e>d2Z@G d3d4 d4e	j4ZAe#G d5d6 d6e!ZBe#G d7d8 d8eBZCG d9d: d:eBeZDe#d;d<G d=d> d>eBZEg d?ZFdS )BzPyTorch JetMoe model.    N)ListOptionalTupleUnion)nn)
functional   )ACT2FN)CacheDynamicCache)GenerationMixin)AttentionMaskConverter)!flash_attn_supports_top_left_maskis_flash_attn_available)MoeCausalLMOutputWithPastMoeModelOutputWithPast SequenceClassifierOutputWithPast)ROPE_INIT_FUNCTIONSdynamic_rope_update)PreTrainedModel)auto_docstringcan_return_tupleis_torch_flex_attn_availablelogging   )JetMoeConfig)	BlockMask)make_flex_block_causal_mask)_flash_attention_forward   gate_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:
        gate_logits:
            Logits from the `gate`, 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_gateZcompute_devicer$   Y/var/www/auris/lib/python3.10/site-packages/transformers/models/jetmoe/modeling_jetmoe.py
<listcomp>T       z,load_balancing_loss_func.<locals>.<listcomp>dim)
isinstancetupledevicetorchcatr   r   softmaxtopkZone_hotmeanfloatshapeexpandreshaper%   sum	unsqueeze)r    r!   top_kr"   Zconcatenated_gate_logitsZrouting_weights_Zselected_expertsZ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_func2   s>   



rA   c                       s6   e Zd Zdedededdf fddZdd	 Z  ZS )
JetMoeParallelExpertsr!   
input_sizeoutput_sizer#   Nc                    s6   t    tt|||| _|| _|| _|| _	dS )a  
        Initialize the JetMoeParallelExperts module.
        The experts weights are stored in [num_experts, output_size, input_size] format. Such that it's compatible with
        many MoE libraries, such as [Megablock](https://github.com/databricks/megablocks) and
        [ScatterMoE](https://github.com/shawntan/scattermoe), as well as the
        [MoE kernel](https://github.com/vllm-project/vllm/blob/main/vllm/model_executor/layers/fused_moe/fused_moe.py)
        used in vllm.

        Args:
            num_experts (int):
                Number of experts.
            input_size (int):
                Size of the input.
            output_size (int):
                Size of the output.
        N)
super__init__r   	Parameterr1   emptyweightr!   rC   rD   )selfr!   rC   rD   	__class__r$   r(   rF      s
   

zJetMoeParallelExperts.__init__c                 C   sP   |j |dd}g }t| jD ]}|t|| | j|  qtj|dd}|S )a  
        Forward pass of the JetMoeParallelExperts module.

        Args:
            inputs (Tensor):
                Input tensor.
            expert_size:
                Expert size information.

        Returns:
            Tensor: Output tensor.
        r   r+   )	splitranger!   appendFZlinearrI   r1   r2   )rJ   Zinputsexpert_sizeZ
input_listZoutput_listiresultsr$   r$   r(   forward   s   zJetMoeParallelExperts.forward__name__
__module____qualname__intrF   rT   __classcell__r$   r$   rK   r(   rB      s    rB   c                       s2   e Zd Zdededef fddZdd Z  ZS )JetMoeTopKGatingrC   r!   r<   c                    s2   t    || _|| _|| _tj||dd| _dS )a  
        Initialize the top-k gating mechanism.

        Args:
            input_size (`int`):
                Size of the input.
            num_experts (`int`):
                Number of experts.
            top_k (`int`):
                Number of top experts to select.
        FbiasN)rE   rF   r!   rC   r<   r   Linearlayer)rJ   rC   r!   r<   rK   r$   r(   rF      s
   
zJetMoeTopKGating.__init__c                 C   s   |  | }|j| jdd\}}tj|dd|}tj|d| j	g|j
|jd}|d|d}| d}| }| }	|	d\}
}|j| jdd}| }|| }|||||fS )Nr   r+   r   dtyper0   trunc)Zrounding_mode)r_   r6   r4   r<   r1   r3   Ztype_aszerossizer!   ra   r0   Zscatterlongr:   tolistflattensortdiv)rJ   hidden_stateslogitsZtop_k_logitsZtop_k_indicesZtop_k_gatesrc   ZgatesrQ   Ztop_k_expertsr=   index_sorted_expertsbatch_indexbatch_gatesr$   r$   r(   rT      s   zJetMoeTopKGating.forwardrU   r$   r$   rK   r(   r[      s    r[   c                       s.   e Zd ZdZdef fddZdd Z  ZS )	JetMoeMoEz
    A Sparsely gated mixture of experts layer with 1-layer Feed-Forward networks as experts.

    Args:
        config:
            Configuration object with model hyperparameters.
    configc                    s   t t|   |j| _|j| _t|j | _t	j
t	| j| _t|j| j| jd | _t|j| j| j| _t| j|j|jd| _d S )Nr   rC   r!   r<   )rE   ro   rF   hidden_sizerC   Zintermediate_sizer	   Zactivation_function
activationr1   r   rG   rH   r]   rB   num_local_expertsinput_linearoutput_linearr[   num_experts_per_tokrouterrJ   rp   rK   r$   r(   rF      s   zJetMoeMoE.__init__c                 C   s   |  \}}}|d|}| |\}}}}}	|| }
| |
|}|jddd}| |d |d  }| ||}||dddf  }tj|| | j	f|j
|jd}|d||}|||| j	}|| j }||	fS )a  
        Forward pass of the mixture of experts layer.

        Args:
            layer_input (Tensor):
                Input tensor.

        Returns:
            Tensor:
                Output tensor.
            Tensor:
                Router logits.
        r-   r   r+   r   r   Nr`   )rd   r9   rx   ru   chunkrs   rv   r1   rc   rC   ra   r0   	index_addviewr]   )rJ   layer_inputbszlengthemb_sizer=   rm   rn   rQ   router_logitsexpert_inputsrj   Zchunked_hidden_statesexpert_outputsrc   layer_outputr$   r$   r(   rT      s   
zJetMoeMoE.forward)rV   rW   rX   __doc__r   rF   rT   rZ   r$   r$   rK   r(   ro      s    ro   c                       s>   e Zd ZdZdef fddZdd Zdd Zd	d
 Z  Z	S )	JetMoeMoAz
    A Sparsely gated mixture of attention layer with pairs of query- and output-projections as experts.

    Args:
        config:
            Configuration object with model hyperparameters.
    rp   c                    s   t t|   |j| _|j| _|j|j | _|j	| _
tjt| j| _t| j| j| j| _t| j| j| j| _t| j| j| j
d| _d S )Nrq   )rE   r   rF   rt   r!   rr   rC   kv_channelsnum_key_value_headsrw   r<   r1   r   rG   rH   r]   rB   ru   rv   r[   rx   ry   rK   r$   r(   rF   %  s   zJetMoeMoA.__init__c                 C   s   |  \}}}|d|}| |\}}}}}	||||f}
|| }| ||}tj|| | j | jf|j|j	d}|
d||}|||| jd}||	|
fS )z
        Map inputs to attention experts according to routing decision and compute query projection inside each experts.
        r-   r`   r   )rd   r9   rx   ru   r1   rc   r<   rr   ra   r0   r{   r|   )rJ   r}   r~   r   r   rl   rm   rn   rQ   r   	topo_infor   r   rc   r   r$   r$   r(   map7  s   
zJetMoeMoA.mapc                 C   s   |  \}}}}|d|}|\}}}	}
|| }| ||
}||	dddf  }tj|| | jf|j|jd}|d||}|	||| j}|| j
 }|S )zu
        Compute output projection inside each attention experts and merge the outputs of different experts.
        r-   Nr`   r   )rd   r9   rv   r1   rc   rC   ra   r0   r{   r|   r]   )rJ   r}   r   r~   r   krr   rl   rm   rn   rQ   r   r   rc   r   r$   r$   r(   reduceN  s   
zJetMoeMoA.reducec                 C   s   t d)Nz-This module doesn't support call and forward.)NotImplementedError)rJ   r}   r$   r$   r(   rT   d     zJetMoeMoA.forward)
rV   rW   rX   r   r   rF   r   r   rT   rZ   r$   r$   rK   r(   r     s    r   c                       s.   e Zd Zd fdd	Zdd Zdd Z  ZS )	JetMoeRMSNormư>c                    s&   t    tt|| _|| _dS )z<
        JetMoeRMSNorm is equivalent to T5LayerNorm
        N)rE   rF   r   rG   r1   ZonesrI   variance_epsilon)rJ   rr   epsrK   r$   r(   rF   j  s   

zJetMoeRMSNorm.__init__c                 C   sJ   |j }|tj}|djddd}|t|| j  }| j|| S )Nr   r-   T)Zkeepdim)	ra   r%   r1   float32powr5   Zrsqrtr   rI   )rJ   rj   input_dtypeZvariancer$   r$   r(   rT   r  s
   zJetMoeRMSNorm.forwardc                 C   s   t | jj d| j S )Nz, eps=)r/   rI   r7   r   rJ   r$   r$   r(   
extra_repry  s   zJetMoeRMSNorm.extra_repr)r   )rV   rW   rX   rF   rT   r   rZ   r$   r$   rK   r(   r   i  s    r   c                       s8   e Zd Zddef fddZe edd Z  Z	S )JetMoeRotaryEmbeddingNrp   c                    s   t    t|dr|jd ur|jd|jd| _nd| _|j| _|j| _|| _	t
| j | _| | j	|\}| _| jd|dd | j| _d S )Nrope_scaling	rope_typetypedefaultinv_freqF)
persistent)rE   rF   hasattrr   getr   Zmax_position_embeddingsZmax_seq_len_cachedZoriginal_max_seq_lenrp   r   Zrope_init_fnattention_scalingZregister_bufferr   Zoriginal_inv_freq)rJ   rp   r0   r   rK   r$   r(   rF     s   
zJetMoeRotaryEmbedding.__init__c           
      C   s   | j d d d d f  |jd dd|j}|d d d d d f  }t|jjtr6|jjdkr6|jjnd}t	j
|dd+ | |  dd}t	j||fdd	}| | j }| | j }	W d    n1 smw   Y  |j|jd
|	j|jd
fS )Nr   r-   r   ZmpscpuF)device_typeenabledr   r+   )ra   )r   r6   r8   r7   r%   r0   r.   r   strr1   Zautocast	transposer2   cosr   sinra   )
rJ   xposition_idsZinv_freq_expandedZposition_ids_expandedr   ZfreqsZembr   r   r$   r$   r(   rT     s   0&zJetMoeRotaryEmbedding.forwardN)
rV   rW   rX   r   rF   r1   Zno_gradr   rT   rZ   r$   r$   rK   r(   r   ~  s
    r   c                 C   sH   | dd| j d d f }| d| j d d df }tj| |fddS )z*Rotates half the hidden dims of the input..Nr-   r   r+   )r7   r1   r2   )r   x1Zx2r$   r$   r(   rotate_half  s   r   c                 C   sD   | |}| |}| | t| |  }|| t||  }||fS )a  Applies Rotary Position Embedding to the query and key tensors.

    Args:
        q (`torch.Tensor`): The query tensor.
        k (`torch.Tensor`): The key tensor.
        cos (`torch.Tensor`): The cosine part of the rotary embedding.
        sin (`torch.Tensor`): The sine part of the rotary embedding.
        position_ids (`torch.Tensor`, *optional*):
            Deprecated and unused.
        unsqueeze_dim (`int`, *optional*, defaults to 1):
            The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
            sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
            that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
            k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
            cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
            the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
    Returns:
        `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
    )r;   r   )qr   r   r   r   Zunsqueeze_dimZq_embedZk_embedr$   r$   r(   apply_rotary_pos_emb  s
   

r   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 )JetMoeAttentionzH
    Multi-headed attention from 'Attention Is All You Need' paper.
    Nrp   	layer_idxc                    s   t    || _|| _d| _|du rtd| jj d |j	| _
|j| _|j|j | _|j| _|j| _|j| _t|| _tjj|j| jd dd| _t|| _dS )z
        Initialize the JetMoeAttention module.

        Args:
            config:
                Configuration object with model hyperparameters.
            layer_idx:
                Index of the layer in the model.
        TNz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.r   Fr\   )rE   rF   rp   r   	is_causalloggerwarning_oncerL   rV   rw   r<   attention_dropoutr   r   kv_projection_sizeZnum_attention_heads	num_headshead_dimr   expertsr1   r   r^   rr   kv_projr   
rotary_embrJ   rp   r   rK   r$   r(   rF     s"   


zJetMoeAttention.__init__Frj   r"   r   past_key_valueoutput_attentions	use_cachecache_positionr#   c                 C   s"  |  \}}	}
| j|\}}}| |jddd\}}|||	| j| jdd}|||	| j	| jdd}|||	| j	| jdd}| 
||\}}t||||\}}|d url|||d}|||| j|\}}|d| jdd}|d| jdd}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| j!}| j"||}|||	d}|sd }||||fS )Nr   r-   r+   r   r   r   r   r   )r,   ra   )ptrainingz `attn_output` should be of size z	, but is )#rd   r   r   r   rz   r|   r   r   r   r   r   r   updater   repeatr<   r1   matmulmathsqrtr7   r   r   r3   r   r%   ra   dropoutr   r   
ValueError
contiguousr9   r   r   )rJ   rj   r"   r   r   r   r   r   r~   q_lenr=   query_statesr   r   
key_statesvalue_statesr   r   cache_kwargsattn_weightscausal_maskattn_outputr$   r$   r(   rT     sB   
 &zJetMoeAttention.forwardr   NNNFFN)rV   rW   rX   r   r   r   rY   rF   r1   Tensor
LongTensorr
   boolr   rT   rZ   r$   r$   rK   r(   r     s4    %	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  eej f f fddZ  ZS )JetMoeSdpaAttentionz
    JetMoe attention module using torch.nn.functional.scaled_dot_product_attention. This module inherits from
    `JetMoeAttention` as the weights of the module stays untouched. The only changes are on the forward pass to adapt to
    SDPA API.
    NFrj   r"   r   r   r   r   r   r#   c              	      s  |rt d t j|||||||dS | \}}	}
| j|\}}}| |jddd\}}|	||	| j
| jdd}|	||	| j| jdd}|	||	| j| jdd}| ||\}}t||||\}}|d ur|||d}|||| j|\}}|d| jdd}|d| jdd}|}|d ur|d d d d d d d |jd f }|jjd	kr|d ur| }| }| }|d u r|	dkrd
nd}tjjj||||| jr| jnd|d}|dd }|||	| j| j}| j ||}|	||	d}|d ||fS )Na  JetMoeModel is using JetMoeSdpaAttention, 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.rj   r"   r   r   r   r   r   r   r-   r+   r   r   r   cudaTF        )Z	attn_maskZ	dropout_pr   )!r   r   rE   rT   rd   r   r   r   rz   r|   r   r   r   r   r   r   r   r   r   r<   r7   r0   r   r   r1   r   r   Zscaled_dot_product_attentionr   r   r9   r   r   )rJ   rj   r"   r   r   r   r   r   r~   r   r=   r   r   r   r   r   r   r   r   r   r   r   rK   r$   r(   rT   /  s^   

&	zJetMoeSdpaAttention.forwardr   )rV   rW   rX   r   r1   r   r   r   r
   r   r   rT   rZ   r$   r$   rK   r(   r   '  s2    
&	r   c                       s   e Zd Z fddZ						ddeej deej deej dee d	ee	 d
ee	 deej de
eejeej f eeejeej eejdf f  f fddZ  ZS )JetMoeFlashAttention2c                    s   t  j|i | t | _d S r   )rE   rF   r   _flash_attn_uses_top_left_mask)rJ   argskwargsrK   r$   r(   rF     s   zJetMoeFlashAttention2.__init__NFrj   r"   r   r   r   r   r   r#   .c              
   C   s  d}|  \}}	}
| j|\}}}| |jddd\}}|||	| j| jdd}|||	| j	| jdd}|||	| j	| jdd}| 
||\}}t||||\}}|durn|||d}|||| j|\}}|d| jdd}|d| jdd}|dd}|dd}|dd}| jr| jnd}|j}|tjkrt rt }nt| jd	r| jj}n| jjj}td
| d ||}||}||}t|||||	|| j| j d|}|!||	| j| j"}| j#||}|||	|
}|sd}||||fS )a  
        Forward pass of the JetMoeAttention module.

        Args:
            hidden_states (Optional[torch.FloatTensor]): Input hidden states.
            attention_mask (Optional[torch.FloatTensor]): Attention mask.
            layer_past (Optional[Tuple[torch.Tensor]]): Past layer state.
            use_cache (Optional[bool]): Whether to use cached states.
            output_attentions (Optional[bool]): Whether to output attention weights.
            cache_position (Optional[torch.LongTensor]): Position of the cache.

        Returns:
            Union[Tuple[torch.Tensor, Tuple[torch.Tensor]], Optional[Tuple[...]]]: Tuple containing outputs.
        Fr   r-   r+   r   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 .)r   Zuse_top_left_maskr   )$rd   r   r   r   rz   r|   r   r   r   r   r   r   r   r   r   r<   r   r   ra   r1   r   Zis_autocast_enabledZget_autocast_gpu_dtyper   rp   r   rI   r   r   r%   r   r   r   r9   r   r   )rJ   rj   r"   r   r   r   r   r   r~   r   rr   r   r   r   r   r   r   r   r   Zdropout_rater   Ztarget_dtyper   r   r$   r$   r(   rT     sf   






	zJetMoeFlashAttention2.forwardr   )rV   rW   rX   rF   r   r1   FloatTensorr   r
   r   r   r   r   rT   rZ   r$   r$   rK   r(   r     s:    	"r   )eagerflash_attention_2sdpac                       s   e Zd Zddedee f fddZ							ddeej deej	 d	ee
ej  d
eej dee dee dee deej	 dee
ej ee
eje
ejdf f  f fddZ  ZS )JetMoeBlockNrp   r   c                    sB   t    t|j| _t|j ||| _t|j| _t	|| _
dS )z
        Initialize the JetMoeBlock module.

        Args:
            config:
                Configuration object with model hyperparameters.
        N)rE   rF   r   rr   input_layernormJETMOE_ATTENTION_CLASSES_attn_implementationself_attentionpost_attention_layernormro   mlpr   rK   r$   r(   rF     s
   
zJetMoeBlock.__init__Frj   r   r   r"   r   output_router_logitsr   r   r#   .c	              	   C   s   | j | |||||||d\}	}
}}||	 }| | |\}}|| }|f}|r/||
f7 }|r6||f7 }|r>|||f7 }|S )Nr   )r   r   r   r   )rJ   rj   r   r   r"   r   r   r   r   r   Zself_attn_weightsZpresent_key_valueZattn_router_logitsZx_mlpZmlp_router_logitsoutputsr$   r$   r(   rT   	  s(   


zJetMoeBlock.forwardr   )NNNFFFN)rV   rW   rX   r   r   rY   rF   r1   r   r   r   r   r   r   rT   rZ   r$   r$   rK   r(   r     s8    	(
r   c                   @   s8   e Zd ZeZdZdZdgZdgZdZ	dZ
dZdd ZdS )	JetMoePreTrainedModelZtransformerFr   past_key_valuesTc                 C   s   t |tjfr!|jjjd| jjd |jdur|jj	  dS dS t |tj
rD|jjjd| jjd |jdurB|jj|j 	  dS dS t |trR|jjd dS t |trd|jjjd| jjd dS t |trq|jj	  dS t |tr~|jj	  dS dS )zInitialize the weights.r   )r5   ZstdNg      ?)r.   r   r^   rI   dataZnormal_rp   Zinitializer_ranger]   Zzero_	Embeddingpadding_idxr   Zfill_rB   r   ro   )rJ   moduler$   r$   r(   _init_weights<  s&   





z#JetMoePreTrainedModel._init_weightsN)rV   rW   rX   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_classr   r$   r$   r$   r(   r   1  s    r   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eeej f  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eejdf dejdejdedef
ddZedejdededejdejdefd d!Z  ZS )$JetMoeModelz
    Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`JetMoeBlock`]

    Args:
        config:
            JetMoeConfig
    rp   c                    s~   t     j| _ j| _t j j| j| _t	 fddt
 jD | _ j| _t j jd| _d| _|   d S )Nc                    s   g | ]}t  |qS r$   )r   )r&   r   rp   r$   r(   r)   b  r*   z(JetMoeModel.__init__.<locals>.<listcomp>)r   F)rE   rF   pad_token_idr   
vocab_sizer   r   rr   embed_tokensZ
ModuleListrN   r@   layersr   r   Zrms_norm_epsnormgradient_checkpointing	post_initry   rK   r   r(   rF   \  s    zJetMoeModel.__init__c                 C      | j S r   r   r   r$   r$   r(   get_input_embeddingsk     z JetMoeModel.get_input_embeddingsc                 C   
   || _ d S r   r  rJ   valuer$   r$   r(   set_input_embeddingso     
z JetMoeModel.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| 
|}d}|rit|tsid}|d u r_t }n
t|}t	d |
d u r|d uru| nd}tj|||jd  |jd}
|d u r|
d}|d ur| jd	kr|r|jd }|d d d
f   |k}|rtd| |||
||}|}|rdnd }|rdnd }|	rdnd }d }| jD ]Q}|r||f7 }| jr| jr| j|j||||||	|dd	}n|||||||	|d}|d }|r||rdnd }|r||d f7 }|	r%||d |d
 f7 }q| |}|r3||f7 }|r8|nd }|rA| }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`.FTzWe detected that you are passing `past_key_values` as a tuple of tuples. This is deprecated and will be removed in v4.47. Please convert your cache or use an appropriate `Cache` class (https://huggingface.co/docs/transformers/kv_cache#legacy-cache-format)r   r   r0   r   r-   zYou are attempting to perform batched generation with padding_side='right' this may lead to unexpected behaviour for Flash Attention version of JetMoe. Make sure to  call `tokenizer.padding_side  = 'left'` before tokenizing the input. r$   )Zuse_reentrant)r"   r   r   r   r   r   r   r   )last_hidden_stater   rj   
attentionsr   )rp   r   r  r   r   r   r   r   r   r   r   r.   r
   r   Zfrom_legacy_cacheget_seq_lengthr1   aranger7   r0   r;   r   r:   item_update_causal_maskr   Z_gradient_checkpointing_func__call__r   Zto_legacy_cacher   )rJ   r	  r"   r   r   r
  r   r   r  r   r   Zreturn_legacy_cachepast_seen_tokensr>   Zis_padding_rightr   rj   Zall_hidden_statesZall_self_attnsZall_router_logitsZnext_decoder_cacheZdecoder_layerZlayer_outputsZ
next_cacher$   r$   r(   rT   r  s   









zJetMoeModel.forwardFr   input_tensorc                 C   s:  | j jdkr|d ur|dk r|S d S | j jdkr&t|tjr$t|}|S |d ur.| nd}|d ur7|jnd}| j jdkrO|sO|sOt	j
|||| jdrOd S |j}|jd }	|r^| }
nt|tjri|jd	 n||	 d }
| j||	|
|||jd d
}| j jdkr|d ur|jjdv r|st|j}t	||}|S )Nr   r   Zflex_attentionr   Fr   )r
  Zpast_key_values_lengthZis_trainingr   r-   )r?   target_lengthra   r   r>   )r   ZxpuZnpu)rp   r   anyr.   r1   r   r   r  Zis_compileabler   Z_ignore_causal_mask_sdpar   ra   r7   Zget_max_cache_shape5_prepare_4d_causal_attention_mask_with_cache_positionr0   r   finfominZ_unmask_unattended)rJ   r"   r  r   r   r   r  Zusing_compilable_cachera   r?   r  r   	min_dtyper$   r$   r(   r    sT   




zJetMoeModel._update_causal_maskr?   r  ra   r>   c                 K   sD  | dur|   dkr| }|S t|j}tj||f|||jd}|dkr+tj|dd}|tj||jd|ddk9 }|ddddddf 	|ddd}| dur|
 }| jd }	|ddddddd|	f | ddddddf |j }
|
dk}
|ddddddd|	f |
||ddddddd|	f< |S )	aM  
        Creates a causal 4D mask of shape `(batch_size, 1, query_length, key_value_length)` from a 2D mask of shape
        `(batch_size, key_value_length)`, or if the input `attention_mask` is already 4D, do nothing.

        Args:
            attention_mask (`torch.Tensor`):
                A 2D attention mask of shape `(batch_size, key_value_length)` or a 4D attention mask of shape
                `(batch_size, 1, query_length, key_value_length)`.
            sequence_length (`int`):
                The sequence length being processed.
            target_length (`int`):
                The target length: when generating with static cache, the mask should be as long as the static cache,
                to account for the 0 padding, the part of the cache that is not filled yet.
            dtype (`torch.dtype`):
                The dtype to use for the 4D attention mask.
            cache_position (`torch.Tensor`):
                Indices depicting the position of the input sequence tokens in the sequence.
            batch_size (`torch.Tensor`):
                Batch size.
        N   )Z
fill_valuera   r0   r   )Zdiagonalr  r-   r   )r,   r1   r  r  fullr0   Ztriur  r9   r8   cloner7   r%   Zmasked_fill)r"   r?   r  ra   r   r>   r   r   r  Zmask_lengthZpadding_maskr$   r$   r(   r  >  s,    $
6  zAJetMoeModel._prepare_4d_causal_attention_mask_with_cache_position)
NNNNNNNNNN)F)rV   rW   rX   r   r   rF   r  r  r   r   r   r1   r   r   r   r
   r   r   r   r   rT   r  staticmethodrY   ra   r  rZ   r$   r$   rK   r(   r   R  s    	
 
Dr   c                       s   e Zd ZdgZ 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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ejf defdd Z  ZS )"JetMoeForCausalLMzlm_head.weightc                    sP   t  | t|| _|j| _|j| _tj|j|jdd| _	|j
| _
|   d S NFr\   )rE   rF   r   modelr   aux_loss_coefr   r^   rr   lm_headZtie_word_embeddingsr   ry   rK   r$   r(   rF   z  s   
zJetMoeForCausalLM.__init__c                 C      | j jS r   r"  r   r   r$   r$   r(   r    r   z&JetMoeForCausalLM.get_input_embeddingsc                 C      || j _d S r   r&  r  r$   r$   r(   r       z&JetMoeForCausalLM.set_input_embeddingsc                 C   r   r   r$  r   r$   r$   r(   get_output_embeddings  r  z'JetMoeForCausalLM.get_output_embeddingsc                 C   r  r   r)  )rJ   Znew_embeddingsr$   r$   r(   set_output_embeddings  r  z'JetMoeForCausalLM.set_output_embeddingsc                 C   r  r   r"  )rJ   decoderr$   r$   r(   set_decoder  r  zJetMoeForCausalLM.set_decoderc                 C   r   r   r,  r   r$   r$   r(   get_decoder  r  zJetMoeForCausalLM.get_decoderNr   r	  r"   r   r   r
  labelsr   r   r  r   r   logits_to_keepr#   c                 K   s\  |dur|n| j j}|	dur|	n| j j}	| j||||||||	|d	}|j}t|tr0t| dn|}| |dd|ddf }d}|dur|	 }|dddddf 
 }|dddf 
 }|d| j j}|d}||j}| j||fd| j ji|}d}|
rt|j| j| j|}|dur|| j||j 7 }t||||j|j|j|jdS )a  
        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]`.
        N)	r	  r"   r   r   r
  r   r   r  r   .r-   r   r   )lossaux_lossrk   r   rj   r  r   )rp   r   r  r"  r  r.   rY   slicer$  r6   r   r|   r   r%   r0   loss_functionrA   r   r!   rw   r#  r   r   rj   r  )rJ   r	  r"   r   r   r
  r0  r   r   r  r   r   r1  r   r   rj   Zslice_indicesrk   r2  Zshift_logitsZshift_labelsr3  r$   r$   r(   rT     sh   
zJetMoeForCausalLM.forward)NNNNNNNNNNNr   )rV   rW   rX   Z_tied_weights_keysrF   r  r  r*  r+  r.  r/  r   r   r   r1   r   r   r   r   r   r   rY   r   rT   rZ   r$   r$   rK   r(   r   w  sd    	
r   a  
    The JetMoe Model transformer with a sequence classification head on top (linear layer).

    [`JetMoeForSequenceClassification`] 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 )JetMoeForSequenceClassificationc                    s@   t  | |j| _t|| _tj|j| jdd| _| 	  d S r!  )
rE   rF   Z
num_labelsr   r"  r   r^   rr   scorer   ry   rK   r$   r(   rF     s
   
z(JetMoeForSequenceClassification.__init__c                 C   r%  r   r&  r   r$   r$   r(   r    r   z4JetMoeForSequenceClassification.get_input_embeddingsc                 C   r'  r   r&  r  r$   r$   r(   r    r(  z4JetMoeForSequenceClassification.set_input_embeddingsNr	  r"   r   r   r
  r0  r   r   r  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   r
  r   r   r  Nr   r   z=Cannot handle batch sizes > 1 if no padding token is defined.r-   )r0   ra   z will not detect padding tokens in `inputs_embeds`. Results may be unexpected if using padding tokens in conjunction with `inputs_embeds.`r  )rk   r0  pooled_logitsrp   )r2  rk   r   rj   r  )r"  r  r7  r7   rp   r   r   r%   r0   r1   Zint32r  Zargmaxr   r   rL   rV   r5  r   r   rj   r  )rJ   r	  r"   r   r   r
  r0  r   r   r  Ztransformer_outputsrj   rk   r>   Zlast_non_pad_tokenZnon_pad_maskZtoken_indicesr8  r2  r$   r$   r(   rT     sL   


z'JetMoeForSequenceClassification.forward)	NNNNNNNNN)rV   rW   rX   rF   r  r  r   r   r   r1   r   r   r
   r   r   r   rT   rZ   r$   r$   rK   r(   r6    sH    		
r6  )r   r   r   r6  )Nr   N)Nr   )Gr   r   typingr   r   r   r   r1   Ztorch.utils.checkpointr   Ztorch.nnr   rP   Z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_rope_utilsr   r   Zmodeling_utilsr   utilsr   r   r   r   Zconfiguration_jetmoer   Z!torch.nn.attention.flex_attentionr   Zintegrations.flex_attentionr   r   Z
get_loggerrV   r   r   rY   rA   ModulerB   r[   ro   r   r   r   r   r   r   r   r   r   r   r   r   r   r6  __all__r$   r$   r$   r(   <module>   s~   

R-1:M#
cXt8   &V