Skip to content

Fuse GLM native-block routed experts into sparse pkg.nxrt::BlockQuantizedMoE (+ build_from_gguf wiring) - #591

Merged
justinchuby merged 5 commits into
mainfrom
squad/bqmoe-native-fusion
Aug 24, 2026
Merged

justinchuby merged 5 commits into
mainfrom
squad/bqmoe-native-fusion

Conversation

@justinchuby

Copy link
Copy Markdown
Member

Native-block sparse-MoE fusion + build_from_gguf integration

Collapses GLM-style routed native-block expert storms (a per-expert
pkg.nxrt::BlockQuantizedMatMul for every gate/up/down of every expert,
dispatched by an Equal one-hot mask) into one sparse top-k
pkg.nxrt::BlockQuantizedMoE per layer
, reusing the existing native blocks
byte-for-byte (no dequantize, no requantize). Gated on graph/tensor
structure, never on model names.

What's here

  1. Rewrite (rewrite_rules/_block_quantized_moe_fusion.py) — the transform:
    finds the dense-fallback MoE subgraph, validates all layers, then emits.
    Two-pass so an unfusable layer fails atomically with the graph untouched.
  2. Builder integration (integrations/gguf/_builder.py) — wires the fusion
    into build_from_gguf at the single post-export authority point (step
    9b, after pkg.apply_weights, once every native block carries real packed
    bytes), then a final-graph-state honesty gate.

Applicability verdict (Phase-1 audit)

  • GLM-5.2 UD-IQ1_S/M routed experts are per-projection mixed-format per
    layer (fused gate==up in iq1_s/iq1_m; down in a higher-bit format such as
    iq4_xs). A v1 single-format BlockQuantizedMoE therefore fuses 0 GLM
    layers.
  • Expressing a mixed-format layer needs the block_layout_version=2
    per-projection ABI
    (fc1_format/fc2_format/fc3_format). That runtime
    ABI lives on an unmerged onnx-genai branch, so mobius's runnable runtime
    does not yet have it.
  • Honest consequence: GLM-5.2 mixed-format layers typed-reject
    (SparseMoEExportError, message names block_layout_version=2) until the
    runtime ships v2 — we never emit an unrunnable v2 node by default. Uniform
    native-block routed MoE does fuse today (v1).

