
    g                    v   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mZmZmZ ddlmZ dd	lmZmZ dd
lmZmZmZ ddlmZ ddlmZ ddlmZ ddl m!Z!m"Z"m#Z#m$Z$m%Z% ddl&m'Z' ddl(m)Z)  e#            rddl*m+Z+  e'            r esddl,Zej-        .                    e          Z e$j/        e0          Z1dZ2	 	 	 d>deej3        eej3                 df         dee4         deej3                 deej3        e4f         fdZ5 G d de	j6                  Z7d Z8d?dZ9dej3        de4dej3        fd Z: G d! d"e	j6                  Z; G d# d$e;          Z< G d% d&e;          Z=e;e<e=d'Z> G d( d)e	j6                  Z? G d* d+ej@        jA                  ZBd@d,ZC G d- d.e	j6                  ZD G d/ d0e	j6                  ZEd1ZF e!d2eF           G d3 d4e                      ZGd5ZH e!d2eF           G d6 d7eG                      ZI G d8 d9eGe          ZJ e!d:eF           G d; d<eG                      ZKg d=ZLdS )AzPyTorch Phimoe model.    N)ListOptionalTupleUnion)nn   )ACT2FN)CacheDynamicCacheSlidingWindowCacheStaticCache)GenerationMixin)AttentionMaskConverter!_prepare_4d_causal_attention_mask)MoeCausalLMOutputWithPastMoeModelOutputWithPast SequenceClassifierOutputWithPast)ROPE_INIT_FUNCTIONS)PreTrainedModel)#is_torch_greater_or_equal_than_1_13)add_start_docstrings%add_start_docstrings_to_model_forwardis_flash_attn_2_availableloggingreplace_return_docstrings)is_torch_fx_available   )PhimoeConfig)_flash_attention_forwardr      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/phimoe/modeling_phimoe.py
<listcomp>z,load_balancing_loss_func.<locals>.<listcomp>d   s&    -j-j-jPZjmmN.K.K-j-j-j    dim)
isinstancetupledevicetorchcatr   
functional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_funcrP   B   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                   <     e Zd Z	 ddee         f fdZddZ xZS )PhimoeRotaryEmbeddingNconfigc                    t                                                       || _        |j        w|j                            d|j                            d                    | _        |j                            d          | _        |j                            d          | _        nd| _        t          | j                 | _	        d S )N	rope_typetypeshort_mscalelong_mscaledefault)
super__init__rS   rope_scalinggetrU   rW   rX   r   rope_init_fnselfrS   	__class__s     r,   r[   zPhimoeRotaryEmbedding.__init__   s     	*#044[&BUBYBYZ`BaBabbDN & 3 7 7 G GD%266}EED&DN/?r.   c                     d }| j         j        r&|r$|| j         j        d         k    r| j        n| j        }|                     | j         |j        |          \  }}||n|}t          j        ||j        t          j                  }t          j	        ||          }t          j
        ||fd          }|                                |z                      |j                  |                                |z                      |j                  fS )N original_max_position_embeddings)r4   dtyper1   r/   )rS   r\   rX   rW   r^   r4   r5   arangefloat32outerr6   cosr(   rd   sin)	r`   xseq_lenmscaleinv_freqattention_scalingtfreqsembs	            r,   forwardzPhimoeRotaryEmbedding.forward   s   ;# 	 	 T[56XYYY   & 
 '+&7&7QXw&W&W##&,n""&LGGGAx((iB///		F"&&qw//#''))f2D1H1H1Q1QQQr.   N)__name__
__module____qualname__r   r   r[   rr   __classcell__ra   s   @r,   rR   rR      sx         *.@ @&@ @ @ @ @ @R R R R R R R Rr.   rR   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..Nr1   r    r/   )r=   r5   r6   )rj   x1x2s      r,   rotate_halfr|      s]    	
3"!'"+"""	#B	
3q """	#B9rc2YB''''r.   c                     ||                              |          }||                              |          }| |z  t          |           |z  z   }||z  t          |          |z  z   }||fS )an  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.
    )rA   r|   )qkrh   ri   position_idsunsqueeze_dimq_embedk_embeds           r,   apply_rotary_pos_embr      sq    * l

%
%m
4
4C
l

%
%m
4
4C3w;q>>C/0G3w;q>>C/0GGr.   hidden_statesn_repc                     | j         \  }}}}|dk    r| S | dddddddddf                             |||||          } |                     |||z  ||          S )z
    This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
    num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
    r   N)r=   r>   r?   )r   r   batchnum_key_value_headsslenhead_dims         r,   	repeat_kvr      s    
 2?1D.Ehzz!!!!QQQaaa"23::5BUW\^bdlmmM  (;e(CT8TTTr.   c                   p    e Zd ZdZddedee         f fdZdej	        dede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ej	        ej	        f                  deej	        eej	                 eeej	                          f         fdZ xZS )PhimoeAttentionz
    Multi-headed attention from 'Attention Is All You Need' paper. Modified to use sliding window attention: Longformer
    and "Generating Long Sequences with Sparse Transformers".
    NrS   	layer_idxc                    t                                                       || _        || _        |(t                              d| j        j         d           |j        | _        |j	        | _
        | j        | j
        z  | _        |j        | _        | j
        | j        z  | _        |j        | _        |j        | _        d| _        |j        | _        | j        | j
        z  | j        k    r t%          d| j         d| j
         d          t'          j        | j        | j
        | j        z  | j        j                  | _        t'          j        | j        | j        | j        z  | j        j                  | _        t'          j        | j        | j        | j        z  | j        j                  | _        t'          j        | j
        | j        z  | j        | j        j                  | _        d S )NzInstantiating z without passing a `layer_idx` is not recommended and will lead to errors during the forward call if caching is used. Please make sure to provide a `layer_idx` when creating this class.Tz?hidden_size must be divisible by num_heads (got `hidden_size`: z and `num_heads`: z).bias)rZ   r[   rS   r   loggerwarning_oncera   rt   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`   rS   r   ra   s      r,   r[   zPhimoeAttention.__init__   s   ",!8 , , ,   "-3(DN:#)#= $(Nd6N$N!'-'E$ +!'!9MDN*t/???8RVRb 8 8%)^8 8 8   i 0$.4=2PW[WbWqrrrid6FT[Mg
 
 
 id6FT[Mg
 
 
 i >@PW[WbWqrrrr.   tensorrk   bszc                     |                     ||| j        | j                                      dd                                          S )Nr   r    )viewr   r   	transpose
contiguous)r`   r   rk   r   s       r,   _shapezPhimoeAttention._shape  s<    {{3GGQQRSUVWWbbdddr.   Fr   r#   r   past_key_valueoutput_attentions	use_cachecache_positionposition_embeddingsr$   c	                 $   |                                 \  }	}
}|                     |          }|                     |          }|                     |          }|                    |	|
| j        | j                                      dd          }|                    |	|
| j        | j                                      dd          }|                    |	|
| j        | j                                      dd          }|\  }}t          |||||          \  }}|&|||d}|
                    ||| j        |          \  }}t          || j                  }t          || j                  }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    r5t9          d	|	| j        |
| j        f d
|                                            |                    dd                                          }|                    |	|
| j                  }|                      |          }|sd }|||fS )Nr   r    ri   rh   r   r   r1   )r0   rd   )ptrainingz `attn_output` should be of size z	, but is )!sizer   r   r   r   r   r   r   r   r   updater   r   r   r5   matmulmathsqrtr=   r   r7   r8   rf   r(   rd   dropoutr   r   r   r   r?   r   r   )r`   r   r#   r   r   r   r   r   r   r   q_lenrE   query_states
key_statesvalue_statesrh   ri   cache_kwargsattn_weightscausal_maskattn_outputs                        r,   rr   zPhimoeAttention.forward  s    &**,,UA{{=11[[//
{{=11#((eT^T]SS]]^_abcc__S%1I4=YYccdeghii
#((eT5Mt}]]gghiklmm&S#7jRUWZ\h#i#i j%#&snUUL'5'<'<ZW[Wegs't't$J z4+DEE
 t/HII|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<<>>!))#ud6FGGkk+..  	 LL.88r.   rs   NNNFFNN)rt   ru   rv   __doc__r   r   intr[   r5   Tensorr   
LongTensorr
   boolr   rr   rw   rx   s   @r,   r   r      ss        
!s !s| !s !s !s !s !s !s !sFeU\ eC ec e e e e 2637*."'59KO:9 :9|:9 !.:9 u/0	:9
 !:9  :9 :9 !!12:9 &eEL%,,F&GH:9 
u|Xel3XeEL>Q5RR	S:9 :9 :9 :9 :9 :9 :9 :9r.   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
ej        ej        f                  fdZdS )PhimoeFlashAttention2aH  
    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.
    NFr   r#   r   r   r   r   r   r   c	                 b   |                                 \  }	}
}|                     |          }|                     |          }|                     |          }|                    |	|
| j        | j                                      dd          }|                    |	|
| j        | j                                      dd          }|                    |	|
| j        | j                                      dd          }|j	        d         }|||
                    || j                  z  }|\  }}t          |||||          \  }}|&|||d}|                    ||| j        |          \  }}t          || j                  }t          || j                  }| j        sdn| j        }|j        }|t&          j        k    rt'          j                    rt'          j                    }n3t/          | j        d          r| j        j        }n| j        j        j        }t6                              d| d           |                    |          }|                    |          }|                    |          }|                    dd          }|                    dd          }|                    dd          }t=          |||||
