Skip to content

Direct multi-shard GGUF import + GLM-5.2 (glm-dsa→glm_moe_dsa) resolution - #581

Merged
justinchuby merged 2 commits into
mainfrom
feat/gguf-glm52-multishard
Aug 24, 2026
Merged

justinchuby merged 2 commits into
mainfrom
feat/gguf-glm52-multishard

Conversation

@justinchuby

Copy link
Copy Markdown
Member

Summary

Enables importing large split-set GGUF checkpoints directly (north star: unsloth/GLM-5.2-GGUF UD-IQ1_{S,M} — six-file, 201.832 / 212.801 GiB sets) without merging shards into a second on-disk file, resolves the GLM-5.2 glm-dsa architecture to the canonical glm_moe_dsa model type, and adds a fail-closed sparse-MoE honesty gate plus a metadata-only preflight.

This is independent of PR #1854. It does not touch PagedAttention or onnx-genai Slice7A.

1. Multi-shard reader — _shard_set.py

  • GgufShardSet assembles a -000i-of-000N.gguf split set into one logical, GGUFModel-compatible reader. Tensors are read on demand from the owning shard (each memory-mapped by gguf.GGUFReader) — never concatenated into a second ~228 GB GGUF. Memory stays bounded to one tensor/block chunk + metadata.
  • Native IQ blocks preserved byte-for-byte into the existing repacker/external-data path.
  • Discovery confined to the requested directory; driven by authoritative split.* metadata cross-checked against filenames (no blind string concatenation).
  • Fail-closed validation: contiguous split.no, declared split.count/split.tensors.count agreement, unique tensor names, tensor counts, offset/alignment bounds (catches truncated/corrupt shards), architecture/tokenizer/template identity, optional sha256/size checks. Rejects missing / duplicate / mixed-revision / mixed-quant / corrupt shards.
  • open_gguf_model() returns a plain GGUFModel for single files (behaviour unchanged) or a GgufShardSet for split sets.

2. Architecture resolution — _config_mapping.py

  • Explicit, metadata-driven glm-dsa/glm_dsa → glm_moe_dsa format bridge (no filename/model-name heuristics) + GLM-5.2 MLA/MoE/DSA key map.
  • assert_glm_moe_dsa_resolvable() verifies head/layer/expert/MLA/DSA-indexer properties before selecting GlmMoeDsaCausalLMModel, accumulating all missing properties as precise rejection reasons. Wired into build_from_gguf.

3. Sparse-MoE honesty gate — _builder.py, _flags.py

  • Routed IQ/MXFP4 experts lower to per-expert pkg.nxrt::BlockQuantizedMatMul with no sparse top-k fusion (only int4 MatMulNBits fuses into com.microsoft::QMoE) — i.e. dense-all-expert compute. build_from_gguf now fails closed before export with SparseMoEExportError.
  • Opt in via allow_dense_moe / MOBIUS_ALLOW_DENSE_MOE_EXPERTS (non-default, research/correctness only, no throughput claim).

4. Metadata-only preflight — _preflight.py, CLI preflight-gguf

  • preflight_gguf / preflight_local_gguf / preflight_hf_gguf report exact files, bytes, LFS sha256, resolved architecture, and export blockers without downloading tensor payloads (HfApi.get_paths_info + model_info(expand=["gguf"])). Resumable via a JSON cache. Exposed as reusable GGUF-specific library functions (no _weight_loading.py, no duplicate generic CLI machinery).

Preflight output for the north-star repo (metadata only, pinned sha abc55e7…)

UD-IQ1_S: glm-dsa -> glm_moe_dsa | 6 shards | 216,715,360,960 B (201.832 GiB)
          753.9B params | sparse MoE NOT supported | BLOCKER: sparse-MoE fusion
UD-IQ1_M: glm-dsa -> glm_moe_dsa | 6 shards | 228,492,966,624 B (212.801 GiB)
          753.9B params | sparse MoE NOT supported | BLOCKER: sparse-MoE fusion

(Sizes match the task facts exactly; no tensor payloads downloaded.)

Tests

