
    g                        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 dd	lmZmZmZ dd
lmZ ddlmZ ddlmZmZmZ ddlmZ ddlmZm Z m!Z!m"Z"m#Z#m$Z$ ddl%m&Z&  e!            rddl'm(Z(  e#j)        e*          Z+dZ,dZ-	 	 	 d=deej.        eej.                 df         dee/         deej.                 deej.        e/f         fdZ0 G d de	j1                  Z2 G d de	j1                  Z3 G d de	j1                  Z4 G d  d!e	j1                  Z5 G d" d#e	j1                  Z6 G d$ d%e	j1                  Z7d& Z8d>d'Z9 G d( d)e	j1                  Z: G d* d+e:          Z; G d, d-e:          Z<e:e<e;d.Z= G d/ d0e	j1                  Z> G d1 d2e          Z?d3Z@d4ZA ed5e@           G d6 d7e?                      ZB G d8 d9e?e          ZC ed:e@           G d; d<e?                      ZDdS )?zPyTorch JetMoe model.    N)ListOptionalTupleUnion)nn)CrossEntropyLoss)
functional   )ACT2FN)CacheDynamicCacheStaticCache)GenerationMixin)AttentionMaskConverter)MoeCausalLMOutputWithPastMoeModelOutputWithPast SequenceClassifierOutputWithPast)PreTrainedModel)add_start_docstrings%add_start_docstrings_to_model_forwardis_flash_attn_2_available#is_flash_attn_greater_or_equal_2_10loggingreplace_return_docstrings   )JetMoeConfig)_flash_attention_forwardjetmoer      gate_logitsnum_expertsattention_maskreturnc                    | t          | t                    sdS t          | t                    r/| d         j        t          j        fd| D             d          }t          j        j                            |d          }t          j        ||d          \  }}t          j        j        	                    ||          }|@t          j
        |                                d          }	t          j
        |d          }
n.|j        \  }}|j        d         ||z  z  }|dddddddf                             |||||f                              d||                                        }t          j        |                                |z  d          t          j        |d          z  }	|ddddddf                             ||||f                              d|                                        }t          j        ||z  d          t          j        |d          z  }
t          j        |	|
                    d          z            }||z  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                 :    g | ]}|                               S  )to).0
layer_gatecompute_devices     f/var/www/html/ai-engine/env/lib/python3.11/site-packages/transformers/models/jetmoe/modeling_jetmoe.py
<listcomp>z,load_balancing_loss_func.<locals>.<listcomp>[   s&    -j-j-jPZjmmN.K.K-j-j-j    dim)
isinstancetupledevicetorchcatr   r	   softmaxtopkone_hotmeanfloatshapeexpandreshaper'   sum	unsqueeze)r    r!   top_kr"   concatenated_gate_logitsrouting_weights_selected_expertsexpert_masktokens_per_expertrouter_prob_per_expert
batch_sizesequence_lengthnum_hidden_layersexpert_attention_mask router_per_expert_attention_maskoverall_lossr*   s                    @r+   load_balancing_loss_funcrN   9   s   : *[%"@"@q+u%% s$Q.#(9-j-j-j-j^i-j-j-jpq#r#r#r h)112JPR1SSO*_eDDDA(%--.>LLK!J{'8'8':':BBB "'O!C!C!C&4&:#
O4:1=*B^_ 4AAAtT12V&
OUKXYYWR,,R	 	 "Ik&7&7&9&9<Q&QWXYYY\a\e!q]
 ]
 ]
 
 4AAAt+,V&
O[QRRWR%%R	 	) "'?=]+]cd!e!e!ehmhq,!i
 i
 i
 "
 9.1G1Q1QRS1T1TTUUL+%%r-   c                   6     e Zd Zdedededdf fdZd Z xZS )JetMoeParallelExpertsr!   
input_sizeoutput_sizer#   Nc                     t                                                       t          j        t	          j        |||                    | _        || _        || _        || _	        dS )a  
        Initialize the JetMoeParallelExperts module.
        The experts weights are stored in [num_experts, output_size, input_size] format. Such that it's comptible 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   	Parameterr4   emptyweightr!   rQ   rR   )selfr!   rQ   rR   	__class__s       r+   rU   zJetMoeParallelExperts.__init__   sW    " 	l5;{K#T#TUU&$&r-   c                    |                     |d          }g }t          | j                  D ];}|                    t	          j        ||         | j        |                              <t          j        |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FlinearrX   r4   r5   )rY   inputsexpert_size
input_listoutput_listiresultss          r+   forwardzJetMoeParallelExperts.forward   s     \\+1\55
t'(( 	H 	HAqx
1t{1~FFGGGG)KQ///r-   __name__
__module____qualname__intrU   rg   __classcell__rZ   s   @r+   rP   rP      sh        'C 'S 's 't ' ' ' ' ' '.      r-   rP   c                   2     e Zd Zdededef fdZd Z xZS )JetMoeTopKGatingrQ   r!   r@   c                     t                                                       || _        || _        || _        t          j        ||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)rT   rU   r!   rQ   r@   r   Linearlayer)rY   rQ   r!   r@   rZ   s       r+   rU   zJetMoeTopKGating.__init__   sM     	&$
Yz;UCCC


