Skip to content

Commit 7003bc7

Browse files
justinchubyCopilot
andauthored
Direct multi-shard GGUF import + GLM-5.2 (glm-dsa→glm_moe_dsa) resolution (#581)
## 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]> --------- Co-authored-by: Copilot <[email protected]>
1 parent 70b24ed commit 7003bc7

13 files changed

Lines changed: 2845 additions & 13 deletions

‎src/mobius/__main__.py‎

Lines changed: 67 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -686,6 +686,31 @@ def _cmd_convert_comfyui(args: argparse.Namespace) -> None:
686686
print(f" prompt: {wf.prompt!r}")
687687

688688

689+
def _cmd_preflight_gguf(args: argparse.Namespace) -> None:
690+
"""Execute the 'preflight-gguf' subcommand (metadata only)."""
691+
try:
692+
from mobius.integrations.gguf import preflight_gguf
693+
except ImportError:
694+
print(
695+
"GGUF support requires the gguf package. Install with: pip install mobius-onnx[gguf]"
696+
)
697+
raise SystemExit(1)
698+
699+
report = preflight_gguf(
700+
args.source,
701+
filename=getattr(args, "filename", None),
702+
revision=getattr(args, "revision", None),
703+
verify_checksums=getattr(args, "verify_checksums", False),
704+
cache_path=getattr(args, "cache", None),
705+
)
706+
if getattr(args, "json", False):
707+
print(report.to_json())
708+
else:
709+
print(report.render())
710+
if report.blockers:
711+
raise SystemExit(2)
712+
713+
689714
def _cmd_info(args: argparse.Namespace) -> None:
690715
"""Execute the 'info' subcommand."""
691716
from mobius.integrations.diffusers._builder import (
@@ -1136,6 +1161,48 @@ def build_parser() -> argparse.ArgumentParser:
11361161
)
11371162
comfy_parser.set_defaults(func=_cmd_convert_comfyui)
11381163

1164+
# --- preflight-gguf ---
1165+
preflight_parser = subparsers.add_parser(
1166+
"preflight-gguf",
1167+
help="Metadata-only preflight of a GGUF file or split set (local path "
1168+
"or Hugging Face 'owner/repo[:file]'). Reports exact files, bytes, "
1169+
"checksums, resolved architecture, and export blockers (notably the "
1170+
"sparse-MoE fusion blocker) WITHOUT downloading tensor payloads.",
1171+
)
1172+
preflight_parser.add_argument(
1173+
"source",
1174+
help="Local .gguf path / split-set shard / directory, or a Hugging "
1175+
"Face reference 'owner/repo' or 'owner/repo:filename.gguf'.",
1176+
)
1177+
preflight_parser.add_argument(
1178+
"--filename",
1179+
default=None,
1180+
help="Specific shard filename when SOURCE is a bare 'owner/repo'.",
1181+
)
1182+
preflight_parser.add_argument(
1183+
"--revision",
1184+
default=None,
1185+
help="Pinned Hugging Face revision (sha/branch/tag).",
1186+
)
1187+
preflight_parser.add_argument(
1188+
"--verify-checksums",
1189+
action="store_true",
1190+
help="Compute per-shard sha256 for a local set (reads file bytes, not "
1191+
"tensor payloads via the model API).",
1192+
)
1193+
preflight_parser.add_argument(
1194+
"--json",
1195+
action="store_true",
1196+
help="Emit the report as JSON instead of the human-readable summary.",
1197+
)
1198+
preflight_parser.add_argument(
1199+
"--cache",
1200+
default=None,
1201+
help="Optional JSON cache path; a resumable, idempotent preflight reads "
1202+
"from it when present and writes to it otherwise.",
1203+
)
1204+
preflight_parser.set_defaults(func=_cmd_preflight_gguf)
1205+
11391206
return parser
11401207

11411208

‎src/mobius/_flags.py‎

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -178,6 +178,26 @@ class _Flags:
178178
unchanged, so no shipped model's graph changes unless this flag is set.
179179
"""
180180

181+
allow_dense_moe_experts: bool = dataclasses.field(
182+
default_factory=lambda: _env_bool("MOBIUS_ALLOW_DENSE_MOE_EXPERTS", False)
183+
)
184+
"""Opt in to exporting routed MoE experts that have no sparse top-k fusion.
185+
186+
Some quantized MoE checkpoints (notably GLM-5.2 UD-IQ1_{S,M}) lower their
187+
routed experts as per-expert native ``pkg.nxrt::BlockQuantizedMatMul`` nodes
188+
(IQ1/IQ2/… blocks), for which no sparse ``BlockQuantizedMoE`` fusion exists
189+
yet — only the int4 ``MatMulNBits`` dense-fallback → ``com.microsoft::QMoE``
190+
rewrite does. Exporting anyway produces a graph that recomputes **every**
191+
expert for every token (full expert weight traffic), i.e. dense-all-expert
192+
compute with no performance guarantee.
193+
194+
Default ``False``: :func:`~mobius.integrations.gguf.build_from_gguf` fails
195+
closed before export with a typed capability error rather than shipping a
196+
silently-dense graph. Set ``MOBIUS_ALLOW_DENSE_MOE_EXPERTS=1`` (or override
197+
the flag) only for research / correctness study of the dense fallback. This
198+
is **not** a performance path and makes no throughput claim.
199+
"""
200+
181201

182202
# Global singleton — import and use this directly.
183203
flags = _Flags()

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

Lines changed: 37 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -29,14 +29,50 @@
2929

3030
from __future__ import annotations
3131

32-
from mobius.integrations.gguf._builder import build_from_gguf
32+
from mobius.integrations.gguf._builder import (
33+
SparseMoEExportError,
34+
build_from_gguf,
35+
)
36+
from mobius.integrations.gguf._config_mapping import (
37+
GgufArchResolutionError,
38+
resolve_model_type,
39+
)
3340
from mobius.integrations.gguf._mmproj import build_gemma4_vlm_from_gguf
41+
from mobius.integrations.gguf._preflight import (
42+
GgufPreflightReport,
43+
preflight_gguf,
44+
preflight_hf_gguf,
45+
preflight_local_gguf,
46+
)
3447
from mobius.integrations.gguf._runtime_package import write_gguf_runtime_package
48+
from mobius.integrations.gguf._shard_set import (
49+
GgufShardError,
50+
GgufShardManifest,
51+
GgufShardSet,
52+
discover_gguf_shards,
53+
open_gguf_model,
54+
)
3555
from mobius.integrations.gguf._tokenizer import write_gguf_tokenizer_json
3656

3757
__all__ = [
3858
"build_from_gguf",
3959
"build_gemma4_vlm_from_gguf",
4060
"write_gguf_runtime_package",
4161
"write_gguf_tokenizer_json",
62+
# Multi-shard GGUF import
63+
"GgufShardSet",
64+
"GgufShardManifest",
65+
"GgufShardError",
66+
"discover_gguf_shards",
67+
"open_gguf_model",
68+
# Architecture resolution
69+
"resolve_model_type",
70+
"GgufArchResolutionError",
71+
# Sparse-MoE honesty gate
72+
"SparseMoEExportError",
73+
# Metadata-only preflight
74+
"preflight_gguf",
75+
"preflight_local_gguf",
76+
"preflight_hf_gguf",
77+
"GgufPreflightReport",
4278
]

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

Lines changed: 128 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -145,6 +145,86 @@ def _raise_for_sharded_gguf(
145145
)
146146

147147

148+
class SparseMoEExportError(NotImplementedError):
149+
"""Routed MoE experts have no sparse fusion for their quantization.
150+
151+
Raised before export when a checkpoint's routed experts lower to per-expert
152+
native ``pkg.nxrt::BlockQuantizedMatMul`` nodes (e.g. GLM-5.2 UD-IQ1_{S,M})
153+
for which no sparse top-k ``BlockQuantizedMoE`` fusion exists — exporting
154+
anyway would recompute every expert for every token (dense-all-expert
155+
compute) with no performance guarantee.
156+
"""
157+
158+
159+
def _routed_dense_block_expert_paths(module) -> list[str]:
160+
"""Return module paths of routed experts lowered as native block linears.
161+
162+
A routed expert is a :class:`BlockQuantizedLinear` whose qualified name
163+
contains a ``.moe.experts.`` (or bare ``.experts.``) segment but is *not* a
164+
``shared_expert``. These are the modules that, absent a sparse top-k MoE
165+
fusion, force a dense loop over all experts.
166+
"""
167+
from mobius.components import BlockQuantizedLinear
168+
169+
paths: list[str] = []
170+
for name, mod in module.named_modules():
171+
if not isinstance(mod, BlockQuantizedLinear):
172+
continue
173+
if "shared_expert" in name:
174+
continue
175+
if ".experts." not in name:
176+
continue
177+
paths.append(name)
178+
return paths
179+
180+
181+
def _assert_sparse_moe_capability(module, config, *, source: str, allow_dense: bool) -> None:
182+
"""Fail closed when routed IQ-block experts have no sparse MoE fusion.
183+
184+
The int4 ``MatMulNBits`` dense-fallback → ``com.microsoft::QMoE`` rewrite is
185+
the only sparse MoE path today; native IQ/MXFP4 block experts stay as
186+
per-expert ``BlockQuantizedMatMul`` nodes. Exporting those yields a graph
187+
that evaluates every expert for every token. Refuse by default; only proceed
188+
(with a loud warning) when the caller explicitly opts in.
189+
"""
190+
num_experts = int(getattr(config, "num_local_experts", 0) or 0)
191+
if num_experts <= 0:
192+
return
193+
dense_paths = _routed_dense_block_expert_paths(module)
194+
if not dense_paths:
195+
return
196+
197+
example = ", ".join(sorted(dense_paths)[:3])
198+
detail = (
199+
f"{len(dense_paths)} routed expert projections (e.g. {example}) in "
200+
f"{source!r} lower to per-expert native BlockQuantizedMatMul nodes."
201+
)
202+
if allow_dense:
203+
logger.warning(
204+
"allow_dense_moe: exporting %d routed MoE expert(s) as independent "
205+
"BlockQuantizedMatMul nodes for %s. This recomputes EVERY expert for "
206+
"every token (dense-all-expert compute); it is NOT a performance path "
207+
"and makes no throughput claim. %s",
208+
len(dense_paths),
209+
source,
210+
detail,
211+
)
212+
return
213+
214+
raise SparseMoEExportError(
215+
"Sparse-MoE export blocker: "
216+
f"{detail} No sparse top-k BlockQuantizedMoE fusion exists for these "
217+
"block formats — only int4 MatMulNBits experts are fused into "
218+
"com.microsoft::QMoE. Exporting anyway would build a dense-all-expert "
219+
"graph (every expert evaluated for every token) with no performance "
220+
"guarantee, so the build fails closed. To study the dense fallback, "
221+
"re-run with allow_dense_moe=True (or set "
222+
"MOBIUS_ALLOW_DENSE_MOE_EXPERTS=1); this makes no throughput claim. "
223+
"The supported fix is a sparse IQ-block BlockQuantizedMoE fusion "
224+
"(top-k gather over native-block expert weights)."
225+
)
226+
227+
148228
def _preflight_hf_gguf(api: HfApi, repo_id: str, filename: str) -> None:
149229
"""Use Hub metadata to reject known-bad inputs before a multi-GB download."""
150230
source = f"{repo_id}:{filename}"
@@ -184,8 +264,14 @@ def _preflight_hf_gguf(api: HfApi, repo_id: str, filename: str) -> None:
184264

185265
def _validate_gguf_model(gguf_model, *, source: str) -> None:
186266
"""Validate a parsed GGUF before config extraction or graph construction."""
187-
split_count = int(gguf_model.get_metadata("split.count", 1))
188-
_raise_for_sharded_gguf(source=source, split_count=split_count)
267+
from mobius.integrations.gguf._shard_set import GgufShardSet
268+
269+
# A GgufShardSet has already assembled and structurally validated the whole
270+
# split set, so the single-file "sharded input is unsupported" guard must
271+
# not fire for it. Plain single-file GGUFModels still reject a lone shard.
272+
if not isinstance(gguf_model, GgufShardSet):
273+
split_count = int(gguf_model.get_metadata("split.count", 1))
274+
_raise_for_sharded_gguf(source=source, split_count=split_count)
189275
_raise_for_unsupported_gguf_architecture(
190276
gguf_model.architecture,
191277
source=source,
@@ -250,6 +336,7 @@ def build_from_gguf(
250336
mmproj: str | Path | None = None,
251337
static_cache: bool = False,
252338
max_seq_len: int | None = None,
339+
allow_dense_moe: bool | None = None,
253340
) -> ModelPackage:
254341
"""Build an ONNX :class:`ModelPackage` from a GGUF file.
255342
@@ -308,6 +395,14 @@ def build_from_gguf(
308395
max_seq_len: Maximum sequence length for the static cache buffers.
309396
Only used when ``static_cache=True``. Defaults to the model's
310397
``max_position_embeddings``.
398+
allow_dense_moe: Opt in to exporting routed MoE experts that have no
399+
sparse top-k fusion (they lower to per-expert native
400+
``BlockQuantizedMatMul`` nodes, i.e. dense-all-expert compute with
401+
no performance guarantee). When ``None`` (default), the value of
402+
the ``allow_dense_moe_experts`` flag is used, which defaults to
403+
``False`` — the build fails closed with a typed capability error
404+
rather than silently shipping a dense graph. This is a research /
405+
correctness knob and makes no throughput claim.
311406
312407
Returns:
313408
A :class:`ModelPackage` containing the built model(s).
@@ -346,7 +441,7 @@ def build_from_gguf(
346441
GGUF_ARCH_TO_MODEL_TYPE,
347442
gguf_to_config,
348443
)
349-
from mobius.integrations.gguf._reader import GGUFModel
444+
from mobius.integrations.gguf._shard_set import open_gguf_model
350445
from mobius.integrations.gguf._tensor_processors import (
351446
process_tensors,
352447
)
@@ -360,12 +455,19 @@ def build_from_gguf(
360455
"override; the static cache is wired through CausalLMTask."
361456
)
362457

363-
# 1. Parse GGUF file (auto-download from HF Hub when given "owner/repo[:filename]")
458+
from mobius._flags import flags as _mobius_flags
459+
460+
if allow_dense_moe is None:
461+
allow_dense_moe = _mobius_flags.allow_dense_moe_experts
462+
463+
# 1. Parse GGUF file (auto-download from HF Hub when given "owner/repo[:filename]").
464+
# A ``-000i-of-000N.gguf`` split set is assembled directly from its shards
465+
# (never merged into a second on-disk GGUF); a plain file opens as before.
364466
gguf_path = _resolve_gguf_path(gguf_path)
365-
gguf_model = GGUFModel(gguf_path)
467+
gguf_model = open_gguf_model(gguf_path)
366468
_validate_gguf_model(gguf_model, source=str(gguf_path))
367469
gguf_arch = gguf_model.architecture
368-
logger.info("Loaded GGUF file: %s (arch=%s)", gguf_path, gguf_arch)
470+
logger.info("Loaded GGUF model: %s (arch=%s)", gguf_path, gguf_arch)
369471
preserve_quantization = keep_quantized and _has_quantized_weights(gguf_model, gguf_arch)
370472
if keep_quantized and not preserve_quantization:
371473
logger.info("GGUF contains no mapped quantized weights; using the float import path")
@@ -376,6 +478,16 @@ def build_from_gguf(
376478
if model_type is None:
377479
model_type = GGUF_ARCH_TO_MODEL_TYPE.get(gguf_arch, gguf_arch)
378480

481+
# 2b. Architecture-resolution safety rail. When the GGUF architecture string
482+
# bridges to a specialised registry key, verify the metadata-derived config
483+
# actually describes that architecture before selecting its model class, so
484+
# a mislabelled or incomplete GGUF fails closed with precise reasons instead
485+
# of silently building the wrong graph.
486+
if model_type == "glm_moe_dsa":
487+
from mobius.integrations.gguf._config_mapping import assert_glm_moe_dsa_resolvable
488+
489+
assert_glm_moe_dsa_resolvable(config, gguf_arch, source=str(gguf_path))
490+
379491
# ``dataclasses.replace`` below (dtype / quantization) returns a fresh
380492
# instance that does NOT carry the private ``_gguf_*`` attributes set by
381493
# gguf_to_config (they are plain attributes, not dataclass fields). Capture
@@ -489,6 +601,13 @@ def build_from_gguf(
489601
module = module_class(config)
490602
if preserve_quantization:
491603
_replace_native_block_linears(module, gguf_model, gguf_arch)
604+
# Sparse-MoE honesty gate: routed experts lowered as native
605+
# BlockQuantizedMatMul nodes have no sparse top-k fusion yet, so the
606+
# exported graph would recompute every expert for every token. Fail
607+
# closed here (before export) unless the caller explicitly opts in.
608+
_assert_sparse_moe_capability(
609+
module, config, source=str(gguf_path), allow_dense=allow_dense_moe
610+
)
492611
pkg = build_from_module(
493612
module, config, resolved_task, execution_provider=execution_provider
494613
)
@@ -1164,7 +1283,7 @@ def _can_quantize_embedding(
11641283
if is_tencent_q1_0_layout(gguf_model):
11651284
return False
11661285

1167-
for tensor in gguf_model._reader.tensors:
1286+
for tensor in gguf_model.reader_tensors():
11681287
if map_gguf_to_hf_names(tensor.name, gguf_arch) != "model.embed_tokens.weight":
11691288
continue
11701289
shape = tuple(reversed(tensor.shape))
@@ -1314,7 +1433,7 @@ def _load_dequantized_state_dict(
13141433
for gguf_name, np_array in tqdm.tqdm(
13151434
gguf_model.tensor_items(),
13161435
desc="Dequantizing tensors",
1317-
total=len(gguf_model._tensor_index),
1436+
total=gguf_model.num_tensors,
13181437
):
13191438
hf_name = name_mapper(gguf_name, gguf_arch)
13201439
if hf_name is not None:
@@ -1415,7 +1534,7 @@ def _load_quantized_state_dict(
14151534
for gguf_name, raw, qtype, np_shape in tqdm.tqdm(
14161535
gguf_model.tensor_items_raw(),
14171536
desc="Repacking tensors",
1418-
total=len(gguf_model._tensor_index),
1537+
total=gguf_model.num_tensors,
14191538
):
14201539
hf_name = name_mapper(gguf_name, gguf_arch)
14211540
if hf_name is None:

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

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -661,7 +661,10 @@ def test_embedding_quantization_check_is_metadata_only(self, monkeypatch):
661661
tensor_type=GGMLQuantizationType.Q4_0,
662662
shape=(64, 256),
663663
)
664-
model = SimpleNamespace(_reader=SimpleNamespace(tensors=[tensor]))
664+
model = SimpleNamespace(
665+
_reader=SimpleNamespace(tensors=[tensor]),
666+
reader_tensors=lambda: [tensor],
667+
)
665668

666669
assert _can_quantize_embedding(model, "llama", bits=4, block_size=32)
667670

0 commit comments

Comments
 (0)