Skip to content

Commit c047f77

Browse files
justinchubyCopilot
andauthored
feat(gguf): auto-detect + export Qwen3.5/3.8 MTP self-speculative head from GGUF (#529)
## What Recovers the **Multi-Token-Prediction (MTP / "nextn") self-speculative head** that the Qwen3.8-27B ONNX export was silently dropping, and emits it **automatically whenever the source GGUF ships the head** — no CLI flag, no config toggle. The MTP sidecar is a purely-additive artifact (`mtp/model.onnx` + shared embedding/lm_head + `SpeculatorConfig` metadata) that existing consumers ignore, so it is driven entirely by source-tensor presence: **emit MTP iff available.** ## Auto-detect (presence-driven, no flag) The decision is made by `has_mtp_head(config)` — true when the config carries `_gguf_mtp_block_indices`, which `gguf_to_config` populates from the source GGUF. **Exact presence check:** - Metadata key `<arch>.nextn_predict_layers > 0` (for Qwen3.8-27B: `qwen35.nextn_predict_layers = 1`, `block_count = 65`), which yields `_gguf_mtp_block_indices = [decoder_layers .. decoder_layers + nextn - 1]` (here `[64]`), and - the trailing block's `blk.<N>.nextn.*` tensors — `nextn.eh_proj` (the `fc`), `nextn.enorm`, `nextn.hnorm`, `nextn.shared_head_norm` — plus that block's own attention (`attn_q/k/v/output`, `attn_q_norm/k_norm`, `attn_norm`, `post_attention_norm`) and FFN (`ffn_gate/up/down`) sublayer. Behavior: - **Source has the nextn head** -> always emit the `mtp/model.onnx` sidecar + the backbone `hidden_states.<N-1>` seed output + a `SpeculatorConfig` (`proposal_type: mtp`) block in `inference_metadata.yaml`. - **Source has no nextn head** -> emit nothing; text-only output is byte-for-byte identical to today. - `--static-cache` skips the head (it needs the dynamic concat-grow cache), logged as info; those exports are unchanged. MTP dims are derived entirely from GGUF/source metadata (hidden size, heads, head_dim, KV heads, rope, quant) — no hardcoding. ## Root cause The dense Qwen3.5/3.8 GGUF (e.g. `unsloth/Qwen3.8-27B`) ships a trained MTP head as the **trailing `blk.<N>` block** (for 27B: `blk.64`), tagged by `<arch>.nextn_predict_layers`. `gguf_to_config` read that key **only to subtract the block** from `num_hidden_layers`, and the text-only backbone build never made a second pass — so the head tensors were dropped. ## Changes - **`integrations/gguf/_config_mapping.py`** — surface `_gguf_nextn_predict_layers` / `_gguf_mtp_block_indices` (the trailing block previously only subtracted). - **`integrations/gguf/_mtp.py`** (new) — `has_mtp_head` (presence check), `map_gguf_mtp_to_hf_names` (GGUF `blk.<N>.nextn.*` + attn/ffn -> `Qwen35MtpModel` stems), `derive_mtp_config` (**all dims inherited from the backbone config — no hardcoding**), `build_mtp_head_from_gguf` (reuses `Qwen35MtpModel`/`Qwen35MtpTask` and the existing quantized/dequantized loaders via an injectable `name_mapper`; `fc` is quantized on the same main-layer path). The two `pre_fc_norm_*` `OffsetRMSNorm` `+1` offsets missed by the generic norm strip are handled explicitly. - **`integrations/gguf/_builder.py`** — steps 4b (seed output) and 10 (attach `pkg.mtp_head`) gate on `has_mtp_head(config)` alone (auto-detect); `static_cache` skips the head via a logged info. The quantized/dequantized loaders gained optional `name_mapper` / `warn_unmapped` params (backward compatible). - **`__main__.py`** — when `pkg.mtp_head` is present, save it into `output_dir/mtp/` and write speculator metadata. (No new CLI flag.) - **`integrations/onnx_genai/inference_metadata.py`** — `write_mtp_speculator_metadata` (`proposal_type: mtp`, `target_hidden_output`, `mtp_hidden`, single-layer KV). - **`integrations/gguf/_mtp_test.py`** (new) — mapping, config derivation, tiny-GGUF head emission, **and auto-detect** (nextn GGUF auto-emits the head with `mtp_hidden` output; plain GGUF omits it). ## Validation (partial — stated explicitly) - **Unit + tiny-GGUF: 9 MTP tests PASS**, incl. auto-detect through `build_from_gguf` (source with nextn -> `pkg.mtp_head` attached; source without -> absent). Emitted head initializers include `fc.weight_t`, `pre_fc_norm_embedding.weight`, `pre_fc_norm_hidden.weight`, `norm.weight`, `layers.0.self_attn.q_proj.weight_t`; graph output `mtp_hidden`; every initializer has backing weights. `_config_mapping` / `_tensor_mapping` suites still pass (74 total). - **Real 16 GB GGUF `blk.64` shape contract VERIFIED** against the metadata-derived head — all 15 head tensors map, backbone excluded: - `attn_q` = (12288, 5120) = (2*NH*HD, H) -> **doubled-Q output gating** - `attn_k`/`attn_v` = (1024, 5120) = (NKV*HD, H); `attn_output` = (5120, 6144) = (H, NH*HD) - `nextn.eh_proj` = (5120, 10240) = (H, 2H) — the `fc` GEMM (Q8_0 while projections are Q4_0; mixed quant handled per-tensor) - **Not run:** a full 27B int4 head export through onnxruntime (heavy; the local venv's older `onnx_ir` lacks `max_shard_size_bytes`, which also breaks the pre-existing `test_default_quantized_package_save_reload` — unrelated to this change). ## Real artifact produced + two export-path fixes Producing the real int4/bf16 27B artifact surfaced two defects that made the MTP sidecar silently degenerate. Both are now fixed (commit `987c8d04`): 1. **`Qwen35TextModel.forward` ignored `output_layer_indices`** — it always returned a 2-tuple, so the backbone never emitted the `hidden_states.{N-1}` seed the head consumes; `speculator.target_hidden_output` pointed at a non-existent output. Added the same capture path as `base.py` `TextModel` (returns the selected per-layer post-residual hidden states so `HybridCausalLMTask` emits `hidden_states.{idx}`). 2. **`build_from_gguf` dropped the `_gguf_*` nextn metadata under `--dtype`** — an explicit dtype (or quantization) triggers `dataclasses.replace`, which returns a fresh config without the plain `_gguf_*` attributes, so `has_mtp_head` saw nothing and skipped the head. Now captured into locals right after `gguf_to_config` (like `_gguf_model_type`) and re-attached before step 4b. Regression test added (`test_mtp_survives_dtype_replace`). `write_mtp_speculator_metadata` also now emits `embedding_weights`, `lm_head_weights`, and `vocab_size`. ### Full export — VALIDATED end-to-end Command: ``` python -m mobius build-gguf /home/justinchu/qwen38-gguf/Qwen3.8-27B-Q4_0.gguf \ --output /home/justinchu/qwen38-27b-int4-mtp-cuda --dtype bf16 --runtime onnx-genai ``` - **Layout:** `model.onnx` (2.2 MB) + `model.onnx.data` (17.4 GB), `mtp/model.onnx` (38 KB) + `mtp/model.onnx.data` (354 MB), `inference_metadata.yaml`, `tokenizer.json`. Total **17 GB**. - **Main model exposes** `hidden_states.63` = `[batch, sequence_len, 5120]` — exactly `speculator.target_hidden_output`. - **MTP head I/O:** inputs `inputs_embeds`, `hidden_states`, `attention_mask`, `position_ids`, `past_key_values.0.{key,value}`; outputs `mtp_hidden` + `present.0.{key,value}` (single full-attention layer KV). `fc.weight_t` = (10240, 5120); q/k/v/o + gate/up/down projections are int4 `MatMulNBits` (UINT8 packed, block-32) following the main-layer path; `eh_proj` stays bf16 (Q8_0 in source). Shared embedding/lm_head are reused from the main model (named in the speculator block), not duplicated. - **SpeculatorConfig block:** `proposal_type: mtp`, `num_speculative_tokens: 1`, `model_path: mtp/model.onnx`, `mtp_hidden_output: mtp_hidden`, `kv_mode: hidden_threaded`, `embedding_weights: model.embed_tokens.weight`, `lm_head_weights: lm_head.weight`, `target_hidden_output: hidden_states.63`, `hidden_size: 5120`, `vocab_size: 248320`. - **Tests:** 53 pass (MTP + qwen35 backbone + qwen35-mtp suites), including the new seed-output and dtype-replace regressions. ## Runtime schema-conformance fix (metadata block) The first emitted metadata used a `speculator:` block whose field names the onnx-genai runtime cannot parse, so `InferenceMetadata.speculative` deserialized to `None` and the sidecar was silently ignored (text-only decode). Now conformed exactly to the authoritative schema (onnx-genai `crates/onnx-genai-metadata`: `schema/generation.rs` `SpeculatorConfig`, `parser.rs` `resolve_mtp`, `config.rs` `validate_resolved_mtp_config`) — commit `b6747e63`: - Top-level key `speculator` -> **`speculative`** (the runtime key; alias `speculator_config`). `speculator` was unknown -> dropped. - `model_path` -> **`model`**; `hidden_size` -> **`target_hidden_size`**. - `kv_mode: hidden_threaded` (engine-internal enum) -> **`proposal_local`** (only valid `MtpKvMode` for this k=1 head). - `embedding_weights`/`lm_head_weights` flat strings -> nested **`embedding`/`lm_head`** `MtpTargetInitializer` objects `{source: target_initializer, name: ...}`. - Added **`target_hidden_layout: BSH`** (rank-3 `[batch,seq,hidden]` seed) + **`hc_mult: 1`** (`resolve_mtp` requires `hc_mult>0`; `validate_resolved_mtp_config` pins it to 1 for BSH). - Omit `mtp_state_output` (an `hc_mult==1` head has no recurrent Hyper-Connection state; the sidecar emits only `mtp_hidden` + `present.0.{key,value}`). Emitted block: ```yaml speculative: proposal_type: mtp num_speculative_tokens: 1 model: mtp/model.onnx target_hidden_layout: BSH hc_mult: 1 mtp_hidden_output: mtp_hidden kv_mode: proposal_local embedding: {source: target_initializer, name: model.embed_tokens.weight} lm_head: {source: target_initializer, name: lm_head.weight} target_hidden_output: hidden_states.63 target_hidden_size: 5120 vocab_size: 248320 ``` Test `TestMtpSpeculatorMetadata` asserts the exact keys/values and validates the emitted YAML against onnx-genai's published `inference_metadata.schema.json`. (The existing 17 GB artifact's metadata was hand-patched for the benchmark; not re-exported.) ## Why Unblocks **MTP self-speculative decode** for Qwen3.8-27B batch=1 decode on H200. The engine side already landed in **onnx-genai #1598** (recurrent-state commit-by-accepted-prefix); `mtp.rs`/`MtpDecodeSession` + `SpeculatorConfig` consume exactly this sidecar. Any Qwen3.5/3.8 GGUF that ships the head now exports it end-to-end automatically. Co-authored-by: Copilot <[email protected]> --------- Co-authored-by: Copilot <[email protected]> Copilot-Session: d60eb808-7cc6-4abc-b48d-2a6dd3841624
1 parent 7295814 commit c047f77

10 files changed

Lines changed: 826 additions & 12 deletions

File tree

‎src/mobius/__main__.py‎

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -575,6 +575,18 @@ def _cmd_build_gguf(args: argparse.Namespace) -> None:
575575
path = os.path.join(output_dir, "model.onnx")
576576
print(f"Saved {name} to {path}")
577577

578+
# Save the trailing MTP / "nextn" self-speculative head sidecar (when the
579+
# GGUF shipped one) into a ``mtp/`` subdirectory next to the backbone.
580+
mtp_head = getattr(pkg, "mtp_head", None)
581+
if mtp_head is not None:
582+
mtp_dir = os.path.join(output_dir, "mtp")
583+
mtp_head.save(
584+
mtp_dir,
585+
external_data=args.external_data,
586+
max_workers=args.max_workers,
587+
)
588+
print(f"Saved mtp head to {os.path.join(mtp_dir, 'model.onnx')}")
589+
578590
runtime = getattr(args, "runtime", None)
579591
if runtime in ("onnx-genai", "ort-genai"):
580592
from mobius.integrations.gguf import write_gguf_runtime_package
@@ -587,6 +599,16 @@ def _cmd_build_gguf(args: argparse.Namespace) -> None:
587599
)
588600
for name, path in artifacts.items():
589601
print(f" {name}: {path}")
602+
if mtp_head is not None:
603+
from mobius.integrations.onnx_genai.inference_metadata import (
604+
write_mtp_speculator_metadata,
605+
)
606+
607+
spec_path = write_mtp_speculator_metadata(
608+
output_dir, backbone_config=getattr(pkg, "config", None)
609+
)
610+
if spec_path is not None:
611+
print(f" speculator: {spec_path}")
590612

