Skip to content

Commit 2e5b433

Browse files
committed
fix(moe): fix QMoE routing/layout bugs found via actual onnxruntime-genai execution
Structural graph export (Olive RTN + MobiusBuilder) previously succeeded for Qwen3.5-MoE models, but the exported model.onnx had never actually been loaded/run with onnxruntime-genai. Doing so surfaced five real, pre-existing bugs in the QMoE fused-expert path and genai_config generation: 1. Router gate weight orphaned as an unqualified "weight" graph input. MoELayer._qmoe_forward() called self.gate.qmoe_routing() directly instead of through self.gate(op, ...), bypassing Module.__call__'s parameter realization (which qualifies "weight" into "<prefix>.gate.weight"). Fixed by manually pushing the gate's module scope and realizing its parameters first, mirroring the existing pattern in gemma4_assistant.py. 2. router_probs was hard-cast to float32, but QMoE's router_probs input shares type constraint "T" with the hidden_states input (per contrib_defs.cc) -- it must match hidden_states' actual dtype (e.g. fp16). Fixed with CastLike instead of a fixed Cast(..., FLOAT). 3. swiglu_fusion=2 (concatenated gate/up layout) is not supported by the CPU QMoE kernel in this ORT build (only swiglu_fusion=1, interleaved, is). Fixed by reordering fc1_experts_weights/fc1_scales/fc1_experts_zero_points rows from HF's concatenated [gate;up] layout to the interleaved [g_0,u_0,g_1,u_1,...] layout via a graph-level reshape/transpose/reshape (folded away at session load since it's applied to a constant initializer), matching the existing swiglu_fusion=1 path in gemma4.py. 4. router_probs/router_weights were left 3D (batch, seq, num_experts) when QMoE requires strictly 2D (num_tokens, num_experts). Added _flatten_to_2d() to collapse leading dims before the QMoE call. 5. genai_config's past_present_share_buffer auto-detection only checked for GroupQueryAttention nodes, defaulting to False for hybrid models that mix LinearAttention (recurrent state, e.g. Qwen3.5's GatedDeltaNet) with standard Attention. LinearAttention's recurrent state requires past_present_share_buffer=True unconditionally, so detection now also checks for LinearAttention nodes. All five were verified against actual onnxruntime-genai execution of an Olive RTN + MobiusBuilder export of a tiny Qwen3.5-MoE test model, fixed one at a time, and each confirmed to move execution further before the next bug surfaced. Not related to PR #493 (linear_class threading) or #491 (suffix mismatch) -- these bugs exist independently in the base QMoE/ genai-config code and were simply never exercised by prior structural-only export tests. Updated _moe_test.py's swiglu_fusion assertions from 2 to 1 to match.
1 parent 01008cf commit 2e5b433

3 files changed

Lines changed: 110 additions & 14 deletions

File tree

‎src/mobius/components/_moe.py‎

Lines changed: 94 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,45 @@
1515
from mobius.components._mlp import MLP
1616

1717

