Repository navigation
Commit c047f77
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-2a6dd38416241 parent 7295814 commit c047f77
10 files changed
Lines changed: 826 additions & 12 deletions
File tree
- src/mobius
- integrations
- gguf
- onnx_genai
- models
| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
| |||
575 | 575 | | |
576 | 576 | | |
577 | 577 | | |
| 578 | + | |
| 579 | + | |
| 580 | + | |
| 581 | + | |
| 582 | + | |
| 583 | + | |
| 584 | + | |
| 585 | + | |
| 586 | + | |
| 587 | + | |
| 588 | + | |
| 589 | + | |
578 | 590 | | |
579 | 591 | | |
580 | 592 | | |
| |||
587 | 599 | | |
588 | 600 | | |
589 | 601 | | |
| 602 | + | |
| 603 | + | |
| 604 | + | |
| 605 | + | |
| 606 | + | |
| 607 | + | |
| 608 | + | |
| 609 | + | |
| 610 | + | |
| 611 | + | |
590 | 612 | | |
591 | 613 | | |
592 | 614 | | |
| |||
| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
| |||
21 | 21 | | |
22 | 22 | | |
23 | 23 | | |
24 | | - | |
| 24 | + | |
25 | 25 | | |
26 | 26 | | |
27 | 27 | | |
| |||
376 | 376 | | |
377 | 377 | | |
378 | 378 | | |
| 379 | + | |
| 380 | + | |
| 381 | + | |
| 382 | + | |
| 383 | + | |
| 384 | + | |
| 385 | + | |
| 386 | + | |
379 | 387 | | |
380 | 388 | | |
381 | 389 | | |
| |||
437 | 445 | | |
438 | 446 | | |
439 | 447 | | |
| 448 | + | |
| 449 | + | |
| 450 | + | |
| 451 | + | |
| 452 | + | |
| 453 | + | |
| 454 | + | |
| 455 | + | |
| 456 | + | |
| 457 | + | |
| 458 | + | |
| 459 | + | |
| 460 | + | |
| 461 | + | |
| 462 | + | |
| 463 | + | |
| 464 | + | |
| 465 | + | |
| 466 | + | |
| 467 | + | |
| 468 | + | |
| 469 | + | |
| 470 | + | |
| 471 | + | |
| 472 | + | |
| 473 | + | |
| 474 | + | |
| 475 | + | |
| 476 | + | |
| 477 | + | |
| 478 | + | |
| 479 | + | |
| 480 | + | |
| 481 | + | |
| 482 | + | |
| 483 | + | |
| 484 | + | |
| 485 | + | |
| 486 | + | |
| 487 | + | |
440 | 488 | | |
441 | 489 | | |
442 | 490 | | |
| |||
496 | 544 | | |
497 | 545 | | |
498 | 546 | | |
| 547 | + | |
| 548 | + | |
| 549 | + | |
| 550 | + | |
| 551 | + | |
| 552 | + | |
| 553 | + | |
| 554 | + | |
| 555 | + | |
| 556 | + | |
| 557 | + | |
| 558 | + | |
| 559 | + | |
| 560 | + | |
| 561 | + | |
| 562 | + | |
| 563 | + | |
| 564 | + | |
| 565 | + | |
| 566 | + | |
| 567 | + | |
499 | 568 | | |
500 | 569 | | |
501 | 570 | | |
| |||
1221 | 1290 | | |
1222 | 1291 | | |
1223 | 1292 | | |
| 1293 | + | |
| 1294 | + | |
1224 | 1295 | | |
1225 | | - | |
| 1296 | + | |
| 1297 | + | |
| 1298 | + | |
| 1299 | + | |
| 1300 | + | |
| 1301 | + | |
| 1302 | + | |
1226 | 1303 | | |
1227 | 1304 | | |
1228 | 1305 | | |
1229 | 1306 | | |
1230 | 1307 | | |
1231 | 1308 | | |
1232 | 1309 | | |
| 1310 | + | |
| 1311 | + | |
| 1312 | + | |
1233 | 1313 | | |
1234 | 1314 | | |
1235 | 1315 | | |
1236 | 1316 | | |
1237 | 1317 | | |
1238 | 1318 | | |
1239 | | - | |
| 1319 | + | |
1240 | 1320 | | |
1241 | 1321 | | |
1242 | 1322 | | |
1243 | 1323 | | |
1244 | 1324 | | |
1245 | 1325 | | |
1246 | 1326 | | |
1247 | | - | |
| 1327 | + | |
| 1328 | + | |
1248 | 1329 | | |
1249 | 1330 | | |
1250 | 1331 | | |
| |||
1253 | 1334 | | |
1254 | 1335 | | |
1255 | 1336 | | |
| 1337 | + | |
| 1338 | + | |
1256 | 1339 | | |
1257 | 1340 | | |
1258 | 1341 | | |
| |||
1289 | 1372 | | |
1290 | 1373 | | |
1291 | 1374 | | |
| 1375 | + | |
| 1376 | + | |
| 1377 | + | |
1292 | 1378 | | |
1293 | 1379 | | |
1294 | 1380 | | |
| |||
1331 | 1417 | | |
1332 | 1418 | | |
1333 | 1419 | | |
1334 | | - | |
| 1420 | + | |
1335 | 1421 | | |
1336 | | - | |
| 1422 | + | |
| 1423 | + | |
1337 | 1424 | | |
1338 | 1425 | | |
1339 | 1426 | | |
| |||
| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
| |||
262 | 262 | | |
263 | 263 | | |
264 | 264 | | |
| 265 | + | |
| 266 | + | |
265 | 267 | | |
266 | 268 | | |
267 | 269 | | |
| |||
272 | 274 | | |
273 | 275 | | |
274 | 276 | | |
| 277 | + | |
| 278 | + | |
| 279 | + | |
| 280 | + | |
| 281 | + | |
| 282 | + | |
| 283 | + | |
275 | 284 | | |
276 | 285 | | |
277 | 286 | | |
| |||
499 | 508 | | |
500 | 509 | | |
501 | 510 | | |
| 511 | + | |
| 512 | + | |
| 513 | + | |
| 514 | + | |
| 515 | + | |
502 | 516 | | |
503 | 517 | | |
504 | 518 | | |
| |||
0 commit comments