2121import logging
2222import re
2323from collections import Counter
24- from collections .abc import Iterable , Mapping
24+ from collections .abc import Callable , Iterable , Mapping
2525from pathlib import Path
2626from 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(
12211290def _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
0 commit comments