18+
def _interleave_gate_up_rows(
19+
op: OpBuilder, tensor: ir.Value, num_experts: int, fc1_out: int
20+
) -> ir.Value:
21+
"""Reorder fc1 gate/up rows from HF-concatenated to QMoE-interleaved layout.
22+
23+
mobius stores ``fc1_*`` parameters chunked as ``[E, 2*inter, ...]`` with
24+
the first ``inter`` rows holding the gate projection and the next
25+
``inter`` rows holding the up projection (matching HuggingFace
26+
``experts.gate_up_proj``). ``swiglu_fusion=1`` requires the interleaved
27+
layout ``[g_0, u_0, g_1, u_1, ...]`` instead -- it is the only layout the
28+
CPU QMoE kernel supports (``contrib_ops/cpu/moe/moe_quantization_cpu.cc``).
29+
Reshape/transpose/reshape the row dimension to reorder it; this operates
30+
on a constant initializer so ORT folds it away at session load (mirrors
31+
the unquantized-MoE interleave in ``gemma4.py``).
32+
"""
33+
half = fc1_out // 2
34+
trailing = op.Shape(tensor, start=2)
35+
split_shape = op.Concat(op.Constant(value_ints=[num_experts, 2, half]), trailing, axis=0)
36+
reshaped = op.Reshape(tensor, split_shape)
37+
transposed = op.Transpose(reshaped, perm=[0, 2, 1, 3])
38+
merge_shape = op.Concat(op.Constant(value_ints=[num_experts, fc1_out]), trailing, axis=0)
39+
return op.Reshape(transposed, merge_shape)
40+
41+
42+
def _flatten_to_2d(op: OpBuilder, tensor: ir.Value) -> ir.Value:
43+
"""Flatten leading (batch, sequence, ...) dims into one, keeping the last.
44+
45+
QMoE's ``router_probs`` and ``router_weights`` inputs require a strictly
46+
2D ``(num_tokens, num_experts)`` shape (unlike ``input``/hidden_states,
47+
which accepts 2D or 3D) -- see ``contrib_defs.cc``. Router logits are
48+
computed from a possibly-3D ``hidden_states`` (``batch, seq, hidden``),
49+
so collapse everything but the last dim.
50+
"""
51+
last_dim = op.Shape(tensor, start=-1)
52+
flat_shape = op.Concat(op.Constant(value_ints=[-1]), last_dim, axis=0)
53+
return op.Reshape(tensor, flat_shape)
54+
55+
56+
1857
class TopKGate(nn.Module):
1958
"""Standard top-k expert routing gate.
2059
@@ -56,7 +95,10 @@ def qmoe_routing(self, op: OpBuilder, hidden_states: ir.Value):
5695
"""
5796
weight_t = op.Transpose(self.weight, perm=[1, 0])
5897
router_logits = op.MatMul(hidden_states, weight_t)
59-
router_logits = op.Cast(router_logits, to=ir.DataType.FLOAT.value)
98+
# QMoE's ``router_probs`` input shares type constraint "T" with
99+
# ``input`` (see contrib_defs.cc), so it must match hidden_states'
100+
# dtype rather than a fixed float32.
101+
router_logits = op.CastLike(router_logits, hidden_states)
60102
return router_logits, None, True, 1.0
61103

62104

@@ -92,7 +134,7 @@ def forward(self, op: OpBuilder, hidden_states: ir.Value):
92134
def qmoe_routing(self, op: OpBuilder, hidden_states: ir.Value):
93135
"""Return selection and aggregation tensors for QMoE.
94136
95-
``router_probs`` (QMoE input 1) is the raw float32 logits and the
137+
``router_probs`` (QMoE input 1) is the raw logits (cast to hidden_states's dtype) and the
96138
pre-softmaxed probabilities are passed as ``router_weights`` (input
97139
14). CUDA QMoE ignores ``router_weights`` and applies softmax-top-k on
98140
``router_probs``, so feeding logits reproduces ``forward`` exactly
@@ -105,7 +147,10 @@ def qmoe_routing(self, op: OpBuilder, hidden_states: ir.Value):
105147
"""
106148
weight_t = op.Transpose(self.weight, perm=[1, 0])
107149
router_logits = op.MatMul(hidden_states, weight_t)
108-
router_logits = op.Cast(router_logits, to=ir.DataType.FLOAT.value)
150+
# QMoE's ``router_probs`` input shares type constraint "T" with
151+
# ``input`` (see contrib_defs.cc), so it must match hidden_states'
152+
# dtype rather than a fixed float32.
153+
router_logits = op.CastLike(router_logits, hidden_states)
109154
routing_probs = op.Softmax(router_logits, axis=-1)
110155
return router_logits, routing_probs, self.norm_topk_prob, 1.0
111156