r-   c                    |                      |                                          }|                    | j        d          \  }}t	          j        |d                              |          }t	          j        |                    d          | j	        g|j
        |j                  }|                    d|d          }|                                                    d          }|                                }|                                }	|	                    d          \  }
}|                    | j        d          }|                                }||         }|||||fS )Nr   r.   r   dtyper3   trunc)rounding_mode)ru   r:   r7   r@   r4   r6   type_aszerossizer!   rx   r3   scatterlongr>   tolistflattensortdiv)rY   hidden_stateslogitstop_k_logitstop_k_indicestop_k_gatesr|   gatesrb   top_k_expertsrC   index_sorted_expertsbatch_indexbatch_gatess                 r+   rg   zJetMoeTopKGating.forward   sQ   M**0022&,kk$*!k&D&D#mmLa888@@OO a  $"23;;LU`Ug
 
 
 a22jjll&&q))!((** &--//"/"4"4Q"7"7*..tz.QQ "))++!"67#[+{FRRr-   rh   rn   s   @r+   rp   rp      sq        D3 DS D D D D D D D(S S S S S S Sr-   rp   c                   .     e Zd ZdZdef fdZd Z x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                    t          t          |                                            |j        | _        |j        | _        t          |j                 | _        t          j
                            t          j        | j                            | _        t          |j        | j        | j        dz            | _        t          |j        | j        | j                  | _        t%          | j        |j        |j                  | _        d S )Nr   rQ   r!   r@   )rT   r   rU   hidden_sizerQ   intermediate_sizer   activation_function
activationr4   r   rV   rW   rs   rP   num_local_expertsinput_linearoutput_linearrp   num_experts_per_tokrouterrY   r   rZ   s     r+   rU   zJetMoeMoE.__init__   s    i''))) ,!3 !;<H&&u{4?'C'CDD	1&2JDO]a]mpq]qrr263KTM]_c_noo&0,
 
 
r-   c                 h   |                                 \  }}}|                    d|          }|                     |          \  }}}}}	||         }
|                     |
|          }|                    dd          }|                     |d                   |d         z  }|                     ||          }||dddf         z  }t          j        ||z  | j	        f|j
        |j                  }|                    d||          }|                    ||| j	                  }|| j        z   }||	fS )a  
        Forward pass of the mixture of experts layer.

        Args:
            layer_input (Tensor):
                Input tensor.

        Returns:
            Tensor:
                Output tensor.
            Tensor:
                Router logits.
        r0   r   r.   r   r   Nrw   )r}   r=   r   r   chunkr   r   r4   r|   rQ   rx   r3   	index_addviewrs   )rY   layer_inputbszlengthemb_sizerC   r   r   rb   router_logitsexpert_inputsr   chunked_hidden_statesexpert_outputsr|   layer_outputs                   r+   rg   zJetMoeMoE.forward   sA    !, 0 0 2 2VX!))"h77BF++kBZBZ?;[-#K0))-EE - 3 3A2 3 > >(=a(@AADYZ[D\\++M;GG'+aaag*>>S6\4?;>CW`n`uvvvq+~FF#((fdoFF#di/]**r-   )ri   rj   rk   __doc__r   rU   rg   rm   rn   s   @r+   r   r      s]         
| 
 
 
 
 
 
 + + + + + + +r-   r   c                   :     e Zd ZdZdef fdZd Zd Zd Z x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.
    r   c                    t          t          |                                            |j        | _        |j        | _        |j        |j        z  | _        |j	        | _
        t          j                            t          j        | j                            | _        t!          | j        | j        | j                  | _        t!          | j        | j        | j                  | _        t'          | j        | j        | j
                  | _        d S )Nr   )rT   r   rU   r   r!   r   rQ   kv_channelsnum_key_value_headsr   r@   r4   r   rV   rW   rs   rP   r   r   rp   r   r   s     r+   rU   zJetMoeMoA.__init__*  s    i'')))!3 ,!-0JJ/
H&&u{4?'C'CDD	1$2BDOUYUeff243CTEUW[Wfgg&(*
 
 
r-   c                    |                                 \  }}}|                    d|          }|                     |          \  }}}}}	||||f}
||         }|                     ||          }t	          j        ||z  | j        z  | j        f|j        |j	                  }|
                    d||          }|                    ||| j        d          }||	|
fS )z
        Map inputs to attention experts according to routing decision and compute query projection inside each experts.
        r0   rw   r   )r}   r=   r   r   r4   r|   r@   r   rx   r3   r   r   )rY   r   r   r   r   r   r   r   rb   r   	topo_infor   r   r|   r   s                  r+   mapzJetMoeMoA.map<  s     !, 0 0 2 2VX!))"h77UYU`U`alUmUmRk;]);[Q	 $K0**=+FF 6\DJ&(89AU^l^s
 
 
 q*>OO#((fdj"EE]I55r-   c                    |                                 \  }}}}|                    d|          }|\  }}}	}
||         }|                     ||
          }||	dddf         z  }t          j        ||z  | j        f|j        |j                  }|                    d||          }|	                    ||| j                  }|| j
        z   }|S )zu
        Compute output projection inside each attention experts and merge the outputs of different experts.
        r0   Nrw   r   )r}   r=   r   r4   r|   rQ   rx   r3   r   r   rs   )rY   r   r   r   r   kr   r   r   r   rb   r   r   r|   r   s                  r+   reducezJetMoeMoA.reduceS  s     '2&6&6&8&8#VQ!))"k::FOCk; $$89++M;GG (+aaag*>> S6\4?;>CW`n`uvvvq+~FF#((fdoFF#di/r-   c                      t          d          )Nz-This module doesn't support call and forward.)NotImplementedError)rY   r   s     r+   rg   zJetMoeMoA.forwardi  s    !"QRRRr-   )
ri   rj   rk   r   r   rU   r   r   rg   rm   rn   s   @r+   r   r   !  s         
| 
 
 
 
 
 