||t?          | j        d	d           | j         
	  	        }|!                    |	|
| j"                  #                                }| $                    |          }|sd }|||fS )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   r=   get_usable_lengthr   r   r   r   r   r   r   rd   r5   rf   is_autocast_enabledget_autocast_gpu_dtypehasattrrS   r   weightr   r   r(   r   getattrr   r?   r   r   r   )r`   r   r#   r   r   r   r   r   r   r   r   rE   r   r   r   
kv_seq_lenrh   ri   r   dropout_rateinput_dtypetarget_dtyper   r   s                           r,   rr   zPhimoeFlashAttention2.forwardW  s?    &**,,UA{{=11[[//
{{=11#((eT^T]SS]]^_abcc__S%1I4=YYccdeghii
#((eT5Mt}]]gghiklmm%b)
%.:::t~VVVJ&S#7jRUWZ\h#i#i j%#&snUUL'5'<'<ZW[Wegs't't$J z4+DEE
 t/HII"&-KssT5K
 #(%-''(** 8$;==&?@@ 8#{B#{17$ $ $ $   (??<88L#|44J'??<88L $--a33))!Q//
#--a33.% "4;0@$GGn

 

 

 "))#ud6FGGRRTTkk+..  	 LL.88r.   r   )rt   ru   rv   r   r5   r   r   r   r
   r   r   rr   r'   r.   r,   r   r   P  s          2637*."'59KOS9 S9|S9 !.S9 u/0	S9
 !S9  S9 S9 !!12S9 &eEL%,,F&GHS9 S9 S9 S9 S9 S9r.   r   c                   4    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
ej        ej        f                  de
ej        eej                 ee
ej                          f         f fdZ xZS )PhimoeSdpaAttentionz
    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.
    NFr   r#   r   r   r   r   r   r   r$   c	           	      ~   |rBt                               d           t                                          |||||||          S |                                \  }	}
}|                     |          }|                     |          }|                     |          }|                    |	|
| j	        | j
                                      dd          }|                    |	|
