+
    "Ý³jæ}  ã                   ó  € R t ^ RIHt ^ RIt^ RIHt ^ RIHt ^ RIHtH	t	 ^ RI
HtHt ^ RIHtHt ^ RIHt ]! ]4      t ^ R	IHt R
tRtRtRRR
R^RRR./RRR
R^/RRR
R^/RRRR^//t ! R R]P6                  4      tR R ltR R ltR R ltR R lt R R  lt!R! R" lt"R# R$ lt#R% R& lt$R' R( lt%R) R* lt&R+ R, lt'R- R. lt(R/ R0 lt)R1 R2 lt*R3 R4 lt+R5 R6 lt,R;R7 R8 llt-]R3R9 R: llt.R#   ] d    RtRt L¸i ; i)<a—  
Custom experts implementation for transformers' MOE integration.

This module provides a `linear_loop` experts implementation that uses
individual nn.Linear layers per expert instead of fused 3D Parameters.
This enables proper quantization of MOE expert weights.

The implementation integrates with transformers' `use_experts_implementation`
decorator and `ALL_EXPERTS_FUNCTIONS` registry.

Usage:

    from auto_round.modeling.fused_moe.moe_experts_interface import prepare_model_for_moe_quantization
    # Before quantization
    prepare_model_for_moe_quantization(model)

    # Now the model uses linear_loop forward which supports quantized nn.Linear layers
)Ú
MethodTypeN)ÚLogBar)Únn)ÚMODEL_CONFIGÚPATCH)Úcompile_module_name_filterÚmatches_module_name_filter)Úclear_memoryÚto_meta)ÚDEBUG_ON)ÚALL_EXPERTS_FUNCTIONSTFÚlinear_loopÚbatched_inputÚgate_up_projÚis_input_projÚoutput_multiplierÚ
split_intoÚ	gate_projÚup_projÚ	down_projc                   ó   € ] tR t^EtRtRtR# )Ú_ExpertContaineraŒ  Lightweight container for a single expert's projection layers.