$6 6 6.  ,S S S S S S Sr-   r   c                   ,     e Zd Zd fd	Zd Zd Z xZS )JetMoeRMSNormư>c                     t                                                       t          j        t	          j        |                    | _        || _        dS )z<
        JetMoeRMSNorm is equivalent to T5LayerNorm
        N)rT   rU   r   rV   r4   onesrX   variance_epsilon)rY   r   epsrZ   s      r+   rU   zJetMoeRMSNorm.__init__o  sD     	l5:k#:#:;; #r-   c                    |j         }|                    t          j                  }|                    d                              dd          }|t          j        || j        z             z  }| j        |                    |          z  S )Nr   r0   T)keepdim)	rx   r'   r4   float32powr9   rsqrtr   rX   )rY   r   input_dtypevariances       r+   rg   zJetMoeRMSNorm.forwardw  s|    #)%((77 $$Q'',,R,>>%Ht?T4T(U(UU{]--k::::r-   c                 H    t          | j        j                   d| j         S )Nz, eps=)r2   rX   r;   r   rY   s    r+   
extra_reprzJetMoeRMSNorm.extra_repr~  s&    )**II$2GIIIr-   )r   )ri   rj   rk   rU   rg   r   rm   rn   s   @r+   r   r   n  sb        $ $ $ $ $ $; ; ;J J J J J J Jr-   r   c                   R     e Zd Zd fd	Z ej                    dd            Z xZS )JetMoeRotaryEmbedding   '  Nc                 :   t                                                       || _        || _        || _        d| j        t          j        d| j        dt
          j                                                  | j        z  z  z  }| 	                    d|d           d S )N      ?r   r   rx   inv_freqF)tensor
persistent)
rT   rU   r/   max_position_embeddingsbaser4   arangeint64r:   register_buffer)rY   r/   r   r   r3   r   rZ   s         r+   rU   zJetMoeRotaryEmbedding.__init__  s    '>$	$)Q!5;(W(W(W(](](_(_bfbj(jklZUKKKKKr-   c                 "   | j                             |j                   | j         d d d d f                                                             |j        d         dd          }|d d d d d f                                         }|j        j        }t          |t                    r|dk    r|nd}t          j
        |d          5  |                                |                                z                      dd          }t          j        ||fd	          }|                                }	|                                }
d d d            n# 1 swxY w Y   |	                    |j        
          |
                    |j        
          fS )Nr   r0   r   mpscpuF)device_typeenabledr   r.   r   )r   r'   r3   r:   r<   r;   typer1   strr4   autocast	transposer5   cossinrx   )rY   xposition_idsseq_leninv_freq_expandedposition_ids_expandedr   freqsembr   r   s              r+   rg   zJetMoeRotaryEmbedding.forward  s    	""" M$4-8>>@@GGHZ[\H]_acdee ,QQQaaaZ 8 > > @ @ hm%/S%A%AekUZFZFZkk`e^UCCC 	 	&,,..1F1L1L1N1NNYYZ[]^__E)UEN333C''))C''))C		 	 	 	 	 	 	 	 	 	 	 	 	 	 	
 vvAGv$$cff17f&;&;;;s   A>EEE)r   r   NN)ri   rj   rk   rU   r4   no_gradrg   rm   rn   s   @r+   r   r     sk        L L L L L L U]__< < < _< < < < <r-   r   c                     | dd| j         d         dz  f         }| d| j         d         dz  df         }t          j        | |fd          S )z*Rotates half the hidden dims of the input..Nr0   r   r.   )r;   r4   r5   )r   x1x2s      r+   rotate_halfr     s]    	
3"!'"+"""	#B	
3q """	#B9rc2YB''''r-   c                     |                     |          }|                     |          }| |z  t          |           |z  z   }||z  t          |          |z  z   }||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   unsqueeze_dimq_embedk_embeds           r+   apply_rotary_pos_embr     sc    ( --
&
&C
--
&
&C3w;q>>C/0G3w;q>>C/0GGr-   c                       e Zd ZdZddedee         f f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Z xZS )JetMoeAttentionzH
    Multi-headed attention from 'Attention Is All You Need' paper.
    Nr   	layer_idxc                 B   t                                                       || _        || _        d| _        |(t
                              d| j        j         d           |j	        | _
        |j        | _        |j        |j        z  | _        |j        | _        |j        | _        |j        | _        t%          |          | _        t(          j                            |j        | j        dz  d          | _        t3          |j        |j        |j                  | _        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   Frr   )r   r   )rT   rU   r   r   	is_causalloggerwarning_oncerZ   ri   r   r@   attention_dropoutr   r   kv_projection_sizenum_attention_heads	num_headshead_dimr   expertsr4   r   rt   r   kv_projr   r   
rope_theta
rotary_embrY   r   r   rZ   s      r+   rU   zJetMoeAttention.__init__  s    	",!8 , , ,   /
!'!9"("4v7Q"Q#)#= 3* ((xv'94;RUV;V]bcc/$*$B"
 
 
r-   Fr   r"   r   past_key_valueoutput_attentions	use_cachecache_positionr#   c                    |                                 \  }}	}
| j                            |          \  }}}|                     |                              dd          \  }}|                    ||	| j        | j                                      dd          }|                    ||	| j	        | j                                      dd          }|                    ||	| j	        | j                                      dd          }| 
                    ||          \  }}t          ||||          \  }}|&|||d}|                    ||| j        |          \  }}|                    d| j        dd          }|                    d| j        dd          }t!          j        ||                    dd                    t%          j        | j                  z  }|$|d d d d d d d |j        d         f         }||z   }t*          j                            |dt           j                                      |j                  }t*          j                            || j        | j        	          }t!          j        ||          }|                                 || j        |	| j        fk    r5t=          d
|| j        |	| j        f d|                                            |                    dd                                          }|                     ||	| j        | j!                  }| j        "                    ||          }|                    ||	d          }|sd }||||fS )Nr   r0   r.   r   r   r   r
  r
   )r/   rx   )ptrainingz `attn_output` should be of size z	, but is )#r}   r  r   r  r   r   r   r  r   r   r  r   updater   repeatr@   r4   matmulmathsqrtr;   r   r	   r6   r   r'   rx   dropoutr   r  
