Repository navigation
Direct multi-shard GGUF import + GLM-5.2 (glm-dsa→glm_moe_dsa) resolution - #581
Conversation
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]>
Performance Comparison
|
| 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())) |
There was a problem hiding this comment.
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.
| 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) |
| 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) |
| 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]>
Independent review resolved (reviewer excluded Batty)Verdict: APPROVE WITH NITS — no blockers/majors. The two minor findings are addressed in
Suite: |
Independent review — APPROVE FOR MERGEReviewed at HEAD Gates (run independently)
Checklist verification
Non-blocking follow-ups
Merge recommendationWorth 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. |
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]>
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]>
…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]>
…+ 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]>
Summary
Enables importing large split-set GGUF checkpoints directly (north star:
unsloth/GLM-5.2-GGUFUD-IQ1_{S,M} — six-file, 201.832 / 212.801 GiB sets) without merging shards into a second on-disk file, resolves the GLM-5.2glm-dsaarchitecture to the canonicalglm_moe_dsamodel 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.pyGgufShardSetassembles a-000i-of-000N.ggufsplit set into one logical,GGUFModel-compatible reader. Tensors are read on demand from the owning shard (each memory-mapped bygguf.GGUFReader) — never concatenated into a second ~228 GB GGUF. Memory stays bounded to one tensor/block chunk + metadata.split.*metadata cross-checked against filenames (no blind string concatenation).split.no, declaredsplit.count/split.tensors.countagreement, 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 plainGGUFModelfor single files (behaviour unchanged) or aGgufShardSetfor split sets.2. Architecture resolution —
_config_mapping.pyglm-dsa/glm_dsa→glm_moe_dsaformat 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 selectingGlmMoeDsaCausalLMModel, accumulating all missing properties as precise rejection reasons. Wired intobuild_from_gguf.3. Sparse-MoE honesty gate —
_builder.py,_flags.pypkg.nxrt::BlockQuantizedMatMulwith no sparse top-k fusion (only int4MatMulNBitsfuses intocom.microsoft::QMoE) — i.e. dense-all-expert compute.build_from_ggufnow fails closed before export withSparseMoEExportError.allow_dense_moe/MOBIUS_ALLOW_DENSE_MOE_EXPERTS(non-default, research/correctness only, no throughput claim).4. Metadata-only preflight —
_preflight.py, CLIpreflight-ggufpreflight_gguf/preflight_local_gguf/preflight_hf_ggufreport 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…)(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(fullintegrations/gguf/suite +_flags_test.py);ruff check+ruff formatclean.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
BlockQuantizedMoEfusion (top-k gather over native-block expert weights) so IQ1 routed experts stop lowering to per-expert denseBlockQuantizedMatMul.Co-authored-by: Copilot [email protected]