Each expert has its projections (e.g., gate_proj, up_proj, down_proj)
as direct attributes. When attached as numbered children of the experts
module (e.g., module.add_module("0", container)), PyTorch naturally
produces state_dict keys like: {prefix}0.gate_proj.weight
which matches the standard checkpoint format without any hooks.
© N)Ú__name__Ú
__module__Ú__qualname__Ú__firstlineno__Ú__doc__Ú__static_attributes__r   ó    Úg/home/luca/screen-checking/.venv/lib/python3.14/site-packages/defuser/modeling/moe_experts_interface.pyr   r   E   s   † ñó 	r   r   c                ó$   € V ^8„  d   QhR\         /# ©é   Úreturn©Úbool)Úformats   "r    Ú__annotate__r(   R   s   € ÷ !ñ !¤$ñ !r   c                 ó   € \         # )z9Check if linear_loop experts implementation is available.)ÚHAS_EXPERTS_INTERFACEr   r   r    Úis_linear_loop_availabler+   R   s   € ä Ð r   c                ó¦   € V ^8„  d   QhR\         P                  R\        P                  R,          R\        P                  R\        P                  /# )r#   ÚmoduleÚgate_outNÚup_outr$   ©r   ÚModuleÚtorchÚTensor)r'   s   "r    r(   r(   W   sE   € ÷ %ñ %Ü�I‰Ið%ä�l‰l˜TÕ!ð%ô �L‰Lð%ô ‡\�\ñ	%r   c                óx  € Vf<   \        V RR4      pVf#   \        V P                  P                   R24      hV! V4      # \	        V R4      '       d)   V P                  \        P                  ! W.RR7      4      # \        V RR4      pVf#   \        V P                  P                   R24      hV! V4      V,          # )zEApply the expert activation path for gated and non-gated expert MLPs.NÚact_fnz, must define `act_fn` for non-gated experts.Ú_apply_gate©Údimz. must define either `_apply_gate` or `act_fn`.éÿÿÿÿ)ÚgetattrÚAttributeErrorÚ	__class__r   Úhasattrr6   r2   Úcat)r-   r.   r/   r5   s   &&& r    Ú_apply_expert_gater?   W   s¶   € ð ÒÜ˜ ¨4Ó0ˆØŠ>Ü  F×$4Ñ$4×$=Ñ$=Ð#>Ð>jÐ!kÓlÐlÙ�f‹~Ðäˆv�}×%Ò%Ø×!Ñ!¤%§)¢)¨XÐ,>ÀBÔ"GÓHÐHä�V˜X tÓ,€FØ‚~Ü × 0Ñ 0× 9Ñ 9Ð:Ð:hÐiÓjÐjÙ�(Ó˜fÕ$Ð$r   c          
      ó¸   € V ^8„  d   QhR\         P                  R\        P                  R\        P                  R\        P                  R\        P                  /# )r#   ÚselfÚhidden_statesÚtop_k_indexÚtop_k_weightsr$   r0   )r'   s   "r    r(   r(   l   sU   € ÷ `ñ `Ü�i‰ið`ä—|‘|ð`ô —\‘\ð`ô —|‘|ð	`ô
 ‡\�\ñ`r   c                óÆ  € \         '       d4   \        P                  R\         RV P                  P
                   24       VP                  4       ^8X  de   VP                  w  rEpVP                  RV4      pVP                  RVP                  R4      4      pVP                  RVP                  R4      4      pMRRrTVP                  R4      pVP                  pVP                  R4      pVP                  ^ 4      p	V P                  p
\        P                  ! W—R7      P                  ^4      P                  RV4      P!                  R4      pVP!                  R4      P#                  VP$                  4      pVP!                  R4      pW,          p\        P&                  ! VP                  ^ 4      WgVP$                  R7      p\)        V
4       FÂ  pVV8H  pVP+                  4       '       g   K   VV,          p\-        V \/        V4      4      p\1        VR4      '       d$   VP3                  V4      pVP5                  V4      pMRpVP5                  V4      p\7        V VV4      pVP9                  V4      pVP#                  VP$                  4      VV&   KÄ  	  WüP                  R4      ,          pVP                  W˜V4      P;                  ^R7      pVe   VP                  WEV4      pV# )	a[  Forward using individual nn.Linear layers per expert.

This implementation loops over experts and accesses per-expert containers
(self._modules["0"], self._modules["1"], ...) each with gate_proj,
up_proj, and down_proj as nn.Linear layers (or quantized equivalents),
enabling proper quantization support.

Expected module structure:
    - Numbered children (0, 1, ..., num_experts-1), each an _ExpertContainer with:
        - gate_proj: nn.Linear (in_features=hidden_dim, out_features=intermediate_dim)
        - up_proj: nn.Linear (in_features=hidden_dim, out_features=intermediate_dim)
        - down_proj: nn.Linear (in_features=intermediate_dim, out_features=hidden_dim)
    - act_fn: activation function
    - num_experts: number of experts
    - _apply_gate: optional custom gating function

Args:
    self: The experts module
    hidden_states: Input tensor of shape (num_tokens, hidden_dim)
    top_k_index: Selected expert indices of shape (num_tokens, top_k)
    top_k_weights: Expert weights of shape (num_tokens, top_k)

Returns:
    final_hidden_states: Output tensor of shape (num_tokens, hidden_dim)
úUsing ú experts forward for N)Údevice©rH   Údtyper   r7   r9   )r   ÚloggerÚdebugÚLINEAR_LOOP_IMPLr<   r   r8   ÚshapeÚviewÚsizerH   Únum_expertsr2   ÚarangeÚ	unsqueezeÚexpandÚreshapeÚtorJ   ÚzerosÚrangeÚanyr:   Ústrr=   r   r   r?   r   Úsum)rA   rB   rC   rD   Ú
batch_sizeÚseq_lenÚ
hidden_dimrH   Ú	num_top_kÚ
num_tokensrQ   Ú	token_idxÚsample_weightsÚ
expert_idsÚselected_hidden_statesÚout_per_sampleÚ
expert_idxÚmaskÚexpert_inputÚexpertr.   r/   Ú	gated_outÚ
expert_outÚfinal_hidden_statess   &&&&                     r    Úlinear_loop_experts_forwardrm   l   s˜  € ÷> ƒx”—‘ Ô'7Ð&8Ð8MÈdÏnÉn×NeÑNeÐMfÐgÔhð ×ÑÓ˜aÔØ*7×*=Ñ*=Ñ'ˆ
˜ZØ%×*Ñ*¨2¨zÓ:ˆØ!×&Ñ& r¨;×+;Ñ+;¸BÓ+?Ó@ˆØ%×*Ñ*¨2¨}×/AÑ/AÀ"Ó/EÓF‰à" D�GØ"×'Ñ'¨Ó+ˆ
à×!Ñ!€FØ× Ñ  Ó$€IØ×#Ñ# AÓ&€JØ×"Ñ"€Kô —’˜ZÔ7×AÑAÀ!ÓD×KÑKÈBÐPYÓZ×bÑbÐceÓf€IØ"×*Ñ*¨2Ó.×1Ñ1°-×2EÑ2EÓF€NØ×$Ñ$ RÓ(€Jð +Õ5Ðô —[’[ §¡°Ó!2°JÐUb×UhÑUhÔi€Nô ˜KÖ(ˆ
à˜ZÑ'ˆØ�x‰x�zŠzÙà-¨dÕ3ˆô ˜œs :›Ó/ˆÜ�6˜;×'Ò'Ø×'Ñ'¨Ó5ˆHØ—^‘^ LÓ1‰FàˆHØ—^‘^ LÓ1ˆFÜ& t¨X°vÓ>ˆ	ð ×%Ñ% iÓ0ˆ
ð  *Ÿ}™}¨^×-AÑ-AÓBˆ�tÓñ- )ð2 $×&>Ñ&>¸rÓ&BÕB€Nð )×-Ñ-¨jÀZÓP×TÑTÐYZÐTÓ[Ðð ÒØ1×6Ñ6°zÈJÓWÐàÐr   c                óx   € V ^8„  d   QhR\         P                  R\        P                  R\        P                  /# )r#   rA   rB   r$   r0   )r'   s   "r    r(   r(   Ï   s5   € ÷ Fñ F¬¯	©	ð FÄ%Ç,Á,ð FÔSX×S_ÑS_ñ Fr   c                ó>  € \         '       d4   \        P                  R\         RV P                  P
                   24       VP                  R4      pVP                  V P                  RV4      p. p\        V P                  4       Fn  p\        V \        V4      4      pW5,          pVP                  V4      pVP                  V4      p	\        WV	4      p
VP                  VP!                  V
4      4       Kp  	  \"        P$                  ! V^ R7      P'                  RV4      # )a…  Run defused experts for models that feed experts as expert-major input batches.

Llama4 is the current example: upstream code repeats and pre-weights tokens,
then calls ``experts(hidden_states)`` where the leading dimension is laid out
as ``[expert0_tokens, expert1_tokens, ...]``. This forward keeps that public
contract while still executing per-expert ``nn.Linear`` modules internally.
rF   rG   r7   r9   )r   rK   rL   ÚBATCHED_INPUT_IMPLr<   r   rP   rO   rQ   rX   r:   rZ   r   r   r?   Úappendr   r2   ÚstackrU   )rA   rB   r^   Úexpert_inputsÚexpert_outputsrf   ri   rh   r.   r/   rj   s   &&         r    Úbatched_input_experts_forwardru   Ï   sñ   € ÷ ƒx”—‘ Ô'9Ð&:Ð:OÐPT×P^ÑP^×PgÑPgÐOhÐiÔjà×#Ñ# BÓ'€JØ!×&Ñ& t×'7Ñ'7¸¸ZÓH€MØ€Nä˜D×,Ñ,Ö-ˆ
Ü˜œs :›Ó/ˆØ$Õ0ˆØ×#Ñ# LÓ1ˆØ—‘ Ó-ˆÜ& t°vÓ>ˆ	Ø×Ñ˜f×.Ñ.¨yÓ9Ö:ñ .ô �;Š;�~¨1Ô-×5Ñ5°b¸*ÓEÐEr   c                ó$   € V ^8„  d   QhR\         /# r"   r%   )r'   s   "r    r(   r(   è   s   € ÷ ñ ¤dñ r   c                 ó  € \         '       g   \        P                  R4       R# \        \        P
                  9  dE   \        \        P
                  \        &   \        '       d   \        P                  R\         R24       R# )z‡Register the linear_loop experts implementation with transformers.

Returns:
    True if registration was successful, False otherwise.
z”transformers.integrations.moe.ALL_EXPERTS_FUNCTIONS not available. linear_loop experts implementation not registered. Requires transformers >= 5.0.0FzRegistered 'z' experts implementationT)	r*   rK   ÚwarnrM   r   Ú_global_mappingrm   r   rL   r   r   r    Úregister_linear_loop_expertsrz   è   s`   € ÷ !Ó Ü�‰ð-ô	
ñ
 äÔ4×DÑDÔDÜB]Ô×-Ñ-Ô.>Ñ?ß‹8”V—\‘\ LÔ1AÐ0BÐBZÐ"[Ô\ár   c                óZ   € V ^8„  d   QhR\         P                  R\        \        ,          /# )r#   Úmodelr$   ©r   r1   ÚlistÚdict)r'   s   "r    r(   r(   ý   s"   € ÷ 
ñ 
¤r§y¡yð 
´T¼$µZñ 
r   c                óô   € \        V RR4      p\        VRR4      pVf   . # \        P                  ! V/ 4      P                  \        P                  . 4      p\        V\        4      '       d   V.# \        V4      # )zEReturn declarative experts-defusion specs for the current model type.ÚconfigNÚ
model_type)r:   r   Úgetr   ÚEXPERTS_DEFUSEÚ
isinstancer   r~   )r|   r�   r‚   Úspecss   &   r    Ú_model_experts_defuse_specsr‡   ý   sl   € ä�U˜H dÓ+€FÜ˜ ¨tÓ4€JØÒØˆ	ä×Ò˜Z¨Ó,×0Ñ0´×1EÑ1EÀrÓJ€EÜ�%œ×ÒØˆwˆÜ�‹;Ðr   c                óD   € V ^8„  d   QhR\         P                  R\        /# ©r#   r-   r$   ©r   r1   rZ   )r'   s   "r    r(   r(   
  s"   € ÷ Hñ HœrŸy™yð H¬Sñ Hr   c                ó`   € V P                   P                   RV P                   P                   2# )zAReturn a stable import-style class path for matching model specs.Ú.)r<   r   r   )r-   s   &r    Ú_module_class_pathr�   
  s-   € à×Ñ×)Ñ)Ð*¨!¨F×,<Ñ,<×,EÑ,EÐ+FÐGÐGr   c                ót   € V ^8„  d   QhR\         P                  R\        \        ,          R\        R,          /# )r#   r-   r†   r$   Nr}   )r'   s   "r    r(   r(     s.   € ÷ 	ñ 	¬"¯)©)ð 	¼DÄ½Jð 	Ì4ÐRVÍ;ñ 	r   c                ó”   € \        V 4      pV P                  P                  pV F   pVP                  R4      pWRV09   g   K  Vu # 	  R# )zIFind the first declarative experts-defusion spec that matches ``module``.Úmodule_classN)r�   r<   r   rƒ   )r-   r†   Úmodule_pathÚmodule_nameÚspecÚtargets   &&    r    Ú_matching_experts_defuse_specr•     sJ   € ä$ VÓ,€KØ×"Ñ"×+Ñ+€KãˆØ—‘˜.Ó)ˆØ ;Ð/Ö/ØŠKñ ñ r   c                óH   € V ^8„  d   QhR\         P                  R\        RR/# )r#   r-   Úimplementationr$   NrŠ   )r'   s   "r    r(   r(     s*   € ÷ 