ValueError
contiguousr=   r   r   )rY   r   r"   r   r  r  r	  r
  r   q_lenrC   query_statesr   r   
key_statesvalue_statesr   r   cache_kwargsattn_weightscausal_maskattn_outputs                         r+   rg   zJetMoeAttention.forward  sa    &**,,UA151A1A-1P1P.mY#'<<#>#>#D#DQB#D#O#O 
L#((eT^T]SS]]^_abcc__S%1I4=YYccdeghii
#((eT5Mt}]]gghiklmm??<>>S#7jRUWZ#[#[ j%#&snUUL'5'<'<ZW[Wegs't't$J  &&q$*a;;
#**1dj!Q??|L*2F2Fq!2L2LMMPTPYZ^ZgPhPhh%(AAAqqq2HJ4DR4H2H)HIK'+5L },,\r,WWZZ[g[mnn},,\T=S^b^k,lll<>>#t~udm!LLL)CPTP]3^ ) )$$&&) )  
 "++Aq11<<>>!))#udj$BYZZl))+yAA!&&sE266  	 LL.-GGr-   r   NNNFFN)ri   rj   rk   r   r   r   rl   rU   r4   Tensor
LongTensorr   boolr   rg   rm   rn   s   @r+   r   r     s)        $
 $
| $
 $
 $
 $
 $
 $
 $
R 2637*."'599H 9H|9H !.9H u/0	9H
 !9H  9H 9H !!129H 
u|Xel3XeEL>Q5RR	S9H 9H 9H 9H 9H 9H 9H 9Hr-   r   c                       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Z x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.
    NFr   r"   r   r  r  r	  r
  r#   c           	      $   |rBt                               d           t                                          |||||||          S |                                \  }}	}
| j                            |          \  }}}|                     |                              dd          \  }}|	                    ||	| j
        | j                                      dd          }|	                    ||	| j        | j                                      dd          }|	                    ||	| j        | j                                      dd          }|                     ||          \  }}t          ||||          \  }}|&|||d}|                    ||| j        |          \  }}|                    d| j        dd          }|                    d| j        dd          }|}||d d d d d d d |j        d         f         }|j        j        d	k    r>|<|                                }|                                }|                                }||	dk    rd
nd}t0          j        j                            ||||| j        r| j        n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.r   r"   r   r  r  r	  r
  r   r0   r.   r   r  r  cudaTF        )	attn_mask	dropout_pr   )!r   r   rT   rg   r}   r  r   r  r   r   r   r  r   r   r  r   r  r   r  r@   r;   r3   r   r  r4   r   r	   scaled_dot_product_attentionr  r   r=   r   r   )rY   r   r"   r   r  r  r	  r
  r   r  rC   r  r   r   r  r  r   r   r  r  r   r  rZ   s                         r+   rg   zJetMoeSdpaAttention.forward3  sG     	[   77??+-)-"3#- #    &**,,UA151A1A-1P1P.mY#'<<#>#>#D#DQB#D#O#O 
L#((eT^T]SS]]^_abcc__S%1I4=YYccdeghii
#((eT5Mt}]]gghiklmm??<>>S#7jRUWZ#[#[ j%#&snUUL'5'<'<ZW[Wegs't't$J  &&q$*a;;
#**1dj!Q??$%%aaaAAA/E1A"1E/E&EFK #v--+2I'2244L#..00J'2244L (/EAIIDD5	h)FF!04Fd,,3 G 
 
 "++Aq11<<>>!))#udj$BYZZl))+yAA!&&sE266D.-??r-   r   )ri   rj   rk   r   r4   r!  r   r"  r   r#  r   rg   rm   rn   s   @r+   r%  r%  +  s         2637*."'59M@ M@|M@ !.M@ u/0	M@
 !M@  M@ M@ !!12M@ 
u|Xel3XeEL>Q5RT\]b]iTjj	kM@ M@ M@ M@ M@ M@ M@ M@ M@ M@r-   r%  c                   h    e Zd Z f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Z xZS )JetMoeFlashAttention2c                 b     t                      j        |i | t                       | _        d S r   )rT   rU   r   _flash_attn_uses_top_left_mask)rY   argskwargsrZ   s      r+   rU   zJetMoeFlashAttention2.__init__  s9    $)&)))
 3V2W2W.W+++r-   NFr   r"   r   r  r	  r  r
  r#   .c           
         d}|                                 \  }}	}
| j                            |          \  }}}|                     |                              dd          \  }}|                    ||	| j        | j                                      dd          }|                    ||	| j	        | j                                      dd          }|                    ||	| j	        | j                                      dd          }| 
                    ||          \  }}t          ||||          \  }}|&|||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'          j                    rt'          j                    }n3t/          | j        d	          r| j        j        }n| j        j        j        }t6                              d
| d           |                    |          }|                    |          }|                    |          }t=          |||||	|| j        | j                                       |          }|!                    ||	| 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   r0   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  use_top_left_maskr   )$r}   r  r   r  r   r   r   r  r   r   r  r   r  r   r  r@   r  r   rx   r4   r   is_autocast_enabledget_autocast_gpu_dtypehasattrr   r4  rX   r   r   r'   r   r0  r   r=   r   r   )rY   r   r"   r   r  r	  r  r
  r   r  r   r  r   r   r  r  r   r   r  dropout_rater   target_dtyper  r  s                           r+   rg   zJetMoeFlashAttention2.forward  sa   6 ""/"4"4"6"6UK 261A1A-1P1P.mY#'<<#>#>#D#DQB#D#O#O 
