Skip to content

Commit bd666bc

Browse files
justinchubyCopilot
andcommitted
fix(models): stack per-expert GPTQ/AWQ MoE experts into fused QMoE (#513)
Per-expert GPTQ/AWQ MoE checkpoints (e.g. Qwen1.5-MoE-A2.7B-GPTQ-Int4) store every routed expert as a separate module, so the generic MoE models (MoECausalLMModel, Qwen2MoECausalLMModel, Ernie45MoECausalLMModel, Glm4MoECausalLMModel) emitted an unfused graph: per-expert MatMulNBits + Equal masking with empty fc1/fc2 QMoE initializers. The runtime then computes every expert each token. The native QMoE packer (pack_qmoe_expert_weights) expects the fused expert-major tensors that Olive emits, which per-expert checkpoints do not provide. Add stack_per_expert_moe_weights to bridge the two: after the MatMulNBits reshape, concatenate each expert's gate/up projections in HF-concatenated [gate; up] order and stack all experts into a new leading dim, producing the fused gate_up_proj / down_proj tensors the packer consumes. Wire the generic MoE models through preprocess_quantized_weights with qmoe_target_path=".mlp" so the stacking + packing runs. Result on Qwen1.5-MoE-A2.7B-GPTQ-Int4 (measured, RTX 4060): the graph now emits 24 fused com.microsoft::QMoE nodes (one per layer), 0 Equal ops, and populated fc1/fc2 expert weights (fc1 [60, 2816, 1024]). Numerically equivalent to the dense per-expert reference: identical argmax and top-5, max abs first-step logit diff 0.072 over 151,936 logits (fp32 A/B on CUDA, same weights) — consistent with fused-SwiGLU FP accumulation order, not a wrong expert mapping. Symmetric GPTQ (sym=True) drops zero-points on both the dense and QMoE paths (implicit zp=8), so no zero-point transport is added; asymmetric transport remains out of scope. Co-authored-by: Copilot <[email protected]>
1 parent 4dbab45 commit bd666bc

3 files changed

Lines changed: 258 additions & 7 deletions

File tree

‎src/mobius/_weight_utils.py‎

Lines changed: 88 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -621,6 +621,88 @@ def _reshape_packed_qzeros(value: torch.Tensor, bits: int, n_blocks: int) -> tor
621621
return flat_uint8[..., :zp_cols]
622622

623623

624+
def stack_per_expert_moe_weights(
625+
state_dict: dict[str, torch.Tensor],
626+
*,
627+
qmoe_target_path: str,
628+
) -> dict[str, torch.Tensor]:
629+
"""Stack per-expert quantized MoE projections into fused expert-major tensors.
630+
631+
GPTQ/AWQ MoE checkpoints store every routed expert as a separate module
632+
(``…{qmoe_target_path}.experts.{i}.{gate,up,down}_proj.*``). The native QMoE
633+
packer (:func:`pack_qmoe_expert_weights`) instead expects the fused
634+
expert-major tensors that Olive emits
635+
(``…{qmoe_target_path}.experts.gate_up_proj.*`` and ``…experts.down_proj.*``
636+
with a leading expert dimension). This bridges the two so a per-expert
637+
GPTQ/AWQ checkpoint can drive the fused ``com.microsoft::QMoE`` path.
638+
639+
Runs on the already-reshaped MatMulNBits layout produced by
640+
:func:`preprocess_gptq_weights` / :func:`preprocess_awq_weights` (suffixes
641+
``.weight`` ``[N, n_blocks, blob]``, ``.scales`` ``[N, n_blocks]``,
642+
``.zero_points`` ``[N, zp_cols]``). For each expert, gate and up are
643+
concatenated along the output-row dimension in HF-concatenated ``[gate; up]``
644+
order (the layout ``_interleave_gate_up_rows`` expects), then all experts are
645+
stacked into a new leading dimension. Non-expert keys pass through unchanged;
646+
per-expert ``bias`` and ``g_idx`` are dropped (the QMoE ABI carries neither).
647+
648+
A no-op (returns the input unchanged) when the state dict already holds
649+
fused expert-major tensors (e.g. Olive checkpoints), so it is safe to call
650+
on any quantized MoE state dict.
651+
"""
652+
experts_root = f"{qmoe_target_path}.experts."
653+
projections = ("gate_proj", "up_proj", "down_proj")
654+
stack_suffixes = ("weight", "scales", "zero_points")
655+
656+
# groups[expert_prefix][suffix][proj][expert_index] = tensor
657+
groups: dict[str, dict[str, dict[str, dict[int, torch.Tensor]]]] = {}
658+
passthrough: dict[str, torch.Tensor] = {}
659+
for key, value in state_dict.items():
660+
marker = experts_root
661+
pos = key.find(marker)
662+
matched = False
663+
if pos != -1:
664+
rest = key[pos + len(marker) :] # e.g. "0.gate_proj.weight"
665+
idx_str, _, tail = rest.partition(".")
666+
if idx_str.isdigit() and tail:
667+
proj, _, suffix = tail.partition(".")
668+
if proj in projections:
669+
if suffix in stack_suffixes:
670+
prefix = key[: pos + len(marker) - 1] # ".../experts"
671+
groups.setdefault(prefix, {}).setdefault(suffix, {}).setdefault(
672+
proj, {}
673+
)[int(idx_str)] = value
674+
matched = True
675+
elif suffix in ("bias", "g_idx"):
676+
# Not carried into the QMoE ABI; drop.
677+
matched = True
678+
if not matched:
679+
passthrough[key] = value
680+
681+
if not groups:
682+
return state_dict
683+
684+
def _stack_dense(by_idx: dict[int, torch.Tensor]) -> torch.Tensor:
685+
return torch.stack([by_idx[i] for i in range(len(by_idx))], dim=0)
686+
687+
result = dict(passthrough)
688+
for prefix, by_suffix in groups.items():
689+
for suffix, by_proj in by_suffix.items():
690+
gate = by_proj.get("gate_proj")
691+
up = by_proj.get("up_proj")
692+
down = by_proj.get("down_proj")
693+
if gate is not None and up is not None:
694+
if gate.keys() != up.keys():
695+
raise ValueError(f"Mismatched gate/up experts for {prefix} ({suffix})")
696+
fused_gate_up = torch.stack(
697+
[torch.cat([gate[i], up[i]], dim=0) for i in range(len(gate))],
698+
dim=0,
699+
)
700+
result[f"{prefix}.gate_up_proj.{suffix}"] = fused_gate_up
701+
if down is not None:
702+
result[f"{prefix}.down_proj.{suffix}"] = _stack_dense(down)
703+
return result
704+
705+
624706
def pack_qmoe_expert_weights(
625707
state_dict: dict[str, torch.Tensor],
626708
*,
@@ -1096,6 +1178,9 @@ def _is_packed_key(key: str, float_key: str) -> bool:
10961178
head_key=head_key,
10971179
)
10981180
if use_qmoe and qmoe_target_path is not None:
1181+
return_state_dict = stack_per_expert_moe_weights(
1182+
return_state_dict, qmoe_target_path=qmoe_target_path
1183+
)
10991184
return_state_dict = pack_qmoe_expert_weights(
11001185
return_state_dict, target_moe_path=qmoe_target_path
11011186
)
@@ -1109,5 +1194,8 @@ def _is_packed_key(key: str, float_key: str) -> bool:
11091194
if tie_embeddings and not tied_quantized_table:
11101195
tie_word_embeddings(state_dict, embed_key=embed_key, head_key=head_key)
11111196
if use_qmoe and qmoe_target_path is not None:
1197+
state_dict = stack_per_expert_moe_weights(
1198+
state_dict, qmoe_target_path=qmoe_target_path
1199+
)
11121200
state_dict = pack_qmoe_expert_weights(state_dict, target_moe_path=qmoe_target_path)
11131201
return state_dict

‎src/mobius/_weight_utils_test.py‎

Lines changed: 142 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@
2020
split_fused_qkv,
2121
split_gate_up_proj,
2222
split_interleaved_qkv,
23+
stack_per_expert_moe_weights,
2324
strip_prefix,
2425
tie_word_embeddings,
2526
vlm_decoder_weights,
@@ -979,6 +980,48 @@ def test_rejects_unsupported_qmoe_quantization_method(self):
979980
qmoe_quant_methods=("olive",),
980981
)
981982