Vñ 
V¤b§i¡ið 
VÄð 
VÈñ 
Vr   c                ó¦   € V\         8X  d   \        \        V 4      V n        R# V\        8X  d   \        \
        V 4      V n        R# \        RV 24      h)zGAttach a generic forward implementation directly to one experts module.Nz,Unsupported experts forward implementation: )rM   r   rm   Úforwardrp   ru   Ú
ValueError)r-   r—   s   &&r    Ú_install_instance_forwardr›     sL   € àÔ)Ô)Ü#Ô$?ÀÓHˆŒÙàÔ+Ô+Ü#Ô$AÀ6ÓJˆŒÙä
ÐCÀNÐCSÐTÓ
UÐUr   c                óf   € V ^8„  d   QhR\         P                  R\        \        \        3,          /# r‰   )r   r1   r   rZ   )r'   s   "r    r(   r(   (  s&   € ÷ %ñ %¤r§y¡yð %´T¼#¼t¸)µ_ñ %r   c           
     óˆ  € / pV P                   V P                  3 UUUu/ uF@  pVP                  4        F)  w  r4\        V\        P
                  4      '       g   K'  W4bK+  	  KB  	  pppp\        P                  4        F7  w  rgVP                  V4      pVf   K  VP                  4       ^8X  g   K3  WqV&   K9  	  V'       g|   VP                  4        Fg  w  r˜V	P                  R4      '       d   K  Vf   K$  VP                  4       ^8X  g   K;  \        '       d   \        P                  RV	 24       RRR^/W&   Ki  	  V# u upppi )ax  Detect which expert projections exist in the module.