| j        | j
                                      dd          }|                    |	|
| j        | j
                                      dd          }|\  }}t          |||||          \  }}|&|||d}|                    ||| j        |          \  }}t!          || j                  }t!          || j                  }|}||d d d d d d d |j        d         f         }|j        j        dk    r>|<|                                }|                                }|                                }||
dk    rdnd	}t,          j        j                            ||||| j        r| j        nd
|          }|                    dd                                          }|                    |	|
| j                  }|                     |          }|d |fS )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   rZ   rr   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r=   r4   rV   r   r5   r   r7   scaled_dot_product_attentionr   r   r   r   )r`   r   r#   r   r   r   r   r   r   r   r   rE   r   r   r   rh   ri   r   r   r   r   ra   s                        r,   rr   zPhimoeSdpaAttention.forward  s     	[   77??+-)-"3#$7 #    &**,,UA{{=11[[//
{{=11#((eT^T]SS]]^_abcc__S%1I4=YYccdeghii
#((eT5Mt}]]gghiklmm&S#7jRUWZ\h#i#i j%#&snUUL'5'<'<ZW[Wegs't't$Jz4+DEE
 t/HII$%(AAAqqq2HJ4DR4H2H)HIK #v--.2L'2244L#..00J'2244L
 (/EAIIDD5	h)FF!04Fd,,3 G 
 
 "++Aq11<<>>!&&sE43CDDkk+..D.00r.   r   )rt   ru   rv   r   r5   r   r   r   r
   r   r   rr   rw   rx   s   @r,   r   r     s          2637*."'59KOM1 M1|M1 !.M1 u/0	M1
 !M1  M1 M1 !!12M1 &eEL%,,F&GHM1 
u|Xel3XeEL>Q5RR	SM1 M1 M1 M1 M1 M1 M1 M1 M1 M1r.   r   )eagerflash_attention_2sdpac                   *     e Zd Zdef fdZd Z xZS )PhimoeBlockSparseTop2MLPrS   c                    t                                                       |j        | _        |j        | _        t          j        | j        | j        d          | _        t          j        | j        | j        d          | _	        t          j        | j        | j        d          | _
        t          |j                 | _        d S NFr   )rZ   r[   intermediate_sizeffn_dimr   
hidden_dimr   r   w1w2w3r	   
hidden_actact_fnr_   s     r,   r[   z!PhimoeBlockSparseTop2MLP.__init__  s    / ,)DOT\FFF)DL$/FFF)DOT\FFFV./r.   c                     |                      |                     |                    |                     |          z  }|                     |          }|S rs   )r   r   r   r   )r`   r   current_hidden_statess      r,   rr   z PhimoeBlockSparseTop2MLP.forward  sJ     $DGGM,B,B C CdggmF\F\ \ $(= > >$$r.   )rt   ru   rv   r   r[   rr   rw   rx   s   @r,   r   r     sS        	0| 	0 	0 	0 	0 	0 	0% % % % % % %r.   r   c                       e Zd Zedej        dej        dej        dej        dej        f
d            Zedej        fd            Zd	S )
MultiplierProcessorscores
multiplierrF   masked_gatesmask_for_onec                 :    |                      |||           ||z  S )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   rF   r   r   s         r,   rr   zMultiplierProcessor.forward   s(    . 	j*:LIIIL((r.   grad_at_outputc                     | j         \  }}}||z  }||                    d          z  }|                    d||           |ddddfS )aB  
        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.
        r1   )r0   indexsrcN)saved_tensorsmulscatter_add_)r   r   r   rF   r   grad_at_scores_expandeds         r,   backwardzMultiplierProcessor.backward:  sx     695F2