L#((eT^T]SS]]^_abcc__S%1I4=YYccdeghii
#((eT5Mt}]]gghiklmm??<>>S#7jRUWZ#[#[ j%#&snUUL'5'<'<ZW[Wegs't't$J  &&q$*a;;
#**1dj!Q?? $--a33))!Q//
#--a3315Gt--C #(%-''(** 9$;==&?@@ 9#{B#|28$ $ $ $   (??<88L#|44J'??<88L. "An	
 	
 	
 "[// 	 "))#udj$BYZZl))+yAA!&&sE;??  	 LL.-GGr-   r   )ri   rj   rk   rU   r   r4   FloatTensorr"  r   r#  r   r   r!  rg   rm   rn   s   @r+   r.  r.    sP       X X X X X 7;37*.$),159gH gH 12gH !!23gH u/0	gH
 !gH D>gH $D>gH !!12gH 
elE%,//0u|U5<%8%c@Q:RRST	V
gH gH gH gH gH gH gH gHr-   r.  )eagerflash_attention_2sdpac                   v    e Zd Zddedee         f f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Z xZS )JetMoeBlockNr   r   c                    t                                                       t          |j                  | _        t          |j                 ||          | _        t          |j                  | _        t          |          | _
        dS )z
        Initialize the JetMoeBlock module.

        Args:
            config:
                Configuration object with model hyperparameters.
        N)rT   rU   r   r   input_layernormJETMOE_ATTENTION_CLASSES_attn_implementationself_attentionpost_attention_layernormr   mlpr  s      r+   rU   zJetMoeBlock.__init__  sp     	,V-?@@6v7RSTZ\eff(5f6H(I(I%V$$r-   Fr   r   r  r"   r  output_router_logitsr	  r
  r#   .c	           	         |                      |                     |          ||||||          \  }	}
}}||	z   }|                     |                     |                    \  }}||z   }|f}|r||
fz  }|r||fz  }|r|||fz  }|S )Nr'  )rF  rC  rH  rG  )rY   r   r   r  r"   r  rI  r	  r
  r  self_attn_weightspresent_key_valueattn_router_logitsx_mlpmlp_router_logitsoutputss                   r+   rg   zJetMoeBlock.forward  s     QUPcPc..}==)%)/) Qd Q
 Q
M&(9;M &3#'88D,I,I-,X,X#Y#Y  %- " 	,)++G 	,)++G 	=)+<<<Gr-   r   )NNNFFFN)ri   rj   rk   r   r   rl   rU   r4   r<  r"  r   r!  r#  r   rg   rm   rn   s   @r+   rA  rA    sD       % %| % % % % % % %$ 488<6:,1/4$)59% % 12% u/0% !u|!45	%
 !!23% $D>% 'tn% D>% !!12% 
uU\"HU5<uGXZ]G]A^3^-_$``	a% % % % % % % %r-   rA  c                   <    e Zd ZdZeZdZdZdgZdgZ	dZ
dZdZd ZdS )	JetMoePreTrainedModelz
    An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
    models.
    transformerFrA  past_key_valuesTc                    t          |t          j        f          rT|j        j                            d| j        j                   |j         |j        j        	                                 dS dS t          |t          j
                  r_|j        j                            d| j        j                   |j        +|j        j        |j                 	                                 dS dS t          |t          j                  r?|j        j        	                                 |j        j                            d           dS t          |t                    r-|j        j                            d| j        j                   dS t          |t                    r |j        j        	                                 dS t          |t                     r |j        j        	                                 dS dS )zInitialize the weights.r)  )r9   stdNr   )r1   r   rt   rX   datanormal_r   initializer_rangers   zero_	Embeddingpadding_idx	LayerNormfill_rP   r   r   )rY   modules     r+   _init_weightsz#JetMoePreTrainedModel._init_weightsE  s   fryl++ 	% M&&CT[5R&SSS{& &&((((( '&-- 	%M&&CT[5R&SSS!-"6#56<<>>>>> .--- 	%K""$$$M$$S))))) 566 	%M&&CT[5R&SSSSS	** 	%K""$$$$$	** 	%K""$$$$$	% 	%r-   N)ri   rj   rk   r   r   config_classbase_model_prefixsupports_gradient_checkpointing_no_split_modules_skip_keys_device_placement_supports_flash_attn_2_supports_sdpa_supports_cache_classr`  r&   r-   r+   rR  rR  6  sb         
  L%&+#&#4"5!N % % % % %r-   rR  aI  
    This model is a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) sub-class. Use
    it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and
    behavior.

    Parameters:
        config ([`JetMoeConfig`]): Model configuration class with all the parameters of the model.
            Initializing with a config file does not load the weights associated with the model, only the
            configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.