Honesty / fail-closed policy

  • Default allow_dense_moe=False. Unsupported layers (mixed w/o v2, per-expert
    bias, ragged/incomplete groups) raise the shared SparseMoEExportError
    atomically; the graph is left as the original dense storm.
  • _perproj_bqmoe_v2_runtime_available() gates v2 emission on
    MOBIUS_ENABLE_BQMOE_PERPROJ_V2 (default off). Flip it only once the
    onnx-genai v2 runtime ships.
  • The pre-export module-level gate call was removed (it would reject the
    layers the fusion now collapses); enforcement moved to the final graph
    state
    — the fusion's atomic reject + a _assert_sparse_moe_graph backstop
    that fails closed on any surviving routed .experts. BlockQuantizedMatMul
    storm. Single mechanism, no duplicate gate. Batty's _assert_sparse_moe_capability
    / _routed_dense_block_expert_paths (Direct multi-shard GGUF import + GLM-5.2 (glm-dsa→glm_moe_dsa) resolution #581) stay defined for their unit tests.
  • allow_dense_moe=True may warn + retain the dense fallback, but never
    counts as a performance path (no throughput claim).

Emitted ABI (unchanged runtime contract)

BlockQuantizedMoE 9 inputs, FLOAT32: [input, router_logits, fc1_experts_weights(uint8 4D), fc1_bias?, fc2_experts_weights, fc2_bias?, fc3_experts_weights?, fc3_bias?, router_weights?]. Uniform layer → format
attr (v1). Mixed layer → block_layout_version=2 + fc1_format/fc2_format/
fc3_format. Expert banks are the source native blocks stacked verbatim
(byte-preservation asserted in tests).

Tests (same commits)

  • Rewrite unit (_block_quantized_moe_fusion_test.py, 23): GLM-style
    Sigmoid+TopK+normalize routing, top-k {1,8}, byte-preserving stacking,
    atomic fail-closed (dropped/duplicate/ragged/mixed-bias experts), structural
    proof the expert matmuls collapse, and the new v2-runtime gate (uniform
    fuses without v2; mixed typed-rejects without v2; mixed emits v2 when opted in).
  • Builder integration (_block_quantized_moe_builder_test.py, 20): step-9b
    helpers on synthetic exported packages (default fail-closed, v2 opt-in, dense
    retention, byte-preserving banks, deterministic external data, final-state
    backstop) plus 5 real end-to-end build_from_gguf builds on synthetic
    native-block MoE GGUFs (qwen3_moe / qwen2_moe, which lower through the
    identical routed dense-loop → BlockQuantizedMatMul storm and the same step-9b
    authority point):
    • uniform → one BlockQuantizedMoE, only attention matmuls remain (no storm);
    • mixed → SparseMoEExportError (GLM-5.2's honest path);
    • mixed + MOBIUS_ENABLE_BQMOE_PERPROJ_V2=1 → one v2 node;
    • allow_dense_moe=True → dense storm retained (no fused node);
    • shared expert stays dense while the routed storm collapses.

Full rewrite_rules/ + integrations/gguf/ suites: 576 passed, 1 skipped.
ruff check + ruff format --check: clean.

Remaining typed blockers (not overclaimed)

  1. v2 per-projection runtime ABI is unmerged in onnx-genai → GLM-5.2
    mixed-format typed-rejects end-to-end until it ships. Uniform native-block
    MoE fuses today.
  2. No A100 benchmark yet — deferred until a runnable shape-faithful
    importer path exists (GLM-5.2 can't build to a runnable graph until v2 lands).
    Full-model speed is not claimed.
  3. _builder.py merge coordination — Sapper's GGUF export preflight: block-preserving lossless-only classification + budget (reconciled into #581) #578 (unmerged) also rewrites
    _builder.py; a future rebase will need coordinator-mediated conflict
    resolution. No live collision on this base.

Dependency on Batty's sharded import

Builds on the merged #581 (GgufShardSet, glm-dsa → glm_moe_dsa bridge,
shared SparseMoEExportError) and #576; rebased cleanly on 059bf5f. Only
uses those committed public interfaces — no edits to shard-reader / architecture-
mapping files.

Draft — do not merge. Requesting independent review (excluding author).

justinchuby and others added 4 commits August 24, 2026 11:11
…zedMoE

Rewrite a dense-fallback GGUF/native-block MoE (each routed expert its own
gate/up/down BlockQuantizedMatMul, masked after the fact) into a single
sparse top-k pkg.nxrt::BlockQuantizedMoE that reads only the selected
experts' native blocks.

- Reuses the IQ/native blocks byte-for-byte (expert-major stack/concat, no
  dequant/requant); there are no scales or zero-points to carry.
- Expresses GLM-5.2 UD-IQ1 mixed per-projection formats (gate/up in one
  native format, down in another) via block_layout_version=2 and
  fc1/fc2/fc3_format; a uniform-format layer stays on v1.
- Reconstructs routing gate-agnostically from the graph's selected_experts /
  routing_weights tensors: a [tokens,experts] one-hot mask feeds router_logits
  and the scattered per-expert weights feed router_weights with
  normalize_routing_weights=0, so softmax / sigmoid+bias+scaling gates all
  fuse. Verified correct against both the CPU oracle and the CUDA route
  kernel (both gather router_weights at the selected experts).
- Property-gated and fails closed with a typed reason (mixed formats across
  experts, biased experts, incomplete/untraceable groups); never silently
  dense-evaluates every expert. Shared expert preserved.

Structural + byte-preservation + routing-reconstruction tests included;
numeric parity lives in the onnx-genai Rust CPU oracle.

Co-authored-by: Copilot <[email protected]>
Independent review found that the fusability check only verified the
traced expert ids were gap-free (ids == range(len(ids))). A dropped
highest-id expert leaves survivors 0..E-2, which still looks contiguous,
so the layer would fuse an expert bank narrower than the router selects
over -- leaving ScatterElements to index out of bounds.

Record the full declared-id set from the per-expert Equal masks up front
and require every declared expert to be fully traced; otherwise fail
closed and keep the dense graph. Add regression tests for a dropped
trailing expert and for an expert wired to a non-shared routing-weights
tensor.

Co-authored-by: Copilot <[email protected]>
…e_moe

Integrate with the sparse-MoE honesty gate merged in #581. The fusion
now uses the shared mobius.integrations.gguf.SparseMoEExportError instead
of a private best-effort skip: a routed native-block MoE that cannot be
collapsed into one expert-major bank (mixed native formats, per-expert
bias, incomplete/untraceable expert group, ragged shapes) fails closed by
default, matching build_from_gguf's gate. allow_dense_moe (defaulting to
the MOBIUS_ALLOW_DENSE_MOE_EXPERTS flag) downgrades the abort to a loud
warning that keeps the runnable dense fallback.

Split _fuse_layer into a pure _plan_layer (all validation + byte-stacking,
no graph mutation) and _emit_layer, and run the driver in two passes so
every candidate is validated before any node is emitted -- a fail-closed
layer never leaves the graph half-rewritten. A selector with no
native-block experts is still skipped silently (e.g. int4 MatMulNBits MoE).

SparseMoEExportError / _flags are imported lazily so the generic
rewrite_rules layer keeps no import-time edge into the GGUF export stack.
Update fail-closed tests to assert the typed error + untouched graph, and
add an allow_dense_moe opt-in test.

Co-authored-by: Copilot <[email protected]>
Collapse GLM-style routed native-block expert storms into one sparse top-k
pkg.nxrt::BlockQuantizedMoE per layer at the single post-export authority
point in build_from_gguf, and fail closed honestly when the target runtime
cannot represent the layer.

Rewrite (fuse_block_quantized_moe):
* Add a perproj_v2_runtime capability flag. A layer that mixes native block
  formats across its fc1/fc2/fc3 banks (GLM-5.2 UD-IQ1: iq1 gate/up + a
  higher-bit down) can only be expressed with the block_layout_version=2
  per-projection ABI. When the runtime does not implement v2, _plan_layer now
  fails closed (typed reject) before any graph mutation instead of emitting an
  unrunnable v2 node. The rewrite is a pure transform, so the flag defaults to
  True; the GGUF export authority passes the real runtime capability.

Builder integration (build_from_gguf):
* Move the sparse-MoE honesty gate from the pre-export torch-module level to
  the final graph state. The pre-export gate call is removed (it would reject
  the very layers the fusion can now collapse); Batty's gate functions stay
  defined for their direct unit tests. New step 9b runs after pkg.apply_weights
  (once every native block carries real packed bytes): _fuse_native_block_moe
  collapses the routed storm byte-for-byte, then _assert_sparse_moe_graph is a
  backstop that fails closed on any surviving routed per-expert
  BlockQuantizedMatMul storm. allow_dense_moe (default False) warns + retains
  the dense fallback with no throughput claim.
* _perproj_bqmoe_v2_runtime_available gates v2 emission on
  MOBIUS_ENABLE_BQMOE_PERPROJ_V2 (default False) so mixed-format GLM-5.2 layers
  typed-reject until the onnx-genai v2 runtime ABI ships rather than overclaim.

Tests:
* Rewrite unit tests for the v2-runtime gate (uniform fuses without v2; mixed
  typed-rejects without v2; mixed emits v2 when opted in).
* New builder-integration suite exercises the step 9b helpers on synthetic
  exported packages (default fail-closed, v2 opt-in, dense retention,
  byte-preserving banks, deterministic external data, final-state backstop) and
  drives five end-to-end build_from_gguf builds on synthetic native-block MoE
  GGUFs (qwen3_moe / qwen2_moe): uniform -> one BlockQuantizedMoE + no storm;
  mixed -> SparseMoEExportError; mixed + v2 opt-in -> one v2 node;
  allow_dense_moe -> dense storm retained; shared expert stays dense.

Co-authored-by: Copilot <[email protected]>
@github-actions

github-actions Bot commented Aug 24, 2026 •

Copy link
Copy Markdown

🏗️ Architecture Diff

Comparing 059bf5f → b256920

Model Sub-model Changes Status

No architecture changes detected. ✅


Legend: ⚪ No change · 🔵 Minor (attrs/inits) · 🟡 Moderate (nodes added/removed) · 🔴 Major (interface changed)

@github-actions

github-actions Bot commented Aug 24, 2026 •

Copy link
Copy Markdown

Performance Comparison

Comparing 059bf5f → b256920

Model Metric Baseline Current Delta
bert (feature-extraction) model_size_bytes 359 KB 359 KB +0.0% ⚪
bert (feature-extraction) num_nodes 68 68 +0.0% ⚪
falcon model_size_bytes 364 KB 364 KB +0.0% ⚪
falcon num_nodes 66 66 +0.0% ⚪
gemma2 model_size_bytes 428 KB 428 KB +0.0% ⚪
gemma2 num_nodes 105 105 +0.0% ⚪
gpt2 model_size_bytes 388 KB 388 KB +0.0% ⚪
gpt2 num_nodes 54 54 +0.0% ⚪
llama model_size_bytes 425 KB 425 KB +0.0% ⚪
llama num_nodes 60 60 +0.0% ⚪
llama (static-cache) model_size_bytes 425 KB 425 KB +0.0% ⚪
llama (static-cache) num_nodes 56 56 +0.0% ⚪
mamba (ssm-text-generation) model_size_bytes 296 KB 296 KB +0.0% ⚪
mamba (ssm-text-generation) num_nodes 94 94 +0.0% ⚪
phi3 model_size_bytes 421 KB 421 KB +0.0% ⚪
phi3 num_nodes 58 58 +0.0% ⚪
phi3 (static-cache) model_size_bytes 421 KB 421 KB +0.0% ⚪
phi3 (static-cache) num_nodes 54 54 +0.0% ⚪
qwen2 model_size_bytes 425 KB 425 KB +0.0% ⚪
qwen2 num_nodes 60 60 +0.0% ⚪
qwen2 (static-cache) model_size_bytes 425 KB 425 KB +0.0% ⚪
qwen2 (static-cache) num_nodes 56 56 +0.0% ⚪
qwen3_5_moe (hybrid-text-generation) model_size_bytes 506 KB 506 KB +0.0% ⚪
qwen3_5_moe (hybrid-text-generation) num_nodes 264 264 +0.0% ⚪
qwen3_5_text (hybrid-text-generation) model_size_bytes 458 KB 458 KB +0.0% ⚪
qwen3_5_text (hybrid-text-generation) num_nodes 126 126 +0.0% ⚪
qwen3_5_vl (hybrid-qwen-vl) model_size_bytes 977 KB 977 KB +0.0% ⚪
qwen3_5_vl (hybrid-qwen-vl) num_nodes 428 428 +0.0% ⚪
t5 (seq2seq) model_size_bytes 836 KB 836 KB +0.0% ⚪
t5 (seq2seq) num_nodes 176 176 +0.0% ⚪
whisper (speech-to-text) model_size_bytes 1008 KB 1008 KB +0.0% ⚪
whisper (speech-to-text) num_nodes 128 128 +0.0% ⚪

No performance regressions.

_E2E_KV = 2
_E2E_VOCAB = 256

_E2E_NATIVE = {"iq4_xs": "IQ4_XS", "iq1_s": "IQ1_S"}
@justinchuby

Copy link
Copy Markdown
Member Author

Independent review verdict — PR #591 (native-block routed MoE → one pkg.nxrt::BlockQuantizedMoE per layer + build_from_gguf integration)

REJECT WITH REVISION

Reviewed read-only at exact HEAD e851b2e63d4991970cdc913b5c24037f5fa79427 (author Roy-1) in an isolated worktree, against latest main (059bf5f), merged #581 (7003bc7), and #576. Independently ran the focused + full suites and lint. Requested by Justin Chu.

The transform itself is correct, well-tested, and byte-preserving. There is one blocker, and it is exactly the one flagged for scrutiny: the block_layout_version=2 opt-in is a bare environment flag with no actual runtime-capability verification, and it is wired into the production export path.

Blocker — v2 opt-in can build an unrunnable production graph from a bare env flag (honesty gate)

_builder.py::_perproj_bqmoe_v2_runtime_available() is named as a runtime-capability probe but only reads MOBIUS_ENABLE_BQMOE_PERPROJ_V2; it performs no introspection of the deployed pkg.nxrt runtime (there is no v2 capability/version symbol probed anywhere — the v2 ABI is, by the PR's own statement, unmerged in onnx-genai).

Consequences, verified by reading the build path end-to-end:

  • It is wired into the single production authority point (build_from_gguf → step 9b → _fuse_native_block_moe, _builder.py:762). Setting MOBIUS_ENABLE_BQMOE_PERPROJ_V2=1 makes a GLM-5.2-style mixed-format layer emit a block_layout_version=2 node.
  • There is no downstream op-support validation after step 9b (confirmed by reading build_from_gguf through step 10). So the build reports success while producing a graph the current runtime cannot execute — the failure is deferred to load/inference time, far from the build.
  • This directly contradicts the PR's own central invariant ("we never emit an unrunnable v2 node"). The "by default" qualifier hides that the opt-in has no safety rail beyond a trusted env var, and no production/experimental fence.
  • Broader form: the public rewrite API fuse_block_quantized_moe(...) (now exported in rewrite_rules/__all__) defaults perproj_v2_runtime=True (_block_quantized_moe_fusion.py:832). A direct caller on a mixed-format graph therefore emits a v2 node with no gate at all — the builder's env check is the only guard, and even that is trust-based.

This also runs against the team standing directive (.squad/decisions.md): env knobs "must not hide default regressions" / unsupported behavior. An env toggle that silently ships an unrunnable production artifact with a green build is precisely that.

Note this is materially different from an inert/byte-identical default-off seam: flipping this flag does not do "nothing," it produces a known-broken artifact.

Required revision (narrow):

  1. Gate v2 emission on a real typed runtime capability — probe an actual v2-capability symbol/version exported by the pkg.nxrt/onnx-genai runtime, so the env flag can only narrow (never force) v2 when the runtime genuinely lacks it; or
  2. Until that runtime symbol exists, fence the flag as explicitly experimental/non-production so the production build_from_gguf path cannot emit a v2 node claimed as runnable (e.g. require an in-process experimental sentinel and/or emit a prominent unrunnable-until-runtime-ships refusal), and rename _perproj_bqmoe_v2_runtime_available() so it does not claim to check runtime availability when it only reads an env var. Consider flipping the public API default to perproj_v2_runtime=False (fail-safe) so direct callers cannot emit an ungated v2 node.

The default-off, fail-closed path and everything below stays exactly as-is; this is a small, well-scoped change.

Everything else — verified green

  • Two-pass atomic before graph mutation: pass 1 validates + byte-stacks every layer into _FusionPlan with zero mutation; pass 2 emits. The first unfusable layer (default) raises SparseMoEExportError before any emit — fail-closed tests assert BlockQuantizedMoE == 0 and Equal == E (dense graph untouched).
  • Byte-preservation: fused SwiGLU (fc1 = concat(gate, up), swiglu_fusion=2) and unfused (fc1=gate, fc3=up, swiglu_fusion=0) both stack uint8 blocks verbatim (np.stack/concatenate); tests assert array_equal per expert, dtype UINT8.
  • Single post-weight authority point: step 9b, after pkg.apply_weights (once native blocks carry real packed bytes). One _fuse_native_block_moe + one _assert_sparse_moe_graph backstop.
  • No duplicate pre/post honesty mechanism: the pre-export _assert_sparse_moe_capability call is removed from the build flow (definition retained only for Direct multi-shard GGUF import + GLM-5.2 (glm-dsa→glm_moe_dsa) resolution #581's own unit tests); enforcement is now the fusion's atomic reject + the final-graph backstop that fails closed on any surviving routed .experts. BlockQuantizedMatMul storm (skips shared_expert).
  • Gate-agnostic routing: one-hot router_logits (ScatterElements of 1.0) + scattered router_weights, normalize_routing_weights=0; the NumPy kernel-selection model test proves top-k re-selects exactly the dense experts and gathers exactly the dense weights. Softmax / sigmoid+bias / legacy gate*Sigmoid(gate) / Swish and f16-Cast-wrapped graphs all trace.
  • Fail-closed coverage (atomic, dense untouched): mixed format across experts, per-expert bias, incomplete/untraceable group, dropped highest-id expert (declared-id set is the authority, not gap-freeness), alien routing-weights tensor, ragged packed shapes.
  • Shared expert stays dense: qwen2_moe e2e leaves the 3 shared projections as BlockQuantizedMatMul while the routed 12→1 collapse (matmul == 7).
  • allow_dense_moe=True: warns + retains the runnable dense fallback, fused == 0, never a success/throughput claim.
  • Deterministic external data / banks; rebased cleanly on latest main (includes Direct multi-shard GGUF import + GLM-5.2 (glm-dsa→glm_moe_dsa) resolution #581 GgufShardSet/glm-dsa→glm_moe_dsa + shared SparseMoEExportError, and Stream sharded safetensors export + resumable full-checkpoint preflight #576); uses only committed public interfaces (no shard-reader / arch-mapping edits).

Tests / lint (independently run)

  • Focused new suites: 23 + 20 = 43 passed (_block_quantized_moe_fusion_test.py, _block_quantized_moe_builder_test.py), including 5 real end-to-end build_from_gguf builds (uniform→one v1 node; mixed→SparseMoEExportError; mixed+_V2=1→one v2 node; allow_dense→storm retained; shared-expert survives).
  • _glm_moe_dsa_test.py (Direct multi-shard GGUF import + GLM-5.2 (glm-dsa→glm_moe_dsa) resolution #581 sparse-MoE gate): 16 passed — the retained pre-export gate still works for its unit tests.
  • Full rewrite_rules/ + integrations/gguf/: 576 passed, 1 skipped (matches the PR's claim).
  • ruff check + ruff format --check on all 5 changed files: clean / already formatted. (The 19 ruff check . errors are all in pyproject.toml, which this PR does not touch — pre-existing, out of scope.)

Base / rebase ordering

Ownership (reviewer lockout)

Per the enforced lockout, author Roy-1 does not revise this. Suggested revision owner: Batty — authored #581's capability gate and the shared SparseMoEExportError this reuses, and spans Models & Export + the runtime side needed to define a real v2 capability probe. Sapper coordinates the _builder.py/#578 overlap; arbiter Gaff (Roy is the author, so cannot self-arbitrate). Excludes Roy-1.

Draft — not merged. Independent read-only review; requested by Justin Chu.

…verclaim

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]>
@justinchuby

Copy link
Copy Markdown
Member Author

Revision — v2 honesty blocker addressed (narrow), for Gaff re-review

Addresses the single blocker in the REJECT-WITH-REVISION verdict (e851b2e): the block_layout_version=2 opt-in was a bare env flag (_perproj_bqmoe_v2_runtime_available() → MOBIUS_ENABLE_BQMOE_PERPROJ_V2) with no real runtime-capability verification, wired into the production build_from_gguf authority point — so a green build could ship an unrunnable graph. Roy‑1 is under reviewer lockout and did not revise this; revision owned by Batty.

Since no shipped onnx‑genai runtime implements the per‑projection v2 ABI and no typed capability handshake exists yet, I took the fail‑closed option (verdict option 2, made strict): production never emits v2.

What changed (revision commit b256920, 4 files)

  • _builder.py — deleted _perproj_bqmoe_v2_runtime_available() and the now‑unused os import. _fuse_native_block_moe no longer passes any v2 flag, so the production path always typed‑rejects a mixed‑format layer with SparseMoEExportError. MOBIUS_ENABLE_BQMOE_PERPROJ_V2 is retired and has no effect on any build.
  • _block_quantized_moe_fusion.py — flipped the public fuse_block_quantized_moe default from perproj_v2_runtime=True to fail‑closed, renamed the parameter to the private, test‑only _allow_perproj_v2_schema (default False). A direct public caller now rejects mixed‑format v2 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 that node is documented as schema‑only, never runnable. Reject message no longer advertises an env override.

What did not change (approved behavior preserved)

Two‑pass atomic fusion, byte‑preservation (fused/unfused SwiGLU), single step‑9b authority point + backstop, gate‑agnostic routing, all across‑expert fail‑closed cases, allow_dense_moe dense‑fallback retention, shared‑expert‑stays‑dense, deterministic external data. The v2 schema transform itself is untouched — it is now reached only through the explicit test‑only hook.

Evidence (independently run in this worktree)

  • Env cannot bypass (new): MOBIUS_ENABLE_BQMOE_PERPROJ_V2 in every truthy spelling (1/true/TRUE/yes/on) still typed‑rejects at _fuse_native_block_moe and end‑to‑end through build_from_gguf, dense graph left untouched; env + allow_dense keeps the runnable dense fallback (never a v2 node).
  • Public default fails closed (new): direct fuse_block_quantized_moe(model) on a mixed‑format layer raises SparseMoEExportError (block_layout_version=2), graph untouched; v1 uniform still fuses; private _allow_perproj_v2_schema=True still builds the v2 shape (schema‑only).
  • Focused suites: 42 passed (_block_quantized_moe_fusion_test.py, _block_quantized_moe_builder_test.py).
  • Full rewrite_rules/ + integrations/gguf/: 575 passed, 1 skipped (net −1 test: the removed env‑probe test has no successor; Direct multi-shard GGUF import + GLM-5.2 (glm-dsa→glm_moe_dsa) resolution #581's _glm_moe_dsa_test.py still green).
  • ruff check + ruff format --check on all 4 changed files: clean.

Limitations / scope

Draft — not merged. Stopping for independent Gaff re‑review. Requested by Justin Chu.

@justinchuby

Copy link
Copy Markdown
Member Author

APPROVE FOR MERGE

Independent re-review of the narrow Batty revision at exact HEAD b256920e97c63859a698a40df99d9cf5af5f64fa (read-only). This addresses the sole blocker from the prior REJECT (the MOBIUS_ENABLE_BQMOE_PERPROJ_V2 bare env flag could make build_from_gguf emit an unrunnable block_layout_version=2 per-projection node from the production path while reporting a green build). Roy-1 remains locked out; verified they did not contribute this revision (single fix commit b256920 on top of the rejected e851b2e).

Blocker resolution — verified

Env pseudo-capability fully removed from production/CLI/direct defaults.

  • _perproj_bqmoe_v2_runtime_available() and the now-unused import os are deleted from _builder.py.
  • Repo-wide grep: MOBIUS_ENABLE_BQMOE_PERPROJ_V2, _perproj_bqmoe_v2_runtime_available, and the old perproj_v2_runtime parameter have zero references in production src/. The env name survives only in _block_quantized_moe_builder_test.py as a constant used to assert it is retired.
  • _fuse_native_block_moe (the production authority path) now calls fuse_block_quantized_moe(model, allow_dense_moe=allow_dense) with no v2 argument → fail-closed default.

All truthy old env values cannot emit v2.

  • test_builder_env_flag_cannot_force_v2 is parametrized over ["1", "true", "TRUE", "yes", "on"]; every spelling still raises SparseMoEExportError (match block_layout_version=2), emits 0 BlockQuantizedMoE nodes, and leaves the dense graph untouched (Equal count unchanged). test_builder_env_flag_with_allow_dense_keeps_runnable_fallback confirms env+allow_dense yields the runnable dense fallback, never a v2 node.

Public API fails closed by default.

  • fuse_block_quantized_moe(...) default is now the private _allow_perproj_v2_schema: bool = False. A direct public call on a mixed-format layer typed-rejects by default (test_mixed_format_rejects_v2_by_default); v1 uniform still fuses (test_uniform_format_still_fuses_to_v1).

Private schema-only hook is unreachable from production and clearly non-runnable.

  • _allow_perproj_v2_schema is a leading-underscore, default-False, test-only switch; the only =True call sites are in _block_quantized_moe_fusion_test.py (schema-shape assertions).
  • block_layout_version=2 is set at exactly one place (_plan_layer), strictly under the allow_perproj_v2_schema branch.
  • build_from_gguf's public signature exposes no v2 parameter (only allow_dense_moe), so the CLI physically cannot pass a v2 opt-in through. Docstrings state the emitted v2 node is schema-only and never runnable until a typed runtime-capability handshake ships. test_perproj_v2_schema_hook_is_test_only documents and covers this.

v1 approved behavior and graph atomicity unchanged.

  • The fix commit touches only the v2 parameter/reject-message plumbing plus the two test files (2 prod + 2 test files, +128/−110); the v1 byte-stacking, two-pass plan-before-mutate, check_fusable/_fail_closed, shared-expert handling, and determinism logic are untouched.
  • Confirmed by tests: v1 uniform collapses to one BQMoE with block_layout_version absent and the shared expert left dense (test_builder_fuses_uniform_native_moe); mixed-format reject is atomic with the dense graph intact (test_builder_mixed_format_typed_rejects_without_v2_runtime); fc2 bank is byte-for-byte (test_builder_bank_bytes_are_byte_preserved); external data is byte-identical across runs (test_builder_fusion_is_deterministic).

Independent test/lint runs (isolated worktree, PYTHONPATH=src)

  • Focused (both changed test files): 42 passed
  • Full rewrite_rules/ + integrations/gguf/: 575 passed, 1 skipped
  • ruff check on the 4 changed files: All checks passed!
  • ruff format --check on the 4 changed files: 4 files already formatted

Non-blocking

Verdict: APPROVE FOR MERGE. Do not merge here (draft, and rebase recommended). The honestly-scoped next step remains a typed runtime-capability handshake before any per-projection v2 path is exposed to production.

— Independent reviewer, requested by Justin Chu

@justinchuby
justinchuby marked this pull request as ready for review August 24, 2026 19:54
@justinchuby
justinchuby requested review from a team and a lite review from Copilot August 24, 2026 19:54
@justinchuby
justinchuby merged commit 0665542 into main Aug 24, 2026
24 checks passed
@justinchuby
justinchuby deleted the squad/bqmoe-native-fusion branch August 24, 2026 19:54

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

This PR adds a graph rewrite + GGUF builder integration to collapse dense routed native-block MoE “expert storms” (per-expert pkg.nxrt::BlockQuantizedMatMul gated by Equal masks) into a single sparse pkg.nxrt::BlockQuantizedMoE node per layer, preserving native-block bytes and enforcing a fail-closed “no dense-all-expert export by default” policy at the final (post-apply_weights) graph state.

Changes:

  • Introduces fuse_block_quantized_moe() rewrite to detect, validate, and fuse dense routed native-block MoE subgraphs into one BlockQuantizedMoE per layer.
  • Wires the fusion into build_from_gguf after pkg.apply_weights, plus a final-graph-state backstop gate to fail closed if any routed .experts. storms remain.
  • Adds unit + builder integration tests (including end-to-end synthetic GGUF builds) to assert structural collapse and byte preservation.

Reviewed changes

Copilot reviewed 5 out of 5 changed files in this pull request and generated 4 comments.

Show a summary per file
File Description
src/mobius/rewrite_rules/_block_quantized_moe_fusion.py Implements the two-pass (plan/emit) native-block MoE fusion rewrite and fail-closed error path.
src/mobius/rewrite_rules/_block_quantized_moe_fusion_test.py Adds structural/byte-preservation tests and fail-closed scenarios for the rewrite.
src/mobius/rewrite_rules/init.py Exposes fuse_block_quantized_moe from the rewrite_rules package.
src/mobius/integrations/gguf/_builder.py Integrates fusion at step 9b and adds a final-graph-state sparse-MoE honesty gate.
src/mobius/integrations/gguf/_block_quantized_moe_builder_test.py Tests builder-side wiring, honesty policy, determinism, and end-to-end synthetic GGUF builds.

💡 Add a code-review agent skill or configure MCP servers for context-aware, tailored reviews. Learn more in the docs.

Comment on lines +748 to +752
moe_out = moe.outputs[0]
moe_out.name = f"{prefix}.bqmoe_output"
moe_out.type = ir.TensorType(ir.DataType.FLOAT)
moe_out.shape = moe_input.shape

Comment on lines +267 to +270
for node in model.graph:
if node.op_type != "BlockQuantizedMatMul":
continue
weight = node.inputs[1] if len(node.inputs) > 1 else None
Comment on lines +238 to +244
A layer that mixes native formats across its fc1/fc2/fc3 banks (GLM-5.2
UD-IQ1) can only be expressed with the ``block_layout_version=2``
per-projection ABI, which no shipped onnx-genai runtime executes yet. The
production builder therefore never enables v2: such layers always
typed-reject here rather than emit an unrunnable node. There is no
environment or CLI opt-in -- v2 stays a schema-construction test path until a
real typed runtime-capability handshake exists.
Comment on lines +301 to +305
bias_inputs = None
if bias_expert == e:
bias_arr = rng.standard_normal(INTER).astype(np.float32)
bias_inputs = _init(graph, f"expert{e}.down.bias", bias_arr, ir.DataType.FLOAT)
dw = _init(graph, f"expert{e}.down_proj.weight", down_w, ir.DataType.UINT8)
justinchuby added a commit that referenced this pull request Aug 24, 2026
…on primitives (DRAFT) (#602)

## Summary

DeepSeek-V4 real-checkpoint blocker **B2**: generic **block-FP8 /
packed-FP4 weight-loading + expert-emission primitives**, classified by
tensor *properties* (never by model name). Separate artifact from PR
#591 (native BQMoE fusion) — touches none of its files, and does not
touch `deepseek_v4.py` (Deckard/CSA #593).

### Root cause
`QuantizationConfig.from_transformers` treated `quant_method='fp8'` as
ordinary per-tensor float8 and returned `None`, so the model built bf16
`Linear` initializers. The real experts are **FP4-packed in int8**
(E2M1, block-32, UE8M0 micro-scales), so a packed `[2048,2048]` expert
was compared to its logical `[2048,4096]` initializer → confusing
`Weight shape mismatch`. Projections are **block-FP8** (E4M3 weight + 2D
UE8M0 `[128,128]` block scales).

### What this adds (`mobius.integrations._block_quant`)
- **`BlockQuantScheme`** — property parser over `quantization_config` +
top-level `expert_dtype`. Per-tensor fp8 (no `weight_block_size`) is
*not* owned.
- **`QuantizedTensorDescriptor`** — clean, breaking contract: logical
**and** packed shape, weight qtype, block geometry, scale
name/dtype/shape/layout, exact byte counts, routed/shared role.
- **`classify_tensor` / `validate_descriptor`** — distinguish
`ORDINARY`, `BLOCK_FP8`, `FP4_PACKED`, `UNSUPPORTED`. Logical-vs-packed
shape, scale pairing, and wrong/missing/orphan scales fail closed. **No
dequantization, no copy-to-float.**
- **`read_raw_tensor_bytes` / `LazyRawTensor`** — byte-exact,
header-only, bounded lazy per-shard loading (one tensor resident).
- **`stack_expert_bank` / `PackedExpertBank`** — byte-exact expert-major
bank packing (reusable lowering primitive; ragged banks are a hard
error).
- **`runtime_representation_gap` / `plan_routed_expert_bank`** — the
**emission gate**.

### ABI verdict (why it typed-rejects, no fake fusion)
onnx-genai `nxrt` CPU kernels (`block_quantized_{matmul,moe}.rs`) accept
only the **interleaved llama.cpp `block_mxfp4`** layout (QK=32, 17
bytes/block) and the `iq*` GGUF formats:
- **block-FP8** projections → no `block_fp8` BlockFormat + no
E4M3×2D-UE8M0 dequant path → **typed reject**.
- **FP4 experts** are numerically MXFP4 but stored **planar** (separate
I8 nibbles + separate E8M0 block-32 scale), while nxrt MXFP4 needs a
**single interleaved tensor** → **typed reject** (planar→interleaved
transcode is unproven; no planar-FP4 bank ABI).

`plan_routed_expert_bank` raises `BlockQuantExportError` naming the
exact gap rather than emitting an unrunnable node. **No dense fallback,
no env-flag emission.**

### `from_transformers` change (property-guarded)
Block-scaled fp8 / fp4-expert checkpoints now surface a precise typed
blocker instead of `None → shape-mismatch`. Ordinary per-tensor fp8
still returns `None`; GPTQ/AWQ/GGUF/ModelOpt paths unchanged.

### Preflight (B2 moved)
`ArchitectureConfig.from_file(<real checkpoint>)` now raises
`BlockQuantExportError` with the exact layout + ABI gap — the failure
moved from a confusing shape-mismatch to an actionable typed reject.

### Tests
Real `quantization_config` + a measured slice of the checkpoint index
metadata + tiny synthetic packed safetensors (real `I8` / `F8_E4M3` /
`F8_E8M0` dtypes): classification, logical-vs-packed validation, byte
preservation, scale pairing (missing/duplicate/orphan/wrong),
shared-vs-routed, bounded lazy load, byte-exact bank stacking, emission
typed-reject. An opt-in suite exercises the mounted checkpoint headers
directly. `ruff check` + `ruff format` clean.

### Deckard #593 handoff (stable public API)
`from mobius.integrations._block_quant import (BlockQuantScheme,
QuantizedTensorDescriptor, QuantKind, classify_tensor,
validate_descriptor, build_descriptors, pair_weight_scales,
read_raw_tensor_bytes, LazyRawTensor, stack_expert_bank,
PackedExpertBank, plan_routed_expert_bank, runtime_representation_gap,
BlockQuantError, BlockQuantValidationError, BlockQuantExportError)`. No
edits to `deepseek_v4.py`.

### Remaining typed blockers (not this PR)
1. nxrt has **no block-FP8 BlockFormat**.
2. FP4 experts are **planar**, nxrt MXFP4 is **interleaved** — needs a
proven byte-exact planar→interleaved transcode **or** a planar-FP4 bank
ABI extension.
3. End-to-end runnable export additionally needs Deckard's model wiring
(#593).

No A100 benchmark (no runnable shape-faithful path yet). **Draft — do
not merge.**

🤖 Flagged for squad review (needs review): touches the shared
`QuantizationConfig.from_transformers` config seam.

Co-authored-by: Copilot <[email protected]>
justinchuby added a commit that referenced this pull request Aug 25, 2026
…ion) [Slice 3B] (#599)

## Slice 3B — Mobius opt-in `--paged-attention` export (dense MLA,
LATENT)

Emits `com.microsoft::PagedAttention` v1 in **LATENT / absorbed-MLA**
mode for property-compatible **dense MLA** (DeepSeek-V2/V3, GLM-5.2
`--glm-full-attention`). Builds on the merged onnx-genai native runtime
contract: audit/typed-validator/oracle (#1940), KV index emission
(#1955), CUDA LATENT kernel (#1978).

### Guarantees
- **Default off.** Feature-off exports are **byte-identical** to the
current dense-MLA graph (all new code is gated behind the flag/task). A
byte-identical test locks this.
- **Property-based eligibility, never model names.** Decided from
semantic geometry: latent width, `v_head_size`, partial-RoPE suffix
(`rotary_offset = kv_lora_rank`), cache dtype (fp16/bf16), and the
onnx-genai-kv page/block constraints (head_size %8, kv_lora %8,
rotary_dim %16, rotary_offset %8, block pow2 ≥16).
- **Typed reject, never silent fallback.** Active query-dependent sparse
selection (GLM **DSA/IndexShare**, DeepSeek-V4 **CSA/HCA**), **MTP**,
**quantized cache**, **head_sink**, **qk-norm**, **sliding window** all
raise a typed reason at model construction / build. Feature-on with an
incompatible geometry errors. GLM's *vestigial* indexer config (dropped
under `--glm-full-attention`) does **not** reject.
- **One cache authority.** The op consumes/mutates caller-owned page
buffers in place; Mobius **allocates no pages** and creates no second
cache manager. `onnx-genai-kv` stays the sole authority. The graph binds
caller-owned `block_table` / `slot_mapping` / cumulative + past lengths
/ per-layer LATENT `key_cache`, aliases the cache in place, and derives
token positions from the length tensors (no `position_ids` input).

### Emitted contract
- One `PagedAttention` node per layer, `_domain="com.microsoft"`, LATENT
attrs (`kv_cache_layout=LATENT`, `kv_num_heads=1`, explicit `scale`,
`v_head_size=kv_lora_rank`, `rotary_offset=kv_lora_rank`,
`do_rotary=1`); `rotary_dim` is **derived** from `cos_cache`, never
emitted.
- Model inputs: `input_ids`, `block_table` (i32), `slot_mapping` (i32),
`cumulative_sequence_length` (i32), `past_seqlens` (i32), per-layer
`key_cache.{i}` `[num_blocks, block_size, 1, head_size]`. Outputs:
`logits`, `updated_key_cache.{i}` (aliases input).
- `kv_b_proj` is absorbed into the query/output projections at
weight-apply time; numeric contract mirrors the onnx-genai equivalence
oracle.

### Tests (same commit)
- **component** (`components/_paged_mla_test.py`): eligibility rejects,
absorption, numpy **decomposed-vs-absorbed LATENT parity** (rel < 1e-6),
structural emission.
- **model-level** (`models/paged_mla_export_test.py`): feature-off
byte-identical; feature-on structural + exact op
attrs/inputs/outputs/model IO; typed rejects (DSA/CSA/HCA/MTP/window);
torch-tensor weight absorption; DeepSeek-V3 path proves eligibility is
not name-gated.
- **CLI** (`tests/cli_test.py`): `--features paged-attention` plumbing +
task resolution + mutual-exclusion errors.
- Existing GLM / DeepSeek / task / build-graph tests pass unchanged.

### Scope / gates
- **No full-size performance claim.** Tiny correctness only. Native
runtime full-size verification is separate.
- Executing the emitted graph needs **ORT ≥ 1.29 CUDA** (contrib op is
unknown to the base onnx checker, so model-level assertions are
structural).
- Avoids #578 (GGUF preflight) and #591 (BQMoE) files.

**Draft — do not merge.** Independent review required (reviewer
excluding Leon/Sapper; Gaff or Roy final approval).

Co-authored-by: Copilot <[email protected]>

---------

Co-authored-by: Copilot <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants