Skip to content

Commit b256920

Browse files
justinchubyCopilot
andcommitted
fix(gguf): fail closed for per-projection v2 -- remove the env-only overclaim
Reviewer revision (Gaff REJECT-WITH-REVISION on #591): the block_layout_version=2 opt-in was a bare environment flag wired into the production export path, so MOBIUS_ENABLE_BQMOE_PERPROJ_V2=1 could make build_from_gguf emit a v2 node the current runtime cannot execute while still reporting a green build. No shipped onnx-genai runtime implements the per-projection v2 ABI and there is no typed runtime-capability handshake yet, so v2 must never be reachable from production. Honesty fix (narrow; approved fusion/builder behavior unchanged): * Remove _perproj_bqmoe_v2_runtime_available() and the now-unused os import. The production authority path (_fuse_native_block_moe) no longer enables v2 at all: a mixed-format layer always typed-rejects with SparseMoEExportError. The env var is retired and has no effect on any build. * Flip the public fuse_block_quantized_moe default from perproj_v2_runtime=True to fail-closed, and rename the parameter to the private, test-only _allow_perproj_v2_schema (default False). A direct public caller now rejects a mixed-format v2 layer by default; the only way to emit a v2 node is an explicit schema-construction test opt-in, unreachable from the builder, CLI, or environment, and the node it builds is schema-only and never runnable. * Update the _plan_layer reject message: no env override; v2 stays a schema-construction test path until a typed runtime-capability handshake ships. Tests: * New: setting the retired MOBIUS_ENABLE_BQMOE_PERPROJ_V2 (every truthy spelling) cannot bypass the blocker -- _fuse_native_block_moe and end-to-end build_from_gguf both still raise SparseMoEExportError with the dense graph left untouched; env + allow_dense keeps the runnable dense fallback, never a v2 node. * Direct public fuse_block_quantized_moe rejects mixed-format v2 by default; v1 uniform still fuses; the private schema hook stays covered for the v2 shape. * Removed the two runtime-probe tests and the two v2-via-env emission tests (the env capability they asserted no longer exists). Focused 42 passed; full rewrite_rules/ + integrations/gguf/ 575 passed, 1 skipped. ruff check + ruff format --check clean on all four changed files. Co-authored-by: Copilot <[email protected]>
1 parent e851b2e commit b256920

4 files changed

Lines changed: 128 additions & 110 deletions

File tree

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

Lines changed: 49 additions & 36 deletions
Original file line numberDiff line numberDiff line change
@@ -4,13 +4,13 @@
44
"""Builder-side wiring for the native-block sparse-MoE fusion + honesty gate.
55
66
These tests exercise the ``build_from_gguf`` post-export integration points
7-
(:func:`_fuse_native_block_moe`, :func:`_assert_sparse_moe_graph`, and the
8-
:func:`_perproj_bqmoe_v2_runtime_available` runtime-capability probe) on synthetic
7+
(:func:`_fuse_native_block_moe`, :func:`_assert_sparse_moe_graph`) on synthetic
98
exported packages -- i.e. the graph state the builder hands to the fusion after
109
``pkg.apply_weights``. They are distinct from the rewrite-rule unit tests: the
11-
focus here is the *builder's* honesty policy (default fail-closed, per-projection
12-
v2 runtime gate, opt-in dense retention, and the final-graph-state backstop),
13-
byte-preserving expert banks, and deterministic external data.
10+
focus here is the *builder's* honesty policy (default fail-closed for
11+
mixed-format per-projection v2 with no environment opt-in, opt-in dense
12+
retention, and the final-graph-state backstop), byte-preserving expert banks,
13+
and deterministic external data.
1414
1515
Native IQ/GGUF blocks are codebook-based and cannot be dequantized in NumPy, so
1616
correctness is proven structurally (the routed expert storm collapses; the shared
@@ -32,7 +32,6 @@
3232
from mobius.integrations.gguf._builder import (
3333
_assert_sparse_moe_graph,
3434
_fuse_native_block_moe,
35-
_perproj_bqmoe_v2_runtime_available,
3635
_routed_dense_block_matmul_nodes,
3736
)
3837
from mobius.rewrite_rules._block_quantized_moe_fusion import _NATIVE_BLOCK_FORMATS
@@ -61,17 +60,26 @@ def _moe(pkg: ModelPackage) -> ir.Node:
6160

6261

6362
# --------------------------------------------------------------------------- #
64-
# Runtime-capability probe #
63+
# The retired env flag cannot force an unrunnable v2 node through the builder #
6564
# --------------------------------------------------------------------------- #
66-
def test_perproj_v2_runtime_probe_defaults_false(monkeypatch) -> None:
67-
monkeypatch.delenv(_V2_ENV, raising=False)
68-
assert _perproj_bqmoe_v2_runtime_available() is False
69-
70-
7165
@pytest.mark.parametrize("value", ["1", "true", "TRUE", "yes", "on"])
72-
def test_perproj_v2_runtime_probe_env_opt_in(monkeypatch, value) -> None:
66+
def test_builder_env_flag_cannot_force_v2(monkeypatch, value) -> None:
67+
"""The retired ``MOBIUS_ENABLE_BQMOE_PERPROJ_V2`` env flag cannot bypass the blocker.
68+
69+
A mixed-format (v2-only) layer must typed-reject through the builder no matter
70+
how the old opt-in env var is set: production never emits an unrunnable v2
71+
node from an environment variable. The reject is atomic -- the dense graph is
72+
left untouched.
73+
"""
7374
monkeypatch.setenv(_V2_ENV, value)
74-
assert _perproj_bqmoe_v2_runtime_available() is True
75+
pkg, _ = _pkg(gate_fmt="iq1_s", up_fmt="iq1_s", down_fmt="iq4_xs")
76+
equal_before = _count(pkg, "Equal")
77+
78+
with pytest.raises(SparseMoEExportError, match=r"block_layout_version=2"):
79+
_fuse_native_block_moe(pkg, allow_dense=False)
80+
81+
assert _count(pkg, "BlockQuantizedMoE") == 0
82+
assert _count(pkg, "Equal") == equal_before # untouched
7583

7684

7785
# --------------------------------------------------------------------------- #
@@ -115,18 +123,22 @@ def test_builder_mixed_format_typed_rejects_without_v2_runtime(monkeypatch) -> N
115123
assert _count(pkg, "Equal") == equal_before # untouched
116124

117125

118-
def test_builder_mixed_format_fuses_with_v2_runtime(monkeypatch) -> None:
119-
"""With the v2 runtime opted in, a mixed-format layer fuses to a v2 node."""
126+
def test_builder_env_flag_with_allow_dense_keeps_runnable_fallback(monkeypatch) -> None:
127+
"""Env flag set + allow_dense keeps the runnable dense storm, never a v2 node.
128+
129+
The only non-reject escape for a mixed-format layer is the explicit dense
130+
fallback (every expert per token, no throughput claim). Even then the builder
131+
must not emit a ``block_layout_version=2`` node from the retired env flag.
132+
"""
120133
monkeypatch.setenv(_V2_ENV, "1")
121134
pkg, _ = _pkg(gate_fmt="iq1_s", up_fmt="iq1_s", down_fmt="iq4_xs")
122-
fused = _fuse_native_block_moe(pkg, allow_dense=False)
123-
_assert_sparse_moe_graph(pkg, source="mixed.gguf", allow_dense=False)
135+
equal_before = _count(pkg, "Equal")
124136

125-
assert fused == 1
126-
attrs = _moe(pkg).attributes
127-
assert attrs["block_layout_version"].value == 2
128-
assert attrs["fc1_format"].value == "iq1_s"
129-
assert attrs["fc2_format"].value == "iq4_xs"
137+
fused = _fuse_native_block_moe(pkg, allow_dense=True)
138+
139+
assert fused == 0 # nothing fused
140+
assert _count(pkg, "BlockQuantizedMoE") == 0 # no v2 node emitted from the env flag
141+
assert _count(pkg, "Equal") == equal_before # runnable dense fallback preserved
130142

131143

132144
def test_builder_allow_dense_retains_dense_fallback(monkeypatch) -> None:
@@ -232,8 +244,10 @@ def test_gate_opt_in_allows_leftover_storm() -> None:
232244
# exercise the identical routed dense-loop -> BlockQuantizedMatMul storm and the
233245
# same step 9b authority point with a tiny, self-contained model, so they are
234246
# the honest end-to-end proof for the fusion wiring. GLM-5.2's own layers are
235-
# per-projection mixed-format, so end-to-end they can only typed-reject until the
236-
# v2 runtime ships (covered by the mixed-format case below).
247+
# per-projection mixed-format, so end-to-end they can only typed-reject until a
248+
# real typed v2 runtime-capability handshake ships -- no environment flag can
249+
# force a v2 node (covered by the mixed-format reject + env-cannot-force cases
250+
# below).
237251

238252
_E2E_HID = 64
239253
_E2E_MOE_INTER = 32
@@ -363,22 +377,21 @@ def test_e2e_mixed_format_typed_rejects_through_builder(monkeypatch, tmp_path) -
363377
build_from_gguf(path, keep_quantized=True)
364378

365379

366-
def test_e2e_mixed_format_fuses_with_v2_runtime(monkeypatch, tmp_path) -> None:
367-
"""Opting the v2 runtime in emits a single per-projection v2 BQMoE end-to-end."""
380+
def test_e2e_env_flag_cannot_force_v2_through_builder(monkeypatch, tmp_path) -> None:
381+
"""The retired env flag cannot make ``build_from_gguf`` emit a v2 node.
382+
383+
End-to-end, a GLM-5.2-style per-projection mixed GGUF must still raise
384+
``SparseMoEExportError`` with the old opt-in env var set: there is no
385+
production, CLI, or environment path to an unrunnable v2 node.
386+
"""
368387
from mobius.integrations.gguf import build_from_gguf
369388

370389
monkeypatch.setenv(_V2_ENV, "1")
371-
path = tmp_path / "mixed-moe-v2.gguf"
390+
path = tmp_path / "mixed-moe-env.gguf"
372391
_write_native_moe_gguf(path, down_fmt="iq4_xs")
373392

374-
pkg = build_from_gguf(path, keep_quantized=True)
375-
moe, matmul = _e2e_ops(pkg)
376-
assert moe == 1
377-
assert matmul == 4
378-
attrs = _moe(pkg).attributes
379-
assert attrs["block_layout_version"].value == 2
380-
assert attrs["fc1_format"].value == "iq1_s"
381-
assert attrs["fc2_format"].value == "iq4_xs"
393+
with pytest.raises(SparseMoEExportError, match=r"block_layout_version=2"):
394+
build_from_gguf(path, keep_quantized=True)
382395

383396

384397
def test_e2e_allow_dense_retains_storm_through_builder(monkeypatch, tmp_path) -> None:

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

Lines changed: 14 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,6 @@
1919
__all__ = ["build_from_gguf"]
2020

2121
import logging
22-
import os
2322
import re
2423
from collections import Counter
2524
from collections.abc import Callable, Iterable, Mapping
@@ -226,46 +225,33 @@ def _assert_sparse_moe_capability(module, config, *, source: str, allow_dense: b
226225
)
227226

228227

229-
def _perproj_bqmoe_v2_runtime_available() -> bool:
230-
"""Whether the deployed pkg.nxrt runtime implements the v2 BlockQuantizedMoE ABI.
231-
232-
A layer that mixes native block formats across its fc1/fc2/fc3 banks (e.g.
233-
GLM-5.2 UD-IQ1 with an iq1 gate/up and a higher-bit down projection) can only
234-
be expressed with the ``block_layout_version=2`` per-projection
235-
``BlockQuantizedMoE`` ABI. That ABI is not yet merged/released in the
236-
onnx-genai runtime, so emitting a v2 node here would build an ONNX graph the
237-
current runtime cannot execute -- an overclaim. Default ``False`` makes such
238-
mixed-format layers fail closed (typed reject) until the runtime ships v2;
239-
set ``MOBIUS_ENABLE_BQMOE_PERPROJ_V2=1`` only once it does.
240-
"""
241-
return os.environ.get("MOBIUS_ENABLE_BQMOE_PERPROJ_V2", "").strip().lower() in {
242-
"1",
243-
"true",
244-
"yes",
245-
"on",
246-
}
247-
248-
249228
def _fuse_native_block_moe(pkg, *, allow_dense: bool) -> int:
250229
"""Collapse routed native-block expert storms into sparse ``BlockQuantizedMoE``.
251230
252231
Runs on the final, fully-weighted graph so the fusion can stack each layer's
253232
per-expert native blocks byte-for-byte into one expert-major bank. Every
254233
candidate layer is validated before any node is emitted, so an unfusable
255-
layer (mixed format with no v2 runtime, per-expert bias, ragged/incomplete
256-
group) raises :class:`SparseMoEExportError` atomically with the graph
257-
untouched, unless ``allow_dense`` downgrades it to a warning + dense keep.
234+
layer (per-expert bias, ragged/incomplete group, ...) raises
235+
:class:`SparseMoEExportError` atomically with the graph untouched, unless
236+
``allow_dense`` downgrades it to a warning + dense keep.
237+
238+
A layer that mixes native formats across its fc1/fc2/fc3 banks (GLM-5.2
239+
UD-IQ1) can only be expressed with the ``block_layout_version=2``
240+
per-projection ABI, which no shipped onnx-genai runtime executes yet. The
241+
production builder therefore never enables v2: such layers always
242+
typed-reject here rather than emit an unrunnable node. There is no
243+
environment or CLI opt-in -- v2 stays a schema-construction test path until a
244+
real typed runtime-capability handshake exists.
258245
"""
259246
# Imported lazily: the generic rewrite lives in the rewrite_rules package and
260247
# must not be pulled into the GGUF import graph at module load time.
261248
from mobius.rewrite_rules import fuse_block_quantized_moe
262249

263-
perproj_v2 = _perproj_bqmoe_v2_runtime_available()
264250
fused = 0
265251
for model in pkg.values():
266-
fused += fuse_block_quantized_moe(
267-
model, allow_dense_moe=allow_dense, perproj_v2_runtime=perproj_v2
268-
)
252+
# No ``_allow_perproj_v2_schema`` argument: the production authority path
253+
# always fails closed for mixed-format v2 (fail-safe default).
254+
fused += fuse_block_quantized_moe(model, allow_dense_moe=allow_dense)
269255
return fused
270256

271257

‎src/mobius/rewrite_rules/_block_quantized_moe_fusion.py‎

Lines changed: 32 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -604,15 +604,19 @@ class _FusionPlan:
604604
experts: int
605605

606606

607-
def _plan_layer(layer: _DenseMoELayer, index: int, *, perproj_v2_runtime: bool) -> _FusionPlan:
607+
def _plan_layer(
608+
layer: _DenseMoELayer, index: int, *, allow_perproj_v2_schema: bool
609+
) -> _FusionPlan:
608610
"""Validate and byte-stack one native MoE layer without touching the graph.
609611
610-
``perproj_v2_runtime`` declares whether the target runtime implements the
611-
``block_layout_version=2`` per-projection ``BlockQuantizedMoE`` ABI. When a
612-
layer mixes native formats across its fc1/fc2/fc3 banks it can only be
613-
expressed as a v2 node; if the runtime cannot execute v2, planning fails
614-
closed here (before any graph mutation) rather than emitting an unrunnable
615-
node.
612+
``allow_perproj_v2_schema`` is a private, test-only switch. A layer that
613+
mixes native formats across its fc1/fc2/fc3 banks can only be expressed as a
614+
``block_layout_version=2`` per-projection node, and no shipped onnx-genai
615+
runtime executes that ABI yet. It therefore defaults off on every production,
616+
CLI, and environment path, and planning fails closed for such a layer (before
617+
any graph mutation) rather than emitting an unrunnable node. It is set
618+
``True`` only by schema-construction tests that assert the v2 node's shape;
619+
the node they build is not runnable and must never be shipped.
616620
"""
617621
ids = sorted(layer.experts)
618622
gate_nodes = [layer.experts[i].gate for i in ids]
@@ -668,14 +672,16 @@ def _plan_layer(layer: _DenseMoELayer, index: int, *, perproj_v2_runtime: bool)
668672
if len(distinct) == 1:
669673
attributes["format"] = next(iter(distinct))
670674
else:
671-
if not perproj_v2_runtime:
675+
if not allow_perproj_v2_schema:
672676
raise _UnfusableError(
673677
"mixed per-projection native formats "
674678
f"{sorted(distinct)} can only be expressed with the "
675679
"block_layout_version=2 per-projection BlockQuantizedMoE ABI, "
676-
"which the target runtime does not implement -- emitting a v2 "
677-
"node would build an unrunnable graph (overclaim). Set "
678-
"MOBIUS_ENABLE_BQMOE_PERPROJ_V2=1 only once the runtime ships it"
680+
"which no shipped onnx-genai runtime implements -- emitting a v2 "
681+
"node would build an unrunnable graph (overclaim), so export "
682+
"fails closed. There is no production, CLI, or environment opt-in; "
683+
"v2 stays a schema-construction test path until a typed runtime "
684+
"capability handshake ships"
679685
)
680686
attributes["block_layout_version"] = 2
681687
# ``format`` is the required base/fallback; per-projection attributes
@@ -829,7 +835,7 @@ def fuse_block_quantized_moe(
829835
model: ir.Model,
830836
*,
831837
allow_dense_moe: bool | None = None,
832-
perproj_v2_runtime: bool = True,
838+
_allow_perproj_v2_schema: bool = False,
833839
) -> int:
834840
"""Fuse every dense-fallback native-block MoE subgraph into ``BlockQuantizedMoE``.
835841
@@ -858,14 +864,17 @@ def fuse_block_quantized_moe(
858864
``allow_dense_moe_experts`` flag / ``MOBIUS_ALLOW_DENSE_MOE_EXPERTS``
859865
environment variable is used. This is a research/correctness path
860866
only and makes no throughput claim.
861-
perproj_v2_runtime: Whether the target runtime implements the
862-
``block_layout_version=2`` per-projection ``BlockQuantizedMoE`` ABI
863-
(mixed native formats across a layer's fc1/fc2/fc3 banks, e.g.
864-
GLM-5.2 UD-IQ1 with an iq1 gate/up and a higher-bit down). This is a
865-
pure graph transform, so it defaults to ``True`` (v2 is always
866-
representable); the GGUF export authority passes the actual runtime
867-
capability so a mixed-format layer fails closed rather than emitting
868-
an unrunnable v2 node when the runtime has not shipped v2 yet.
867+
_allow_perproj_v2_schema: Private, test-only switch. A layer that mixes
868+
native formats across its fc1/fc2/fc3 banks (e.g. GLM-5.2 UD-IQ1 with
869+
an iq1 gate/up and a higher-bit down) can only be expressed with the
870+
``block_layout_version=2`` per-projection ``BlockQuantizedMoE`` ABI.
871+
No shipped onnx-genai runtime implements that ABI, so this defaults to
872+
``False`` (fail closed): the production ``build_from_gguf`` path never
873+
sets it, and a mixed-format layer typed-rejects rather than emitting an
874+
unrunnable v2 node. It is ``True`` only in schema-construction tests
875+
that assert the v2 node's shape; that node is not runnable and must
876+
never be shipped. Until a real typed runtime-capability handshake
877+
exists there is no production, CLI, or environment path to v2.
869878
870879
Returns:
871880
The number of MoE layers fused.
@@ -893,7 +902,9 @@ def fuse_block_quantized_moe(
893902
continue
894903
try:
895904
layer.check_fusable()
896-
plans.append(_plan_layer(layer, index, perproj_v2_runtime=perproj_v2_runtime))
905+
plans.append(
906+
_plan_layer(layer, index, allow_perproj_v2_schema=_allow_perproj_v2_schema)
907+
)
897908
except _UnfusableError as reason:
898909
_fail_closed(layer, reason, allow_dense=allow_dense_moe)
899910

0 commit comments

Comments
 (0)