77
88import dataclasses
99import math
10+ from collections .abc import Callable
1011
1112import onnx_ir as ir
1213from onnxscript import OpBuilder , nn
@@ -54,6 +55,80 @@ def _flatten_to_2d(op: OpBuilder, tensor: ir.Value) -> ir.Value:
5455 return op .Reshape (tensor , flat_shape )
5556
5657
58+ def _scatter_selected_to_full (
59+ op : OpBuilder ,
60+ routing_weights : ir .Value ,
61+ selected_experts : ir .Value ,
62+ num_experts : int ,
63+ ) -> tuple [ir .Value , ir .Value ]:
64+ """Adapt an already-selected (routing_weights, selected_experts) pair.
65+
66+ (top-k-shaped, e.g. ``[..., top_k]``) into the full ``[..., num_experts]``
67+ ``(router_probs, router_weights)`` tensors QMoE requires.
68+
69+ QMoE always performs its own top-k selection over ``router_probs``
70+ (governed by the ``k`` attribute); there is no ABI to hand it externally
71+ chosen expert indices directly. This matters for gates whose selection is
72+ not expressible as "top-k of a per-expert score", most notably hash-table
73+ routing (e.g. DeepSeek-V4's ``tid2eid`` lookup): the natural per-expert
74+ score used to pick a weight need not rank the selected experts above the
75+ rest, so passing it straight through as ``router_probs`` could make QMoE's
76+ internal top-k pick a *different* set of experts than the gate actually
77+ chose.
78+
79+ This adapter sidesteps that by constructing ``router_probs`` as ``-inf``
80+ everywhere except a constant positive marker at exactly the selected
81+ positions: any of the ``top_k`` marked slots trivially outranks every
82+ ``-inf`` slot, so QMoE's internal top-k recovers precisely the selected
83+ expert set regardless of relative order among ties. ``router_weights`` is
84+ the real per-slot weight scattered at the same positions (zero
85+ elsewhere, never read since QMoE only gathers ``router_weights`` at its
86+ own top-k selection, which is exactly the scattered set). This changes
87+ neither the selection algorithm nor the weight values -- it only encodes
88+ an already-final ``(routing_weights, selected_experts)`` pair in the
89+ tensor shape QMoE's ABI requires, the same idea ``DeepSeekMoEGate``
90+ already uses (mask non-selected groups to ``-inf`` before ``TopK``).
91+
92+ Requires ``routing_weights`` to be non-negative (true for softmax/
93+ sigmoid/sqrt-softplus scoring, the scoring functions used by every
94+ caller today) and ``normalize_routing_weights=0`` at the QMoE call site,
95+ since these weights are already final and must not be re-normalized.
96+ Also requires ``selected_experts`` to name ``top_k`` *distinct* experts
97+ per token: ``ScatterElements`` does not accumulate duplicate indices, so
98+ a repeated expert would silently drop one of its contributions. Every
99+ gate in this module (and DeepSeek-V4's hash table) already guarantees
100+ this -- top-k selection over a score tensor never repeats an index, and
101+ a hash table has no reason to route a token to the same expert twice.
102+
103+ CPU-only correctness: ORT's CPU QMoE honors Input 14 (``router_weights``)
104+ by gathering it at the selected experts, but CUDA QMoE ignores Input 14
105+ and always derives weights by softmax-top-k over ``router_probs`` itself
106+ (see ``contrib_ops/cpu/moe/moe_quantization_cpu.cc`` vs
107+ ``contrib_ops/cuda/moe/moe_quantization.cc``). Unlike ``TopKGate``/
108+ ``SoftmaxTopKGate``/``SigmoidTopKGate`` above, whose selection score
109+ doubles as (a monotonic function of) the aggregation weight -- so raw
110+ logits can be passed as ``router_probs`` and CUDA's internal recompute
111+ reproduces ``forward()`` exactly -- callers of this adapter select
112+ experts by an index with no such relationship to a per-expert score
113+ (hash lookup, or a selection tensor that differs from the weighting
114+ tensor, e.g. DeepSeek noaux_tc-style bias-corrected top-k). There is no
115+ ``router_probs`` encoding that makes CUDA's forced internal recompute
116+ reproduce the correct weights in that case. This is the same limitation
117+ already present in ``DeepSeekMoEGate.qmoe_routing`` (V3) and is tracked
118+ upstream at https://github.com/microsoft/onnxruntime/pull/31570 (adds
119+ CUDA ``router_weights`` support). Until that lands, callers of this
120+ adapter are CPU-EP-correct only; do not execute on the CUDA EP.
121+ """
122+ lead_shape = op .Shape (selected_experts , end = - 1 )
123+ full_shape = op .Concat (lead_shape , op .Constant (value_ints = [num_experts ]), axis = 0 )
124+ neg_inf = op .Expand (op .CastLike (float ("-inf" ), routing_weights ), full_shape )
125+ marker = op .Expand (op .CastLike (1.0 , routing_weights ), op .Shape (selected_experts ))
126+ router_probs = op .ScatterElements (neg_inf , selected_experts , marker , axis = - 1 )
127+ zeros = op .Expand (op .CastLike (0.0 , routing_weights ), full_shape )
128+ router_weights = op .ScatterElements (zeros , selected_experts , routing_weights , axis = - 1 )
129+ return router_probs , router_weights
130+
131+
57132class TopKGate (nn .Module ):
58133 """Standard top-k expert routing gate.
59134
@@ -320,13 +395,28 @@ def __init__(
320395 config : ArchitectureConfig ,
321396 gate : nn .Module | None = None ,
322397 linear_class : type | None = None ,
398+ expert_factory : Callable [[ArchitectureConfig , type | None ], nn .Module ] | None = None ,
399+ activation_alpha : float | None = None ,
400+ activation_beta : float | None = None ,
401+ swiglu_limit : float | None = None ,
323402 ):
324403 super ().__init__ ()
325404 assert config .num_local_experts is not None
326405 assert config .num_experts_per_tok is not None
327406 self .num_experts = config .num_local_experts
328407 self .top_k = config .num_experts_per_tok
329408 self ._qmoe_quantization = _supported_qmoe_quantization (config .quantization )
409+ # Clipped-SwiGLU attributes (QMoE's ``activation_alpha``/``activation_beta``/
410+ # ``swiglu_limit``). Left ``None`` by default so existing callers get a
411+ # byte-identical QMoE call (the attributes are simply omitted, even though
412+ # the schema defaults happen to match the plain-SwiGLU behaviour already in
413+ # use). Callers with a clipped-SwiGLU expert (e.g. DeepSeek-V4) pass these
414+ # explicitly; ``swiglu_limit`` must be finite to actually clip, or
415+ # ``math.inf`` to disable clipping (QMoE treats ``0.0`` as "clip to zero",
416+ # not "no limit" -- see ``qmoe_routing`` callers for the exact mapping).
417+ self .activation_alpha = activation_alpha
418+ self .activation_beta = activation_beta
419+ self .swiglu_limit = swiglu_limit
330420 if gate is not None :
331421 self .gate = gate
332422 else :
@@ -346,11 +436,12 @@ def __init__(
346436 # native QMoE ABI). Without threading it here, this fallback
347437 # path would silently lose quantization for every per-expert
348438 # MLP even though the caller requested a quantized linear_class.
439+ # ``expert_factory`` lets callers with a non-standard expert MLP
440+ # (e.g. DeepSeek-V4's clipped-SwiGLU expert) reuse this dense
441+ # fallback instead of duplicating the mask-and-sum loop below.
442+ factory = expert_factory or (lambda cfg , lc : MLP (cfg , linear_class = lc ))
349443 self .experts = nn .ModuleList (
350- [
351- MLP (expert_config , linear_class = linear_class )
352- for _ in range (self .num_experts )
353- ]
444+ [factory (expert_config , linear_class ) for _ in range (self .num_experts )]
354445 )
355446
356447 def _init_qmoe_parameters (self , expert_config : ArchitectureConfig ) -> None :
@@ -400,7 +491,7 @@ def _init_qmoe_parameters(self, expert_config: ArchitectureConfig) -> None:
400491 dtype = ir .DataType .UINT8 ,
401492 )
402493
403- def _qmoe_forward (self , op : OpBuilder , hidden_states : ir .Value ):
494+ def _qmoe_forward (self , op : OpBuilder , hidden_states : ir .Value , * gate_args ):
404495 quantization = self ._qmoe_quantization
405496 assert quantization is not None
406497 # ``qmoe_routing`` is called directly (not via ``self.gate(op, ...)``)
@@ -423,7 +514,7 @@ def _qmoe_forward(self, op: OpBuilder, hidden_states: ir.Value):
423514 for param in self .gate .parameters (recurse = False ):
424515 param ._realize (op .builder ) # pylint: disable=protected-access
425516 router_probs , router_weights , normalize , output_scale = self .gate .qmoe_routing (
426- op , hidden_states
517+ op , hidden_states , * gate_args
427518 )
428519 finally :
429520 op .builder .pop_module ()
@@ -445,6 +536,17 @@ def _qmoe_forward(self, op: OpBuilder, hidden_states: ir.Value):
445536 if self .fc1_experts_zero_points is not None
446537 else None
447538 )
539+ # ``activation_alpha``/``activation_beta``/``swiglu_limit`` are only
540+ # passed when a caller explicitly set them (e.g. DeepSeek-V4's
541+ # clipped-SwiGLU expert); omitting them for every other existing
542+ # caller keeps their emitted QMoE node byte-identical to before.
543+ activation_kwargs = {}
544+ if self .activation_alpha is not None :
545+ activation_kwargs ["activation_alpha" ] = self .activation_alpha
546+ if self .activation_beta is not None :
547+ activation_kwargs ["activation_beta" ] = self .activation_beta
548+ if self .swiglu_limit is not None :
549+ activation_kwargs ["swiglu_limit" ] = self .swiglu_limit
448550 result = op .QMoE (
449551 hidden_states ,
450552 router_probs ,
@@ -470,16 +572,17 @@ def _qmoe_forward(self, op: OpBuilder, hidden_states: ir.Value):
470572 quant_type = "int" ,
471573 weights_prepacked = 0 ,
472574 _domain = "com.microsoft" ,
575+ ** activation_kwargs ,
473576 )
474577 if output_scale != 1.0 : # noqa: RUF069
475578 result = op .Mul (result , op .CastLike (output_scale , result ))
476579 return result
477580
478- def forward (self , op : OpBuilder , hidden_states : ir .Value ):
581+ def forward (self , op : OpBuilder , hidden_states : ir .Value , * gate_args ):
479582 if self .experts is None :
480- return self ._qmoe_forward (op , hidden_states )
583+ return self ._qmoe_forward (op , hidden_states , * gate_args )
481584
482- routing_weights , selected_experts = self .gate (op , hidden_states )
585+ routing_weights , selected_experts = self .gate (op , hidden_states , * gate_args )
483586
484587 result = None
485588 for expert_idx , expert in enumerate (self .experts ):
0 commit comments