This function scans the module for any registered 3D Parameter / Tensor
attributes. It first checks known projection names, then discovers any
unknown 3D registered tensors.

Returns:
    Dict mapping projection names to their config, only for projections that exist
    as 3D registered Parameter / Tensor in the module.
Ú_z"Discovered unknown 3D projection: r   Tr   )Ú_parametersÚ_buffersÚitemsr…   r2   r3   ÚKNOWN_PROJECTION_PATTERNSrƒ   r8   Ú
startswithr   rK   rL   )
r-   ÚdetectedÚregistryÚnameÚtensorÚlocal_tensorsÚ	proj_namer�   ÚparamÚ	attr_names
   &         r    Ú_detect_expert_projectionsr¬   (  s  € ð €Hð
  ×+Ñ+¨V¯_©_Ñ=õá=ˆHØ$ŸN™NÖ,‰LˆDÜ�fœeŸl™l×+ô 	ˆŠá,ñ 	Ù=ð ò ô 7×<Ñ<Ö>Ñˆ	Ø×!Ñ! )Ó,ˆØÔ §¡£°Ö!1Ø"(�YÓñ ?÷ Ø -× 3Ñ 3Ö 5ÑˆIØ×#Ñ# C×(Ò(ÙØÔ  U§Y¡Y£[°AÖ%5ç“8œVŸ\™\Ð,NÈyÈkÐ*ZÔ[Ø'6¸Ð>QÐSTÐ&U�Ó#ñ !6ð €Oùô/s   Ÿ7D=Á
D=c                ór   € V ^8„  d   QhR\         P                  R\        R\        P                  R,          /# )r#   r-   r¦   r$   N©r   r1   rZ   r2   r3   )r'   s   "r    r(   r(   P  s.   € ÷ ñ ¤2§9¡9ð ´Cð ¼E¿L¹LÈ4Õ<Oñ r   c                óú   € V P                   P                  V4      p\        V\        P                  4      '       d   V# V P
                  P                  V4      p\        V\        P                  4      '       d   V# R# )zKReturn a direct registered parameter or buffer without touching properties.N)rŸ   rƒ   r…   r2   r3   r    )r-   r¦   r§   s   && r    Ú_get_registered_tensorr°   P  s]   € ð ×Ñ×#Ñ# DÓ)€FÜ�&œ%Ÿ,™,×'Ò'Øˆà�_‰_× Ñ  Ó&€FÜ�&œ%Ÿ,™,×'Ò'Øˆár   c          
      óˆ   € V ^8„  d   QhR\         P                  R\        R\        P                  R\        P                  RR/# )r#   r-   r¦   r§   Úsourcer$   Nr®   )r'   s   "r    r(   r(   ^  s?   € ÷ -ñ -¬¯	©	ð -¼ð -ÄeÇlÁlð -Ô\a×\hÑ\hð -Ðmqñ -r   c                óÎ   € \        V\        P                  4      '       d4   V P                  V\        P                  ! W#P                  R7      4       R# V P                  W4       R# )zJRegister ``tensor`` using the same parameter-vs-buffer kind as ``source``.©Úrequires_gradN)r…   r   Ú	ParameterÚregister_parameterrµ   Úregister_buffer)r-   r¦   r§   r²   s   &&&&r    Ú_set_registered_tensor_liker¹   ^  sB   € ô �&œ"Ÿ,™,×'Ò'Ø×!Ñ! $¬¯ª°V×K_ÑK_Ô(`Öaà×Ñ˜tÖ,r   c                óD   € V ^8„  d   QhR\         P                  R\        /# r‰   )r   r1   r&   )r'   s   "r    r(   r(   g  s   € ÷ 
2ñ 
2¬¯	©	ð 
2´dñ 
2r   c                óT   € \        V P                  RR4      pVf   R# \        VR4      # )zÐCheck if experts module supports @use_experts_implementation decorator.

Only experts classes decorated with @use_experts_implementation will use
our linear_loop forward. Others need full module replacement.
r™   NFÚ__wrapped__)r:   r<   r=   )r-   Úforward_methods   & r    Ú_experts_supports_decoratorr¾   g  s.   € ô ˜V×-Ñ-¨y¸$Ó?€NØÒÙä�> =Ó1Ð1r   c          
      ó~   € V ^8„  d   QhR\         P                  R\        R\        R\        \
        \
        3,          /# )r#   rª   r�   Úis_transposedr$   )r2   r3   r   r&   ÚtupleÚint)r'   s   "r    r(   r(   t  s9   € ÷ %ñ %œUŸ\™\ð %´4ð %Ìð %ÔQVÔWZÔ\_ÐW_ÕQ`ñ %r   c                ó¼   € V P                   ^,          V P                   ^,          rCVP                  R^4      pV'       d   Y4rvMY4rgV^8”  d   Wu,          V,          pWg3# )a8  Infer input and output dimensions for a projection.