a	  
    Args:
        input_ids (`torch.LongTensor` of shape `({0})`):
            Indices of input sequence tokens in the vocabulary.

            Indices can be obtained using [`AutoProcenizer`]. See [`PreTrainedTokenizer.encode`] and
            [`PreTrainedTokenizer.__call__`] for details.

            [What are input IDs?](../glossary#input-ids)
        attention_mask (`torch.FloatTensor` of shape `({0})`, *optional*):
            Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:

            - 1 for tokens that are **not masked**,
            - 0 for tokens that are **masked**.

            [What are attention masks?](../glossary#attention-mask)
        position_ids (`torch.LongTensor` of shape `({0})`, *optional*):
            Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
            config.n_positions - 1]`.

            [What are position IDs?](../glossary#position-ids)
        inputs_embeds (`torch.FloatTensor` of shape `({0}, hidden_dim)`, *optional*):
            Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
            is useful if you want more control over how to convert *input_ids* indices into associated vectors than the
            model's internal embedding lookup matrix.
        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_hidden_states (`bool`, *optional*):
            Whether or not to return the hidden states of all layers. See `hidden_states` 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.
        return_dict (`bool`, *optional*):
            Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
        cache_position (`torch.LongTensor` of shape `(sequence_length)`, *optional*):
            Indices depicting the position of the input sequence tokens in the sequence. Contrarily to `position_ids`,
            this tensor is not affected by padding. It is used to update the cache in the correct position and to infer
            the complete sequence length.
zTThe bare JetMoe Model outputting raw hidden-states without any specific head on top.c                       e Zd ZdZdef fdZd Zd Z ee	          	 	 	 	 	 	 	 	 	 	 	 dd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         dee
j                 deeef         fd            Zde
j        de
j        de
j        d
edef
dZede
j        dedede
j        de
j        de
j        defd            Z xZS )JetMoeModelz
    Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`JetMoeBlock`]

    Args:
        config:
            JetMoeConfig
    r   c                    t                                                     j        | _        j        | _        t          j        j        j        | j                  | _        t          j	        fdt          j                  D                       | _        j        | _        t          j        j                  | _        d| _        |                                  d S )Nc                 0    g | ]}t          |          S r&   )rA  )r(   r   r   s     r+   r,   z(JetMoeModel.__init__.<locals>.<listcomp>  s#    $u$u$u	[%C%C$u$u$ur-   )r   F)rT   rU   pad_token_idr\  
vocab_sizer   r[  r   embed_tokens
ModuleListr]   rJ   layersrE  r   rms_norm_epsnormgradient_checkpointing	post_initr   s    `r+   rU   zJetMoeModel.__init__  s       !. +L):F<NPTP`aam$u$u$u$uUZ[a[sUtUt$u$u$uvv$*$?!!&"4&:MNNN	&+#r-   c                     | j         S r   ro  r   s    r+   get_input_embeddingsz JetMoeModel.get_input_embeddings  s      r-   c                     || _         d S r   rw  rY   values     r+   set_input_embeddingsz JetMoeModel.set_input_embeddings  s    !r-   N	input_idsr"   r   rT  inputs_embedsr	  r  output_hidden_statesrI  return_dictr
  r#   c                    ||n| j         j        }||n| j         j        }|	|	n| j         j        }	||n| j         j        }|
|
n| j         j        }
|d u |d uz  rt          d          | j        r%| j        r|rt          
                    d           d}||                     |          }d}|rVt          |t                    sAd}|t                      }n.t          j        |          }t          
                    d           |B||                                nd}t#          j        |||j        d         z   |j                  }||                    d          }|_| j        d	k    rT|rR|j        d         }|d d d
f                                                                         |k    }|rt          d          |                     |||||          }|}|rdnd }|rdnd }|	rdnd }d }| j        D ]}|r||fz  }| j        r+| j        r$|                     |j        ||||||	|d	  	        }n |||||||	|          }|d         }|r||rdnd         }|r||d         fz  }|	r||d         |d
         fz  }|                     |          }|r||fz  }|r|nd }|r|                                }|
st?          d ||||fD                       S tA          |||||          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   r3   r>  r0   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&   )use_reentrant)r"   r   r  r  rI  r	  r   r  c              3      K   | ]}||V  	d S r   r&   )r(   vs     r+   	<genexpr>z&JetMoeModel.forward.<locals>.<genexpr>6  s(      ttqfgfsfsfsfsfsttr-   )last_hidden_staterT  r   
attentionsr   )!r   r  r  rI  r	  use_return_dictr  rt  r  r   r   ro  r1   r   r   from_legacy_cacheget_seq_lengthr4   r   r;   r3   r?   rE  r>   item_update_causal_maskrq  _gradient_checkpointing_func__call__rs  to_legacy_cacher2   r   )rY   r}  r"   r   rT  r~  r	  r  r  rI  r  r
  return_legacy_cachepast_seen_tokensrH   is_padding_rightr  r   all_hidden_statesall_self_attnsall_router_logitsnext_decoder_cachedecoder_layerlayer_outputs
next_caches                            r+   rg   zJetMoeModel.forward  sT    2C1N--TXT_Tq$8$D  $+Jj 	 %9$D  $+Jj 	 "+!6IIDK<Q	%0%<kk$+B]-t";< 	[YZZZ& 	4= 	Y 	j   I  --i88M $ 
	Z?? 
	"&&"..."."@"Q"Q##^   !CRC^==???de"\ "2]5H5K"KTaTh  N )33A66L%$*CGZ*Z*Z_h*Z&,Q/J-aaae488::??AAZO  ]  
 ..M>?L]
 
 & #7@BBD0:d"6@BBD!![ $	L $	LM# 6!m%55!* t}  $ A A!*! #%("' !B 
! 
! !.!#.!-#2&7)='! ! ! *!,M R%28I3P11q%Q"  6=#3"55# L!mB&7r9J%KK!		-00   	2-!11+4>''$
 	6#3355J 	utt]J@QSa$btttttt%+&+%+
 
 
 	
r-   input_tensorc           
         | j         j        dk    r
|d|v r|S d S ||                                nd}t          |t                    }| j         j        dk    r#|s!|st          j        |||| j                  rd S |j        |j	        }	}|j
        d         }
|r|                                }n/t          |t          j                  r|j
        d         n||
z   dz   }|                     ||
|||	||j
        d                   }| j         j        dk    rB|@|j	        j        d	k    r0|s.t          j        |          j        }t          j        ||          }|S )
Nr>  r)  r   r?  )r~  past_key_values_lengthis_trainingr   r0   )rI   target_lengthrx   r3   r
  rH   r(  )r   rE  r  r1   r   r   _ignore_causal_mask_sdpar  rx   r3   r;   get_max_cache_shaper4   r!  5_prepare_4d_causal_attention_mask_with_cache_positionr   finfomin_unmask_unattended)rY   r"   r  r
  rT  r  r  using_static_cacherx   r3   rI   r  r  	min_dtypes                 r+   r  zJetMoeModel._update_causal_mask@  s    ;+/BBB)c^.C.C%%4
 @O?Z?99;;;`a'EE ;+v55>P5Yj5%>*'7 M	    t$*L,?v&,Q/ 	+??AAMM nel;;<$R((%7!;  PP+')#)!, Q 
 
 K,66*%*f44% 5 E**.I0CKQZ[[Kr-   rI   r  rx   r3   rH   c                    | |                                  dk    r| }n+t          j        |          j        }	t          j        ||f|	||          }|dk    rt          j        |d          }|t          j        ||          |                    dd          k    z  }|ddddddf                             |ddd          }| |	                                }| j
        d         }
