
    Z js                        S SK Jr  S SKJr  S SKrS SKJr  SSK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Jr  SSKJrJr  SSKJr  SSKJrJr  SSKJrJr  SSK J!r!J"r"  SSK#J$r$  SSK%J&r&J'r'J(r(J)r)  SSK*J+r+J,r,  SSK-J.r.J/r/  SSK0J1r1   " S S\Rd                  5      r3\" S5       " S S\Rd                  5      5       r4 " S S\Rd                  5      r5 " S S\Rd                  5      r6\ " S S \Rd                  5      5       r7 " S! S"\Rd                  5      r8S# r9\" S$5      S>S% j5       r:S&\Rv                  S'\<S(\Rv                  4S) jr= S?S*\Rd                  S+\Rv                  S,\Rv                  S-\Rv                  S.\Rv                  S-  S/\>S0\>S1\$\&   4S2 jjr?\" \:5       " S3 S4\Rd                  5      5       r@ " S5 S6\5      rA " S7 S8\"5      rB\' " S9 S:\B5      5       rC\' " S; S<\B\5      5       rD/ S=QrEg)@    )Callable)OptionalN)nn   )initialization)ACT2FN)CacheDynamicCache)GenerationMixin)use_experts_implementationuse_kernel_forward_from_hubuse_kernel_func_from_hubuse_kernelized_func)create_causal_mask!create_sliding_window_causal_mask)GradientCheckpointingLayer)MoeCausalLMOutputWithPastMoeModelOutputWithPast)ROPE_INIT_FUNCTIONSdynamic_rope_update)ALL_ATTENTION_FUNCTIONSPreTrainedModel)Unpack)TransformersKwargsauto_docstringcan_return_tupleis_grouped_mm_available)maybe_autocastmerge_with_config_defaults)OutputRecordercapture_outputs   )AfmoeConfigc                      ^  \ rS rSr% \R
                  \S'   SS\4U 4S jjjr\	   SS\S-  S\
S   S\S-  S	\S
\4   4S jj5       r\R                  " 5       \S 5       5       rSrU =r$ )AfmoeRotaryEmbedding1   inv_freqNconfigc                   > [         TU ]  5         UR                  U l        UR                  U l        Xl        U R
                  R                  S   U l        U R                  nU R                  S:w  a  [        U R                     nU" U R
                  U5      u  o@l
        U R                  SUSS9  U R                  SUR                  5       SS9  g )N	rope_typedefaultr'   F)