Args:
    param: The 3D projection tensor (num_experts, dim1, dim2)
    config: Projection config with is_input_proj and output_multiplier
    is_transposed: Whether weights are stored transposed

Returns:
    (in_features, out_features) for the Linear layer
r   )rN   rƒ   )rª   r�   rÀ   Údim1Údim2Ú
multiplierÚin_featuresÚout_featuress   &&&     r    Ú_infer_dimensionsrÉ   t  sZ   € ð —‘˜Q• §¡¨Q¥ˆ$Ø—‘Ð/°Ó3€Jçà$(‘\ð %)�kð �A„~Ø#Õ1°JÕ>ˆàÐ$Ð$r   c                ó¶   € V ^8„  d   QhR\         P                  R\        R\        R\        R\
        P                  R\
        P                  R\        R,          /# )	r#   r-   r©   rQ   rÀ   rJ   Útarget_devicer$   N)	r   r1   rZ   rÂ   r&   r2   rJ   rH   r~   )r'   s   "r    r(   r(   �  sg   € ÷ eñ eÜ—	‘	ðeäðeô ðeô ð	eô
 �{‰{ðeô —|‘|ðeô 
ˆD…[ñer   c           	     ó>  € \        W4      pVe   VP                  4       ^8w  d   R# \        P                  VRRR^/4      p\	        WgV4      w  r‰V R2p
\        W
4      p\        V\        P                  4      pVP                  pVP                  R8H  p\        V\        P                  4      '       d   VP                  MRpV'       EgW   VP                  4       P                  4       pV'       d   VP                  ^^4      pVP!                  4       '       g   VP#                  4       pVP%                  ^ 4      pV'       d„   VP                  4       P                  4       pVP!                  4       '       g   VP#                  4       pVP%                  ^ 4      p\        V\        P                  4      '       d   VP                  MRp \'        W\)        V4      4       RpV'       d   \'        W
\)        V4      4       Rp\*        '       d   \,        P/                  RV R	24       . p\3        V4       FÚ  p\        P4                  ! W‰WÄRR
7      pV'       g¦   XV,          pVP                  R8w  d   VP7                  WTR7      p\        P                  ! VVR7      Vn        V'       dU   XV,          pVP                  R8w  d   VP7                  VVP:                  R7      p\        P                  ! VXR7      Vn        VP?                  V4       KÜ  	  V#   \0         d     Lúi ; i)að  Unfuse a single projection from a 3D registered tensor to Linear layers.

Optimized to keep peak device memory low while preserving the module's
original device placement:
- Moves the full 3D tensor to CPU in a single transfer
- Performs batch transpose on CPU if needed
- Releases the original fused parameter before allocating defused linears
- Re-materializes each expert linear back onto ``target_device``

Args:
    module: The experts module
    proj_name: Name of the projection attribute
    num_experts: Number of experts
    is_transposed: Whether weights are stored transposed
    dtype: Data type for the Linear layers
    target_device: Device for the Linear layers

Returns:
    List of Linear layers, or None if projection doesn't exist
Nr   Tr   Ú_biasÚmetaFzReleased memory for z using to_meta())ÚbiasrJ   rH   ÚcpurI   r´   ) r°   r8   r¢   rƒ   rÉ   r…   r2   r3   rH   Útyper   r¶   rµ   ÚdetachrÐ   Ú	transposeÚis_contiguousÚ
contiguousÚunbindÚsetattrr
   r   rK   rL   Ú	ExceptionrX   ÚLinearrV   ÚweightrJ   rÏ   rq   )r-   r©   rQ   rÀ   rJ   rË   rª   r�   rÇ   rÈ   Ú	bias_nameÚ