$l'*4".1C1CB1G1G"G,," 	- 	
 	
 	
 $
 	
r.   N)rt   ru   rv   staticmethodr5   r   rr   r  r'   r.   r,   r   r     s        )) L)  ,	)
 l) l) ) ) \)2 

 
 
 \
 
 
r.   r   c                 l   |dk    rt          d          t          j                    5  |                     dd          \  }}|                                                     |          }|| z
  |z  d|z  k    }ddd           n# 1 swxY w Y   |                     |t          d                    }|ru|t          j        |t          j	        	          
                                                                z
                      d
          d                             d          }n|}t          j        |d
          }|                    d|          }	|r|                    dd          \  }
}t          j        ||k    t          j        |
          dk              }t          j        d|d                              |          }t&                              | |	|||          }n|	}t          j        | d|t          d                    }t          j                    5  |                    dd          \  }}|                                                     |          }|| z
  |z  d|z  k    }ddd           n# 1 swxY w Y   |                    |t          d                    }|ru|t          j        |t          j	        	          
                                                                z
                      d
          d                             d          }n|}t          j        |d
          }|                    d|          }|r|                    dd          \  }
}t          j        ||k    t          j        |
                                          dk              }t          j        d|d                              |          }t&                              | ||||          }n|}t          j        ||fd
          }t          j        ||fd
          }||fS )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 2r1   T)r0   keepdim)minNz-inf)memory_formatr/   r   )r0   r   g      ?gioT?gK=U?)alpha)r   r5   no_gradmaxabsclampmasked_fillr<   
empty_likelegacy_contiguous_formatexponential_logrA   r8   gather
logical_or	rand_likeaddtype_asr   applyscatteruniform_concat)r   
jitter_epsr   rB   mask_logits_thresholdmax_indfactorr   rF   multiplier_o
max_scoresr   r   masked_scoresmasked_gates_top2selected_experts_top2multiplier_top2_omask_for_one_top2multiplier_top2s                      r,   sparsemixerr)  ]  s   $ zz3444 
 _ _)/D)I)I&w##(=#>>"7&"@F!JqS]~ ^	_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ %%&;U6]]KKL 
# "<u?]^^^kkmmqqsst SRS[[	
 Yr]] 	 # =2666L&&25E&FFL "*..2t.DD
G''OJ''$.
 

 yVDDDLL\ZZ(..
 


 "
 M
f	 M 
 _ _)6):):r4):)P)P&w##(=#>>"7&"@F!JqS]~ ^	_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ &112GvWW ( ""#4EDbccc
 SRS[[ Yr]] 	 !(&7R@@@)00R?T0UU ,/33D3II
G!,!W,OJ''0022T9
 

 "If.?vNNNVVWhii-33!
 
 ,z?;DDDJ|%57L$MSUVVV 	 s%   ABBB(AJJ
J
c                   F     e Zd ZdZ fdZdej        dej        fdZ xZS )PhimoeSparseMoeBlocka  
    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 accomodate 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                                                       j        | _        j        | _        j        | _        j        | _	        t          j        | j        | j        d          | _        t          j        fdt          | j                  D                       | _        j        | _        j        | _        d S )NFr   c                 .    g | ]}t                    S r'   )r   )r)   rE   rS   s     r,   r-   z1PhimoeSparseMoeBlock.__init__.<locals>.<listcomp>  s"    %h%h%h1&>v&F&F%h%h%hr.   )rZ   r[   r   r   r   r   num_local_expertsr"   num_experts_per_tokrB   r   r   gate