New synthetic split-set fixtures (built with GGUFWriter(split_max_tensors=N)): happy 2/3 shards with tensors split across files, order independence, directory open, discovery confinement, missing/duplicate/mixed-metadata/duplicate-tensor/corrupt-offset/truncated/checksum-mismatch rejection, offset/alignment, bounded-memory (tracemalloc) instrumentation, deterministic manifest/checksums, IQ1 native block byte-for-byte preservation; arch-bridge valid/invalid; sparse-MoE honesty rejection; metadata-only preflight (local + faked Hub asserting no download). Existing single-file GGUF behaviour unchanged.

423 passed (full integrations/gguf/ suite + _flags_test.py); ruff check + ruff format clean.

Not in scope / next slice

No full-size performance claim and no dense-all-expert success. The exact next slice is a sparse IQ-block BlockQuantizedMoE fusion (top-k gather over native-block expert weights) so IQ1 routed experts stop lowering to per-expert dense BlockQuantizedMatMul.

⚠️ Do not merge without explicit approval; requires independent review (excluding Batty).

Co-authored-by: Copilot [email protected]

Enable importing large split-set GGUF checkpoints (e.g. unsloth/GLM-5.2-GGUF
UD-IQ1_{S,M}, six-file 200+ GiB sets) directly, without merging shards into a
second on-disk file, and resolve the GLM-5.2 `glm-dsa` architecture to the
canonical `glm_moe_dsa` model type with fail-closed validation.

Multi-shard reader (_shard_set.py)
- GgufShardSet assembles a split set into one logical GGUFModel-compatible
  reader. Tensors are read on demand from the owning shard (each memory-mapped),
  so memory stays bounded to one tensor/block chunk plus metadata regardless of
  total size. Native IQ blocks are preserved byte-for-byte.
- Discovery is confined to the requested directory and driven by authoritative
  split.* metadata cross-checked against -000i-of-000N filenames (no blind
  string concatenation). Validation fails closed on missing/duplicate/
  mixed-revision/mixed-quant/corrupt shards (contiguous split.no, declared
  split.count/tensors.count agreement, unique tensor names, offset/alignment
  bounds, optional sha256/size checks).
- open_gguf_model() returns a plain GGUFModel for single files (unchanged
  behaviour) or a GgufShardSet for split sets; build_from_gguf uses it.

Architecture resolution (_config_mapping.py)
- Explicit, metadata-driven glm-dsa/glm_dsa -> glm_moe_dsa format bridge (no
  filename/model-name heuristics) plus a GLM-5.2 MLA/MoE/DSA key map.
- assert_glm_moe_dsa_resolvable() verifies head/layer/expert/MLA/DSA-indexer
  properties before selecting GlmMoeDsaCausalLMModel and reports every missing
  property (precise rejection reasons), wired into build_from_gguf.

Sparse-MoE honesty gate (_builder.py, _flags.py)
- Routed IQ/MXFP4 experts lower to per-expert BlockQuantizedMatMul nodes with
  no sparse top-k fusion (only int4 MatMulNBits fuses into com.microsoft::QMoE),
  i.e. dense-all-expert compute. build_from_gguf now fails closed before export
  with SparseMoEExportError. Opt in via allow_dense_moe / MOBIUS_ALLOW_DENSE_MOE_EXPERTS
  (non-default, research only, no throughput claim).

Metadata-only preflight (_preflight.py, CLI preflight-gguf)
- preflight_gguf/preflight_local_gguf/preflight_hf_gguf report exact files,
  bytes, LFS sha256 checksums, resolved architecture, and export blockers
  (notably the sparse-MoE blocker) without downloading tensor payloads. Uses
  HfApi.get_paths_info + model_info(expand=gguf). Resumable via a JSON cache.

Tests: synthetic split-set fixtures (happy 2/3 shards, order independence,
missing/duplicate/mixed/corrupt shards, checksum mismatch, offset/alignment,
bounded-memory instrumentation, deterministic manifest/checksums, IQ1 native
block preservation), arch-bridge valid/invalid, honesty-gate rejection, and
metadata-only preflight (local + faked Hub). Existing single-file behaviour
unchanged (423 gguf+flags tests pass).

Co-authored-by: Copilot <[email protected]>
@justinchuby
justinchuby requested review from a team and a lite review from Copilot August 24, 2026 04:52
@github-actions

github-actions Bot commented Aug 24, 2026 •

Copy link
Copy Markdown

🏗️ Architecture Diff

Comparing 89ff75f → 563f178

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 89ff75f → 563f178

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.