bias_paramÚhas_biasÚsource_deviceÚis_metaÚweight_requires_gradÚweights_cpuÚweight_slicesÚbias_cpuÚbias_slicesÚbias_requires_gradÚlinearsÚiÚlinearrÚ   rÏ   s   &&&&&&                    r    Ú_unfuse_single_projectionré   �  s”  € ô8 # 6Ó5€EØ‚}˜Ÿ	™	› qÔ(Ùô '×*Ñ*¨9°ÈÐNaÐcdÐ6eÓf€Fô !2°%ÀÓ OÑ€Kð �+˜UÐ#€IÜ'¨Ó:€JÜ˜*¤e§l¡lÓ3€Hà—L‘L€MØ× Ñ  FÑ*€GÜ2<¸UÄBÇLÁL×2QÒ2Q˜5×.Ò.ÐW\Ð÷ ˆ7à—l‘l“n×(Ñ(Ó*ˆßà%×/Ñ/°°1Ó5ˆKð ×(Ñ(×*Ò*Ø%×0Ñ0Ó2ˆKà#×*Ñ*¨1Ó-ˆçØ!×(Ñ(Ó*×.Ñ.Ó0ˆHà×)Ñ)×+Ò+Ø#×.Ñ.Ó0�Ø"Ÿ/™/¨!Ó,ˆKÜ=GÈ
ÔTV×T`ÑT`×=aÒ=a ×!9Ò!9ÐglÐð	Ü�F¤w¨u£~Ô6ØˆEßÜ˜¬7°:Ó+>Ô?Ø!�
ß‹xœŸ™Ð(<¸Y¸KÐGWÐ&XÔYð
 €GÜ�;Öˆä—’˜;¸8ÐY_Ô`ˆçØ" 1Õ%ˆFØ×!Ñ! UÔ*ØŸ™¨-˜ÓE�ÜŸLšL¨Ð?SÔTˆFŒMßØ" 1•~�Ø ×%Ñ%¨Ô.ØŸ7™7¨-¸t¿z¹z˜7ÓJ�DÜ Ÿlšl¨4Ð?QÔR�”à�‰�vÖñ  ð" €Nøô- ô 	Ùð	ús   ÇAL ÈL ÌLÌLc                ó<   € V ^8„  d   QhR\         P                  RR/# )r#   r-   r$   N)r   r1   )r'   s   "r    r(   r(   ø  s"   € ÷ Qñ Q¬¯©ð Q°tñ Qr   c                ó  a€ V P                   pRVP                  9   d   R# VP                  oV3R lpW!n        RVn        \	        VR4      '       d   RVP                  9  d   R pR pR pW1n        WAn        WQn        R# R# )	a8  Install compact __repr__ on the module's class.

Collapses identical _ExpertContainer children into a range display,
similar to nn.ModuleList::

    GptOssExperts(
      (0-63): 64 x _ExpertContainer(
        (gate_proj): Linear(...)
        (up_proj): Linear(...)
        (down_proj): Linear(...)
      )
    )
Ú_compact_expert_repr_installedNc           
      óˆ  <€ ^ RI Hp . p. pV P                  P                  4        FA  w  rE\	        V\
        4      '       d   VP                  WE34       K/  VP                  WE34       KC  	  V'       g	   S! V 4      # . pV P                  4       pV'       d!   VP                  VP                  R4      4       V F0  w  rE\        V4      pV! V^4      pVP                  RV RV 24       K2  	  V^ ,          ^ ,          p	VR	,          ^ ,          p
\        V^ ,          ^,          4      p\        V4      pV! V^4      pV^8”  d   VP                  RV	 RV
 RV RV 24       MVP                  RV	 RV 24       V P                  4       R,           pV'       d'   VRRP                  V4      ,           R,           ,          pVR,          pV# )
é    )Ú
_addindentÚ
Ú(z): Ú-z x z
  Ú)r9   )Útorch.nn.modules.modulerï   Ú_modulesr¡   r…   r   rq   Ú
extra_reprÚextendÚsplitÚreprÚlenÚ	_get_nameÚjoin)rA   rï   Úexpert_itemsÚother_itemsÚkeyÚchildÚlinesrö   Úmod_strÚ	first_keyÚlast_keyÚsample_reprÚnÚmain_strÚ_original_reprs   &             €r    Ú_compact_reprÚ3_install_compact_expert_repr.<locals>._compact_repr  sœ  ø€ Ý6ð ˆØˆØŸ-™-×-Ñ-Ö/‰JˆCÜ˜%Ô!1×2Ò2Ø×#Ñ# S LÖ1à×"Ñ" C <Ö0ñ	 0÷ Ù! $Ó'Ð'àˆØ—_‘_Ó&ˆ
ßØ�L‰L˜×)Ñ)¨$Ó/Ô0ó &‰JˆCÜ˜5“kˆGÙ  ¨!Ó,ˆGØ�L‰L˜1˜S˜E  W IÐ.Ö/ñ &ð ! •O AÕ&ˆ	Ø Õ# AÕ&ˆÜ˜<¨�?¨1Õ-Ó.ˆÜ�ÓˆÙ  ¨aÓ0ˆØˆqŒ5Ø�L‰L˜1˜Y˜K q¨¨
°#°a°S¸¸K¸=ÐIÕJà�L‰L˜1˜Y˜K s¨;¨-Ð8Ô9à—>‘>Ó# cÕ)ˆßØ˜ §¡¨UÓ!3Õ3°dÕ:Õ:ˆHØ�C�ˆØˆr   TÚ__getitem__c                 ó,   € \        V \        V4      4      # ©N)r:   rZ   )rA   Úidxs   &&r    Ú_getitemÚ._install_compact_expert_repr.<locals>._getitem=  s   € Ü˜4¤ S£Ó*Ð*r   c                 ó   € V P                   # r  )rQ   )rA   s   &r    Ú_lenÚ*_install_compact_expert_repr.<locals>._len@  s   € Ø×#Ñ#Ð#r   c              3   ót   "  € \        V P                  4       F  p\        V \        V4      4      x € K  	  R # 5ir  )rX   rQ   r:   rZ   )rA   rç   s   & r    Ú_iterÚ+_install_compact_expert_repr.<locals>._iterC  s+   é € Ü˜4×+Ñ+Ö,�Ü˜d¤C¨£FÓ+Ô+ó -ùs   ‚68)r<   Ú__dict__Ú__repr__rì   r=   r  Ú__len__Ú__iter__)r-   Úclsr	  r  r  r  r  s   &     @r    Ú_install_compact_expert_reprr  ø  s}   ø€ ð ×
Ñ
€CØ'¨3¯<©<Ô7Ùà—\‘\€Nõ)ðV !„LØ)-€CÔ&ô �3˜×&Ò&¨-¸s¿|¹|Ô*Kò	+ò	$ò	,ð #ŒØŒØŽñ +Lr   c                ó€   € V ^8„  d   QhR\         P                  R\        R\        \        ,          R,          R\        /# )r#   r-   Úcheck_decoratorÚprojection_namesNr$   )r   r1   r&   r~   rZ   )r'   s   "r    r(   r(   L  sC   € ÷ Mñ MÜ—	‘	ðMäðMô œs�) dÕ*ðMô 
ñ	Mr   c           
     ól  € V'       d1   \         P                  4        UUu/ uF  w  r4W29   g   K  W4bK  	  pppM\        V 4      pV'       g   R# V'       dA   \        V 4      '       g0   \        P                  RV P                  P                   R24       R# \        \        V4      4      p\        W4      pVP                  ^ ,          p\        V RR4      p	V	fB   VR9   d   RV9  d   RV9  d   Rp	M)VP                  ^,          VP                  ^,          rºW«8  p	VP                  pVP                  P                  R8w  d   VP                  MR	p/ p. pVP                  4        EF™  w  ppVP!                  R
4      pV'       g   K"  \        V V4      pVe   VP#                  4       ^8w  d   KI  V	'       d   ^M^pVP%                  \'        V4      VR7      pV R2p\        V V4      pRp\)        V\*        P,                  4      '       d2   VP#                  4       ^8X  d   VP%                  \'        V4      ^R7      p\/        \1        VV4      4       FP  w  pw  pp\3        V VVV4       Ve   \3        V V R2VV,          V4       \         P!                  VRRR^/4      VV&   KR  	  \5        V V4       Ve   \5        V V4       VP7                  V4       \8        '       g   EKz  \        P                  RV RV RV R24       EKœ  	  V F  pWS K  	  VP;                  V4       / pV FK  p\=        V VW‰WÍ4      pVf   K  \5        V V4       V R2p\?        V V4      '       d   \5        V V4       VVV&   KM  	  V'       g   R# \A        V4       FV  p\C        4       pVP                  4        F  w  pp\E        VVVV,          4       K  	  V PG                  \I        V4      V4       KX  	  \?        V R4      '       g   W€n%        RV n&        RV n'        V PQ                  4        F
  pRVn'        K  	  \S        V 4       R# u uppi )am  Convert fused 3D expert weights to per-expert containers of nn.Linear layers.

This function modifies the module in-place, replacing fused 3D Parameters
with numbered _ExpertContainer children, each holding nn.Linear projections.

Args:
    module: The experts module to unfuse
    check_decorator: If True, only unfuse if the module supports
        @use_experts_implementation decorator. Default is True.
    projection_names: Optional list of projection names to unfuse.
        If None, auto-detects from KNOWN_PROJECTION_PATTERNS.

Returns:
    True if unfusing was successful, False if module doesn't match pattern
FzSkipping unfuse for z.: does not support @use_experts_implementationrÀ   Nr   r   rÎ   rÐ   r   r7   rÍ   r   Tr   zSplit z -> z: z expertsrQ   >   r   r   )*r¢   r¡   r¬   r¾   rK   rL   r<   r   ÚnextÚiterr°   rN   r:   rJ   rH   rÑ   rƒ   r8   Úchunkrú   r…   r2   r3   Ú	enumerateÚzipr¹   Údelattrrq   r   Úupdateré   r=   rX   r   r×   Ú
add_modulerZ   rQ   Ú_unfused_expertsÚ_is_hf_initializedÚmodulesr  ) r-   r  r  r¦   r�   Údetected_projectionsÚfirst_proj_nameÚfirst_paramrQ   rÀ   rÄ   rÅ   rJ   rË   Úextra_projectionsÚfused_to_remover©   r   rª   Ú	split_dimÚsplit_paramsrÛ   rÜ   Úbias_splitsrç   Ú
split_nameÚsplit_paramÚproj_linearsræ   rf   Ú	containerr   s    &&&                             r    Ú_unfuse_experts_weights_inplacer8  L  s  € ÷* ä-F×-LÑ-LÔ-Nô 
Ù-N™\˜TÐRVÑRjŒLˆDŠLÑ-Nð 	ñ  
Ðô  :¸&ÓAÐçÙ÷ Ô:¸6×BÒBÜ�‰Ð+¨F×,<Ñ,<×,EÑ,EÐ+FÐFtÐuÔvÙô œ4Ð 4Ó5Ó6€OÜ(¨ÓA€KØ×#Ñ# AÕ&€Kô ˜F O°TÓ:€MØÒð Ð7Ô7ØÐ&:Ô:ØÐ#7Ô7à!‰Mà$×*Ñ*¨1Õ-¨{×/@Ñ/@ÀÕ/C�$Ø ™KˆMà×Ñ€EØ*5×*<Ñ*<×*AÑ*AÀVÔ*K�K×&Ò&ÐQV€Mð ÐØ€OØ1×7Ñ7×9Ñˆ	�6Ø—Z‘Z Ó-ˆ
ßÙÜ& v¨yÓ9ˆØŠ=˜EŸI™I›K¨1Ô,Ùç&‘A¨Aˆ	Ø—{‘{¤3 z£?¸	�{ÓBˆð !�k Ð'ˆ	Ü+¨F°IÓ>ˆ
ØˆÜ�j¤%§,¡,×/Ò/°J·N±NÓ4DÈÔ4IØ$×*Ñ*¬3¨z«?ÀÐ*ÓBˆKä,5´c¸*ÀlÓ6SÖ,TÑ(ˆAÑ(�
˜Kô (¨°
¸KÈÔOØÒ&Ü+¨F°z°lÀ%Ð4HÈ+ÐVWÍ.ÐZdÔeÜ,E×,IÑ,IØ˜_¨dÐ4GÈÐKó-Ð˜jÓ)ñ -Uô 	�˜	Ô"ØÒ!Ü�F˜IÔ&Ø×Ñ˜yÔ)ßŽ8”V—\‘\ F¨9¨+°T¸*¸ÀRÈÀ}ÐT\Ð"]×^ñ? :óD  ˆØ Ò&ñ  à×ÑÐ 1Ô2ð €LÛ)ˆ	Ü+¨F°I¸{Ð[`ÓpˆØÔÜ�F˜IÔ&à$˜+ UÐ+ˆIÜ�v˜y×)Ò)Ü˜ 	Ô*Ø&-ˆL˜Ó#ñ *÷ Ùô
 ˜KÖ(ˆ
Ü$Ó&ˆ	Ø".×"4Ñ"4Ö"6ÑˆI�wÜ�I˜y¨'°*Õ*=Ö>ñ #7à×Ñœ#˜j›/¨9Ö5ñ	 )ô �6˜=×)Ò)Ø(Ôð #€FÔð !%€FÔØ—‘Ö!ˆØ#'ˆÖ ñ "ô ! Ô(áùóo 
s
    
P0¯P0c                óf   € V ^8„  d   QhR\         P                  R\        R\        \        ,          /# )r#   r|   r—   r$   )r   r1   rZ   r~   )r'   s   "r    r(   r(   Ü  s3   € ÷ Dñ DÜ�9‰9ðDäðDô 
Œ#…Yñ	Dr   c                óÜ  € \        4       '       g   \        R4      h. p. p\        V 4      p\        V4      pV P	                  4        Fð  w  rx\        Wv4      '       g   K  \        W…4      p	V	en   \        VRV	P                  R4      R7      '       dK   \        W‰R,          4       VP                  V4       \        '       d   \        P                  RV R24       K”  \        V4      '       g   K§  VP                  V4       VP                  V4       \        '       g   K×  \        P                  RV R	24       Kò  	  V'       d«   \        '       d#   \        P                  R
\        V4       R24       \!        4        V'       dk   \#        V R4      '       dY   \%        V P&                  RR4      p
V
'       d   T
MTpW°P&                  n        \        '       d   \        P                  RV R	24       V# )ad  Prepare a model for MOE quantization using transformers' experts interface.

This function:
1. Registers the linear_loop experts implementation with transformers
2. Sets model.config._experts_implementation = implementation
3. Unfuses all fused MOE expert weights into per-expert containers of nn.Linear

After calling this function, the model's forward pass will use individual
nn.Linear layers per expert, which can be quantized normally.

Args:
    model: The model to prepare
    implementation: The experts implementation to use (default: "linear_loop")

Returns:
    List of module names that were unfused
zxFailed to register linear_loop experts implementation. This requires transformers >= 5.0.0 with MOE integration support.NFr  )r  r  Úforward_implz[MoE Prep] Unfused 'z' via declarative specÚ'z[MoE Prep] Unfused z MOE experts modulesr�   Úexperts_implementationz,Set model.config._experts_implementation = ')rz   ÚRuntimeErrorr‡   r   Únamed_modulesr   r•   r8  rƒ   r›   rq   r   rK   rL   Úinforú   r	   r=   r:   r�   Ú_experts_implementation)r|   r—   Úfilter_rulesÚunfused_modulesÚdecorated_unfused_modulesÚexperts_defuse_specsÚmodule_name_filterr¦   r-   r“   Ú
saved_implÚimpl_to_sets   &&&         r    Ú"prepare_model_for_moe_quantizationrI  Ü  s—  € ô, (×)Ò)ÜðPó
ð 	
ð €OØ "ÐÜ6°uÓ=ÐÜ3°LÓAÐØ×+Ñ+Ö-‰ˆÜ)¨$×CÒCÙÜ,¨VÓJˆØÒÔ ?ØØ!Ø!ŸX™XÐ&8Ó9÷!
ó !
ô
 & f°>Õ.BÔCØ×"Ñ" 4Ô(ß‹xœŸ™Ð(<¸T¸FÐBXÐ&YÔZÙä*¨6×2Ô2Ø×"Ñ" 4Ô(Ø%×,Ñ,¨TÔ2ß�xœŸ™Ð(<¸T¸FÀ!Ð&DÖEñ# .÷, ß‹8”V—[‘[Ð#6´s¸?Ó7KÐ6LÐL`Ð!aÔbÜŒ÷ %¬°¸×)AÒ)AÜ  §¡Ð/GÈÓNˆJß(2™*¸ˆKØ3>�L‰LÔ0ß‹xœŸ™Ð(TÐU`ÐTaÐabÐ&cÔdàÐr   )TN)/r   Útypesr   r2   Úlogbarr   r   Údefuser.model_registryr   r   Údefuser.utils.commonr   r   Údefuser.utils.devicer	   r
   Údefuserr   r   rK   Útransformers.integrations.moer   r*   ÚImportErrorrM   rp   r¢   r1   r   r+   r?   rm   ru   rz   r‡   r�   r•   r›   r¬   r°   r¹   r¾   rÉ   ré   r  r8  rI  r   r   r    Ú<module>rR     s>  ðñõ& ã Ý Ý ç 6ß Wß 6å á	�Ó	€ð!ÝCà Ðð !Ð Ø$Ð ð �_ dÐ,?ÀÀLÐS^Ð`iÐRjÐkØ�/ 4Ð)<¸aÐ@Ø� Ð':¸AÐ>Ø�/ 5Ð*=¸qÐAðÐ ô
	�r—y‘yô 
	õ!õ
%õ*`õFFõ2õ*
õHõ
	õ
Võ%õPõ-õ
2õ%õ8eõPQ÷hMðd +Ø÷Dñ Døð] ô !Ø!ÐØ Òð!ús   Á C3 Ã3DÄ D