
    ^jC                     d   d Z ddlmZ ddlZddlmZ ddlmZ ddlm	Z	m
Z
 ddlmZ dd	lmZmZ dd
lmZ ddlmZmZ ddlmZmZ ddlmZ ddlmZmZmZmZ ddlm Z  ddl!m"Z"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-m.Z. ddl/m0Z0  ejb                  e2      Z3 G d de)      Z4 G d de%      Z5 G d de.      Z6 G d dejn                        Z8 G d d e-      Z9 G d! d"ejn                        Z: G d# d$e'      Z; G d% d&e      Z< G d' d(e      Z=e G d) d*e=             Z> G d+ d,e(e=e      Z?g d-Z@y).zPyTorch AFMoE model.    )CallableN)nn   )initialization)CacheDynamicCache)GenerationMixin)create_causal_mask!create_sliding_window_causal_mask)GradientCheckpointingLayer)MoeCausalLMOutputWithPastMoeModelOutputWithPast)ALL_ATTENTION_FUNCTIONSPreTrainedModel)Unpack)TransformersKwargsauto_docstringcan_return_tuplelogging)merge_with_config_defaults)OutputRecordercapture_outputs   )GptOssRMSNorm)LlamaAttentionLlamaForCausalLMLlamaRotaryEmbeddingapply_rotary_pos_embeager_attention_forward)Qwen2MoeExpertsQwen2MoeMLP   )AfmoeConfigc                       e Zd Zy)AfmoeRotaryEmbeddingN__name__
__module____qualname__     r/var/www/ramen.bs-engineer-server.com/venv/lib/python3.12/site-packages/transformers/models/afmoe/modular_afmoe.pyr%   r%   /       r+   r%   c                       e Zd Zy)AfmoeRMSNormNr&   r*   r+   r,   r/   r/   3   r-   r+   r/   c                       e Zd Zy)AfmoeMLPNr&   r*   r+   r,   r1   r1   7   r-   r+   r1   c                   Z     e Zd ZdZ fdZdej                  dej                  fdZ xZS )AfmoeTokenChoiceRouterz
    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         |           || _        |j                  | _        |j
                  | _        |j                  | _        t        j                  |j                  |j
                  d      | _
        y NFbias)super__init__confignum_experts_per_toktop_knum_expertsroute_scaler   Linearhidden_sizegateselfr:   	__class__s     r,   r9   zAfmoeTokenChoiceRouter.__init__B   s^    //
!--!--IIf00&2D2D5Q	r+   hidden_statesexpert_biasc                    |j                   \  }}}|j                  d|      }| j                  |      j                  t        j
                        }t	        j                  |      }t	        j                  ||z   | j                  d      \  }}|j                  d|      }|j                  dd      dz   }	||	z  }|| j                  z  }|||fS )Nr"   )kdim)rJ   indexT)rJ   keepdimg#B;)shapeviewrA   totorchfloat32sigmoidtopkr<   gathersumr>   )
rC   rE   rF   _
hidden_dimrouter_logitsscoresselected_experts
top_scoresdenominators
             r,   forwardzAfmoeTokenChoiceRouter.forwardJ   s    (..1j%**2z:		-033EMMB}-#jj+)=QRS]]q0@]A
 nnTn:UB+-
$"2"22
j*:::r+   )	r'   r(   r)   __doc__r9   rP   Tensorr]   __classcell__rD   s   @r,   r3   r3   ;   s)    R;U\\ ; ;r+   r3   c                       e Zd Zy)AfmoeExpertsNr&   r*   r+   r,   rc   rc   Y   r-   r+   rc   c                   (     e Zd ZdZ fdZd Z xZS )AfmoeSparseMoeBlockz
    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                 2   t         |           || _        t        |      | _        t        ||j                  |j                  z        | _        t        |      | _
        t        j                  t        j                  |j                        d      | _        y )NF)requires_grad)r8   r9   r:   r3   routerr1   moe_intermediate_sizenum_shared_expertsshared_expertsrc   expertsr   	ParameterrP   zerosr=   rF   rB   s     r,   r9   zAfmoeSparseMoeBlock.__init__e   sp    ,V4&vv/K/KfNgNg/gh#F+<<F4F4F(GW\]r+   c                    |j                   \  }}}|j                  d|      }| j                  || j                        \  }}}| j	                  |      j                  |||      }	| j                  |||      j                  |||      }
|	|
z   S )NrH   )rM   rN   rh   rF   rk   rl   )rC   rE   
batch_sizeseq_lenrW   hidden_states_flatrV   r[   rZ   shared_outputrouted_outputs              r,   r]   zAfmoeSparseMoeBlock.forwardm   s    *7*=*='
GZ*//J? +/++mTEUEU*V':' ++,>?DDZQXZde%79I:V[[
 },,r+   )r'   r(   r)   r^   r9   r]   r`   ra   s   @r,   re   re   ]   s    ^-r+   re   c                        e Zd ZdZdedef fdZ	 ddej                  de	ej                  ej                  f   dej                  dz  d	e
dz  d
ee   de	ej                  ej                  f   fdZ xZS )AfmoeAttentionaJ  
    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         |   ||       |j                  |   dk(  | _        | j                  r|j                  nd | _        t        | j                  |j                        | _        t        | j                  |j                        | _	        t        j                  |j                  |j                  | j                  z  d      | _        y )Nsliding_attentionepsFr6   )r8   r9   layer_typesis_local_attentionsliding_windowr/   head_dimrms_norm_epsq_normk_normr   r?   r@   num_attention_heads	gate_projrC   r:   rw   rD   s      r,   r9   zAfmoeAttention.__init__   s    + #)"4"4Y"?CV"V7;7N7Nf33TX"4==f6I6IJ"4==f6I6IJ6#5#5v7Q7QTXTaTa7ahmnr+   NrE   position_embeddingsattention_maskpast_key_valuekwargsreturnc                    |j                   d d }g |d| j                  }| j                  |      j                  |      }| j	                  |      j                  |      }	| j                  |      j                  |      }
| j                  |      }| j                  |      j                  dd      }| j                  |	      j                  dd      }	|
j                  dd      }
| j                  r|\  }}t        ||	||      \  }}	| |j                  |	|
| j                        \  }	}
t        j                  | j                   j"                  t$              } || ||	|
f|| j&                  sdn| j(                  | j*                  | j,                  d|\  }} |j                  g |d j/                         }|t1        j2                  |      z  }| j5                  |      }||fS )NrH   r"   r           )r   dropoutscalingr~   )rM   r   q_projrN   k_projv_projr   r   	transposer   r}   r   updaterw   r   get_interfacer:   _attn_implementationr   trainingattention_dropoutr   r~   
contiguousrP   rR   o_proj)rC   rE   r   r   r   r   input_shapehidden_shapequery_states
key_statesvalue_statesgate_statescossinattention_interfaceoutputattn_weightsattn_outputs                     r,   r]   zAfmoeAttention.forward   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';L*VY[^'_$L*%'5'<'<ZW[WeWe'f$J(?(M(MKK,,.E)
  3	
 

 *#}}C$2H2HLL..
 
 
 
 .k.2.99;%--44kk&)L((r+   )N)r'   r(   r)   r^   r#   intr9   rP   r_   tupler   r   r   r]   r`   ra   s   @r,   rv   rv   |   s    	o{ 	os 	o  (,.)||.) #5<<#=>.) t+	.)
 .) +,.) 
u||U\\)	*.)r+   rv   c                       e Zd ZdZdedef fdZ	 	 	 	 	 ddej                  dej                  dz  dej                  dz  d	e
dz  d
edz  deej                  ej                  f   dz  dee   dej                  fdZ xZS )AfmoeDecoderLayerz
    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:   rw   c                 (   t         |           |j                  | _        || _        t	        ||      | _        t        |j                  |j                        | _        t        |j                  |j                        | _	        t        |j                  |j                        | _
        t        |j                  |j                        | _        ||j                  k\  | _        | j                  rt        |      | _        y t!        |      | _        y )N)r:   rw   rz   )r8   r9   r@   rw   rv   	self_attnr/   r   input_layernormpost_attention_layernormpre_mlp_layernormpost_mlp_layernormnum_dense_layersmoe_enabledre   mlpr1   r   s      r,   r9   zAfmoeDecoderLayer.__init__   s    !--"'vK  ,F,>,>FDWDWX(4V5G5GVM`M`(a% ".f.@.@fFYFY!Z".v/A/AvGZGZ"[ %(?(??*62DH'DHr+   NrE   r   position_idsr   	use_cacher   r   r   c           
         |}| j                  |      } | j                  d||||||d|\  }}	| j                  |      }||z   }|}| j                  |      }| j	                  |      }| j                  |      }||z   }|S )N)rE   r   r   r   r   r   r*   )r   r   r   r   r   r   )
rC   rE   r   r   r   r   r   r   residualrV   s
             r,   r]   zAfmoeDecoderLayer.forward   s     ! ,,];)4>> 
')%) 3
 
q 55mD =0 !..}=///> =0r+   )NNNNN)r'   r(   r)   r^   r#   r   r9   rP   r_   
LongTensorr   boolr   r   r   FloatTensorr]   r`   ra   s   @r,   r   r      s    ({ (s (2 /304'+!%HL!||! t+! &&-	!
 ! $;! #5<<#=>E! +,! 
		!r+   r   c                   z     e Zd ZU dZeed<   dZdgZdgZ e	e
d      eedZg d	Zd
Zd
Zd
Zd
Zd
Zd
Z fdZ xZS )AfmoePreTrainedModelz
    An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
    models.
    r:   modelr   past_key_valuesr   )rK   )rX   rE   
attentions)r   r   r   r   r   r   normrF   Tc                    t         |   |       | j                  j                  }t	        |t
              rEt        j                  |j                  d|       t        j                  |j                  d|       yt	        |t              r*t        j                  |j                  j                         yt	        |t              r t        j                  |j                         yy)zInitialize the weightsr   )meanstdN)r8   _init_weightsr:   initializer_range
isinstancerc   initnormal_gate_up_proj	down_projr3   zeros_rA   weightre   rF   )rC   moduler   rD   s      r,   r   z"AfmoePreTrainedModel._init_weights#  s    f%kk++fl+LL,,3C@LL))= 67KK**+ 34KK**+ 5r+   )r'   r(   r)   r^   r#   __annotations__base_model_prefix_no_split_modules_skip_keys_device_placementr   r3   r   rv   _can_record_outputs_keep_in_fp32_modules_supports_sdpa_supports_flash_attn_supports_flex_attn_can_compile_fullgraph_supports_attention_backendsupports_gradient_checkpointingr   r`   ra   s   @r,   r   r     sx    
 ,-#4"5'(>aH*$
	 N!"&&*#
, 
,r+   r   c                        e Zd ZdZdef fdZeee	 	 	 	 	 	 dde	j                  dz  de	j                  dz  de	j                  dz  de	j                  dz  d	edz  d
edz  dee   deez  fd                     Z xZS )
AfmoeModelz
    Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`AfmoeDecoderLayer`]

    Args:
        config: AfmoeConfig
    r:   c           	         t         |   |       |j                  | _        |j                  | _        t        j                  |j                  |j                  | j                        | _        t        j                  t        |j                        D cg c]  }t        ||       c}      | _        t        |j                  |j                        | _        t#        |      | _        d| _        | j)                          y c c}w )Nrz   r:   F)r8   r9   pad_token_idpadding_idx
vocab_sizer   	Embeddingr@   embed_tokens
ModuleListrangenum_hidden_layersr   layersr/   r   r   r%   
rotary_embgradient_checkpointing	post_initr   s      r,   r9   zAfmoeModel.__init__9  s     !.. ++LL):):F<N<NPTP`P`ammCHIaIaCbcivy1c
 !!3!39L9LM	.f=&+# ds   DN	input_idsr   inputs_embedsr   r   r   r   r   c           
         |d u |d uz  rt        d      |r|t        | j                        }|| j                  |      }|V||j	                         nd}t        j                  |j                  d   |j                        |z   }|j                  d      }t        |x}	t              s(| j                  |||d}
t        di |
t        di |
d}	|}| j                  j                  r|| j                  j                  dz  z  }| j!                  ||      }t#        | j$                        D ].  \  }} ||f|	| j                  j&                  |      ||||d	|}0 | j)                  |      }t+        ||r|
      S d 
      S )Nz:You must specify exactly one of input_ids or inputs_embedsr   r   r"   )device)r:   r   r   r   )full_attentionry   g      ?)r   r   r   r   r   )last_hidden_stater   r*   )