f"{directory} contains more than one GGUF split set ({summaries}); "
"point at a specific shard file to disambiguate."
)
(prefix, count), _files = next(iter(groups.items()))

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 extends the GGUF integration to support directly reading multi-shard GGUF split sets as a single logical model (without re-merging shards), adds a metadata-only “preflight-gguf” capability for local/Hugging Face sources, and introduces a GLM-5.2 (glm-dsa) → canonical glm_moe_dsa architecture bridge plus a fail-closed sparse-MoE “honesty gate”.

Changes:

  • Add a shard-set reader (GgufShardSet + open_gguf_model) and update GGUF import paths to work for both single-file and split sets.
  • Add metadata-only GGUF preflight (library + CLI) to report shard files/bytes/checksums, resolved architecture, and export blockers without downloading tensor payloads.
  • Add explicit GLM-5.2 architecture resolution and enforce a fail-closed export blocker when routed native-block MoE experts would export as dense-all-expert compute (unless explicitly opted in).

Reviewed changes

Copilot reviewed 13 out of 13 changed files in this pull request and generated 3 comments.

Show a summary per file
File Description
src/mobius/integrations/gguf/_tencent_q1_0.py Avoids assuming a single-file _reader when checking Tencent Q1_0 layout (split sets return “not Tencent”).
src/mobius/integrations/gguf/_shard_set.py Implements split-set discovery, validation, and on-demand tensor reading across shards.
src/mobius/integrations/gguf/_shard_set_test.py Adds synthetic fixtures and validation/memory/IQ-block-preservation tests for shard sets.
src/mobius/integrations/gguf/_reader.py Adds num_tensors and reader_tensors() to support split-set-compatible callers.
src/mobius/integrations/gguf/_preflight.py Implements metadata-only preflight for local and Hugging Face GGUF references (including sparse-MoE blocker reporting).
src/mobius/integrations/gguf/_preflight_test.py Tests preflight logic (local + fake Hub API) and enforces “no download” behavior.
src/mobius/integrations/gguf/_glm_moe_dsa_test.py Tests GLM-5.2 architecture bridge and sparse-MoE honesty gate behavior.
src/mobius/integrations/gguf/_config_mapping.py Adds glm-dsa/glm_dsa → glm_moe_dsa mapping, GLM DSA key map, and resolvability assertions.
src/mobius/integrations/gguf/_builder.py Switches GGUF open path to open_gguf_model, adds sparse-MoE export blocker, and wires GLM bridge validation.
src/mobius/integrations/gguf/_builder_test.py Updates a test fixture to use reader_tensors() instead of _reader.tensors directly.
src/mobius/integrations/gguf/init.py Re-exports new GGUF APIs/errors (shards, preflight, resolution, honesty gate).
src/mobius/_flags.py Adds allow_dense_moe_experts flag (env override) for opting into dense MoE expert export.
src/mobius/main.py Adds preflight-gguf CLI subcommand.

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

Comment on lines +161 to +168
if len(groups) > 1:
summaries = ", ".join(f"{prefix}-*-of-{count:05d}" for prefix, count in sorted(groups))
raise GgufShardError(
f"{directory} contains more than one GGUF split set ({summaries}); "
"point at a specific shard file to disambiguate."
)
(prefix, count), _files = next(iter(groups.items()))
return _collect_shard_group(directory, prefix, count)
Comment on lines +505 to +511
source_path = Path(source)
looks_local = source_path.exists() or (
source_path.parent.exists() and source_path.parent != source_path
)
if looks_local:
return preflight_local_gguf(source, verify_checksums=verify_checksums)
return preflight_hf_gguf(str(source), filename=filename, revision=revision, token=token)
Comment on lines +519 to +522
if parsed is None:
# Single explicit file (not a shard); return just it.
match = [f for f in gguf_files if f.rsplit("/", 1)[-1] == base]
return match or [filename]
…ory test