persistentoriginal_inv_freq)super__init__max_position_embeddingsmax_seq_len_cachedoriginal_max_seq_lenr(   rope_parametersr*   compute_default_rope_parametersr   attention_scalingregister_bufferclone)selfr(   devicerope_init_fnr'   	__class__s        y/root/GenerationalWealth/GenerationalWealth/venv/lib/python3.13/site-packages/transformers/models/afmoe/modeling_afmoe.pyr/   AfmoeRotaryEmbedding.__init__4   s    "("@"@$*$B$B!44[A!%!E!E>>Y&.t~~>L+7V+L((ZeD0(..2BuU    r9   ztorch.deviceseq_lenreturnztorch.Tensorc           	         U R                   S   n[        U SS5      =(       d    U R                  U R                  -  nSnSU[        R
                  " SUS[        R                  S9R                  U[        R                  S9U-  -  -  nXe4$ )	aH  
Computes the inverse frequencies according to the original RoPE implementation
Args:
    config ([`~transformers.PreTrainedConfig`]):
        The model configuration.
    device (`torch.device`):
        The device to use for initialization of the inverse frequencies.
    seq_len (`int`, *optional*):
        The current sequence length. Unused for this type of RoPE.
Returns:
    Tuple of (`torch.Tensor`, `float`), containing the inverse frequencies for the RoPE embeddings and the
    post-processing scaling factor applied to the computed cos/sin (unused in this type of RoPE).

rope_thetahead_dimNg      ?r      dtype)r9   rF   )	r3   getattrhidden_sizenum_attention_headstorcharangeint64tofloat)r(   r9   r?   basedimattention_factorr'   s          r<   r4   4AfmoeRotaryEmbedding.compute_default_rope_parametersD   s    & %%l3fj$/c63E3EIcIc3c U\\!S!5;;?BB&X]XcXcBdgjjk
 ))r>   c                 L   U R                   S S S 2S 4   R                  5       R                  UR                  S   SS5      R	                  UR
                  5      nUS S 2S S S 24   R                  5       n[        UR
                  R                  [        5      (       a0  UR
                  R                  S:w  a  UR
                  R                  OSn[        USS9   UR                  5       UR                  5       -  R                  SS5      n[        R                  " Xf4SS	9nUR                  5       U R                  -  nUR                  5       U R                  -  n	S S S 5        WR	                  UR                   S
9W	R	                  UR                   S
94$ ! , (       d  f       N@= f)Nr   r"   mpscpuF)device_typeenabledrD   rP   rE   )r'   rN   expandshaperM   r9   
isinstancetypestrr   	transposerJ   catcosr5   sinrF   )
r8   xposition_idsinv_freq_expandedposition_ids_expandedrW   freqsembra   rb   s
             r<   forwardAfmoeRotaryEmbedding.forwardb   sN    !MM$4-8>>@GGHZHZ[\H]_acdehhijiqiqr ,QaZ 8 > > @'1!((--'E'E!((--[`J`ahhmmfkUC&,,.1F1L1L1NNYYZ[]^_E))UN3C'')d444C'')d444C	 D vvAGGv$cff177f&;;; DCs   BF
F#)r5   r(   r1   r2   r*   N)NNN)__name__
__module____qualname____firstlineno__rJ   Tensor__annotations__r#   r/   staticmethodr   inttuplerN   r4   no_gradr   ri   __static_attributes____classcell__r;   s   @r<   r%   r%   1   s    llV{ V V  %)+/"*d"*(* t* 
~u$	%	* *: ]]_<  <r>   r%   RMSNormc                   `   ^  \ rS rSrS	S\SS4U 4S jjjrS\R                  4S jrS r	Sr
U =r$ )
AfmoeRMSNormr   epsr@   Nc                    > [         TU ]  5         [        R                  " [        R
                  " U5      5      U l        X l        g)z+
AfmoeRMSNorm is equivalent to T5LayerNorm
N)r.   r/   r   	ParameterrJ   onesweightvariance_epsilon)r8   rH   r}   r;   s      r<   r/   AfmoeRMSNorm.__init__t   s/     	ll5::k#:; #r>   c                    UR                   nUR                  [        R                  5      nUR	                  S5      R                  SSS9nU[        R                  " X0R                  -   5      -  nU R                  U-  R                  U5      $ )NrD   rT   T)keepdim)	rF   rM   rJ   float32powmeanrsqrtr   r   )r8   hidden_statesinput_dtypevariances       r<   ri   AfmoeRMSNorm.forward|   sw    #))%((7 $$Q',,R,>%H?T?T4T(UUm+//<<r>   c                 ^    [        U R                  R                  5       SU R                   3$ )Nz, eps=)rt   r   r[   r   )r8   s    r<   
extra_reprAfmoeRMSNorm.extra_repr   s*    ))*+6$2G2G1HIIr>   )r   r   )gư>)rl   rm   rn   ro   rN   r/   rJ   rp   ri   r   rv   rw   rx   s   @r<   r{   r{   r   s7    $ $$ $ $= =J Jr>   r{   c                   2   ^  \ rS rSrSU 4S jjrS rSrU =r$ )AfmoeMLP   c                   > [         TU ]  5         Xl        UR                  U l        Uc  UR                  OU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 NFbias)r.   r/   r(   rH   intermediate_sizer   Linear	gate_projup_proj	down_projr   
hidden_actact_fn)r8   r(   r   r;   s      r<   r/   AfmoeMLP.__init__   s    !--=N=V!9!9\m4#3#3T5K5KRWXyy!1!143I3IPUV4#9#94;K;KRWXV../r>   c                     U R                  U R                  U R                  U5      5      U R                  U5      -  5      nU$ rk   )r   r   r   r   )r8   rc   r   s      r<   ri   AfmoeMLP.forward   s6    NN4;;t~~a/@#ADLLQRO#ST	r>   )r   r(   r   r   rH   r   r   rk   )rl   rm   rn   ro   r/   ri   rv   rw   rx   s   @r<   r   r      s    0 r>   r   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
$ )AfmoeTokenChoiceRouter   z
Token-choice top-K router for MoE routing.

This router assigns each token to the top-K experts based on sigmoid scores, matching the released checkpoints.
c                    > [         TU ]  5         Xl        UR                  U l        UR
                  U l        UR                  U l        [        R                  " UR                  UR
                  SS9U l
        g r   )r.   r/   r(   num_experts_per_toktop_knum_expertsroute_scaler   r   rH   gater8   r(   r;   s     r<   r/   AfmoeTokenChoiceRouter.__init__   s\    //
!--!--IIf00&2D2D5Q	r>   r   expert_biasc                    UR                   u    p4UR                  SU5      nU R                  U5      R                  [        R
                  5      n[        R                  " U5      n[        R                  " Xb-   U R                  SS9u  p7UR                  SUS9nUR                  SSS9S-   n	X-  nXR                  -  nXXU4$ )NrT   r"   )krP   )rP   indexT)rP   r   g#B;)r[   viewr   rM   rJ   r   sigmoidtopkr   gathersumr   )
r8   r   r   _
hidden_dimrouter_logitsscoresselected_experts
top_scoresdenominators
             r<   ri   AfmoeTokenChoiceRouter.forward   s    (..1%**2z:		-033EMMB}-#jj)=QRS]]q0@]A
 nnTn:UB-
"2"22
*:::r>   )r(   r   r   r   r   rl   rm   rn   ro   __doc__r/   rJ   rp   ri   rv   rw   rx   s   @r<   r   r      s.    R;U\\ ; ; ;r>   r   c                      ^  \ rS rSrSrU 4S jrS\R                  S\R                  S\R                  S\R                  4S jrS	r	U =r
$ )
AfmoeExperts   z2Collection of expert weights stored as 3D tensors.c                   > [         TU ]  5         UR                  U l        UR                  U l        UR
                  U l        [        R                  " [        R                  " U R                  SU R                  -  U R                  5      5      U l        [        R                  " [        R                  " U R                  U R                  U R                  5      5      U l        [        UR                     U l        g )NrD   )r.   r/   r   rH   r   moe_intermediate_sizeintermediate_dimr   r   rJ   emptygate_up_projr   r   r   r   r   s     r<   r/   AfmoeExperts.__init__   s    !-- ,, & < <LLT5E5Eq4K`K`G`bfbqbq)rsekk$2B2BDOOUYUjUj&klV../r>   r   top_k_indextop_k_weightsr@   c                 X   [         R                  " U5      n[         R                  " 5          [         R                  R                  R                  X R                  S9nUR                  SSS5      n[         R                  " UR                  SS9S5      R                  5       nS S S 5        W H  nUS   nXpR                  :X  a  M  [         R                  " WU   5      u  pX   n
[        R                  R                  XR                  U   5      R                  SSS9u  pU R                  U5      U-  n[        R                  R                  XR                   U   5      nXXS 4   -  nUR#                  SXR%                  UR&                  5      5        M     U$ ! , (       d  f       N= f)N)num_classesrD   r"   r   )rT   rY   rT   )rJ   
zeros_likeru   r   
functionalone_hotr   permutegreaterr   nonzerowherelinearr   chunkr   r   
index_add_rM   rF   )r8   r   r   r   final_hidden_statesexpert_mask
expert_hit
expert_idx	top_k_pos	token_idxcurrent_stater   upcurrent_hidden_statess                 r<   ri   AfmoeExperts.forward   so    $..}=]]_((--55kO_O_5`K%--aA6K{8'DaHPPRJ 
 %J#AJ---#(;;{:/F#G I)4M}}++M;L;LZ;XY__`agi_jHD$(KK$5$:!$&MM$8$89NP^P^_iPj$k!$9)`dJd<e$e!**1i9Q9QReRkRk9lm % #"# _s   A7F
F))r   r   r   r   r   r   r   rx   s   @r<   r   r      sK    <0#||# \\# ||	#
 
# #r>   r   c                   2   ^  \ rS rSrSrU 4S jrS rSrU =r$ )AfmoeSparseMoeBlock   z
Mixture of Experts (MoE) module for AFMoE.

This module implements a sparse MoE layer with both shared experts (always active) and
routed experts (activated based on token-choice routing).
c                 ,  > [         TU ]  5         Xl        [        U5      U l        [        XR                  UR                  -  5      U l        [        U5      U l
        [        R                  " [        R                  " UR                  5      SS9U l        g )NF)requires_grad)r.   r/   r(   r   routerr   r   num_shared_expertsshared_expertsr   expertsr   r   rJ   zerosr   r   r   s     r<   r/   AfmoeSparseMoeBlock.__init__   sl    ,V4&v/K/KfNgNg/gh#F+<<F4F4F(GW\]r>   c                    UR                   u  p#nUR                  SU5      nU R                  XR                  5      u  pgnU R	                  U5      R                  X#U5      n	U R                  XXU5      R                  X#U5      n
X-   $ )NrT   )r[   r   r   r   r   r   )r8   r   
batch_sizer?   r   hidden_states_flatr   r   r   shared_outputrouted_outputs              r<   ri   AfmoeSparseMoeBlock.forward   s    *7*=*='
Z*//J? 7;kk-QaQa6b3#3 ++,>?DDZZde%7:V[[
 ,,r>   )r(   r   r   r   r   )	rl   rm   rn   ro   r   r/   ri   rv   rw   rx   s   @r<   r   r      s    ^- -r>   r   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..NrT   rD   rY   )r[   rJ   r`   )rc   x1x2s      r<   rotate_halfr      sZ    	
3"!''"+"""	#B	
3q ""	#B99rc2YB''r>   rotary_pos_embc                     UR                  U5      nUR                  U5      nX-  [        U 5      U-  -   nX-  [        U5      U-  -   nXV4$ )aI  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.
    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.
)	unsqueezer   )qr   ra   rb   unsqueeze_dimq_embedk_embeds          r<   apply_rotary_pos_embr     sS    & --
&C
--
&Cw;q>C/0Gw;q>C/0Gr>   r   n_repr@   c                     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)r[   rZ   reshape)r   r   batchnum_key_value_headsslenrC   s         r<   	repeat_kvr    s_    
 2?1D1D.Ez!!Qa"23::5W\dlmM  e(CTTTr>   modulequerykeyvalueattention_maskscalingdropoutkwargsc                    [        X R                  5      n[        X0R                  5      n	[        R                  " XR	                  SS5      5      U-  n
Ub  X-   n
[
        R                  R                  U
S[        R                  S9R                  UR                  5      n
[
        R                  R                  XU R                  S9n
[        R                  " X5      nUR	                  SS5      R                  5       nX4$ )NrD   r   rT   )rP   rF   )ptrainingr"   )r  num_key_value_groupsrJ   matmulr_   r   r   softmaxr   rM   rF   r  r  
contiguous)r  r  r  r	  r
  r  r  r  
key_statesvalue_statesattn_weightsattn_outputs               r<   eager_attention_forwardr  )  s     3 ; ;<JU$?$?@L<<';';Aq'ABWLL!#4==((2U]](SVVW\WbWbcL==((6??([L,,|:K''1-88:K$$r>   c                      ^  \ rS rSrSrS\S\4U 4S jjr SS\R                  S\
\R                  \R                  4   S	\R                  S-  S
\S-  S\\   S\
\R                  \R                  4   4S jjrSrU =r$ )AfmoeAttentioniB  a6  
Multi-headed attention module with optional sliding window and gating.

This attention mechanism supports both full attention and sliding window attention,
and includes Q/K normalization and gating of the output. It inherits from [`LlamaAttention`] to minimize the amount
of custom logic we need to maintain.
r(   	layer_idxc                   > [         TU ]  5         Xl        X l        [	        USUR
                  UR                  -  5      U l        UR                  UR                  -  U l	        U R                  S-  U l
        UR                  U l        SU l        [        R                  " UR
                  UR                  U R                  -  UR                  S9U l        [        R                  " UR
                  UR                  U R                  -  UR                  S9U l        [        R                  " UR
                  UR                  U R                  -  UR                  S9U l        [        R                  " UR                  U R                  -  UR
                  UR                  S9U l        UR(                  U   S:H  U l        U R*                  (       a  UR,                  OS U l        [/        U R                  UR0                  S9U l        [/        U R                  UR0                  S9U l        [        R                  " UR
                  UR                  U R                  -  SS9U l        g )NrC   g      Tr   sliding_attentionr}   F)r.   r/   r(   r  rG   rH   rI   rC   r  r  r  attention_dropout	is_causalr   r   attention_biasq_projk_projv_projo_projlayer_typesis_local_attentionsliding_windowr{   rms_norm_epsq_normk_normr   r8   r(   r  r;   s      r<   r/   AfmoeAttention.__init__L  s   "
F4F4F&JdJd4de$*$>$>&B\B\$\!}}d*!'!9!9ii : :T]] JQWQfQf
 ii : :T]] JQWQfQf
 ii : :T]] JQWQfQf
 ii&&68J8JQWQfQf

 #)"4"4Y"?CV"V7;7N7Nf33TX"4==f6I6IJ"4==f6I6IJ6#5#5v7Q7QTXTaTa7ahmnr>   Nr   position_embeddingsr
  past_key_valuer  r@   c                    UR                   S S n/ UQSPU R                  P7nU R                  U5      R                  U5      nU R	                  U5      R                  U5      n	U R                  U5      R                  U5      n
U R                  U5      nU R                  U5      R                  SS5      nU R                  U	5      R                  SS5      n	U
R                  SS5      n
U R                  (       a  Uu  p[        XX5      u  pUb  UR                  XU R                  5      u  p[        R                  " U R                   R"                  [$        5      nU" U UU	U
4UU R&                  (       d  SOU R(                  U R*                  U R,                  S.UD6u  nnUR                  " / UQSP76 R/                  5       nU[0        R2                  " U5      -  nU R5                  U5      nUU4$ )NrT   r"   rD           )r
  r  r  r)  )r[   rC   r#  r   r$  r%  r   r+  r_   r,  r(  r   updater  r   get_interfacer(   _attn_implementationr  r  r   r  r)  r  rJ   r   r&  )r8   r   r/  r
  r0  r  input_shapehidden_shapequery_statesr  r  gate_statesra   rb   attention_interfaceoutputr  r  s                     r<   ri   AfmoeAttention.forwardk  s    $))#2.88b8$--8{{=166|D[[/44\B
{{=166|Dnn]3{{<0::1a@[[,66q!<
#--a3""*HC';LVY'_$L%'5'<'<ZW[WeWe'f$J(?(M(MKK,,.E)
  3	
 

 *#}}C$2H2HLL..
 
 
 
 .k.2.99;%--44kk&)L((r>   )r   r(   r   rC   r!  r(  r,  r$  r  r  r&  r+  r#  r  r)  r%  rk   )rl   rm   rn   ro   r   r#   rs   r/   rJ   rp   rt   r	   r   r   ri   rv   rw   rx   s   @r<   r  r  B  s    o{ os oH (,.)||.) #5<<#=>.) t+	.)
 .) +,.) 
u||U\\)	*.) .)r>   r  c                     ^  \ rS rSrSrS\S\4U 4S jjr     SS\R                  S\R                  S-  S	\R                  S-  S
\S-  S\S-  S\\R                  \R                  4   S-  S\\   S\R                   4S jjrSrU =r$ )AfmoeDecoderLayeri  z
AFMoE decoder layer with dual normalization.

This layer applies self-attention followed by either a dense MLP or MoE block,
with dual normalization (pre and post) around each component.
r(   r  c                   > [         TU ]  5         UR                  U l        X l        [	        XS9U l        [        UR                  UR                  S9U l        [        UR                  UR                  S9U l	        [        UR                  UR                  S9U l
        [        UR                  UR                  S9U l        X!R                  :  U l        U R                  (       a  [        U5      U l        g [!        U5      U l        g )N)r(   r  r  )r.   r/   rH   r  r  	self_attnr{   r*  input_layernormpost_attention_layernormpre_mlp_layernormpost_mlp_layernormnum_dense_layersmoe_enabledr   mlpr   r-  s      r<   r/   AfmoeDecoderLayer.__init__  s    !--"'vK  ,F,>,>FDWDWX(4V5G5GVM`M`(a% ".f.@.@fFYFY!Z".v/A/AvGZGZ"[ %(?(??*62DH'DHr>   Nr   r
  rd   r0  	use_cacher/  r  r@   c           
          UnU R                  U5      nU R                  " SUUUUUUS.UD6u  pU R                  U5      nX-   nUnU R                  U5      nU R	                  U5      nU R                  U5      nX-   nU$ )N)r   r
  rd   r0  rI  r/   )rA  r@  rB  rC  rG  rD  )
r8   r   r
  rd   r0  rI  r/  r  residualr   s
             r<   ri   AfmoeDecoderLayer.forward  s     ! ,,];>> 
')%) 3
 
 55mD 0 !..}=///> 0r>   )	rH   rA  r  rG  rF  rB  rD  rC  r@  )NNNNN)rl   rm   rn   ro   r   r#   rs   r/   rJ   rp   
LongTensorr	   boolrt   r   r   FloatTensorri   rv   rw   rx   s   @r<   r>  r>    s    ({ (s (2 /304'+!%HL!||! t+! &&-	!
 ! $;! #5<<#=>E! +,! 
		! !r>   r>  c                      ^  \ rS rSr% Sr\\S'   SrS/rS/r	\
" \SS9\\S	.r/ S
QrSrSrSr\" 5       rSrSrU 4S jrSrU =r$ )AfmoePreTrainedModeli  zz
An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
models.
r(   modelr>  past_key_valuesr   )r   )r   r   
attentions)rA  rB  rC  rD  r+  r,  normr   Tc                   > [         TU ]  U5        U R                  R                  n[	        U[
        5      (       aA  [        R                  " UR                  SUS9  [        R                  " UR                  SUS9  g[	        U[        5      (       a+  [        R                  " UR                  R                  5        g[	        U[        5      (       a!  [        R                  " UR                  5        gg)zInitialize the weightsr2  )r   stdN)r.   _init_weightsr(   initializer_ranger\   r   initnormal_r   r   r   zeros_r   r   r   r   )r8   r  rX  r;   s      r<   rY  "AfmoePreTrainedModel._init_weights   s    f%kk++fl++LL,,3C@LL))= 677KK**+ 344KK**+ 5r>   rK  )rl   rm   rn   ro   r   r#   rq   base_model_prefix_no_split_modules_skip_keys_device_placementr    r   r>  r  _can_record_outputs_keep_in_fp32_modules_supports_sdpa_supports_flash_attn_supports_flex_attnr   _can_compile_fullgraph_supports_attention_backendsupports_gradient_checkpointingrY  rv   rw   rx   s   @r<   rR  rR    s    
 ,-#4"5'(>aH*$
	 N!  #'&*#
, 
,r>   rR  c                     ^  \ rS rSrSrS\4U 4S jjr\\\	      SS\
R                  S-  S\
R                  S-  S\
R                  S-  S	\
R                  S-  S
\S-  S\S-  S\\   S\\-  4S jj5       5       5       rSrU =r$ )
AfmoeModeli  z
Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`AfmoeDecoderLayer`]

Args:
    config: AfmoeConfig
r(   c           	        > [         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R                  S9U l        [#        US9U l        SU l        U R)                  5         g s  snf )Nr  r(   F)r.   r/   pad_token_idpadding_idx
vocab_sizer   	EmbeddingrH   embed_tokens
ModuleListrangenum_hidden_layersr>  layersr{   r*  rV  r%   
rotary_embgradient_checkpointing	post_initr-  s      r<   r/   AfmoeModel.__init__  s     !.. ++LL):):F<N<NPTP`P`ammCHIaIaCbcCbiv1Cbc
 !!3!39L9LM	.f=&+# ds   C?N	input_idsr
  inputs_embedsrd   rT  rI  r  r@   c           
      .   US L US L-  (       a  [        S5      eU(       a  Uc  [        U R                  S9nUc  U R                  U5      nUcU  Ub  UR	                  5       OSn[
        R                  " UR                  S   UR                  S9U-   nUR                  S5      n[        U=n	[        5      (       d(  U R                  UUUS.n
[        S0 U
D6[        S0 U
D6S.n	UnU R                  R                  (       a  XR                  R                  S-  -  nU R!                  X5      n[#        U R$                  5       H-  u  pU" U4XR                  R&                  U      UUUUS	.UD6nM/     U R)                  U5      n[+        UU(       a  US
9$ S S
9$ )Nz:You must specify exactly one of input_ids or inputs_embedsrm  r   r"   )r9   )r(   r|  r
  rT  )full_attentionr  g      ?)r
  rd   r0  rI  r/  )last_hidden_staterT  rK  )
ValueErrorr
   r(   rr  get_seq_lengthrJ   rK   r[   r9   r   r\   dictr   r   mup_enabledrH   rw  	enumeraterv  r'  rV  r   )r8   r{  r
  r|  rd   rT  rI  r  past_seen_tokenscausal_mask_mappingmask_kwargsr   r/  idecoder_layers                  r<   ri   AfmoeModel.forward%  s    -t";<YZZ0*$++>O  --i8MCRC^==?de <<(;(;A(>}G[G[\_ooL'11!4L ?-FF++!."0#2	K #5"C{"C%F%U%U#
 & ;;"")[[-D-Dc-IJM"oomJ )$++ 6A)2;;3J3J13MN).#$7 M !7 		-0%+/8O
 	
>B
 	
r>   )rr  rx  rv  rV  ro  rw  rp  )NNNNNN)rl   rm   rn   ro   r   r#   r/   r   r   r!   rJ   rN  rp   rP  r	   rO  r   r   rt   r   ri   rv   rw   rx   s   @r<   rk  rk    s    {   .2.22604(,!%<
##d*<
 t+<
 ((4/	<

 &&-<
 <
 $;<
 +,<
 
'	'<
    <
r>   rk  c                   \  ^  \ rS rSrSS0rSS0rSS/S/40rU 4S jr\\	         SS
\
R                  S	-  S\
R                  S	-  S\
R                  S	-  S\S	-  S\
R                  S	-  S\
R                  S	-  S\S	-  S\S	-  S\\
R                  -  S\\   S\4S jj5       5       rSrU =r$ )AfmoeForCausalLMig  zlm_head.weightzmodel.embed_tokens.weightlm_headcolwise_gather_outputr   logitsc                    > [         TU ]  U5        [        U5      U l        UR                  U l        [
        R                  " UR                  UR                  SS9U l        U R                  5         g r   )
r.   r/   rk  rS  rp  r   r   rH   r  ry  r   s     r<   r/   AfmoeForCausalLM.__init__m  sS     '
 ++yy!3!3V5F5FUSr>   Nr{  r
  rd   rT  r|  labelsrI  output_router_logitslogits_to_keepr  r@   c
                    Ub  UOU R                   R                  nU R                  " SUUUUUUUS.U
D6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                  " XU R                  40 U
D6n[        UUUR                  UR                  UR                  UR                  S9$ )ao  
Example:

```python
>>> from transformers import AutoTokenizer, AfmoeForCausalLM

>>> model = AfmoeForCausalLM.from_pretrained("meta-afmoe/Afmoe-2-7b-hf")
>>> tokenizer = AutoTokenizer.from_pretrained("meta-afmoe/Afmoe-2-7b-hf")

>>> 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."
```N)r{  r
  rd   rT  r|  rI  r  )lossr  rT  r   rU  r   rK  )r(   r  rS  r  r\   rs   slicer  loss_functionrp  r   rT  r   rU  r   )r8   r{  r
  rd   rT  r|  r  rI  r  r  r  outputsr   slice_indicesr  r  s                   r<   ri   AfmoeForCausalLM.forwardt  s    B %9$D $++JjJj 	 +/** 	+
)%+'!5	+
 	+
  118B>SV8W8W~ot4]kmA}a,?@A%%fdooPPD(#33!//))!//
 	
r>   )r  rS  rp  )	NNNNNNNNr   )rl   rm   rn   ro   _tied_weights_keys_tp_plan_pp_planr/   r   r   rJ   rN  rp   r	   rP  rO  rs   r   r   r   ri   rv   rw   rx   s   @r<   r  r  g  s(   *,GH23H_-z:;H  .2.204(,26*.!%,0-.<
##d*<
 t+<
 &&-	<

 <
 ((4/<
   4'<
 $;<
 #Tk<
 ell*<
 +,<
 
#<
  <
r>   r  )r  rk  rR  )r"   )r2  )Fcollections.abcr   typingr   rJ   r    r   r[  activationsr   cache_utilsr	   r
   
generationr   integrationsr   r   r   r   masking_utilsr   r   modeling_layersr   modeling_outputsr   r   modeling_rope_utilsr   r   modeling_utilsr   r   processing_utilsr   utilsr   r   r   r   utils.genericr   r   utils.output_capturingr    r!   configuration_afmoer#   Moduler%   r{   r   r   r   r   r   r   rp   rs   r  rN   r  r  r>  rR  rk  r  __all__rK  r>   r<   <module>r     s  * %    & ! . )  S 9 Q K F & b b G E ,><299 ><B Y'J299 J (J(ryy  ;RYY ;< $#299 $# $#N-")) ->( *+ ,2	UU\\ 	U# 	U%,, 	U& %II%<<% 
% <<	%
 LL4'% % % '(%2 )*V)RYY V) +V)r?2 ?D,,? ,,^ V
% V
 V
r J
+_ J
 J
Z Er>   