Skip to content

Commit 85fb322

Browse files
justinchubyCopilot
andauthored
Close pinned GGUF MTP and NextN support (#600)
## Summary - make the pinned llama.cpp `8d9af256337d1a501250f9bbf4c0859a654bddd6` MTP/NextN loader and converter census authoritative across dense, routed, hybrid, draft, and multimodal architecture namespaces - export the exact one-head dense Qwen3.5 auxiliary sidecar while failing closed before graph construction for routed/MoE/hybrid, multi-head, partial, unknown, legacy, scale/state, malformed, and out-of-range contracts - preserve exact target/sidecar embedding, norm, head, packed-weight, and initializer ownership; persist and reload the MTP sidecar as a first-class `ModelPackage` attachment - require immutable selected-file Hub revisions and exact header architecture validation; document downstream runtime support as `DEFERRED` ## Validation - focused MTP suite: 103 passed - affected MTP/GGUF/package/CLI/coverage suites: 817 passed, 225 skipped - broad non-integration suite: 6,525 passed, 52 skipped - full initialized lintrunner format and lint - two independent high-confidence full-diff reviews clean after all findings were fixed ## Runtime status `DEFERRED`: runtime support is not claimed without a pinned real artifact, independent full-logit parity, and deterministic end-to-end speculative/MTP generation. --------- Signed-off-by: Justin Chu <[email protected]> Co-authored-by: Copilot App <[email protected]>
1 parent 43896fa commit 85fb322

11 files changed

Lines changed: 1076 additions & 130 deletions

File tree

‎docs/api/build_from_gguf.md‎

Lines changed: 54 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -616,15 +616,60 @@ covered synthetically, but publication still requires independent real-weight
616616
full-logit parity and deterministic stateful generation parity. Mobius exposes
617617
only the latest recurrent state, not llama.cpp's optional bounded rollback
618618
snapshot planes; rollback/reorder-capable runtime packaging must remain
619-
disabled until that ABI is represented explicitly. Dense Qwen3.5 MTP sidecars
620-
use the post-final-norm `mtp_seed` output while preserving pre-norm
621-
`hidden_states.N` captures. Optional dedicated `nextn.embed_tokens`,
622-
`nextn.shared_head_norm`, and `nextn.shared_head_head` tensors are consumed
623-
when present; otherwise the sidecar explicitly falls back to the backbone
624-
embedding, final norm, and tied or untied output head. Qwen3.5-MoE and
625-
Qwen3-Next MTP blocks are rejected because the current sidecar builder cannot
626-
represent routed experts without dropping tensors. Separate MTP-only files
627-
are outside this cohort.
619+
disabled until that ABI is represented explicitly. The pinned NextN metadata key is exactly
620+
`{general.architecture}.nextn_predict_layers` (GGUF `UINT32`). `block_count`
621+
includes the appended heads, whose indices are
622+
`[block_count-nextn_predict_layers, block_count)`. Mobius represents exactly
623+
one head and rejects larger counts rather than truncating them.
624+
625+
The modern tensor namespace is:
626+
627+
- required: `blk.N.nextn.{eh_proj,enorm,hnorm}.weight`
628+
- optional dedicated ownership:
629+
`blk.N.nextn.{embed_tokens,shared_head_norm,shared_head_head}.weight`
630+
- decoder-block weights: the architecture's ordinary attention, norm, and FFN
631+
tensors at the same `blk.N`
632+
633+
The generic loader can additionally consume `.scale` and `.input_scale`
634+
sidecars for MTP projections. Mobius rejects those sidecars before graph
635+
construction because its MTP quantization ABI cannot represent them.
636+
`nextn.pre_projection.weight` and `nextn.post_projection.weight` are the
637+
distinct legacy/global namespace of `gemma4-assistant`; they are never accepted
638+
as Qwen-style appended-head tensors. Unknown `nextn.*`/`mtp.*`, dotted
639+
`nextn.predict_layers` metadata, mismatched architecture namespaces, missing
640+
required tensors, non-trailing or out-of-range block indices, recurrent MTP
641+
markers, and mixed routed-expert forms also fail closed.
642+
643+
The pinned loader/converter census is closed as follows:
644+
645+
| Mobius verdict | Pinned architectures | Reason |
646+
|---|---|---|
647+
| Export supported | `qwen35` | One dense, full-attention Qwen3.5 decoder block exactly matches the existing text block |
648+
| Rejected, executable upstream sidecar | `bailingmoe3`, `cohere2moe`, `deepseek2`, `deepseek32`, `deepseek4`, `glm-dsa`, `hy_v3`, `mimo2`, `nemotron_h_moe`, `qwen35moe`, `qwen3next`, `step35` | Routed experts, MLA/DSA/KDA, hyper-connections, compressed state, or hybrid recurrent state are not represented |
649+
| Rejected, preserved/skipped upstream | `bailingmoe2`, `dots3note`, `exaone-moe`, `exaone4`, `glm4`, `glm4moe` | The pinned loader consumes or preserves metadata/tensors but has no executable MTP graph |
650+
| Rejected special cases | `gemma4-assistant`, `nemotron_h`, `graniteswitch` | Standalone legacy assistant; converter-conditional MoE ownership; or non-MTP router-layer metadata re-emission |
651+
652+
Dense Qwen3.5 uses the target's dedicated post-final-norm `mtp_seed`; ordinary
653+
`hidden_states.N` remains the distinct pre-final-norm layer capture. The
654+
sidecar normalizes the next-token embedding and seed independently,
655+
concatenates them, projects `2H -> H`, runs one full-attention Qwen3.5 decoder
656+
layer with its own dynamic KV cache, applies the dedicated or target final
657+
norm, and scores through a dedicated head or the target's tied/untied head.
658+
Dedicated embeddings consume `input_ids`; shared embeddings consume
659+
`inputs_embeds`. Static-cache exports are rejected because silently dropping
660+
the sidecar or its independent state is invalid. Packed target embedding/head
661+
ownership remains with the target graph; dedicated sidecar tables are
662+
dequantized to mathematically ordinary MatMul weights, so no target/MTP
663+
initializer is duplicated. `ModelPackage.save()` persists the sidecar under
664+
`mtp/` with weight checks, and `ModelPackage.load()` restores it as
665+
`package.mtp_head`; ordinary API saves cannot silently lose the auxiliary head.
666+
667+
**MTP runtime status: DEFERRED.** The emitted graph and workflow metadata are
668+
an export contract, not evidence that a downstream runtime executes it.
669+
Runtime support requires a pinned real artifact, independent full-vocabulary
670+
logit parity, and deterministic end-to-end speculative/MTP generation with
671+
correct proposal rejection and cache rollback. None has yet been established,
672+
so no runtime-support claim is made.
628673

629674
### Pure recurrent Mamba evidence
630675

‎src/mobius/__main__.py‎

Lines changed: 1 addition & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -669,15 +669,10 @@ def _cmd_build_gguf(args: argparse.Namespace) -> None:
669669
print(f"Saved {name} to {path}")
670670

671671
# Save the trailing MTP / "nextn" self-speculative head sidecar (when the
672-
# GGUF shipped one) into a ``mtp/`` subdirectory next to the backbone.
672+
# GGUF shipped one). ModelPackage.save() persisted it into ``mtp/``.
673673
mtp_head = getattr(pkg, "mtp_head", None)
674674
if mtp_head is not None:
675675
mtp_dir = os.path.join(output_dir, "mtp")
676-
mtp_head.save(
677-
mtp_dir,
678-
external_data=args.external_data,
679-
max_workers=args.max_workers,
680-
)
681676
print(f"Saved mtp head to {os.path.join(mtp_dir, 'model.onnx')}")
682677

683678
draft_manifest = getattr(pkg, "draft_manifest", None)

‎src/mobius/_model_package.py‎

Lines changed: 31 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -80,6 +80,8 @@ class ModelPackage(UserDict[str, ir.Model]):
8080
Attributes:
8181
config: The architecture configuration used to build the models,
8282
or ``None`` if not available (e.g. after :meth:`load`).
83+
mtp_head: Optional nested MTP sidecar package. :meth:`save` persists it
84+
under ``mtp/`` and :meth:`load` restores it automatically.
8385
"""
8486

8587
def __init__(
@@ -95,6 +97,7 @@ def __init__(
9597
self.config = config
9698
# Optional persistence policy attached by the GGUF importer.
9799
self.gguf_reuse_plan: Any = None
100+
self.mtp_head: ModelPackage | None = None
98101
self.policy_components = dict(policy_components or {})
99102
self.adapter_target_manifest = adapter_target_manifest
100103
self.adapter_service_options = adapter_service_options or AdapterServiceOptions()
@@ -140,7 +143,8 @@ def save(
140143
141144
When the package contains a single model, it is saved directly as
142145
``model.onnx`` in *directory*. When multiple models are present,
143-
each is saved in its own subfolder as ``{name}/model.onnx``.
146+
each is saved in its own subfolder as ``{name}/model.onnx``. An attached
147+
:attr:`mtp_head` package is always saved under ``mtp/``.
144148
145149
.. note::
146150
This method writes ONNX files only. If you need a directory that
@@ -274,6 +278,17 @@ def save(
274278
self.save_policy_components(directory, check_weights=check_weights)
275279
if include_adapter_artifacts:
276280
self.save_adapter_artifacts(directory)
281+
if self.mtp_head is not None:
282+
self.mtp_head.save(
283+
os.path.join(directory, "mtp"),
284+
external_data=external_data,
285+
max_shard_size_bytes=max_shard_size_bytes,
286+
max_workers=max_workers,
287+
progress_bar=progress_bar,
288+
check_weights=check_weights,
289+
include_policy_components=include_policy_components,
290+
include_adapter_artifacts=include_adapter_artifacts,
291+
)
277292

278293
def add_policy_component(self, name: str, component: PolicyComponent) -> None:
279294
"""Attach a reusable generation-policy graph to this package."""
@@ -582,30 +597,35 @@ def load(cls, directory: str) -> ModelPackage:
582597
- **Subfolder**: each subdirectory contains ``model.onnx`` → multi-
583598
component package keyed by subfolder name.
584599
600+
A nested ``mtp/model.onnx`` is restored as :attr:`mtp_head`, never as a
601+
primary model component.
602+
585603
Args:
586604
directory: Path to the directory containing models.
587605
588606
Returns:
589607
A new ``ModelPackage`` with one entry per model found.
590608
"""
591609
models: dict[str, ir.Model] = {}
592-
# Check for subfolder layout first
610+
# Preserve the established multi-component precedence while excluding
611+
# the nested MTP auxiliary package from the primary component scan.
593612
for entry in sorted(os.listdir(directory)):
613+
if entry == "mtp":
614+
continue
594615
subdir = os.path.join(directory, entry)
595616
model_path = os.path.join(subdir, "model.onnx")
596617
if os.path.isdir(subdir) and os.path.isfile(model_path):
597618
models[entry] = ir.load(model_path)
598-
if models:
599-
package = cls(models)
600-
package._load_policy_components(directory)
601-
return package
602-
# Fall back to flat layout
603-
for filename in sorted(os.listdir(directory)):
604-
if filename.endswith(".onnx"):
605-
name = filename.removesuffix(".onnx")
606-
models[name] = ir.load(os.path.join(directory, filename))
619+
if not models:
620+
for filename in sorted(os.listdir(directory)):
621+
if filename.endswith(".onnx"):
622+
name = filename.removesuffix(".onnx")
623+
models[name] = ir.load(os.path.join(directory, filename))
607624
package = cls(models)
608625
package._load_policy_components(directory)
626+
mtp_dir = os.path.join(directory, "mtp")
627+
if os.path.isfile(os.path.join(mtp_dir, "model.onnx")):
628+
package.mtp_head = cls.load(mtp_dir)
609629
return package
610630

611631
def _load_policy_components(self, directory: str) -> None:

‎src/mobius/_model_package_test.py‎

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -364,6 +364,34 @@ def test_load_multiple(self, tmp_path):
364364
loaded = ModelPackage.load(str(tmp_path))
365365
assert sorted(loaded) == ["a", "b"]
366366

367+
def test_mtp_head_roundtrip_with_flat_target(self, tmp_path):
368+
pkg = ModelPackage({"model": _make_simple_model("target")})
369+
pkg.mtp_head = ModelPackage({"model": _make_simple_model("mtp")})
370+
371+
pkg.save(str(tmp_path))
372+
loaded = ModelPackage.load(str(tmp_path))
373+
374+
assert sorted(loaded) == ["model"]
375+
assert loaded.mtp_head is not None
376+
assert sorted(loaded.mtp_head) == ["model"]
377+
assert (tmp_path / "mtp" / "model.onnx").exists()
378+
379+
def test_mtp_head_roundtrip_with_multicomponent_target(self, tmp_path):
380+
pkg = ModelPackage(
381+
{
382+
"decoder": _make_simple_model("decoder"),
383+
"embedding": _make_simple_model("embedding"),
384+
}
385+
)
386+
pkg.mtp_head = ModelPackage({"model": _make_simple_model("mtp")})
387+
388+
pkg.save(str(tmp_path))
389+
loaded = ModelPackage.load(str(tmp_path))
390+
391+
assert sorted(loaded) == ["decoder", "embedding"]
392+
assert loaded.mtp_head is not None
393+
assert sorted(loaded.mtp_head) == ["model"]
394+
367395
def test_save_creates_directory(self, tmp_path):
368396
outdir = tmp_path / "nested" / "dir"
369397
pkg = ModelPackage({"m": _make_simple_model()})

0 commit comments

Comments
 (0)