591613

592614
def _cmd_convert_comfyui(args: argparse.Namespace) -> None:

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

Lines changed: 93 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,7 @@
2121
import logging
2222
import re
2323
from collections import Counter
24-
from collections.abc import Iterable, Mapping
24+
from collections.abc import Callable, Iterable, Mapping
2525
from pathlib import Path
2626
from typing import TYPE_CHECKING
2727

@@ -376,6 +376,14 @@ def build_from_gguf(
376376
if model_type is None:
377377
model_type = GGUF_ARCH_TO_MODEL_TYPE.get(gguf_arch, gguf_arch)
378378

379+
# ``dataclasses.replace`` below (dtype / quantization) returns a fresh
380+
# instance that does NOT carry the private ``_gguf_*`` attributes set by
381+
# gguf_to_config (they are plain attributes, not dataclass fields). Capture
382+
# the MTP head metadata here — like ``model_type`` above — so it can be
383+
# re-attached onto the final config for auto-detection (step 4b).
384+
mtp_predict_layers = getattr(config, "_gguf_nextn_predict_layers", 0)
385+
mtp_block_indices = list(getattr(config, "_gguf_mtp_block_indices", []) or [])
386+
379387
if dtype is not None:
380388
resolved = resolve_dtype(dtype)
381389
if resolved is not None:
@@ -437,6 +445,46 @@ def build_from_gguf(
437445
else:
438446
resolved_task = task
439447

448+
# 4b. Auto-detect the Qwen3.5/3.8 MTP / "nextn" self-speculative head: if
449+
# the source GGUF ships the trailing nextn head block (surfaced by
450+
# ``has_mtp_head`` from ``<arch>.nextn_predict_layers`` > 0 + the
451+
# ``blk.<N>.nextn.*`` tensors), always emit the MTP sidecar — it is a purely
452+
# additive artifact that text-only consumers ignore. No opt-in flag: the
453+
# decision is driven entirely by presence in the source. When present, expose
454+
# the backbone's final-layer hidden state as a graph output so the
455+
# orchestrator can seed the head with it (must be set before the graph is
456+
# built). Direct field assignment (not dataclasses.replace) preserves the
457+
# ``_gguf_*`` metadata attributes on the config. Skipped under static_cache
458+
# (the head needs the dynamic concat-grow cache), leaving those exports
459+
# byte-identical to today.
460+
from mobius.integrations.gguf._mtp import build_mtp_head_from_gguf, has_mtp_head
461+
462+
# Re-attach the MTP metadata dropped by the dtype/quantization
463+
# ``dataclasses.replace`` calls above so auto-detection sees it on the final
464+
# config instance (and ``derive_mtp_config`` can read model_type/quant/dtype).
465+
config._gguf_model_type = model_type
466+
config._gguf_nextn_predict_layers = mtp_predict_layers
467+
config._gguf_mtp_block_indices = mtp_block_indices
468+
469+
emit_mtp_head = has_mtp_head(config) and not static_cache
470+
if has_mtp_head(config) and static_cache:
471+
logger.info(
472+
"GGUF ships an MTP/nextn head but static_cache=True is incompatible "
473+
"with the head's dynamic cache; skipping the self-speculative sidecar."
474+
)
475+
476+
if emit_mtp_head:
477+
seed_index = int(config.num_hidden_layers) - 1
478+
existing = list(config.output_layer_indices or [])
479+
if seed_index not in existing:
480+
existing.append(seed_index)
481+
config.output_layer_indices = existing
482+
logger.info(
483+
"MTP head detected in source: exposing backbone hidden-state seed "
484+
"output hidden_states.%d",
485+
seed_index,
486+
)
487+
440488
# 5. Build ONNX graph
441489
module = module_class(config)
442490
if preserve_quantization:
@@ -496,6 +544,27 @@ def build_from_gguf(
496544
prefix_map = getattr(module, "weight_prefix_map", None)
497545
pkg.apply_weights(state_dict, prefix_map=prefix_map)
498546

547+
# 10. Build the trailing MTP / "nextn" self-speculative head sidecar from
548+
# the GGUF's ``blk.<nextn>.*`` tensors (dropped by the backbone build) and
549+
# attach it to the package so the CLI can save it into a ``mtp/`` subdir.
550+
# Auto-detected from source-tensor presence (see step 4b).
551+
if emit_mtp_head:
552+
try:
553+
mtp_pkg = build_mtp_head_from_gguf(
554+
gguf_model,
555+
config,
556+
preserve_quantization=preserve_quantization,
557+
execution_provider=execution_provider,
558+
)
559+
except Exception: # pragma: no cover - defensive: never fail the backbone
560+
logger.exception(
561+
"Failed to build the Qwen3.5/3.8 MTP head sidecar; the backbone "
562+
"model was exported without a self-speculative drafter."
563+
)
564+
mtp_pkg = None
565+
if mtp_pkg is not None:
566+
pkg.mtp_head = mtp_pkg
567+
499568
return pkg
500569

501570

@@ -1221,30 +1290,42 @@ def repack_gguf_weight_to_target(
12211290
def _load_dequantized_state_dict(
12221291
gguf_model,
12231292
gguf_arch: str,
1293+
name_mapper: Callable[[str, str], str | None] | None = None,
1294+
warn_unmapped: bool = True,
12241295
) -> dict:
1225-
"""Load all tensors dequantized to float (Phase 1 path)."""
1296+
"""Load all tensors dequantized to float (Phase 1 path).
1297+
1298+
``name_mapper`` maps a GGUF tensor name to its target state-dict key (or
1299+
``None`` to skip). Defaults to the main-model mapping; the MTP head builder
1300+
injects a head-scoped mapper so the trailing ``blk.<mtp>.nextn.*`` /
1301+
attention block is routed to the head module instead of being dropped.
1302+
"""
12261303
import numpy as np
12271304
import torch
12281305

12291306
from mobius.integrations.gguf._tensor_mapping import (
12301307
map_gguf_to_hf_names,
12311308
)
12321309

1310+
if name_mapper is None:
1311+
name_mapper = map_gguf_to_hf_names
1312+
12331313
state_dict = {}
12341314
for gguf_name, np_array in tqdm.tqdm(
12351315
gguf_model.tensor_items(),
12361316
desc="Dequantizing tensors",
12371317
total=len(gguf_model._tensor_index),
12381318
):
1239-
hf_name = map_gguf_to_hf_names(gguf_name, gguf_arch)
1319+
hf_name = name_mapper(gguf_name, gguf_arch)
12401320
if hf_name is not None:
12411321
# F32/F16 tensors are mmap'd read-only views; make
12421322
# writable so PyTorch can mutate if needed.
12431323
if not np_array.flags.writeable:
12441324
np_array = np.array(np_array)
12451325
state_dict[hf_name] = torch.from_numpy(np_array)
12461326
else:
1247-
logger.warning("Unmapped GGUF tensor: %s (skipped)", gguf_name)
1327+
if warn_unmapped:
1328+
logger.warning("Unmapped GGUF tensor: %s (skipped)", gguf_name)
12481329
return state_dict
12491330

12501331

@@ -1253,6 +1334,8 @@ def _load_quantized_state_dict(
12531334
gguf_arch: str,
12541335
module,
12551336
config,
1337+
name_mapper: Callable[[str, str], str | None] | None = None,
1338+
warn_unmapped: bool = True,
12561339
) -> dict:
12571340
"""Load tensors, preserving native blocks or normalizing to MatMulNBits.
12581341
@@ -1289,6 +1372,9 @@ def _load_quantized_state_dict(
12891372
_reverse_permute,
12901373
)
12911374

1375+
if name_mapper is None:
1376+
name_mapper = map_gguf_to_hf_names
1377+
12921378
# Collect module paths that use QuantizedLinear so we know
12931379
# which .weight parameters should receive repacked data.
12941380
quantized_stems = set()
@@ -1331,9 +1417,10 @@ def _load_quantized_state_dict(
13311417
desc="Repacking tensors",
13321418
total=len(gguf_model._tensor_index),
13331419
):
1334-
hf_name = map_gguf_to_hf_names(gguf_name, gguf_arch)
1420+
hf_name = name_mapper(gguf_name, gguf_arch)
13351421
if hf_name is None:
1336-
logger.warning("Unmapped GGUF tensor: %s (skipped)", gguf_name)
1422+
if warn_unmapped:
1423+
logger.warning("Unmapped GGUF tensor: %s (skipped)", gguf_name)
13371424
continue
13381425

13391426
# Determine the int value of the quant type for can_repack

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

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -262,6 +262,8 @@ def gguf_to_config(
262262
# an extra decoder layer whose linear-attention / GQA initializers have no
263263
# backing GGUF weights and fail the ``_check_weights`` invariant on save.
264264
nextn_layers = metadata.get(f"{gguf_arch}.nextn_predict_layers")
265+
mtp_predict_layers = 0
266+
mtp_block_indices: list[int] = []
265267
if nextn_layers is not None and int(nextn_layers) > 0:
266268
mtp_count = int(nextn_layers)
267269
decoder_layers = int(hf_fields["num_hidden_layers"]) - mtp_count
@@ -272,6 +274,13 @@ def gguf_to_config(
272274
f"({mtp_count}) for architecture {gguf_arch}."
273275
)
274276
hf_fields["num_hidden_layers"] = decoder_layers
277+
# The trailing ``mtp_count`` GGUF blocks (indices ``decoder_layers`` ..
278+
# ``decoder_layers + mtp_count - 1``) hold the self-speculative MTP head
279+
# weights (``blk.<n>.nextn.*`` plus the head's own attention/FFN block).
280+
# Surface them so the builder can emit the MTP sidecar instead of
281+
# silently dropping the tensors.
282+
mtp_predict_layers = mtp_count
283+
mtp_block_indices = list(range(decoder_layers, decoder_layers + mtp_count))
275284

276285
# Derive head_dim if not explicitly provided.
277286
# Prefer attention.key_length (the actual head dimension) over
@@ -499,6 +508,11 @@ def gguf_to_config(
499508
config._gguf_model_type = model_type
500509
config.model_type = model_type
501510

511+
# Re-surface after any postprocessor swap so the MTP metadata survives on
512+
# the final config instance.
513+
config._gguf_nextn_predict_layers = mtp_predict_layers
514+
config._gguf_mtp_block_indices = mtp_block_indices
515+
502516
logger.info(
503517
"Extracted config from GGUF: arch=%s, model_type=%s, "
504518
"hidden=%d, layers=%d, heads=%d, vocab=%d",

0 commit comments

Comments
 (0)