|ddddddd|
f         | ddddddf         z   }|dk    }|ddddddd|
f                             ||	          |ddddddd|
f<   |S )	a  
        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.
            device (`torch.device`):
                The device to plcae the 4D attention mask on.
            cache_position (`torch.Tensor`):
                Indices depicting the position of the input sequence tokens in the sequence.
            batch_size (`torch.Tensor`):
                Batch size.
        N   )
fill_valuerx   r3   r   )diagonalr  r0   r   )r/   r4   r  r  fulltriur   r=   r<   cloner;   masked_fill)r"   rI   r  rx   r3   r
  rH   r2  r  r  mask_lengthpadding_masks               r+   r  zAJetMoeModel._prepare_4d_causal_attention_mask_with_cache_position  s   D %.*<*<*>*>!*C*C(KKE**.I* -0Ye\b  K !###jqAAA5<fEEEH^H^_acdHeHeeeK%dD!!!QQQ&67>>z1bRTUUK))//11,226*111aaaL[L+@ANSTSTSTVZ\`bcbcbcScDdd+q05@AAAqqq,;,AV5W5c5c )6 6AAAqqq!!!\k\12 r-   )NNNNNNNNNNN)ri   rj   rk   r   r   rU   rx  r|  r   JETMOE_INPUTS_DOCSTRINGr4   r"  r   r!  r   r   r   r<  r#  r   r   rg   r  staticmethodrl   rx   r3   r  rm   rn   s   @r+   rj  rj    sW       
 |      ! ! !" " " +*+BCC '+1537KO59$(,0/3/3&*59G
 G
#G
 !.G
 u/0	G

 "%tE4E/F(F"GHG
   12G
 D>G
 $D>G
 'tnG
 'tnG
 d^G
 !!12G
 
u,,	-G
 G
 G
 DCG
T?? l? 	?
 ?  ? ? ? ?B 555 5 {	5
 5 5 5 5 5 \5 5 5 5 5r-   rj  c            !           e Zd ZdgZ fdZd Zd Zd Zd Zd Z	d Z
 ee           eee	          	 	 	 	 	 	 	 	 	 	 	 	 	 dd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         deej                 dedeeef         fd                        Z xZS )JetMoeForCausalLMzlm_head.weightc                 .   t                                          |           t          |          | _        |j        | _        |j        | _        t          j        |j        |j        d          | _	        |j
        | _
        |                                  d S NFrr   )rT   rU   rj  modelrn  aux_loss_coefr   rt   r   lm_headtie_word_embeddingsru  r   s     r+   rU   zJetMoeForCausalLM.__init__  s        ((
 +#1y!3V5FUSSS#)#=  	r-   c                     | j         j        S r   r  ro  r   s    r+   rx  z&JetMoeForCausalLM.get_input_embeddings      z&&r-   c                     || j         _        d S r   r  rz  s     r+   r|  z&JetMoeForCausalLM.set_input_embeddings      "'
r-   c                     | j         S r   r  r   s    r+   get_output_embeddingsz'JetMoeForCausalLM.get_output_embeddings  s
    |r-   c                     || _         d S r   r  )rY   new_embeddingss     r+   set_output_embeddingsz'JetMoeForCausalLM.set_output_embeddings  s    %r-   c                     || _         d S r   r  )rY   decoders     r+   set_decoderzJetMoeForCausalLM.set_decoder  s    


r-   c                     | j         S r   r  r   s    r+   get_decoderzJetMoeForCausalLM.get_decoder  s
    zr-   )output_typera  Nr   r}  r"   r   rT  r~  labelsr	  r  r  rI  r  r
  num_logits_to_keepr#   c                    ||n| j         j        }|	|	n| j         j        }	||n| j         j        }|                     ||||||||	||
  
        }|d         }|                     |dd| dddf                   }d}||                                }|dddddf                                         }|dddf                                         }|                    d| j         j	                  }|                    d          }|
                    |j                  }t                      } |||          }d}|
rRt          |r|j        n|d         | j        | j        |          }|%|| j        |
                    |j                  z  z  }|s |f|dd         z   }|
