
    fTh                    R   S r SSKrSSKJrJrJrJr  SSKrSSKrSSKJ	r	  SSK
Jr  SSKJrJrJrJr  SSKJr  SS	KJrJr  SS
KJr  SSKJrJrJr  SSKJr  SSKJr  SSK J!r!J"r"J#r#J$r$  SSK%J&r&  \" 5       (       a  SSKJ'r'  \#" 5       (       a  SSK(J)r)  SSK*J+r+  \RX                  R[                  \5      r\$R\                  " \/5      r0   S;S\\Rb                  \\Rb                     S4   S\\2   S\\Rb                     S\\Rb                  \24   4S jjr3 " S S\	Rh                  5      r5S r6S<S jr7S\Rb                  S\2S\Rb                  4S jr8 " S  S!\	Rh                  5      r9 " S" S#\95      r: " S$ S%\95      r;\9\:\;S&.r< " S' S(\	Rh                  5      r= " S) S*\R|                  R~                  5      r@S=S+ jrA " S, S-\	Rh                  5      rB " S. S/\	Rh                  5      rC\! " S0 S1\5      5       rD\! " S2 S3\D5      5       rE " S4 S5\D\5      rF\!" S6S79 " S8 S9\D5      5       rG/ S:QrHg)>zPyTorch Phimoe model.    N)ListOptionalTupleUnion)nn   )ACT2FN)CacheDynamicCacheSlidingWindowCacheStaticCache)GenerationMixin)AttentionMaskConverter!_prepare_4d_causal_attention_mask)is_flash_attn_available)MoeCausalLMOutputWithPastMoeModelOutputWithPast SequenceClassifierOutputWithPast)ROPE_INIT_FUNCTIONS)PreTrainedModel)auto_docstringcan_return_tupleis_torch_flex_attn_availablelogging   )PhimoeConfig)_flash_attention_forward)	BlockMask)make_flex_block_causal_maskgate_logitsnum_expertsattention_maskreturnc                    U b  [        U [        5      (       d  g[        U [        5      (       aC  U S   R                  n[        R                  " U  Vs/ s H  oUR                  U5      PM     snSS9n[        R                  R                  R                  WSS9n[        R                  " XrSS9u  p[        R                  R                  R                  X5      n
Uc:  [        R                  " U
R                  5       SS9n[        R                  " USS9nGOUR                  u  pUR                  S   X-  -  nUSSS2SS2SS4   R                  XXU45      R                  SX!5      R                  W5      n[        R                   " U
R                  5       U-  SS9[        R                   " USS9-  nUSSS2SS2S4   R                  XX45      R                  SU5      R                  U5      n[        R                   " UU-  SS9[        R                   " USS9-  n[        R                   " XR#                  S5      -  5      nUU-  $ s  snf )ap  
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   dim)
isinstancetupledevicetorchcattor   
functionalsoftmaxtopkone_hotmeanfloatshapeexpandreshapesum	unsqueeze)r    r!   top_kr"   compute_device
layer_gate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_losss                      b/var/www/auris/envauris/lib/python3.13/site-packages/transformers/models/phimoe/modeling_phimoe.pyload_balancing_loss_funcrJ   7   s+   : *[%"@"@+u%%$Q..#(99^i-j^iPZmmN.K^i-jpq#r hh))112JPR1SO**_DA((%%--.>LK!JJ{'8'8':B "'O!C&4&:&:#
4::1=*B^_ 4AtT12V&OKXYWR,R	 	 "IIk&7&7&9<Q&QWXY\a\e\e!q]
 
 4At+,V&OQRWR%R	 	) "'?=]+]cd!ehmhqhq,!i
 "
 99.1Q1QRS1TTUL+%%[ .ks   Ic                   F   ^  \ rS rSr SS\\   4U 4S jjjrSS jrSrU =r	$ )PhimoeRotaryEmbedding   configc                 |  > [         TU ]  5         Xl        UR                  b{  UR                  R	                  SUR                  R	                  S5      5      U l        UR                  R	                  S5      U l        UR                  R	                  S5      U l        OSU l        [        U R
                     U l	        g )N	rope_typetypeshort_mscalelong_mscaledefault)
super__init__rN   rope_scalinggetrP   rR   rS   r   rope_init_fnselfrN   	__class__s     rI   rV   PhimoeRotaryEmbedding.__init__   s     	*#0044[&BUBUBYBYZ`BabDN & 3 3 7 7 GD%2266}ED&DN/?    c                 t   S nU R                   R                  (       a;  U(       a4  X R                   R                  S   :  a  U R                  OU R                  nU R	                  U R                   UR
                  U5      u  pEUc  UOUn[        R                  " X!R
                  [        R                  S9n[        R                  " Xd5      n[        R                  " Xw4SS9nUR                  5       U-  R                  UR                  5      UR                  5       U-  R                  UR                  5      4$ )N original_max_position_embeddingsr*   dtyper'   r%   )rN   rW   rS   rR   rY   r*   r+   arangefloat32outerr,   cosr-   rb   sin)	r[   xseq_lenmscaleinv_freqattention_scalingtfreqsembs	            rI   forwardPhimoeRotaryEmbedding.forward   s    ;;## [[556XYY   && 
 '+&7&7QXXw&W#&,n"&LLGA(iiB/	F"&&qww/#'')f2D1H1H1QQQr^   )rN   rS   rY   rP   rR   N)
__name__
__module____qualname____firstlineno__r   r   rV   rp   __static_attributes____classcell__r\   s   @rI   rL   rL      s.     *.@&@ @R Rr^   rL   c                     U SSU R                   S   S-  24   nU SU R                   S   S-  S24   n[        R                  " U* U4SS9$ )z*Rotates half the hidden dims of the input..Nr'      r%   )r4   r+   r,   )rh   x1x2s      rI   rotate_halfr~      sZ    	
3"!''"+"""	#B	
3q ""	#B99rc2YB''r^   c                     X$   R                  U5      nX4   R                  U5      nX-  [        U 5      U-  -   nX-  [        U5      U-  -   nXg4$ )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`):
        The position indices of the tokens corresponding to the query and key tensors. For example, this can be
        used to pass offsetted position ids when working with a KV-cache.
    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.
)r8   r~   )qkrf   rg   position_idsunsqueeze_dimq_embedk_embeds           rI   apply_rotary_pos_embr      s]    * 

%
%m
4C


%
%m
4Cw;q>C/0Gw;q>C/0Gr^   hidden_statesn_repc                     U R                   u  p#pEUS:X  a  U $ U SS2SS2SSS2SS24   R                  X#XU5      n U R                  X#U-  XE5      $ )z
This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
r   N)r4   r5   r6   )r   r   batchnum_key_value_headsslenhead_dims         rI   	repeat_kvr      s_    
 2?1D1D.Ez!!Qa"23::5W\dlmM  e(CTTTr^   c                     ^  \ rS rSrSrSS\S\\   4U 4S jjjrS\	R                  S\S\4S	 jr       SS
\	R                  S\\	R                     S\\	R                     S\\   S\S\S\\	R                     S\\\	R                  \	R                  4      S\\	R                  \\	R                     \\\	R                        4   4S jjrSrU =r$ )PhimoeAttention   z
Multi-headed attention from 'Attention Is All You Need' paper. Modified to use sliding window attention: Longformer
and "Generating Long Sequences with Sparse Transformers".
rN   	layer_idxc                   > [         TU ]  5         Xl        X l        Uc-  [        R                  SU R                  R                   S35        UR                  U l        UR                  U l
        U R                  U R                  -  U l        UR                  U l        U R                  U R                  -  U l        UR                  U l        UR                  U l        SU l        UR"                  U l        U R                  U R                  -  U R                  :w  a&  [%        SU R                   SU R                   S35      e[&        R(                  " U R                  U R                  U R                  -  U R                  R*                  S9U l        [&        R(                  " U R                  U R                  U R                  -  U R                  R*                  S9U l        [&        R(                  " U R                  U R                  U R                  -  U R                  R*                  S9U l        [&        R(                  " U R                  U R                  -  U R                  U R                  R*                  S9U l        g )NzInstantiating z without passing a `layer_idx` is not recommended and will lead to errors during the forward call if caching is used. Please make sure to provide a `layer_idx` when creating this class.Tz?hidden_size must be divisible by num_heads (got `hidden_size`: z and `num_heads`: z).bias)rU   rV   rN   r   loggerwarning_oncer\   rs   hidden_sizenum_attention_heads	num_headsr   r   num_key_value_groupsmax_position_embeddings
rope_theta	is_causalattention_dropout
ValueErrorr   Linearattention_biasq_projk_projv_projo_projr[   rN   r   r\   s      rI   rV   PhimoeAttention.__init__   s   " !8!8 9 :, , "--33((DNN:#)#=#= $(NNd6N6N$N!'-'E'E$ ++!'!9!9MMDNN*t/?/??QRVRbRbQc$T^^$4B8  ii 0 0$..4==2PW[WbWbWqWqriid66FT[[MgMg
 iid66FT[[MgMg
 ii >@P@PW[WbWbWqWqrr^   tensorri   bszc                     UR                  X2U R                  U R                  5      R                  SS5      R	                  5       $ )Nr   r{   )viewr   r   	transpose
contiguous)r[   r   ri   r   s       rI   _shapePhimoeAttention._shape  s5    {{3GQQRSUVWbbddr^   r   r"   r   past_key_valueoutput_attentions	use_cachecache_positionposition_embeddingsr#   c	                    UR                  5       u  pnU R                  U5      nU R                  U5      nU R                  U5      nUR	                  XU R
                  U R                  5      R                  SS5      nUR	                  XU R                  U R                  5      R                  SS5      nUR	                  XU R                  U R                  5      R                  SS5      nUu  nn[        XUUU5      u  pUb$  UXS.nUR                  XU R                  U5      u  p[        XR                  5      n[        XR                  5      n[        R                  " XR                  SS5      5      [         R"                  " U R                  5      -  nUb#  US S 2S S 2S S 2S UR$                  S   24   nUU-   n[&        R(                  R+                  US[        R,                  S9R/                  UR0                  5      n[&        R(                  R3                  UU R4                  U R6                  S9n[        R                  " UU5      nUR                  5       XR
                  XR                  4:w  a5  [9        S	XR
                  XR                  4 S
UR                  5        35      eUR                  SS5      R;                  5       nUR=                  XU R>                  5      nU RA                  U5      nU(       d  S nUUU4$ )Nr   r{   rg   rf   r   r   r'   )r&   rb   )ptrainingz `attn_output` should be of size z	, but is )!sizer   r   r   r   r   r   r   r   r   updater   r   r   r+   matmulmathsqrtr4   r   r.   r/   rd   r-   rb   dropoutr   r   r   r   r6   r   r   )r[   r   r"   r   r   r   r   r   r   r   q_lenr>   query_states
key_statesvalue_statesrf   rg   cache_kwargsattn_weightscausal_maskattn_outputs                        rI   rp   PhimoeAttention.forward  s    &**,A{{=1[[/
{{=1#((T^^T]]S]]^_abc__S1I1I4==Yccdeghi
#((T5M5Mt}}]gghiklm&S#7RUWZ\h#i %#&sUL'5'<'<ZW[WeWegs't$J z+D+DE
 /H/HI||L2F2Fq!2LMPTPYPYZ^ZgZgPhh%(Aq2HJ4D4DR4H2H)HIK'+5L }},,\r,WZZ[g[m[mn}},,\T=S=S^b^k^k,lll<>#~~umm!LL2CP]P]3^2_ `$$&') 
 "++Aq1<<>!))#d6F6FGkk+. LL.88r^   )r   rN   r   r   r   r   r   r   r   r   r   r   r   r   r   rr   NNNFFNN)rs   rt   ru   rv   __doc__r   r   intrV   r+   Tensorr   
LongTensorr
   boolr   rp   rw   rx   ry   s   @rI   r   r      s)   
!s| !s !s !sFeU\\ eC ec e 2637*."'59KO:9||:9 !.:9 u//0	:9
 !:9  :9 :9 !!1!12:9 &eELL%,,,F&GH:9 
u||Xell3XeELL>Q5RR	S:9 :9r^   r   c                       \ rS rSrSr       SS\R                  S\\R                     S\\R                     S\\	   S\
S	\
S
\\R                     S\\\R                  \R                  4      4S jjrSrg)PhimoeFlashAttention2iD  a8  
Phimoe flash attention module. This module inherits from `PhimoeAttention` as the weights of the module stays
untouched. The only required change would be on the forward pass where it needs to correctly call the public API of
flash attention and deal with padding tokens in case the input contains any of them.
Nr   r"   r   r   r   r   r   r   c	                 |   UR                  5       u  pnU R                  U5      nU R                  U5      nU R                  U5      nUR	                  XU R
                  U R                  5      R                  SS5      nUR	                  XU R                  U R                  5      R                  SS5      nUR	                  XU R                  U R                  5      R                  SS5      nUR                  S   nUb  XR                  XR                  5      -  nUu  nn[        XUUU5      u  pUb%  UUUS.nUR                  XU R                  U5      u  p[        XR                  5      n[        XR                  5      nU R                   (       d  SOU R"                  nUR$                  nU[&        R(                  :X  a  [&        R*                  " 5       (       a  [&        R,                  " 5       nOR[/        U R0                  S5      (       a  U R0                  R2                  nO U R                  R4                  R$                  n[6        R9                  SU S35        UR;                  U5      nUR;                  U5      nUR;                  U5      nUR                  SS5      nUR                  SS5      nUR                  SS5      n[=        UUUUU
UU[?        U R0                  S	S 5      U R@                  S
9	nURC                  XU RD                  5      RG                  5       nU RI                  U5      nU(       d  S nUWU4$ )Nr   r{   r   r           _pre_quantization_dtypezThe input hidden states seems to be silently casted in float32, this might be related to the fact you have upcasted embedding or layer norm layers in float32. We will cast back the input in .sliding_window)r   r   r   r   )%r   r   r   r   r   r   r   r   r   r4   get_usable_lengthr   r   r   r   r   r   r   rb   r+   rd   is_autocast_enabledget_autocast_gpu_dtypehasattrrN   r   weightr   r   r-   r   getattrr   r6   r   r   r   )r[   r   r"   r   r   r   r   r   r   r   r   r>   r   r   r   
kv_seq_lenrf   rg   r   dropout_rateinput_dtypetarget_dtyper   r   s                           rI   rp   PhimoeFlashAttention2.forwardK  s    &**,A{{=1[[/
{{=1#((T^^T]]S]]^_abc__S1I1I4==Yccdeghi
#((T5M5Mt}}]gghiklm%%b)
%:::~~VVJ&S#7RUWZ\h#i %#&snUL'5'<'<ZW[WeWegs't$J z+D+DE
 /H/HI"&--sT5K5K
 #((%--'((**$;;=&?@@#{{BB#{{1177 >$ (??<8L#|4J'??<8L $--a3))!Q/
#--a3.% "4;;0@$Gnn

 "))#d6F6FGRRTkk+. LL.88r^    r   )rs   rt   ru   rv   r   r+   r   r   r   r
   r   r   rp   rw   r   r^   rI   r   r   D  s     2637*."'59KOS9||S9 !.S9 u//0	S9
 !S9  S9 S9 !!1!12S9 &eELL%,,,F&GHS9 S9r^   r   c                   `  ^  \ rS rSrSr       SS\R                  S\\R                     S\\R                     S\\	   S\
S\
S	\\R                     S
\\\R                  \R                  4      S\\R                  \\R                     \\\R                        4   4U 4S jjjrSrU =r$ )PhimoeSdpaAttentioni  z
Phimoe attention module using torch.nn.functional.scaled_dot_product_attention. This module inherits from
`PhimoeAttention` as the weights of the module stays untouched. The only changes are on the forward pass to adapt to
SDPA API.
r   r"   r   r   r   r   r   r   r#   c	           
      4  > U(       a(  [         R                  S5        [        TU ]  UUUUUUUS9$ UR	                  5       u  pnU R                  U5      nU R                  U5      nU R                  U5      nUR                  XU R                  U R                  5      R                  SS5      nUR                  XU R                  U R                  5      R                  SS5      nUR                  XU R                  U R                  5      R                  SS5      nUu  nn[        XUUU5      u  pUb$  UXS.nUR                  XU R                  U5      u  p[!        XR"                  5      n[!        XR"                  5      nUnUb  US S 2S S 2S S 2S UR$                  S   24   nUR&                  R(                  S:X  a3  Ub0  UR+                  5       nUR+                  5       nUR+                  5       nUc  U
S:  a  SOS	n[,        R.                  R0                  R3                  UUUUU R4                  (       a  U R6                  OS
US9nUR                  SS5      R+                  5       nUR                  XU R8                  5      nU R;                  U5      nUS U4$ )Na  PhimoeModel is using PhimoeSdpaAttention, 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   r{   r   r   cudaTFr   )	attn_mask	dropout_pr   )r   r   rU   rp   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r4   r*   rQ   r   r+   r   r.   scaled_dot_product_attentionr   r   r   r   )r[   r   r"   r   r   r   r   r   r   r   r   r>   r   r   r   rf   rg   r   r   r   r   r\   s                        rI   rp   PhimoeSdpaAttention.forward  s    [ 7?+-)-"3#$7 #   &**,A{{=1[[/
{{=1#((T^^T]]S]]^_abc__S1I1I4==Yccdeghi
#((T5M5Mt}}]gghiklm&S#7RUWZ\h#i %#&sUL'5'<'<ZW[WeWegs't$Jz+D+DE
 /H/HI$%(Aq2HJ4D4DR4H2H)HIK ##v-.2L'224L#..0J'224L
 (/EAID5	hh))FF!04d,,3 G 
 "++Aq1<<>!&&s43C3CDkk+.D.00r^   r   r   )rs   rt   ru   rv   r   r+   r   r   r   r
   r   r   rp   rw   rx   ry   s   @rI   r   r     s     2637*."'59KOM1||M1 !.M1 u//0	M1
 !M1  M1 M1 !!1!12M1 &eELL%,,,F&GHM1 
u||Xell3XeELL>Q5RR	SM1 M1r^   r   )eagerflash_attention_2sdpac                   6   ^  \ rS rSrS\4U 4S jjrS rSrU =r$ )PhimoeBlockSparseTop2MLPi  rN   c                   > [         TU ]  5         UR                  U l        UR                  U l        [        R                  " U R
                  U R                  SS9U l        [        R                  " U R                  U R
                  SS9U l	        [        R                  " U R
                  U R                  SS9U l
        [        UR                     U l        g NFr   )rU   rV   intermediate_sizeffn_dimr   
hidden_dimr   r   w1w2w3r	   
hidden_actact_fnrZ   s     rI   rV   !PhimoeBlockSparseTop2MLP.__init__  s    // ,,))DOOT\\F))DLL$//F))DOOT\\FV../r^   c                     U R                  U R                  U5      5      U R                  U5      -  nU R                  U5      nU$ rr   )r   r   r   r   )r[   r   current_hidden_statess      rI   rp    PhimoeBlockSparseTop2MLP.forward  s>     $DGGM,B CdggmF\ \ $(= >$$r^   )r   r   r   r   r   r   )	rs   rt   ru   rv   r   rV   rp   rw   rx   ry   s   @rI   r   r     s    	0| 	0% %r^   r   c                       \ rS rSr\S\R                  S\R                  S\R                  S\R                  S\R                  4
S j5       r\S\R                  4S	 j5       rS
r	g)MultiplierProcessori  scores
multiplierr?   masked_gatesmask_for_onec                 .    U R                  X#U5        X%-  $ )a  
Forward pass for the custom autograd function.

Args:
    ctx: Context object to save information for backward computation.
    scores (torch.Tensor): Input scores tensor.
    multiplier (torch.Tensor): Multiplier tensor.
    selected_experts (torch.Tensor): Tensor of selected experts.
    masked_gates (torch.Tensor): Masked gates tensor.
    mask_for_one (torch.Tensor): Mask for one tensor.

Returns:
    torch.Tensor: Result of the forward pass.
)save_for_backward)ctxr   r  r?   r  r  s         rI   rp   MultiplierProcessor.forward  s    . 	jLI((r^   grad_at_outputc                 ~    U R                   u  p#nX-  nXAR                  S5      -  nUR                  SUUS9  USSSS4$ )a
  
Backward pass for the custom autograd function.

Args:
    ctx: Context object with saved tensors from the forward pass.
    grad_at_output (torch.Tensor): Gradient at the output.

Returns:
    Tuple[torch.Tensor, None, None, None, None]: Gradients for the inputs.
r'   )r&   indexsrcN)saved_tensorsmulscatter_add_)r  r  r  r?   r  grad_at_scores_expandeds         rI   backwardMultiplierProcessor.backward.  sg     695F5F2
l'4".1C1CB1G"G,," 	- 	
 $
 	
r^   r   N)
rs   rt   ru   rv   staticmethodr+   r   rp   r  rw   r   r^   rI   r   r     sx    )) LL)  ,,	)
 ll) ll) )2 

 
r^   r   c                 j   US:w  a  [        S5      e[        R                  " 5          U R                  SSS9u  pEU R	                  5       R                  US9nX@-
  U-  SU-  :  nSSS5        U R                  W[        S5      5      nU(       ab  U[        R                  " U[        R                  S	9R                  5       R                  5       -
  R                  SS
9S   R                  S5      nOWn[        R                  " USS
9nUR                  SUS9n	U(       a  UR                  SSS9u  p[        R                  " X:H  [        R                   " U
5      S:  5      n[        R"                  " SUSS9R%                  U5      n[&        R)                  U U	UUU5      nOU	n[        R*                  " U SU[        S5      5      n[        R                  " 5          UR                  SSS9u  pEU R	                  5       R                  US9nX@-
  U-  SU-  :  nSSS5        UR                  U[        S5      5      nU(       ab  U[        R                  " U[        R                  S	9R                  5       R                  5       -
  R                  SS
9S   R                  S5      nOWn[        R                  " USS
9nUR                  SUS9nU(       a  UR                  SSS9u  p[        R                  " X:H  [        R                   " U
5      R-                  5       S:  5      n[        R"                  " SUSS9R%                  U5      n[&        R)                  U UUUU5      nOUn[        R.                  " UU4SS
9n[        R.                  " X4SS
9nUU4$ ! , (       d  f       GN4= f! , (       d  f       GN= f)u$  
Sparse mixer function to select top-k experts and compute multipliers.
Based on the paper: https://arxiv.org/pdf/2409.12136
We first replace the TopK(·) function as random sampling of discrete variables
in model training. Then, following Liu et al. (2023a) and Liu et al. (2023b), we apply Heun's
third order method to approximate the expert routing gradient and construct a modified
back-propagation to give a mathematically sound gradient estimation for expert routing.

Args:
    scores (torch.Tensor): Input scores tensor.
    jitter_eps (float): Jitter epsilon for numerical stability.
    training (bool): Flag indicating if the model is in training mode.
    top_k (int): Number of top experts to select.

Returns:
    Tuple[torch.Tensor, torch.Tensor]: Multiplier and selected experts tensors.
r{   ztop_k must be equal to 2r'   T)r&   keepdim)minNz-inf)memory_formatr%   r   )r&   r
  g      ?gioT?gK=U?)alpha)r   r+   no_gradmaxabsclampmasked_fillr3   
empty_likelegacy_contiguous_formatexponential_logr8   r/   gather
logical_or	rand_likeaddtype_asr   applyscatteruniform_concat)r   
jitter_epsr   r9   mask_logits_thresholdmax_indfactorr  r?   multiplier_o
max_scoresr  r  masked_scoresmasked_gates_top2selected_experts_top2multiplier_top2_omask_for_one_top2multiplier_top2s                      rI   sparsemixerr6  Q  s   $ z344 
)/D)I&##(=#>"7"@F!JqS]~ ^	 
 %%&;U6]KL ""<u?]?]^kkmqqst SRS[	
 Yr] 	 # ==26L&&25E&FL*..2t.D
'''OOJ'$.

 yyVDLL\Z(..

 "
 MM
f	M 
)6):):r4):)P&##(=#>"7"@F!JqS]~ ^	 
 &112GvW """#4EDbDbc
 SRS[ Yr] 	 !(&7R@)00R?T0U/33D3I
!,,!,OOJ'002T9

 "IIf.?vNVVWhi-33!
 ,z?;DJ||%5$MSUV 	 G 
f 
s   =N=N#
N #
N2c                   f   ^  \ rS rSrSrU 4S jrS\R                  S\R                  4S jrSr	U =r
$ )PhimoeSparseMoeBlocki  a  
This implementation is
strictly equivalent to standard MoE with full capacity (no
dropped tokens). It's faster since it formulates MoE operations
in terms of block-sparse operations to accommodate imbalanced
assignments of tokens to experts, whereas standard MoE either
(1) drop tokens at the cost of reduced performance or (2) set
capacity factor to number of experts and thus waste computation
and memory on padding.
c                   > [         TU ]  5         UR                  U l        UR                  U l        UR                  U l        UR                  U l	        [        R                  " U R                  U R                  SS9U l        [        R                  " [        U R                  5       Vs/ s H  n[        U5      PM     sn5      U l        UR"                  U l        UR$                  U l        g s  snf r   )rU   rV   r   r   r   r   num_local_expertsr!   num_experts_per_tokr9   r   r   gate
ModuleListranger   expertsrouter_jitter_noiseinput_jitter_noise)r[   rN   r>   r\   s      rI   rV   PhimoeSparseMoeBlock.__init__  s     ,,//!33//
IIdoot/?/?eL	}}PUVZVfVfPg%hPg1&>v&FPg%hi $*#=#= "(";";	 &is   *C.r   r#   c                    UR                   u  p#nU R                  (       aS  U R                  S:  aC  U[        R                  " U5      R                  SU R                  -
  SU R                  -   5      -  nUR                  SU5      nU R                  U5      n[        UU R                  U R                  S9u  pg[        R                  " X#-  U4UR                  UR                  S9n[        R                  R                  R                  XpR                   S9R#                  SSS5      n	[%        U R                   5       H  n
U R&                  U
   n[        R(                  " X   5      u  pUR                   S   S:X  a  MA  US	U4   R+                  SU5      nU" U5      XmUS	4   -  nUR-                  SXR/                  UR                  5      5        M     UR+                  X#U5      nX4$ )
 r         ?r'   )r*  r   )rb   r*   )num_classesr{   r   N)r4   r   rA  r+   r  r(  r   r<  r6  r@  zerosrb   r*   r   r.   r1   r!   permuter>  r?  wherer6   
index_add_r-   )r[   r   rC   rD   r   router_logitsr=   r?   final_hidden_statesr@   
expert_idxexpert_layeridxtop_xcurrent_stater   s                   rI   rp   PhimoeSparseMoeBlock.forward  s   2?2E2E/
Z==T44q8U--m<EEd---sT5L5L/L M &**2z:		-0,7//]]-
) $kk):6m>Q>QZgZnZn
 hh))112BP`P`1aiijkmnpqr   0 01J<<
3L[%<=JC{{1~"
 *$+6>>r:NM$0$?/Y\^bRbBc$c!  **1e5M5MmNaNa5bc 2  299*Wab"11r^   )r?  r   r<  r   rA  r!   r@  r9   )rs   rt   ru   rv   r   rV   r+   r   rp   rw   rx   ry   s   @rI   r8  r8    s-    	<*2U\\ *2ell *2 *2r^   r8  c                     ^  \ rS rSrS\S\4U 4S jjr        SS\R                  S\	\R                     S\	\R                     S\	\\R                        S	\	\   S
\	\   S\	\   S\	\R                     S\	\\R                  \R                  4      S\\R                  \	\\R                  \R                  4      4   4S jjrSrU =r$ )PhimoeDecoderLayeri  rN   r   c                 \  > [         TU ]  5         UR                  U l        [        UR                     " X5      U l        [        U5      U l        [        R                  " UR                  UR                  SS9U l        [        R                  " UR                  UR                  SS9U l        g )NTepselementwise_affine)rU   rV   r   PHIMOE_ATTENTION_CLASSES_attn_implementation	self_attnr8  block_sparse_moer   	LayerNormrms_norm_epsinput_layernormpost_attention_layernormr   s      rI   rV   PhimoeDecoderLayer.__init__  s    !--1&2M2MNva 4V <!||F,>,>FDWDWlpq(*F$7$7D)
%r^   r   r"   r   r   r   output_router_logitsr   r   r   r#   c
                    UnU R                  U5      nU R                  UUUUUUUU	S9u  pnX-   nUnU R                  U5      nU R                  U5      u  pX-   nU4nU(       a  X4-  nU(       a  X4-  nU(       a  X4-  nU$ )a  
Args:
    hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
    attention_mask (`torch.FloatTensor`, *optional*): attention mask of size
        `(batch, sequence_length)` where padding elements are indicated by 0.
    past_key_value (`Tuple(torch.FloatTensor)`, *optional*): cached past key and value projection states
    output_attentions (`bool`, *optional*):
        Whether or not to return the attentions tensors of all attention layers. See `attentions` under
        returned tensors for more detail.
    output_router_logits (`bool`, *optional*):
        Whether or not to return the logits of all the routers. They are useful for computing the router loss, and
        should not be returned during inference.
    use_cache (`bool`, *optional*):
        If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
        (see `past_key_values`).
    cache_position (`torch.LongTensor` of shape `(sequence_length)`, *optional*):
        Indices depicting the position of the input sequence tokens in the sequence.
    kwargs (`dict`, *optional*):
        Arbitrary kwargs to be ignored, used for FSDP and other methods that injects code
        into the model
)r   r"   r   r   r   r   r   r   )r_  r[  r`  r\  )r[   r   r"   r   r   r   rb  r   r   r   kwargsresidualself_attn_weightspresent_key_valuerK  outputss                   rI   rp   PhimoeDecoderLayer.forward&  s    F !,,]; ?Cnn')%)/) 3 ?M 	?
;*; !0 !55mD'+'<'<]'K$ 0 "++G++G''Gr^   )r\  r   r_  r`  r[  )NNNFFFNN)rs   rt   ru   rv   r   r   rV   r+   r   r   r   r   r   FloatTensorrp   rw   rx   ry   s   @rI   rT  rT    s'   

| 

 

 26378<,1/4$)59KOE||E !.E u//0	E
 !u||!45E $D>E 'tnE D>E !!1!12E &eELL%,,,F&GHE 
u  (51B1BEDUDU1U+V"WW	XE Er^   rT  c                   F    \ rS rSr\rSrSrS/rS/r	Sr
SrSrSrSrS rSrg	)
PhimoePreTrainedModelin  modelTrT  past_key_valuesFc                    U R                   R                  n[        U[        R                  5      (       aW  UR
                  R                  R                  SUS9  UR                  b%  UR                  R                  R                  5         g g [        U[        R                  5      (       ad  UR
                  R                  R                  SUS9  UR                  b2  UR
                  R                  UR                     R                  5         g g [        U[        R                  5      (       aJ  UR                  R                  R                  5         UR
                  R                  R                  S5        g g )Nr   )r2   stdrE  )rN   initializer_ranger(   r   r   r   datanormal_r   zero_	Embeddingpadding_idxr]  fill_)r[   modulerp  s      rI   _init_weights#PhimoePreTrainedModel._init_weights{  s   kk++fbii((MM&&CS&9{{&  &&( '--MM&&CS&9!!-""6#5#56<<> .--KK""$MM$$S) .r^   r   N)rs   rt   ru   rv   r   config_classbase_model_prefixsupports_gradient_checkpointing_no_split_modules_skip_keys_device_placement_supports_flash_attn_2_supports_sdpa_supports_cache_class_supports_quantized_cache_supports_static_cachery  rw   r   r^   rI   rl  rl  n  sG    L&*#-.#4"5!N  $"*r^   rl  c                   6  ^  \ rS rSrSrS\4U 4S jjrS rS r\	\
          SS\\R                     S\\R                     S	\\R                     S
\\\R                         S\\R                      S\\   S\\   S\\   S\\   S\\R                     S\4S jj5       5       r SS\\R                  S4   S\R                  S\R                  S
\S\4
S jjr\S\R                  S\S\S\R2                  S\R                  S\S\S
\4S j5       rSrU =r$ )PhimoeModeli  z
Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`PhimoeDecoderLayer`]
Args:
    config: PhimoeConfig
rN   c           	      B  > [         TU ]  U5        UR                  U l        UR                  U l        [
        R                  " UR                  UR                  U R                  5      U l        [
        R                  " [        UR                  5       Vs/ s H  n[        X5      PM     sn5      U l        UR                  U l        [
        R                  " UR                  UR                   SS9U l        [%        US9U l        SU l        U R+                  5         g s  snf )NTrV  )rN   F)rU   rV   pad_token_idrv  
vocab_sizer   ru  r   embed_tokensr=  r>  rE   rT  layersrZ  r]  r^  normrL   
rotary_embgradient_checkpointing	post_initr   s      rI   rV   PhimoeModel.__init__  s     !.. ++LL):):F<N<NPTP`P`ammDI&JbJbDcdDcy2Dcd
 %+$?$?!LL!3!39L9Laef	/v>&+# es   Dc                     U R                   $ rr   r  r[   s    rI   get_input_embeddings PhimoeModel.get_input_embeddings  s       r^   c                     Xl         g rr   r  r[   values     rI   set_input_embeddings PhimoeModel.set_input_embeddings  s    !r^   	input_idsr"   r   rn  inputs_embedsr   r   output_hidden_statesrb  r   r#   c                    Ub  UOU R                   R                  nU	b  U	OU R                   R                  n	Ub  UOU R                   R                  nUb  UOU R                   R                  nUS L US L-  (       a  [        S5      eU R                  (       a/  U R                  (       a  U(       a  [        R                  S5        SnSnU(       aP  [        U[        5      (       d;  SnUc  [        5       nO+[        R                  " U5      n[        R                  S5        Uc  U R                  U5      nU
cD  Ub  UR                  5       OSn[         R"                  " XUR$                  S   -   UR&                  S9n
Uc  U
R)                  S5      nU R+                  X%XU5      nUnU R-                  XS	   S-   S
9nU(       a  SOS nU(       a  SOS nU	(       a  SOS nS nU R.                   H  nU(       a  UU4-  nU R                  (       a6  U R                  (       a%  U R1                  UR2                  UUUUUU	UU
U5
      nOU" UUUUUU	UU
US9	nUS   nU(       a  UU(       a  SOS   nU(       a	  UUS   4-  nU	(       d  M  UUS	   4-  nM     U R5                  U5      nU(       a  UU4-  nU(       a  UOS nU(       a  UR7                  5       n[9        UUUUUS9$ )NzaYou cannot specify both input_ids and inputs_embeds at the same time, and must specify either onezZ`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   r*   r'   )ri   r   )r"   r   r   r   rb  r   r   r   r{   )last_hidden_statern  r   
attentionsrK  )rN   r   rb  r  r   r   r  r   r   r   r(   r
   r   from_legacy_cacher  get_seq_lengthr+   rc   r4   r*   r8   _update_causal_maskr  r  _gradient_checkpointing_func__call__r  to_legacy_cacher   )r[   r  r"   r   rn  r  r   r   r  rb  r   return_legacy_cachepast_seen_tokensr   r   r   all_hidden_statesall_self_attnsall_router_logitsnext_decoder_cachedecoder_layerlayer_outputs
next_caches                          rI   rp   PhimoeModel.forward  s    2C1N-TXT_T_TqTq$8$D $++JjJj 	 %9$D $++JjJj 	 "+!6IDKK<Q<Q	-t";<s  &&4==##p "	 $Z??"&&".."."@"@"Q##^   --i8M!CRC^==?de"\\ ]5H5H5K"KTaThThN )33A6L..>L]
 &"oomTVEWZ[E[o\ #7BD0d"6BD!![[M#!m%55!**t}} $ A A!**! #%("'! !.!#.!-#2&7)='#1(;
! *!,M%28I1q%Q" =#3"55##!mB&7%99!O )R 		-0  -!11+4'$
#335J%+&+%+
 	
r^   r   input_tensorc                    U R                   R                  S:X  a]  UbN  UbK  US S 2S4   R                  5       R                  5       UR	                  5       S   :g  nU(       a  [        S5      eUb  SU;   a  U$ g U R                   R                  S:X  a,  [        U[        R                  5      (       a  [        U5      nU$ Ub  UR                  5       OSn[        U[        5      n[        U[        5      n	U R                   R                  S:X  aQ  U(       dJ  U	(       dC  U(       d<  [        R                  " UUUU R                   R                  U R                   S9(       a  g UR"                  n
[        R$                  " U
5      R&                  nUR(                  S	   nU	(       d  U(       a  UR+                  5       nO5[        U[        R                  5      (       a  UR(                  S   OX|-   S	-   nU R-                  UUUU
UUR(                  S   U R                   US
9nU R                   R                  S:X  a:  Ub7  UR.                  R0                  S;   a  U(       d  [        R2                  " X5      nU$ )Nr   r'   r   zYou are attempting to perform batched generation with padding_side='right' this may lead to unexpected behaviour for Flash Attention version of Phimoe. Make sure to  call `tokenizer.padding_side  = 'left'` before tokenizing the input. r   flex_attentionr   )r  past_key_values_lengthr   is_trainingr   )rD   target_lengthrb   r   rC   rN   rn  )r   xpunpu)rN   rZ  r7   itemr   r   r(   r+   r   r   r  r   r   r   _ignore_causal_mask_sdpar   r   rb   finfor  r4   get_max_cache_shape5_prepare_4d_causal_attention_mask_with_cache_positionr*   rQ   _unmask_unattended)r[   r"   r  r   rn  r   is_padding_rightr  using_static_cacheusing_sliding_window_cacherb   	min_dtyperD   r  r   s                  rI   r  PhimoeModel._update_causal_mask0  s;    ;;++/BB)o.I#1!R%#8#<#<#>#C#C#EIZIZI\]^I_#_ #$a 
 )c^.C%%;;++/??.%,,77!<^!L!!
 @O?Z?99;`a'E%/AS%T" KK,,6'+E%%>>*'7#{{99 MM ""KK&**	&,,Q/%);+??AM
 nell;; $$R(%7!;  PP+')#))!,;;+ Q 	
 KK,,6*%%**.DD%
 1CCK[Kr^   rD   r  rb   rC   c                    U b  U R                  5       S:X  a  U nU$ [        R                  " U5      R                  n	[        R                  " X4XUR
                  S9n[        R                  " X$R
                  S9UR                  SS5      :  n
UR                  5       n[        USS5      (       av  UR                  bi  [        U[        5      (       a  X:  aO  [        R                  " X$R
                  S9UR                  SS5      UR                  -
  :*  nU
R                  U5        X-  nUSSSS2SS24   R                  USSS5      nU b  UR                  5       nU R                   S   U:  a  U SS2SU24   n U R                   S   nUSS2SS2SS2SU24   U SS2SSSS24   R#                  UR
                  5      -   nUS	:H  nUSS2SS2SS2SU24   R%                  X5      USS2SS2SS2SU24'   U$ )
aR  
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.
    config (`PhimoeConfig`):
        The model's configuration class
    past_key_values (`Cache`):
        The cache class that is being used currently to generate
N   )
fill_valuerb   r*   r  r'   r   use_sliding_windowTr   )r&   r+   r  r  fullr*   rc   r6   get_text_configr   r   r(   r   bitwise_or_r5   cloner4   r-   r  )r"   rD   r  rb   r   rC   rN   rn  r   r  diagonal_attend_masktext_configsliding_attend_maskmask_lengthpadding_masks                  rI   r  APhimoeModel._prepare_4d_causal_attention_mask_with_cache_position  s   D %.*<*<*>!*C(K@ = E*..I** 0Y\j\q\qK $)<<F[F[#\_m_u_uA` $  !002K{$8$??KD^D^Dj "/3EFF/Ji*/,,}MbMb*c&..r158R8RR+' )445HI/K%dD!Q&67>>z1bRTUK))//1!''+m;%3A~~4E%FN,2226*1aL[L+@ANSTVZ\`bcScDdDgDg&&E    ,q05@Aq,;,AV5W5c5c 6Aq!\k\12 r^   )rZ  r  r  r  r  rv  r  r  )
NNNNNNNNNN)F)rs   rt   ru   rv   r   r   rV   r  r  r   r   r   r+   r   r   r   rj  r   r   rp   r   r
   r  r  r   rb   r  rw   rx   ry   s   @rI   r  r    s   | "!"  151537=A59$(,0/3/359B
E,,-B
 !.B
 u//0	B

 "$u'8'8"9:B
   1 12B
 D>B
 $D>B
 'tnB
 'tnB
 !!1!12B
 
 B
  B
V #(TellK78T llT 	T
 T  Tl BBB B {{	B
 B B B B Br^   r  c                     ^  \ rS rSrS/rU 4S jrS rS rS rS r	S r
S	 r\\            SS
\\R                      S\\R"                     S\\R                      S\\\R&                        S\\R&                     S\\R                      S\\   S\\   S\\   S\\   S\\R                      S\\\R"                  4   S\4S jj5       5       r       SU 4S jjrSrU =r$ )PhimoeForCausalLMi  zlm_head.weightc                 r  > [         TU ]  U5        [        U5      U l        UR                  U l        [
        R                  " UR                  UR                  U R                  R                  S9U l
        UR                  U l        UR                  U l        UR                  U l        U R                  5         g )Nr   )rU   rV   r  rm  r  r   r   r   rN   lm_head_biaslm_headrouter_aux_loss_coefr:  r!   r;  r  rZ   s     rI   rV   PhimoeForCausalLM.__init__  s      (
 ++yy!3!3V5F5FT[[MeMef$*$?$?!!33#)#=#= r^   c                 .    U R                   R                  $ rr   rm  r  r  s    rI   r  &PhimoeForCausalLM.get_input_embeddings      zz&&&r^   c                 $    XR                   l        g rr   r  r  s     rI   r  &PhimoeForCausalLM.set_input_embeddings      "'

r^   c                     U R                   $ rr   r  r  s    rI   get_output_embeddings'PhimoeForCausalLM.get_output_embeddings  s    ||r^   c                     Xl         g rr   r  )r[   new_embeddingss     rI   set_output_embeddings'PhimoeForCausalLM.set_output_embeddings  s    %r^   c                     Xl         g rr   rm  )r[   decoders     rI   set_decoderPhimoeForCausalLM.set_decoder  s    
r^   c                     U R                   $ rr   r  r  s    rI   get_decoderPhimoeForCausalLM.get_decoder  s    zzr^   r  r"   r   rn  r  labelsr   r   r  rb  r   logits_to_keepr#   c                    U(       ah  U R                   R                  (       aM  UbJ  US   U R                   R                  :X  a-  [        R	                  SU R                   R                   S35        Ub  UOU R                   R
                  nU
b  U
OU R                   R                  n
U	b  U	OU R                   R                  n	U R                  UUUUUUUU	U
US9
nUR                  n[        U[        5      (       a  [        U* S5      OUnU R                  USS2USS24   5      nSnUb  U R                  " UX`R                  40 UD6nSnU
(       aZ  [!        UR"                  U R$                  U R&                  U5      nUb+  UU R(                  UR+                  UR,                  5      -  -  n[/        UUUUR0                  UR2                  UR4                  UR"                  S9$ )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]`.

Example:
```python
>>> from transformers import AutoTokenizer, PhimoeForCausalLM
>>> model = PhimoeForCausalLM.from_pretrained("microsoft/Phi-3.5-MoE-instruct")
>>> tokenizer = AutoTokenizer.from_pretrained("microsoft/Phi-3.5-MoE-instruct")
>>> prompt = "Hey, are you conscious? Can you talk to me?"
>>> inputs = tokenizer(prompt, return_tensors="pt")
>>> # Generate
>>> generate_ids = model.generate(inputs.input_ids, max_length=30)
>>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
"Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you."
```Nr   zZIf you are not using the generate method, you may encounter nonsensical outputs after the z1th token, as the KV cache needs to be recomputed.)
r  r"   r   rn  r  r   r   r  rb  r   )lossaux_losslogitsrn  r   r  rK  )rN   rW   r`   r   warningr   rb  r  rm  r  r(   r   slicer  loss_functionr  rJ   rK  r!   r;  r  r-   r*   r   rn  r   r  )r[   r  r"   r   rn  r  r  r   r   r  rb  r   r  loss_kwargsrh  r   slice_indicesr  r  r  s                       rI   rp   PhimoeForCausalLM.forward  s   J ((*q!T[[%Q%QQNNlmqmxmx  nZ  nZ  m[  [L  M 2C1N-TXT_T_TqTq$8$D $++JjJj 	
 %9$D $++JjJj 	
 +/**)%+'/!5!5) +5 +
  118B>SV8W8W~ot4]kmA}a,?@A%%ffooUUD/%%  ((	H !11HKK4LLL(#33!//))!//
 	
r^   c	                   > U(       ae  U R                   R                  (       aJ  UR                  S   U R                   R                  S-   :  a   US   n
XR                   R                  ::  a  S n[        TU ]  " SUUUUUUUUS.U	D6nU$ )Nr   r   )r  rn  r"   r  r   r   r   r  r   )rN   rW   r4   r`   rU   prepare_inputs_for_generation)r[   r  rn  r"   r  r   r   r   r  rd  past_lengthmodel_inputsr\   s               rI   r  /PhimoeForCausalLM.prepare_inputs_for_generationV  s    $ (("dkk&R&RUV&VV(+KkkJJJ"&w< 

+)')%)

 

 r^   )r  rm  r!   r;  r  r  )NNNNNNNNNNNr   )NNNNNTN)rs   rt   ru   rv   _tied_weights_keysrV   r  r  r  r  r  r  r   r   r   r+   r   r   r   rj  r   r   r   r   rp   r  rw   rx   ry   s   @rI   r  r    s   *+	'(&  151537=A59-1$(,0/3/35934^
E,,-^
 !.^
 u//0	^

 "$u'8'8"9:^
   1 12^
 ))*^
 D>^
 $D>^
 'tn^
 'tn^
 !!1!12^
 c5<</0^
 
#^
  ^
H % %r^   r  a  
    The Phimoe Model transformer with a sequence classification head on top (linear layer).
    [`PhimoeForSequenceClassification`] 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).
    )custom_introc                   *  ^  \ rS rSrU 4S jrS rS r\\         SS\	\
R                     S\	\
R                     S\	\
R                     S\	\   S	\	\
R                     S
\	\
R                     S\	\   S\	\   S\	\   S\4S jj5       5       rSrU =r$ )PhimoeForSequenceClassificationi~  c                    > [         TU ]  U5        UR                  U l        [        U5      U l        [
        R                  " UR                  U R                  SS9U l        U R                  5         g r   )
rU   rV   
num_labelsr  rm  r   r   r   scorer  rZ   s     rI   rV   (PhimoeForSequenceClassification.__init__  sS      ++ (
YYv114??O
 	r^   c                 .    U R                   R                  $ rr   r  r  s    rI   r  4PhimoeForSequenceClassification.get_input_embeddings  r  r^   c                 $    XR                   l        g rr   r  r  s     rI   r  4PhimoeForSequenceClassification.set_input_embeddings  r  r^   r  r"   r   rn  r  r  r   r   r  r#   c
                    U R                  UUUUUUUU	S9n
U
R                  nU R                  U5      nUb  UR                  S   nOUR                  S   nU R                  R
                  c  US:w  a  [        S5      eU R                  R
                  c  SnOUb  XR                  R
                  :g  R                  UR                  [        R                  5      n[        R                  " UR                  S   UR                  [        R                  S9nUU-  R                  S5      nO.Sn[        R                  U R                  R                    S35        U[        R                  " XR                  S	9U4   nSnUb  U R#                  XUU R                  S
9n[%        UUU
R&                  U
R(                  U
R*                  S9$ )ae  
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   rn  r  r   r   r  Nr   r   z=Cannot handle batch sizes > 1 if no padding token is defined.r'   ra   z will not detect padding tokens in `inputs_embeds`. Results may be unexpected if using padding tokens in conjunction with `inputs_embeds.`r  )r  r  pooled_logitsrN   )r  r  rn  r   r  )rm  r  r  r4   rN   r  r   r-   r*   r+   int32rc   argmaxr   r   r\   rs   r  r   rn  r   r  )r[   r  r"   r   rn  r  r  r   r   r  transformer_outputsr   r  rC   last_non_pad_tokennon_pad_masktoken_indicesr  r  s                      rI   rp   'PhimoeForSequenceClassification.forward  s   * 7;jj)%+'/!5 7A 	7
 ,==M* "+J&,,Q/J;;##+
a\]];;##+!#"%)A)AAEEfmmUZU`U`aL!LL)<V]]Z_ZeZefM"/,">!F!Fr!J!#>>**+ ,Z Z
 u||J}}MOaab%%VR_hlhshs%tD/ /??-;;*55
 	
r^   )rm  r  r  )	NNNNNNNNN)rs   rt   ru   rv   rV   r  r  r   r   r   r+   r   r   r
   rj  r   r   rp   rw   rx   ry   s   @rI   r  r  ~  s    '(  151537+/59-1$(,0/3A
E,,-A
 !.A
 u//0	A

 "%A
   1 12A
 ))*A
 D>A
 $D>A
 'tnA
 
*A
  A
r^   r  )rl  r  r  r  )Nr{   N)r   )r{   )Ir   r   typingr   r   r   r   r+   torch.utils.checkpointr   activationsr	   cache_utilsr
   r   r   r   
generationr   modeling_attn_mask_utilsr   r   modeling_flash_attention_utilsr   modeling_outputsr   r   r   modeling_rope_utilsr   modeling_utilsr   utilsr   r   r   r   configuration_phimoer   r   !torch.nn.attention.flex_attentionr   integrations.flex_attentionr   fxwrap
get_loggerrs   r   r   r   rJ   ModulerL   r~   r   r   r   r   r   rY  r   autogradFunctionr   r6  r8  rT  rl  r  r  r  __all__r   r^   rI   <module>r,     sO      / /    ! O O ) a E s s 6 - \ \ . J!!;J
 %*HHMM2S$T ! 
		H	% "&
-1	O&u||U5<<%8$>?O&#O& U\\*	O&
 5<<O&dRBII RD(:	UU\\ 	U# 	U%,, 	Uf9bii f9RZ9O Z9zU1/ U1r . %ryy %$;
%..11 ;
|}@E2299 E2PR Rj *O * *6 '  D
n- nb 	S
&; S
S
lr^   