ValueErrorr   r:   r   get_seq_lengthrP   arangerM   r   	unsqueezer   dictr
   r   mup_enabledr@   r   	enumerater   r|   r   r   )rC   r   r   r   r   r   r   r   past_seen_tokenscausal_mask_mappingmask_kwargsrE   r   idecoder_layers                  r,   r]   zAfmoeModel.forwardH  s    -t";<YZZ0*$++>O  --i8MCRC^==?de <<(;(;A(>}G[G[\_ooL'11!4L ?-F++!."0#2	K #5"C{"C%F%U%U#
 & ;;"")T[[-D-Dc-IJM"oom\J )$++ 6 		A})24;;3J3J13MN).#$7 M		 		-0%+/8O
 	
>B
 	
r+   )NNNNNN)r'   r(   r)   r^   r#   r9   r   r   r   rP   r   r_   r   r   r   r   r   r   r   r]   r`   ra   s   @r,   r   r   0  s    {   .2.22604(,!%<
##d*<
 t+<
 ((4/	<

 &&-<
 <
 $;<
 +,<
 
'	'<
    <
r+   r   c                   B   e Zd ZddiZddiZddgdgfiZd Zee	 	 	 	 	 	 	 	 	 dd	e	j                  dz  d
e	j                  dz  de	j                  dz  dedz  de	j                  dz  de	j                  dz  dedz  dedz  dee	j                  z  dee   defd              Zy)AfmoeForCausalLMzlm_head.weightzmodel.embed_tokens.weightlm_headcolwise_gather_outputrE   logitsc                     t         j                  | |       t        |      | _        |j                  | _        t        j                  |j                  |j                  d      | _        | j                          y r5   )
r   r9   r   r   r   r   r?   r@   r   r   )rC   r:   s     r,   r9   zAfmoeForCausalLM.__init__  sU    %%dF3'
 ++yy!3!3V5F5FUSr+   Nr   r   r   r   r   labelsr   output_router_logitslogits_to_keepr   r   c
                    ||n| j                   j                  } | j                  d|||||||d|
}|j                  }t	        |	t
              rt        |	 d       n|	}| j                  |d d |d d f         }d }| | j                  ||| j                  fi |
}t        |||j                  |j                  |j                  |j                        S )N)r   r   r   r   r   r   r  )lossr   r   rE   r   rX   r*   )r:   r  r   r   r   r   slicer   loss_functionr   r   r   rE   r   rX   )rC   r   r   r   r   r   r  r   r  r  r   outputsrE   slice_indicesr   r  s                   r,   r]   zAfmoeForCausalLM.forward  s      %9$D $++JjJj 	 +5$** 	+
)%+'!5	+
 	+
  118B>SV8W~ot4]kmA}a,?@A%4%%ffdooPPD(#33!//))!//
 	
r+   )	NNNNNNNNr   )r'   r(   r)   _tied_weights_keys_tp_plan_pp_planr9   r   r   rP   r   r_   r   r   r   r   r   r   r   r]   r*   r+   r,   r   r     s'   *,GH23H_-z:;H  .2.204(,26*.!%,0-.+
##d*+
 t++
 &&-	+

 +
 ((4/+
   4'+
 $;+
 #Tk+
 ell*+
 +,+
 
#+
  +
r+   r   )r   r   r   )Ar^   collections.abcr   rP   r    r   r   cache_utilsr   r   
generationr	   masking_utilsr
   r   modeling_layersr   modeling_outputsr   r   modeling_utilsr   r   processing_utilsr   utilsr   r   r   r   utils.genericr   utils.output_capturingr   r   gpt_oss.modeling_gpt_ossr   llama.modeling_llamar   r   r   r   r   qwen2_moe.modeling_qwen2_moer    r!   configuration_afmoer#   
get_loggerr'   loggerr%   r/   r1   Moduler3   rc   re   rv   r   r   r   r   __all__r*   r+   r,   <module>r!     s    $   & . ) R 9 Q F & R R 7 E 4  H , 
		H	%	/ 		= 		{ 	;RYY ;<	? 	-")) ->B)^ B)J?2 ?D*,? *,Z V
% V
 V
r9
')= 9
xr+   