983+
def test_per_expert_gptq_moe_produces_populated_fused_qmoe(self):
984+
"""Per-expert GPTQ experts stack+pack into non-empty fused QMoE params.
985+
986+
This is the end-to-end guard for the per-expert -> fused-QMoE path:
987+
a symmetric GPTQ MoE checkpoint whose routed experts are stored as
988+
separate modules must yield populated ``fc1/fc2_experts_weights`` with a
989+
leading expert axis, and leave no per-expert expert tensors behind.
990+
"""
991+
quantization = QuantizationConfig(bits=4, group_size=32, quant_method="gptq", sym=True)
992+
num_experts = 3
993+
hidden, inter = 256, 128
994+
prefix = "model.layers.0.mlp.experts"
995+
state_dict: dict[str, torch.Tensor] = {}
996+
for e in range(num_experts):
997+
# gate/up: in=hidden(256), out=inter(128); down: in=inter(128), out=hidden(256)
998+
for proj, k, n in (
999+
("gate_proj", hidden, inter),
1000+
("up_proj", hidden, inter),
1001+
("down_proj", inter, hidden),
1002+
):
1003+
k_packed = k * 4 // 32
1004+
n_groups = k // 32
1005+
state_dict[f"{prefix}.{e}.{proj}.qweight"] = torch.randint(
1006+
0, 255, (k_packed, n), dtype=torch.int32
1007+
)
1008+
state_dict[f"{prefix}.{e}.{proj}.scales"] = torch.randn(n_groups, n)
1009+
1010+
result = preprocess_quantized_weights(
1011+
state_dict, quantization, qmoe_target_path=".mlp"
1012+
)
1013+
1014+
fc1 = result["model.layers.0.mlp.fc1_experts_weights"]
1015+
fc2 = result["model.layers.0.mlp.fc2_experts_weights"]
1016+
assert fc1.shape[0] == num_experts
1017+
assert fc2.shape[0] == num_experts
1018+
assert fc1.shape[1] == 2 * inter # gate rows then up rows
1019+
assert fc2.shape[1] == hidden
1020+
assert fc1.numel() > 0 and fc2.numel() > 0
1021+
# No per-expert expert tensors survive the fusion.
1022+
assert not any(".experts." in k and ".gate_proj" in k for k in result)
1023+
assert not any(".experts." in k and ".down_proj" in k for k in result)
1024+
9821025
@pytest.mark.parametrize("flag", ["quantize_embeddings", "quantize_lm_head"])
9831026
def test_rejects_quantized_embedding_or_lm_head(self, flag):
9841027
quantization = QuantizationConfig(
@@ -1251,3 +1294,102 @@ def test_indivisible_mp_num_raises(self):
12511294
"""mp_num that doesn't divide hidden raises ValueError."""
12521295
with pytest.raises(ValueError, match="divisible"):
12531296
split_codegen_qkv(torch.zeros(96, 32), num_heads=4, head_dim=8, mp_num=3)
1297+
1298+
1299+
class TestStackPerExpertMoEWeights:
1300+
"""Per-expert GPTQ/AWQ MoE tensors -> fused expert-major QMoE layout.
1301+
1302+
Runs on the MatMulNBits-reshaped layout produced by preprocess_gptq_weights:
1303+
``.weight`` [N, n_blocks, blob], ``.scales`` [N, n_blocks].
1304+
"""
1305+
1306+
NUM_EXPERTS = 4
1307+
HIDDEN = 8
1308+
INTER = 6
1309+
N_BLOCKS = 2
1310+
BLOB = 2 # bits=4 -> block_size/2
1311+
1312+
def _per_expert_state_dict(self):
1313+
prefix = "model.layers.0.mlp.experts"
1314+
sd = {}
1315+
# Deterministic distinct values so a permutation/gate-up swap is visible.
1316+
for e in range(self.NUM_EXPERTS):
1317+
for proj, out in (
1318+
("gate_proj", self.INTER),
1319+
("up_proj", self.INTER),
1320+
("down_proj", self.HIDDEN),
1321+
):
1322+
base = (e + 1) * 1000 + {"gate_proj": 0, "up_proj": 100, "down_proj": 200}[
1323+
proj
1324+
]
1325+
w = (
1326+
(base + torch.arange(out * self.N_BLOCKS * self.BLOB))
1327+
.reshape(out, self.N_BLOCKS, self.BLOB)
1328+
.to(torch.uint8)
1329+
)
1330+
s = (
1331+
(base + torch.arange(out * self.N_BLOCKS))
1332+
.reshape(out, self.N_BLOCKS)
1333+
.float()
1334+
)
1335+
sd[f"{prefix}.{e}.{proj}.weight"] = w
1336+
sd[f"{prefix}.{e}.{proj}.scales"] = s
1337+
sd[f"{prefix}.{e}.{proj}.bias"] = torch.zeros(out)
1338+
return sd, prefix
1339+
1340+
def test_stacks_into_fused_expert_major(self):
1341+
sd, prefix = self._per_expert_state_dict()
1342+
result = stack_per_expert_moe_weights(sd, qmoe_target_path=".mlp")
1343+
1344+
gu_w = result[f"{prefix}.gate_up_proj.weight"]
1345+
gu_s = result[f"{prefix}.gate_up_proj.scales"]
1346+
dn_w = result[f"{prefix}.down_proj.weight"]
1347+
1348+
assert gu_w.shape == (self.NUM_EXPERTS, 2 * self.INTER, self.N_BLOCKS, self.BLOB)
1349+
assert gu_s.shape == (self.NUM_EXPERTS, 2 * self.INTER, self.N_BLOCKS)
1350+
assert dn_w.shape == (self.NUM_EXPERTS, self.HIDDEN, self.N_BLOCKS, self.BLOB)
1351+
1352+
# Per-expert biases/g_idx are dropped; no per-expert keys survive.
1353+
assert not any(".experts.0." in k for k in result)
1354+
1355+
def test_gate_first_then_up_ordering(self):
1356+
"""fc1 rows must be [gate(0:inter); up(inter:2*inter)] per expert."""
1357+
sd, prefix = self._per_expert_state_dict()
1358+
result = stack_per_expert_moe_weights(sd, qmoe_target_path=".mlp")
1359+
gu_w = result[f"{prefix}.gate_up_proj.weight"]
1360+
for e in range(self.NUM_EXPERTS):
1361+
torch.testing.assert_close(
1362+
gu_w[e, : self.INTER], sd[f"{prefix}.{e}.gate_proj.weight"]
1363+
)
1364+
torch.testing.assert_close(
1365+
gu_w[e, self.INTER :], sd[f"{prefix}.{e}.up_proj.weight"]
1366+
)
1367+
1368+
def test_expert_axis_order_preserved(self):
1369+
"""Stacking must preserve expert index order (catches permutation)."""
1370+
sd, prefix = self._per_expert_state_dict()
1371+
result = stack_per_expert_moe_weights(sd, qmoe_target_path=".mlp")
1372+
dn_w = result[f"{prefix}.down_proj.weight"]
1373+
for e in range(self.NUM_EXPERTS):
1374+
torch.testing.assert_close(dn_w[e], sd[f"{prefix}.{e}.down_proj.weight"])
1375+
1376+
def test_already_fused_is_noop(self):
1377+
"""Olive-style fused expert-major tensors pass through unchanged."""
1378+
sd = {
1379+
"model.layers.0.mlp.experts.gate_up_proj.weight": torch.zeros(
1380+
self.NUM_EXPERTS, 2 * self.INTER, self.N_BLOCKS, self.BLOB
1381+
),
1382+
"model.layers.0.mlp.experts.down_proj.weight": torch.zeros(
1383+
self.NUM_EXPERTS, self.HIDDEN, self.N_BLOCKS, self.BLOB
1384+
),
1385+
}
1386+
result = stack_per_expert_moe_weights(sd, qmoe_target_path=".mlp")
1387+
assert result is sd
1388+
1389+
def test_non_expert_keys_pass_through(self):
1390+
sd, _prefix = self._per_expert_state_dict()
1391+
sd["model.embed_tokens.weight"] = torch.randn(4, 8)
1392+
result = stack_per_expert_moe_weights(sd, qmoe_target_path=".mlp")
1393+
assert torch.equal(
1394+
result["model.embed_tokens.weight"], sd["model.embed_tokens.weight"]
1395+
)

‎src/mobius/models/moe.py‎

Lines changed: 28 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@
1212
from onnxscript import OpBuilder, nn
1313

1414
from mobius._configs import ArchitectureConfig
15+
from mobius._weight_utils import preprocess_quantized_weights
1516
from mobius.components import (
1617
Attention,
1718
Embedding,
@@ -52,6 +53,28 @@ def _quantized_linear_class(config: ArchitectureConfig) -> type | None:
5253
)
5354

5455

56+
def _preprocess_moe_weights(model: nn.Module, state_dict) -> dict:
57+
"""Shared MoE weight preprocessing that routes routed experts through QMoE.
58+
59+
Applies the standard quantization conversion (GPTQ/AWQ/Olive) and, when the
60+
checkpoint's quantization matches the native QMoE ABI, stacks per-expert
61+
projections into the fused expert-major tensors and packs them into
62+
``com.microsoft::QMoE`` parameters (``qmoe_target_path=".mlp"`` — the routed
63+
``self.mlp`` block). Float and non-QMoE checkpoints fall through to the dense
64+
loop-over-experts representation unchanged.
65+
66+
Callers pass a state dict whose HF expert layout has already been
67+
normalised (see :func:`_rename_moe_expert_weights`).
68+
"""
69+
return preprocess_quantized_weights(
70+
state_dict,
71+
getattr(model.config, "quantization", None),
72+
tie_embeddings=model.config.tie_word_embeddings,
73+
qmoe_target_path=".mlp",
74+
qmoe_quant_methods=("gptq", "awq", "olive"),
75+
)
76+
77+
5578
class MoEDecoderLayer(nn.Module):
5679
"""Decoder layer with MoE replacing the standard MLP.
5780
@@ -287,7 +310,7 @@ def preprocess_weights(
287310
self, state_dict: dict[str, torch.Tensor]
288311
) -> dict[str, torch.Tensor]:
289312
state_dict = _rename_moe_expert_weights(state_dict)
290-
return super().preprocess_weights(state_dict)
313+
return _preprocess_moe_weights(self, state_dict)
291314

292315

293316
class Qwen2MoELayer(MoELayer):
@@ -392,7 +415,7 @@ def preprocess_weights(
392415
self, state_dict: dict[str, torch.Tensor]
393416
) -> dict[str, torch.Tensor]:
394417
state_dict = _rename_moe_expert_weights(state_dict)
395-
return super().preprocess_weights(state_dict)
418+
return _preprocess_moe_weights(self, state_dict)
396419

397420

398421
class UngatedSharedMoELayer(MoELayer):
@@ -417,9 +440,7 @@ def __init__(self, config: ArchitectureConfig, gate: nn.Module | None = None):
417440
)
418441
# Quantize the shared expert when the checkpoint does (mobius#513);
419442
# GPTQ/AWQ Ernie4.5-MoE / GLM4-MoE pack ``mlp.shared_expert.*``.
420-
self.shared_expert = MLP(
421-
shared_config, linear_class=_quantized_linear_class(config)
422-
)
443+
self.shared_expert = MLP(shared_config, linear_class=_quantized_linear_class(config))
423444

424445
def forward(self, op: OpBuilder, hidden_states: ir.Value):
425446
# Routed expert output: top-k weighted sum [B, S, H]
@@ -487,7 +508,7 @@ def preprocess_weights(
487508
self, state_dict: dict[str, torch.Tensor]
488509
) -> dict[str, torch.Tensor]:
489510
state_dict = _preprocess_shared_moe_weights(state_dict)
490-
return super().preprocess_weights(state_dict)
511+
return _preprocess_moe_weights(self, state_dict)
491512

492513

493514
class Glm4MoECausalLMModel(CausalLMModel):
@@ -522,7 +543,7 @@ def preprocess_weights(
522543
self, state_dict: dict[str, torch.Tensor]
523544
) -> dict[str, torch.Tensor]:
524545
state_dict = _preprocess_shared_moe_weights(state_dict)
525-
return super().preprocess_weights(state_dict)
546+
return _preprocess_moe_weights(self, state_dict)
526547

527548

528549
class HunYuanMoEV1CausalLMModel(CausalLMModel):

0 commit comments

Comments
 (0)