Independent review (PR #581) raised two minor findings:
- Mixed-quant continuation-shard swap: continuation shards carry no identity
  metadata, so a same-model IQ1_S/IQ1_M swap evades metadata-only validation.
  Document the residual precisely on _IDENTITY_KEYS / _validate_identity /
  GgufShardSet and add a regression test proving the manifest guard
  (expected_sizes/expected_sha256, produced by preflight) fails closed on a
  swapped continuation shard — the byte-exact guard the task requires when
  manifest data exists.
- Bounded-memory test used F32 tensors, which get_tensor returns as memmap
  views that tracemalloc cannot see (vacuous assertion). Switch the fixture to
  native Q8_0 blocks so each get_tensor dequantizes into a real float32 heap
  array; the peak-vs-single-tensor bound is now meaningful.

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

Copy link
Copy Markdown
Member Author

Independent review resolved (reviewer excluded Batty)

Verdict: APPROVE WITH NITS — no blockers/majors. The two minor findings are addressed in 563f178:

  1. Mixed-quant continuation-shard swap — continuation shards carry no identity metadata, so a same-model IQ1_S/IQ1_M swap can't be told apart on metadata alone. This is a fundamental property of GGUF splits. Fix: documented the residual precisely on _IDENTITY_KEYS / _validate_identity / GgufShardSet, and added a regression test (test_manifest_rejects_swapped_continuation_shard) proving the manifest guard (expected_sizes / expected_sha256, produced by the metadata-only preflight from HF LFS metadata) fails closed on a swapped continuation shard — the byte-exact guard the task requires "when manifest data exists". The test also asserts the metadata-only path does not falsely reject (documents the residual).
  2. Bounded-memory test was vacuous — F32 tensors are returned by get_tensor as memmap views that tracemalloc can't see. Fix: the fixture now writes native Q8_0 blocks so each get_tensor dequantizes into a real float32 heap array; the peak-vs-single-tensor bound is now meaningful.

Suite: 402 passed (gguf) + 23 passed (flags); ruff check/format clean. Still do not merge without explicit approval; no performance claim.

@justinchuby

Copy link
Copy Markdown
Member Author

Independent review — APPROVE FOR MERGE

Reviewed at HEAD 563f178 against merge-base 89ff75f (2 commits, +2845/-13, 13 files, all under src/mobius/integrations/gguf/ plus additive CLI wiring). Read-only.

Gates (run independently)

  • pytest src/mobius/integrations/gguf/: 401 passed, 0 failed (142 in the PR-touched files).
  • ruff check (changed files + src/mobius): clean. ruff format --check: 13 files already formatted.
  • Env: py3.12, ort 1.29.0, onnx 1.22.0, hf_hub 1.28.0, editable .[gguf].

Checklist verification

  1. Shard discovery/confinement — directory-confined glob, glob_escape for literal prefixes, contiguous 1..count enforcement, duplicate/missing/out-of-range rejection, split.count/split.no/split.tensors.count agreement, per-shard alignment + tensor-span OOB bounds, identity-key divergence (arch/name/quant-version/file_type/tokenizer/template), optional per-shard sha256/size verification. Fail-closed throughout.
  2. Lazy reads / IQ preservation / bounded memory — per-tensor reads route through the _owner map to the owning shard's own reader; no whole-set concat. Byte-for-byte IQ1 preservation and Q8_0 tracemalloc bound (< 3× one tensor) are asserted with real gguf.GGUFWriter split sets. Single-file path unchanged.
  3. GLM bridge is metadata-driven — resolve_model_type keys off general.architecture, never filename; assert_glm_moe_dsa_resolvable validates layer/head/expert/MLA/DSA-indexer properties and reports all failures; DSA-indexer check gated on use_dsa.
  4. Sparse-MoE honesty gate — fires after _replace_native_block_linears, before export; fails closed by default (allow_dense_moe_experts=False); opt-in path logs a loud warning making no throughput claim; non-MoE and int4/QMoE paths unaffected.
  5. Preflight is metadata-only — HF path uses list_repo_files + get_paths_info (sizes + LFS sha256) + model_info(expand=["gguf"]); a test stub raises if hf_hub_download is ever hit. Revision is pinned through every call; CLI exits 2 on blockers; UD-IQ1_S/M correctly flagged by the native-block regex.
  6. Tests non-vacuous — truncation, tensor-span OOB, duplicate tensor, swapped continuation shard (caught via manifest), bounded dequant allocation, and IQ1 byte preservation are all exercised against genuine synthetic split sets.
  7. Scope — no PagedAttention/Slice7 changes; shared-file edits (__main__.py new subcommand, _flags.py new field) are additive → low rebase risk.

Non-blocking follow-ups

  • Wire the byte-exact manifest into build_from_gguf. build_from_gguf calls open_gguf_model(gguf_path) with no expected_sha256/expected_sizes and no verify_checksums, and the public signature exposes no way to pass a manifest. The documented mitigation for the one gap _validate_identity admits it cannot catch — a same-model IQ1_S↔IQ1_M continuation-shard swap (no identity keys, identical tensor names + split.tensors.count) — therefore protects only direct open_gguf_model/preflight/test callers, not the production build path. Adversarial-input + explicitly documented, so non-blocking, but consider threading the preflight manifest (or verify_checksums) through build_from_gguf in a follow-up.
  • Preflight cache identity. The --cache JSON is keyed solely on the caller-supplied path with no stored source/revision validation on load; reusing one path across repos/revisions returns stale data. Opt-in and off by default (and not in the build trust path), so non-blocking; a source+revision stamp validated on load would harden it.

Merge recommendation

Worth merging ahead of the CUDA/Mobius sparse-MoE fusion work: this is a clean, fail-closed, well-tested foundation (shard-set reader + validators + metadata-only preflight + GLM bridge + honesty gate), and the sparse-MoE blocker correctly prevents shipping a silently dense-all-expert graph.

@justinchuby
justinchuby merged commit 7003bc7 into main Aug 24, 2026
24 checks passed
@justinchuby
justinchuby deleted the feat/gguf-glm52-multishard branch August 24, 2026 08:01
justinchuby added a commit that referenced this pull request Aug 24, 2026
PR #578 was cut against #576 before #581 ("Direct multi-shard GGUF import")
merged into main as 7003bc7. #581 already ships a `preflight-gguf` CLI and the
`mobius.integrations.gguf._preflight` library, so the standalone
`mobius.preflight_gguf` module + second `preflight-gguf` subparser collided with
it (argparse `conflicting subparser` on Python 3.12, breaking the whole CLI) and
re-implemented parallel logic. Per the review, fold the genuinely-additive value
into #581's `_preflight.py` and delete the parallel implementation.

Folded in (reusing #581's GgufShardSet/GGUFModel header reader, metadata-only):
- Block-preserving, lossless-only per-tensor-type classification against the
  *real* repacker (`native_block_spec` / `repack_quant_params`) plus float
  passthrough — no model-name allowlist. Dispositions: passthrough /
  native-preserve / repack / unsupported.
- Real-artifact budget: ONNX external-data output estimate and a weights-only
  VRAM figure derived from the export artifact. Direct random-access shard
  reads, so there is NO merged second-copy budget.
- A blocker listing the *exact* unsupported native qtypes (e.g. Q5_K/Q2_K/Q3_K),
  which — with #581's sparse-MoE fusion gate — are the real remaining code gaps,
  never architecture or sharding.

Removed (net-new, now-invalid blockers): the hardcoded `split.count > 1` refusal
(GgufShardSet imports sharded sets directly), the `merged_input_bytes`
double-copy disk budget, and the `/mnt` staging recommendation. No static
DeepSeek 401/404 blocker, no bandwidth/tok-s inference, no payload download.

Tests: supported sharded set clears shard+arch gates; dispositions match the
real repacker; exact unsupported qtype is the only blocker; budget carries no
second-copy and VRAM derives from the artifact; exactly one `preflight-gguf` CLI
registration (parser builds on 3.12) and no parallel top-level module.

Co-authored-by: Copilot <[email protected]>
justinchuby added a commit that referenced this pull request Aug 24, 2026
PR #578 was cut against #576 before #581 ("Direct multi-shard GGUF import")
merged into main as 7003bc7. #581 already ships a `preflight-gguf` CLI and the
`mobius.integrations.gguf._preflight` library, so the standalone
`mobius.preflight_gguf` module + second `preflight-gguf` subparser collided with
it (argparse `conflicting subparser` on Python 3.12, breaking the whole CLI) and
re-implemented parallel logic. Per the review, fold the genuinely-additive value
into #581's `_preflight.py` and delete the parallel implementation.

Folded in (reusing #581's GgufShardSet/GGUFModel header reader, metadata-only):
- Block-preserving, lossless-only per-tensor-type classification against the
  *real* repacker (`native_block_spec` / `repack_quant_params`) plus float
  passthrough — no model-name allowlist. Dispositions: passthrough /
  native-preserve / repack / unsupported.
- Real-artifact budget: ONNX external-data output estimate and a weights-only
  VRAM figure derived from the export artifact. Direct random-access shard
  reads, so there is NO merged second-copy budget.
- A blocker listing the *exact* unsupported native qtypes (e.g. Q5_K/Q2_K/Q3_K),
  which — with #581's sparse-MoE fusion gate — are the real remaining code gaps,
  never architecture or sharding.

Removed (net-new, now-invalid blockers): the hardcoded `split.count > 1` refusal
(GgufShardSet imports sharded sets directly), the `merged_input_bytes`
double-copy disk budget, and the `/mnt` staging recommendation. No static
DeepSeek 401/404 blocker, no bandwidth/tok-s inference, no payload download.

Tests: supported sharded set clears shard+arch gates; dispositions match the
real repacker; exact unsupported qtype is the only blocker; budget carries no
second-copy and VRAM derives from the artifact; exactly one `preflight-gguf` CLI
registration (parser builds on 3.12) and no parallel top-level module.

Co-authored-by: Copilot <[email protected]>
justinchuby added a commit that referenced this pull request Aug 24, 2026
…izedMoE (+ build_from_gguf wiring) (#591)

## 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` (#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 #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).

---------

Co-authored-by: Copilot <[email protected]>
justinchuby added a commit that referenced this pull request Aug 24, 2026
…+ budget (reconciled into #581) (#578)

## What

Metadata-only, **block-preserving / lossless-only** classification and
budget for
GGUF export, **folded into the #581 preflight library**
(`mobius.integrations.gguf._preflight`).
This is the reconciled revision of the rejected PR: the standalone
`mobius.preflight_gguf` module and its duplicate `preflight-gguf`
subcommand are
gone; the additive value lives on the single #581 code path.

Rebased/rebuilt onto current `main` (now includes #581 `7003bc7` and
#576
`059bf5f`). Base retargeted from the deleted
`sebastian/export-preflight-streaming`
to `main`. Single focused commit; no dependency on #576.

## Why the rejection is addressed

#581 shipped a `preflight-gguf` CLI + preflight library after this
branch was
cut. The old branch added a *second* subparser (breaking
`build_parser()` on
Python 3.12 with `conflicting subparser: preflight-gguf`) and duplicated
header
parsing / shard resolution. It also carried three now-invalid blockers.

**Removed (net-new, now-false):**
- Duplicate module + duplicate `preflight-gguf` CLI ownership — exactly
one
  registration remains (#581's); the parser builds on 3.12.
- Hardcoded `split.count > 1` refusal — `GgufShardSet` imports sharded
sets
directly, so GLM-5.2 `UD-IQ1_S` (6 shards) is **not** rejected for
sharding.
- `merged_input_bytes` / second-copy disk budget — direct random access
means no
  merged file; the budget reflects **real** artifacts only.
- `/mnt` staging recommendation — no environment paths in product
defaults.
- No static DeepSeek 401/404 blocker, no bandwidth/tok-s inference, no
payload
  download (headers only).

**Preserved / folded in (validated against the real repacker):**
- Dynamic architecture lookup (`glm-dsa → glm_moe_dsa`, from #581).
- Per-tensor-type lossless disposition against the **real** repacker
  (`native_block_spec` / `repack_quant_params`) + float passthrough — no
  model-name allowlist: `passthrough` / `native-preserve` / `repack` /
  `unsupported`.
- Real-artifact budget: ONNX external-data output estimate and a
weights-only
VRAM figure derived from the **export artifact** (not the source dtype).
- Honest blockers: the sparse-MoE fusion gate (#581) plus the **exact**
unsupported native qtypes (e.g. `Q5_K/Q2_K/Q3_K`) are the real remaining
code
  gaps for `UD-IQ1_S` — never architecture or sharding.

`GgufPreflightReport` gains additive fields (`type_stats`,
`output_bytes`,
`vram_weights_bytes`, `unsupported_types`) with defaults; #581 APIs
unchanged.

## Tests

Added to `_preflight_test.py` (metadata-only, shape-faithful multi-shard
fixtures): a supported **sharded** set clears the shard + arch gates;
dispositions match the real repacker; an unsupported qtype is the *only*
blocker;
the budget carries no second-copy and VRAM derives from the artifact;
exactly one
`preflight-gguf` CLI registration and no parallel top-level module. Full
`_preflight_test.py` + the GGUF suite (408) + CLI option parity pass;
`ruff`
clean (0.16.2).

Independent re-review requested. Do not merge.

---------

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