ModuleListrangeexpertsrouter_jitter_noiseinput_jitter_noiser_   s    `r,   r[   zPhimoeSparseMoeBlock.__init__  s     ,/!3/
Idot/?eLLL	}%h%h%h%hPUVZVfPgPg%h%h%hii $*#= "(";r.   r   r$   c                    |j         \  }}}| j        rF| j        dk    r;|t          j        |                              d| j        z
  d| j        z             z  }|                    d|          }|                     |          }t          || j	        | j                  \  }}t          j
        ||z  |f|j        |j                  }t          j        j                            || j                                      ddd          }	t%          | j                  D ]}
| j        |
         }t          j        |	|
                   \  }}|j         d         dk    r>|d	|f                             d|          } ||          |||d	f         z  }|                    d||                    |j                             |                    |||          }||fS )
 r   g      ?r1   )r  r   )rd   r4   )num_classesr    r   N)r=   r   r5  r5   r  r  r   r0  r)  r4  zerosrd   r4   r   r7   r:   r"   permuter2  r3  wherer?   
index_add_r(   )r`   r   rJ   rK   r   router_logitsrD   rF   final_hidden_statesrG   
expert_idxexpert_layeridxtop_xcurrent_stater   s                   r,   rr   zPhimoeSparseMoeBlock.forward  s   2?2E/
OZ= 	T4q88U-m<<EEd--sT5L/L  M &**2z::		-00,7/]-
 -
 -
)) $k/):6m>QZgZn
 
 
 h)112BPTP`1aaiijkmnpqrr   011 	d 	dJ<
3L[%<==JC{1~""
 *$+6>>r:NNM$0L$?$?/RWY\^bRbBc$c!  **1e5J5M5MmNa5b5bcccc199*oWabb"M11r.   )	rt   ru   rv   r   r[   r5   r   rr   rw   rx   s   @r,   r+  r+    sh        	 	< < < < <*2U\ *2el *2 *2 *2 *2 *2 *2 *2 *2r.   r+  c                   v    e Zd Zdedef fdZ	 	 	 	 	 	 	 	 ddej        deej                 deej	                 d	ee
ej                          d
ee         dee         dee         deej	                 dee
ej        ej        f                  de
ej        ee
ej        ej        f                  f         fdZ xZS )PhimoeDecoderLayerrS   r   c                 `   t                                                       |j        | _        t          |j                 ||          | _        t          |          | _        t          j	        |j        |j
        d          | _        t          j	        |j        |j
        d          | _        d S )NTepselementwise_affine)rZ   r[   r   PHIMOE_ATTENTION_CLASSES_attn_implementation	self_attnr+  block_sparse_moer   	LayerNormrms_norm_epsinput_layernormpost_attention_layernormr   s      r,   r[   zPhimoeDecoderLayer.__init__&  s    !-1&2MNvW`aa 4V < <!|F,>FDWlpqqq(*F$7D)
 )
 )
%%%r.   NFr   r#   r   r   r   output_router_logitsr   r   r   r$   c
           
         |}|                      |          }|                     ||||||||	          \  }}}||z   }|}|                     |          }|                     |          \  }}||z   }|f}|r||fz  }|r||fz  }|r||fz  }|S )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   )rP  rL  rQ  rM  )r`   r   r#   r   r   r   rR  r   r   r   kwargsresidualself_attn_weightspresent_key_valuer=  outputss                   r,   rr   zPhimoeDecoderLayer.forward2  s    F !,,];; ?Cnn')%)/) 3 ?M 	?
 	?
;(*; !=0 !55mDD'+'<'<]'K'K$} =0 " 	,)++G 	,)++G 	(''Gr.   )NNNFFFNN)rt   ru   rv   r   r   r[   r5   r   r   r   r   r   FloatTensorrr   rw   rx   s   @r,   rE  rE  %  sY       

| 

 

 

 

 

 

 

 26378<,1/4$)59KOE E|E !.E u/0	E
 !u|!45E $D>E 'tnE D>E !!12E &eEL%,,F&GHE 
u (51BEDU1U+V"WW	XE E E E E E E Er.   rE  aI  
    This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
    library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
    etc.)
    This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
    Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
    and behavior.
    Parameters:
        config ([`PhimoeConfig`]):
            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.
zTThe bare Phimoe Model outputting raw hidden-states without any specific head on top.c                   6    e Zd ZeZdZdZdgZdZdZ	dZ
dZd ZdS )PhimoePreTrainedModelmodelTrE  past_key_valuesc                    | j         j        }t          |t          j                  rJ|j        j                            d|           |j         |j        j        	                                 d S d S t          |t          j
                  rS|j        j                            d|           |j        -|j        j        |j                 	                                 d S d S d S )Nr   )r;   std)rS   initializer_ranger2   r   r   r   datanormal_r   zero_	Embeddingpadding_idx)r`   moduler_  s      r,   _init_weightsz#PhimoePreTrainedModel._init_weights  s    k+fbi(( 	?M&&CS&999{& &&((((( '&-- 	?M&&CS&999!-"6#56<<>>>>>	? 	?--r.   N)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_classrg  r'   r.   r,   r[  r[    sV          L&*#-."3!N 	? 	? 	? 	? 	?r.   r[  a  
    Args:
        input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
            Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
            it.

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

            [What are input IDs?](../glossary#input-ids)
        attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *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)

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

            If `past_key_values` is used, optionally only the last `decoder_input_ids` have to be input (see
            `past_key_values`).

            If you want to change padding behavior, you should read [`modeling_opt._prepare_decoder_attention_mask`]
            and modify to your needs. See diagram 1 in [the paper](https://arxiv.org/abs/1910.13461) for more
            information on the default strategy.

            - 1 indicates the head is **not masked**,
            - 0 indicates the head is **masked**.
        position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *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)
        past_key_values (`tuple(tuple(torch.FloatTensor))`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`):
            Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of shape
            `(batch_size, num_heads, sequence_length, embed_size_per_head)`) and 2 additional tensors of shape
            `(batch_size, num_heads, encoder_sequence_length, embed_size_per_head)`.

            Contains pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention
            blocks) that can be used (see `past_key_values` input) to speed up sequential decoding.

            If `past_key_values` are used, the user can optionally input only the last `decoder_input_ids` (those that
            don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of all
            `decoder_input_ids` of shape `(batch_size, sequence_length)`.
        inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *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.
        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`).
        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.
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
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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ded
efd            Z xZS )PhimoeModelz
    Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`PhimoeDecoderLayer`]
    Args:
        config: PhimoeConfig
    rS   c                    t                                                     j        | _        j        | _        t          j        j        j        | j                  | _        t          j	        fdt          j                  D                       | _        j        | _        t          j        j        j        d          | _        t#                    | _        d| _        |                                  d S )Nc                 0    g | ]}t          |          S r'   )rE  )r)   r   rS   s     r,   r-   z(PhimoeModel.__init__.<locals>.<listcomp>  s$    dddy	22dddr.   TrG  )rS   F)rZ   r[   pad_token_idre  
vocab_sizer   rd  r   embed_tokensr1  r2  rL   layersrK  rN  rO  normrR   
rotary_embgradient_checkpointing	post_initr_   s    `r,   r[   zPhimoeModel.__init__  s       !. +L):F<NPTP`aamddddE&JbDcDcddd
 
 %+$?!L!39Laefff	/v>>>&+#r.   c                     | j         S rs   rv  r`   s    r,   get_input_embeddingsz PhimoeModel.get_input_embeddings  s      r.   c                     || _         d S rs   r}  r`   values     r,   set_input_embeddingsz PhimoeModel.set_input_embeddings
  s    !r.   N	input_idsr#   r   r]  inputs_embedsr   r   output_hidden_statesrR  return_dictr   r$   c                 N   ||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          }|                     |||||          }|}|                     ||d	         dz   
          }|rdnd }|rdnd }|	rdnd }d }| j        D ]}|r||fz  }| j        r+| j        r$|                     |j        ||||||	|||
  
        }n |||||||	|||	  	        }|d         }|r||rdnd         }|r||d         fz  }|	r||d	         fz  }|                     |          }|r||fz  }|r|nd }|r|                                }|
st;          d |||||fD                       S t=          |||||          S )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   r4   r1   )rk   r'   )r#   r   r   r   rR  r   r   r   r    c              3      K   | ]}||V  	d S rs   r'   )r)   vs     r,   	<genexpr>z&PhimoeModel.forward.<locals>.<genexpr>  s0        =  === r.   )last_hidden_stater]  r   
attentionsr=  )rS   r   rR  r  r   use_return_dictr   rz  r   r   r   r2   r
   r   from_legacy_cacherv  get_seq_lengthr5   re   r=   r4   rA   _update_causal_maskry  rw  _gradient_checkpointing_func__call__rx  to_legacy_cacher3   r   )r`   r  r#   r   r]  r  r   r   r  rR  r  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                           r,   rr   zPhimoeModel.forward  s    2C1N--TXT_Tq$8$D  $+Jj 	 %9$D  $+Jj 	 "+!6IIDK<Q	%0%<kk$+B]-t";< 	s   & 	"4= 	" "##p   "	 $ 
	Z?? 
	"&&"..."."@"Q"Q##^     --i88M!CRC^==???de"\ "2]5H5K"KTaTh  N )33A66L..M>?L]
 
 &"oom^TVEWZ[E[o\\ #7@BBD0:d"6@BBD!![ '	: '	:M# 6!m%55!* t}  $ A A!*! #%("'! ! !.!#.!-#2&7)='#1(;
! 
! 
! *!,M R%28I3P11q%Q"  6=#3"55# :!mB&7%99!		-00   	2-!11+4>''$
 	6#3355J 	  '5FXij     
 &+&+%+
 
 
 	
r.   input_tensorc                    | j         j        dk    r
|d|v r|S d S ||                                nd}t          |t                    }t          |t
                    }| j         j        dk    r0|s.|s,|s*t          j        |||| j         j        | j	                  rd S |j
        |j        }
}	t          j        |	          j        }|j        d         }|s|r|                                }n/t          |t          j                  r|j        d         n||z   dz   }|                     ||||	|
||j        d         | j         |	  	        }| j         j        dk    r)|'|j        j        d	k    r|st          j        ||          }|S )
Nr   r   r   r   )r  past_key_values_lengthr   is_trainingr   r1   )rK   target_lengthrd   r4   r   rJ   rS   r]  r   )rS   rK  r  r2   r   r   r   _ignore_causal_mask_sdpar   r   rd   r4   r5   finfor  r=   get_max_cache_shaper   5_prepare_4d_causal_attention_mask_with_cache_positionrV   _unmask_unattended)r`   r#   r  r   r]  r   r  using_static_cacheusing_sliding_window_cacherd   r4   	min_dtyperK   r  r   s                  r,   r  zPhimoeModel._update_causal_mask  s    ;+/BBB)c^.C.C%%4
 @O?Z?99;;;`a'EE%/AS%T%T" K,66' 7+E 7% 7 &>*'7#{9 M    t$*L,?vK&&*	&,Q/% 	); 	+??AAMM
 nel;;<$R((%7!;  PP+')#)!,;+ Q 

 

 K,66*%*f44% 5 1CKQZ[[Kr.   rK   r  rd   r4   rJ   c	                 \   | |                                  dk    r| }	nt          j        |          j        }
t          j        ||f|
||          }	t          j        ||          |                    dd          k    }|j        Vt          |t                    r||k    r;t          j        ||          |                    dd          |j        z
  k    }||z  }|	|z  }	|	ddddddf         
                    |ddd          }	| |	                                }	| j        d         |k    r| ddd|f         } | 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 )aU  
        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.
            config (`PhimoeConfig`):
                The model's configuration class
            past_key_values (`Cache`):
                The cache class that is being used currently to generate
        N   )
fill_valuerd   r4   r  r1   r   r   )r0   r5   r  r  fullre   r?   r   r2   r   r>   cloner=   r  )r#   rK   r  rd   r4   r   rJ   rS   r]  r   r  diagonal_attend_masksliding_attend_maskmask_lengthpadding_masks                  r,   r  zAPhimoeModel._prepare_4d_causal_attention_mask_with_cache_position  s2   J %.*<*<*>*>!*C*C(KKE**.I* -0Ye\b  K $)<f#M#M#MP^PfPfgiklPmPm#m $0 "/3EFF @/\iJiJi*/,}V*T*T*T&..r1558MM+' ),??(//K%dD!!!QQQ&67>>z1bRTUUK))//11!'+m;;%3AAA~~4E%FN,226*111aaaL[L+@ANSTSTSTVZ\`bcbcbcScDdd+q05@AAAqqq,;,AV5W5c5c )6 6AAAqqq!!!\k\12 r.   )NNNNNNNNNNN)rt   ru   rv   r   r   r[   r  r  r   PHIMOE_INPUTS_DOCSTRINGr5   r   r   r   r   rY  r   r   r   r   rr   r
   r  r  r   rd   r4   r  rw   rx   s   @r,   rq  rq    s{       
 |      "! ! !" " " +*+BCC '+1537=A59$(,0/3/3&*59K
 K
#K
 !.K
 u/0	K

 "$u'8"9:K
   12K
 D>K
 $D>K
 'tnK
 'tnK
 d^K
 !!12K
 
u,,	-K
 K
 K
 DCK
\II lI 	I
 I  I I I IV @@@ @ {	@
 @ @ @ @ @ @ @ \@ @ @ @ @r.   rq  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	 	 	 	 	 	 	 d fd	Z xZS )PhimoeForCausalLMzlm_head.weightc                 Z   t                                          |           t          |          | _        |j        | _        t          j        |j        |j        | j        j	                  | _
        |j        | _        |j        | _        |j        | _        |                                  d S )Nr   )rZ   r[   rq  r\  ru  r   r   r   rS   lm_head_biaslm_headrouter_aux_loss_coefr.  r"   r/  r{  r_   s     r,   r[   zPhimoeForCausalLM.__init__/  s        ((
 +y!3V5FT[Mefff$*$?!!3#)#= r.   c                     | j         j        S rs   r\  rv  r~  s    r,   r  z&PhimoeForCausalLM.get_input_embeddings;      z&&r.   c                     || j         _        d S rs   r  r  s     r,   r  z&PhimoeForCausalLM.set_input_embeddings?      "'
r.   c                     | j         S rs   r  r~  s    r,   get_output_embeddingsz'PhimoeForCausalLM.get_output_embeddingsC  s
    |r.   c                     || _         d S rs   r  )r`   new_embeddingss     r,   set_output_embeddingsz'PhimoeForCausalLM.set_output_embeddingsG  s    %r.   c                     || _         d S rs   r\  )r`   decoders     r,   set_decoderzPhimoeForCausalLM.set_decoderK  s    


r.   c                     | j         S rs   r  r~  s    r,   get_decoderzPhimoeForCausalLM.get_decoderO  s
    zr.   )output_typerh  Nr   r  r#   r   r]  r  labelsr   r   r  rR  r  r   num_logits_to_keepr$   c                 .   |rL| j         j        r@|>|d         | j         j        k    r(t                              d| j         j         d           ||n| j         j        }|
|
n| j         j        }
|	|	n| j         j        }	||n| j         j        }| 	                    ||||||||	|
||          }|d         }| 
                    |dd| dddf                   }d}| | j        ||| j        fi |}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 )	aC  
        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:
        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   r]  r  r   r   r  rR  r  r   r1   r   )lossaux_losslogitsr]  r   r  r=  )rS   r\   rc   r   warningr   rR  r  r  r\  r  loss_functionru  rP   r=  r"   r/  r  r(   r4   r   r]  r   r  )r`   r  r#   r   r]  r  r  r   r   r  rR  r  r   r  loss_kwargsrX  r   r  r  r  outputs                        r,   rr   zPhimoeForCausalLM.forwardR  s\   Z 	(	 *q!T[%QQQNN Mmqmx  nZ  M  M  M   2C1N--TXT_Tq$8$D  $+Jj 	
 %9$D  $+Jj 	 &1%<kk$+B] **)%+'/!5!5#)  
 
  
mAAA0B/B/C/CQQQ,FGHH%4%ffdoUUUUD 	M/)4E%%'"+ (	 H !1HKK4L4LLL 	DY,F# ."v-'+'7D7V##VC(#3!/)!/
 
 
 	
r.   Tc	                     |rD| j         j        r8|j        d         | j         j        dz   k    r|d         }
|
| j         j        k    rd } t	                      j        d||||||||d|	}|S )Nr   r   )r  r]  r#   r  r   r   r   r  r'   )rS   r\   r=   rc   rZ   prepare_inputs_for_generation)r`   r  r]  r#   r  r   r   r   r  rT  past_lengthmodel_inputsra   s               r,   r  z/PhimoeForCausalLM.prepare_inputs_for_generation  s    $ 	'(	' "dk&RUV&VVV(+KdkJJJ"&<uww< 