r|f|z   }||f|z   n|S t%          ||||j        |j        |j        |j                  S )at  
        Args:
            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]`.

            num_logits_to_keep (`int`, *optional*):
                Calculate logits for the last `num_logits_to_keep` tokens. If `0`, calculate logits for all
                `input_ids` (special case). Only last token logits are needed for generation, and calculating them only for that
                token can save memory, which becomes pretty significant for long sequences or large vocabulary size.

        Returns:
        N)
r}  r"   r   rT  r~  r	  r  r  r  r
  r   .r0   r   )lossaux_lossr   rT  r   r  r   )r   r  r  r  r  r  r:   r  r   rn  r'   r3   r   rN   r   r!   r   r  r   rT  r   r  )rY   r}  r"   r   rT  r~  r  r	  r  r  rI  r  r
  r  rP  r   r   r  shift_logitsshift_labelsloss_fctr  outputs                          r+   rg   zJetMoeForCausalLM.forward  s[   B 2C1N--TXT_Tq$8$D  $+Jj 	 &1%<kk$+B] **)%+'/!5#)  
 
  
mAAA0B/B/C/CQQQ,FGHH\\^^F!#ssAAA+.99;;L!#qrr'?5577L',,R1GHHL',,R00L'??<+>??L'))H8L,77D 	F/)4E%%'"+ (	 H !*X[[-E-EEE 	DY,F# ."v-'+'7D7V##VC(#3!/)!/
 
 
 	
r-   )NNNNNNNNNNNNr   )ri   rj   rk   _tied_weights_keysrU   rx  r|  r  r  r  r  r   r  r   r   _CONFIG_FOR_DOCr4   r"  r   r!  r   r<  r#  rl   r   r   rg   rm   rn   s   @r+   r  r    s       *+	 	 	 	 	' ' '( ( (  & & &     +*+BCC+DSbccc '+1537=A59-1$(,0/3/3&*59"#_
 _
#_
 !._
 u/0	_

 "$u'8"9:_
   12_
 )*_
 D>_
 $D>_
 'tn_
 'tn_
 d^_
 !!12_
  _
 
u//	0_
 _
 _
 dc DC_
 _
 _
 _
 _
r-   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).
    c                   v    e Zd Z fdZd Z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	j
                 dee         dee         dee         dee         deeef         fd            Z xZS )JetMoeForSequenceClassificationc                     t                                          |           |j        | _        t          |          | _        t          j        |j        | j        d          | _        | 	                                 d S r  )
rT   rU   
num_labelsrj  r  r   rt   r   scoreru  r   s     r+   rU   z(JetMoeForSequenceClassification.__init__V  si        + ((
Yv14?OOO
 	r-   c                     | j         j        S r   r  r   s    r+   rx  z4JetMoeForSequenceClassification.get_input_embeddings_  r  r-   c                     || j         _        d S r   r  rz  s     r+   r|  z4JetMoeForSequenceClassification.set_input_embeddingsb  r  r-   Nr}  r"   r   rT  r~  r  r	  r  r  r  r#   c                 "   |
|
n| j         j        }
|                     ||||||||	|
	  	        }|d         }|                     |          }||j        d         }n|j        d         }| j         j        |dk    rt          d          | j         j        d}nv|rt          j        || j         j                  	                                
                    d          dz
  }||j        d         z  }|                    |j                  }nd}|t          j        ||j                  |f         }d}||                     |||| j                   }|
s|f|dd         z   }||f|z   n|S t          |||j        |j        |j        	          S )
a  
        labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
            Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
            config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
            `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
        N)r"   r   rT  r~  r	  r  r  r  r   r   z=Cannot handle batch sizes > 1 if no padding token is defined.r0   r  )r   r  pooled_logitsr   )r  r   rT  r   r  )r   r  r  r  r;   rm  r  r4   eqrl   argmaxr'   r3   r   loss_functionr   rT  r   r  )rY   r}  r"   r   rT  r~  r  r	  r  r  r  transformer_outputsr   r   rH   sequence_lengthsr  r  r  s                      r+   rg   z'JetMoeForSequenceClassification.forwarde  s   ( &1%<kk$+B]"jj)%+'/!5# ) 

 

 ,A.M** "+JJ&,Q/J;#+
a\]]];#+!$#(8It{7O#P#P#T#T#V#V#]#]^`#a#ade#e #3iob6I#I #3#6#6v}#E#E  #% u|Jv}MMMO__`%%VFR_hlhs%ttD 	F#%(;ABB(??F)-)9TGf$$vE/ /?-;*5
 
 
 	
r-   )
NNNNNNNNNN)ri   rj   rk   rU   rx  r|  r   r  r   r4   r"  r!  r   r   r   r<  r#  r   r   rg   rm   rn   s   @r+   r  r  E  s       "    ' ' '( ( ( +*+BCC 151537KO59-1$(,0/3&*E
 E
E,-E
 !.E
 u/0	E

 "%tE4E/F(F"GHE
   12E
 )*E
 D>E
 $D>E
 'tnE
 d^E
 
u66	7E
 E
 E
 DCE
 E
 E
 E
 E
r-   r  )Nr   N)Nr   )Er   r  typingr   r   r   r   r4   torch.utils.checkpointr   torch.nnr   r	   r_   activationsr   cache_utilsr   r   r   
generationr   modeling_attn_mask_utilsr   modeling_outputsr   r   r   modeling_utilsr   utilsr   r   r   r   r   r   configuration_jetmoer   modeling_flash_attention_utilsr   
get_loggerri   r   _CHECKPOINT_FOR_DOCr  r!  rl   rN   ModulerP   rp   r   r   r   r   r   r   r   r%  r.  rD  rA  rR  JETMOE_START_DOCSTRINGr  rj  r  r  r&   r-   r+   <module>r     s      / / / / / / / / / / / /            % % % % % % $ $ $ $ $ $ ! ! ! ! ! ! ; ; ; ; ; ; ; ; ; ; ) ) ) ) ) ) > > > > > >         
 . - - - - -                / . . . . .  KJJJJJJ		H	%	%   "&
-1	O& O&u|U5<%8$>?O&#O& U\*	O&
 5<O& O& O& O&d* * * * *BI * * *Z,S ,S ,S ,S ,Sry ,S ,S ,S^7+ 7+ 7+ 7+ 7+	 7+ 7+ 7+tIS IS IS IS IS	 IS IS ISZJ J J J JBI J J J*< < < < <BI < < <<( ( (   6dH dH dH dH dHbi dH dH dHNU@ U@ U@ U@ U@/ U@ U@ U@pqH qH qH qH qHO qH qH qHj .  5 5 5 5 5") 5 5 5p#% #% #% #% #%O #% #% #%L	 ( V Z b b b b b' b b	 bJ	G
 G
 G
 G
 G
- G
 G
 G
T    V
 V
 V
 V
 V
&; V
 V
!  V
 V
 V
r-   