@@ -154,7 +199,7 @@ def qmoe_routing(self, op: OpBuilder, hidden_states: ir.Value):
154199
"""Return selection and aggregation tensors for QMoE.
155200
156201
The sigmoid-activated probabilities are passed as ``router_weights``
157-
(QMoE input 14) while the raw float32 logits are passed as
202+
(QMoE input 14) while the raw logits (cast to hidden_states's dtype) are passed as
158203
``router_probs`` (input 1). CPU QMoE selects the top-k over
159204
``router_probs`` (sigmoid is monotonic, so logits give the same
160205
selection) and gathers ``router_weights`` at the selected experts,
@@ -164,7 +209,10 @@ def qmoe_routing(self, op: OpBuilder, hidden_states: ir.Value):
164209
"""
165210
weight_t = op.Transpose(self.weight, perm=[1, 0])
166211
router_logits = op.MatMul(hidden_states, weight_t)
167-
router_logits = op.Cast(router_logits, to=ir.DataType.FLOAT.value)
212+
# QMoE's ``router_probs`` input shares type constraint "T" with
213+
# ``input`` (see contrib_defs.cc), so it must match hidden_states'
214+
# dtype rather than a fixed float32.
215+
router_logits = op.CastLike(router_logits, hidden_states)
168216
routing_probs = op.Sigmoid(router_logits)
169217
return (
170218
router_logits,
@@ -298,6 +346,7 @@ def _init_qmoe_parameters(self, expert_config: ArchitectureConfig) -> None:
298346
block_size = quantization.group_size
299347
bits = quantization.bits
300348
fc1_out = 2 * intermediate_size
349+
self._fc1_out = fc1_out
301350
if hidden_size % block_size or intermediate_size % block_size:
302351
raise ValueError(
303352
"QMoE dimensions must be divisible by the quantization group size"
@@ -341,22 +390,56 @@ def _init_qmoe_parameters(self, expert_config: ArchitectureConfig) -> None:
341390
def _qmoe_forward(self, op: OpBuilder, hidden_states: ir.Value):
342391
quantization = self._qmoe_quantization
343392
assert quantization is not None
344-
router_probs, router_weights, normalize, output_scale = self.gate.qmoe_routing(
345-
op, hidden_states
393+
# ``qmoe_routing`` is called directly (not via ``self.gate(op, ...)``)
394+
# because it returns multiple routing tensors rather than following
395+
# the standard forward() signature. ``Module.__call__`` only realizes
396+
# parameters (qualifying their initializer names, e.g.
397+
# "<prefix>.gate.weight") for the module actually invoked through
398+
# ``__call__`` -- see onnxscript/nn/_module.py -- so bypassing it here
399+
# would leave ``self.gate.weight`` registered as a bare, unqualified
400+
# "weight" initializer. Manually push the gate's module scope and
401+
# realize its parameters first, mirroring the pattern used for the
402+
# sparse LM head in gemma4_assistant.py.
403+
op.builder.push_module(self.gate.name or "gate", type(self.gate).__qualname__)
404+
try:
405+
for param in self.gate.parameters():
406+
param._realize(op.builder) # pylint: disable=protected-access
407+
router_probs, router_weights, normalize, output_scale = self.gate.qmoe_routing(
408+
op, hidden_states
409+
)
410+
finally:
411+
op.builder.pop_module()
412+
413+
router_probs = _flatten_to_2d(op, router_probs)
414+
if router_weights is not None:
415+
router_weights = _flatten_to_2d(op, router_weights)
416+
417+
fc1_experts_weights = _interleave_gate_up_rows(
418+
op, self.fc1_experts_weights, self.num_experts, self._fc1_out
419+
)
420+
fc1_scales = _interleave_gate_up_rows(
421+
op, self.fc1_scales, self.num_experts, self._fc1_out
422+
)
423+
fc1_experts_zero_points = (
424+
_interleave_gate_up_rows(
425+
op, self.fc1_experts_zero_points, self.num_experts, self._fc1_out
426+
)
427+
if self.fc1_experts_zero_points is not None
428+
else None
346429
)
347430
result = op.QMoE(
348431
hidden_states,
349432
router_probs,
350-
self.fc1_experts_weights,
351-
self.fc1_scales,
433+
fc1_experts_weights,
434+
fc1_scales,
352435
None,
353436
self.fc2_experts_weights,
354437
self.fc2_scales,
355438
None,
356439
None,
357440
None,
358441
None,
359-
self.fc1_experts_zero_points,
442+
fc1_experts_zero_points,
360443
self.fc2_experts_zero_points,
361444
None,
362445
router_weights,
@@ -365,7 +448,7 @@ def _qmoe_forward(self, op: OpBuilder, hidden_states: ir.Value):
365448
k=self.top_k,
366449
expert_weight_bits=quantization.bits,
367450
block_size=quantization.group_size,
368-
swiglu_fusion=2,
451+
swiglu_fusion=1,
369452
quant_type="int",
370453
weights_prepacked=0,
371454
_domain="com.microsoft",

‎src/mobius/components/_moe_test.py‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -158,7 +158,7 @@ def test_int4_olive_moe_emits_expert_major_qmoe(self):
158158
qmoe = qmoe_nodes[0]
159159
assert qmoe.attributes["k"].value == 6
160160
assert qmoe.attributes["block_size"].value == 32
161-
assert qmoe.attributes["swiglu_fusion"].value == 2
161+
assert qmoe.attributes["swiglu_fusion"].value == 1
162162
assert qmoe.attributes["expert_weight_bits"].value == 4
163163
assert qmoe.attributes["quant_type"].value == "int"
164164
assert qmoe.attributes["weights_prepacked"].value == 0
@@ -210,7 +210,7 @@ def test_int4_moe_emits_expert_major_qmoe(self):
210210
qmoe = qmoe_nodes[0]
211211
assert qmoe.attributes["k"].value == 6
212212
assert qmoe.attributes["block_size"].value == 32
213-
assert qmoe.attributes["swiglu_fusion"].value == 2
213+
assert qmoe.attributes["swiglu_fusion"].value == 1
214214
assert qmoe.attributes["quant_type"].value == "int"
215215
assert qmoe.attributes["weights_prepacked"].value == 0
216216
assert layer.fc1_experts_weights.shape == ir.Shape([64, 64, 32])

‎src/mobius/integrations/ort_genai/auto_export.py‎

Lines changed: 14 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1009,13 +1009,26 @@ def _write_genai_config(
10091009
# shared buffer. Introspect the graph: if there is at least one GQA
10101010
# node, the model supports shared-buffer mode; otherwise force it off
10111011
# regardless of the EP capability flag.
1012+
#
1013+
# ``com.microsoft.LinearAttention`` (linear/recurrent-attention layers,
1014+
# e.g. Qwen3.5's GatedDeltaNet) is a separate, *mandatory* case: its
1015+
# recurrent state requires ``past_present_share_buffer=True`` regardless
1016+
# of whether any other layer uses GQA (ORT GenAI raises "RecurrentState
1017+
# requires past_present_share_buffer=true" otherwise). Hybrid models mix
1018+
# LinearAttention layers with standard (non-GQA) ``Attention`` layers, so
1019+
# this flag must win over the "no GQA" default-off heuristic above.
10121020
decoder_model = pkg.get(decoder_key)
10131021
supports_in_place_kv_cache: bool | None = None
10141022
if decoder_model is not None:
1015-
supports_in_place_kv_cache = any(
1023+
has_gqa = any(
10161024
node.op_type == "GroupQueryAttention" and node.domain == "com.microsoft"
10171025
for node in decoder_model.graph
10181026
)
1027+
has_recurrent_state = any(
1028+
node.op_type == "LinearAttention" and node.domain == "com.microsoft"
1029+
for node in decoder_model.graph
1030+
)
1031+
supports_in_place_kv_cache = has_gqa or has_recurrent_state
10191032

10201033
generator = GenaiConfigGenerator.from_config(
10211034
config,

0 commit comments

Comments
 (0)