+)')%1

 

 

 

 r.   )NNNNNNNNNNNNr   )NNNNNTN)rt   ru   rv   _tied_weights_keysr[   r  r  r  r  r  r  r   r  r   r   _CONFIG_FOR_DOCr5   r   r   r   r   rY  r   r   r   r   rr   r  rw   rx   s   @r,   r  r  ,  s>       *+	 	 	 	 	' ' '( ( (  & & &     +*+BCC+DSbccc '+1537=A59-1$(,0/3/3&*59"#l
 l
#l
 !.l
 u/0	l

 "$u'8"9:l
   12l
 )*l
 D>l
 $D>l
 'tnl
 'tnl
 d^l
 !!12l
  l
  
u//	0!l
 l
 l
 dc DCl
d % % % % % % % % % %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).
    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 )PhimoeForSequenceClassificationc                     t                                          |           |j        | _        t          |          | _        t          j        |j        | j        d          | _        | 	                                 d S r   )
rZ   r[   
num_labelsrq  r\  r   r   r   scorer{  r_   s     r,   r[   z(PhimoeForSequenceClassification.__init__  si        + ((
Yv14?OOO
 	r.   c                     | j         j        S rs   r  r~  s    r,   r  z4PhimoeForSequenceClassification.get_input_embeddings  r  r.   c                     || j         _        d S rs   r  r  s     r,   r  z4PhimoeForSequenceClassification.set_input_embeddings  r  r.   Nr  r#   r   r]  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   r]  r  r   r   r  r  r   r   z=Cannot handle batch sizes > 1 if no padding token is defined.r1   r  )r  r  pooled_logitsrS   )r  r  r]  r   r  )rS   r  r\  r  r=   rt  r   r5   eqr   argmaxr(   r4   re   r  r   r]  r   r  )r`   r  r#   r   r]  r  r  r   r   r  r  transformer_outputsr   r  rJ   sequence_lengthsr  r  r  s                      r,   rr   z'PhimoeForSequenceClassification.forward  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)rt   ru   rv   r[   r  r  r   r  r   r5   r   r   r   r
   r   rY  r   r   r   rr   rw   rx   s   @r,   r  r    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  )r[  rq  r  r  )Nr    N)r   )r    )Mr   r   typingr   r   r   r   r5   torch.utils.checkpointr   activationsr	   cache_utilsr
   r   r   r   
generationr   modeling_attn_mask_utilsr   r   modeling_outputsr   r   r   modeling_rope_utilsr   modeling_utilsr   pytorch_utilsr   utilsr   r   r   r   r   utils.import_utilsr   configuration_phimoer   modeling_flash_attention_utilsr   torch.fxfxwrap
get_loggerrt   r   r  r   r   rP   ModulerR   r|   r   r   r   r   r   rJ  r   autogradFunctionr   r)  r+  rE  PHIMOE_START_DOCSTRINGr[  r  rq  r  r  __all__r'   r.   r,   <module>r     s       / / / / / / / / / / / /            ! ! ! ! ! ! O O O O O O O O O O O O ) ) ) ) ) ) a a a a a a a a         
 7 6 6 6 6 6 - - - - - - @ @ @ @ @ @              8 7 7 7 7 7 . . . . . .  KJJJJJJ  Y. (-6W(X(X% 
	H	%	%  "&
-1	O& O&u|U5<%8$>?O&#O& U\*	O&
 5<O& O& O& O&dR R R R RBI R R RD( ( (   :	UU\ 	U# 	U%, 	U 	U 	U 	Uf9 f9 f9 f9 f9bi f9 f9 f9RZ9 Z9 Z9 Z9 Z9O Z9 Z9 Z9zU1 U1 U1 U1 U1/ U1 U1 U1r .  % % % % %ry % % %$;
 ;
 ;
 ;
 ;
%.1 ;
 ;
 ;
|} } } }@E2 E2 E2 E2 E229 E2 E2 E2PR R R R R R R Rj  Z 
? ? ? ? ?O ? ? 
?,D N Z z z z z z' z z	 zz	} } } } }- } } }@ 	  V
 V
 V
 V
 V
&; V
 V
 V
r  r.   