Skip to content

Commit e5d337b

Browse files
authored
Fuse DeepSeek-V4 routed experts into a single QMoE op per layer (#550)
Replaces the dense 256-expert MatMulNBits/mask Python loop with one fused com.microsoft::QMoE node per layer via MoELayer, preserving DeepSeekV4Gate hash-routing math unchanged. Structural reduction at 256 experts: 1554->18 MatMulNBits, 7508->633 total nodes, 2 QMoE nodes. 88/88 targeted tests pass (CPU EP numeric parity, hash-routing identity, structural fusion, duplicate-expert-index validation). Independent review addressed: CUDA router_weights gap documented (pre-existing, shared with merged V3 code, tracked upstream at microsoft/onnxruntime#31570); hash-table duplicate-index validation added; multi-block quantization test coverage added. Local gates (pytest, ruff check/format) and independent review pass; admin-merged per repo precedent (PR #548) without waiting on long-running L4/L5/Integration jobs.
1 parent cbf4cbd commit e5d337b

7 files changed

Lines changed: 761 additions & 38 deletions

File tree

‎src/mobius/components/_moe.py‎

Lines changed: 112 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@
77

88
import dataclasses
99
import math
10+
from collections.abc import Callable
1011

1112
import onnx_ir as ir
1213
from 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+
57132
class 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):

‎src/mobius/integrations/gguf/_tensor_mapping.py‎

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -251,9 +251,12 @@
251251
),
252252
"blk.{bid}.attn_norm": "model.layers.{bid}.input_layernorm",
253253
"blk.{bid}.ffn_norm": "model.layers.{bid}.post_attention_layernorm",
254-
"blk.{bid}.ffn_gate_inp": "model.layers.{bid}.mlp.gate",
255-
"blk.{bid}.exp_probs_b": "model.layers.{bid}.mlp.gate",
256-
"blk.{bid}.ffn_gate_tid2eid": "model.layers.{bid}.mlp.gate.tid2eid@",
254+
# DeepSeekV4MoE now composes the shared MoELayer (mobius.components._moe),
255+
# so the gate lives one level deeper at mlp.moe.gate.* than the bare
256+
# mlp.gate.* used before the QMoE export change.
257+
"blk.{bid}.ffn_gate_inp": "model.layers.{bid}.mlp.moe.gate",
258+
"blk.{bid}.exp_probs_b": "model.layers.{bid}.mlp.moe.gate",
259+
"blk.{bid}.ffn_gate_tid2eid": "model.layers.{bid}.mlp.moe.gate.tid2eid@",
257260
"blk.{bid}.ffn_gate_exps": "model.layers.{bid}.mlp.experts.gate_proj",
258261
"blk.{bid}.ffn_up_exps": "model.layers.{bid}.mlp.experts.up_proj",
259262
"blk.{bid}.ffn_down_exps": "model.layers.{bid}.mlp.experts.down_proj",

‎src/mobius/integrations/gguf/_tensor_mapping_test.py‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -318,8 +318,8 @@ def test_deepseek4_mapping(self) -> None:
318318
"blk.2.attn_q_a.weight": "model.layers.2.self_attn.q_a_proj.weight",
319319
"blk.2.attn_kv.weight": "model.layers.2.self_attn.kv_proj.weight",
320320
"blk.2.attn_output_a.weight": "model.layers.2.self_attn.o_a_proj.weight",
321-
"blk.2.ffn_gate_tid2eid.weight": "model.layers.2.mlp.gate.tid2eid",
322-
"blk.2.exp_probs_b.bias": "model.layers.2.mlp.gate.bias",
321+
"blk.2.ffn_gate_tid2eid.weight": "model.layers.2.mlp.moe.gate.tid2eid",
322+
"blk.2.exp_probs_b.bias": "model.layers.2.mlp.moe.gate.bias",
323323
"blk.2.hc_attn_fn.weight": "model.layers.2.hc_attn_fn.weight",
324324
"blk.2.attn_sinks.weight": "model.layers.2.self_attn.attn_sink",
325325
"blk.2.attn_compressor_ape.weight": ("model.layers.2.self_attn.compressor.ape"),

‎src/mobius/models/deepseek.py‎

Lines changed: 15 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -108,7 +108,21 @@ def forward(self, op: OpBuilder, hidden_states: ir.Value):
108108
return routing_weights, selected_experts
109109

110110
def qmoe_routing(self, op: OpBuilder, hidden_states: ir.Value):
111-
"""Return distinct expert-selection and aggregation scores for QMoE."""
111+
"""Return distinct expert-selection and aggregation scores for QMoE.
112+
113+
CPU-only correctness: selection uses ``scores_for_choice`` (bias
114+
for V3, unbiased for V2) but aggregation weights come from the
115+
separate, unbiased ``scores`` tensor via QMoE's ``router_weights``
116+
input -- honored by CPU QMoE but ignored by CUDA QMoE, which always
117+
derives weights by softmax-top-k over ``router_probs``
118+
(``scores_for_choice``) itself. There is no ``router_probs``
119+
encoding that reproduces the correct (unbiased) weights through
120+
CUDA's forced internal recompute. Tracked upstream at
121+
https://github.com/microsoft/onnxruntime/pull/31570 (adds CUDA
122+
``router_weights`` support); until that lands, this path is
123+
CPU-EP-correct only. See ``_scatter_selected_to_full`` in
124+
``mobius.components._moe`` for the same limitation on DeepSeek-V4.
125+
"""
112126
scores, scores_for_choice = self._routing_scores(op, hidden_states)
113127
# QMoE's router_probs/router_weights inputs share type constraint "T"
114128
# with hidden_states (see contrib_defs.cc). _routing_scores computes

0 commit comments

Comments
 (0)