Skip to content

Commit edf41ee

Browse files
justinchubyCopilot
andcommitted
Merge current main into restored diffusion branch
Preserve the force-pushed head as backup/catalogue-diffusion-builds-789bd76c, then merge origin/main at c047f77 without rebasing. This restores current MTP and metadata changes while retaining the approved diffusion guidance, clamp dtype, revision propagation, and canonical workflow behavior. Replace the stale GGUF CLI rejection regression with the current supported ort-genai dispatch contract; that contradictory test caused all six Python unit matrix failures after the branch rewrite. Co-authored-by: Copilot <[email protected]> Signed-off-by: justinchuby <[email protected]>
2 parents 789bd76 + c047f77 commit edf41ee

9 files changed

Lines changed: 843 additions & 11 deletions

File tree

‎src/mobius/__main__.py‎

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

582+
# Save the trailing MTP / "nextn" self-speculative head sidecar (when the
583+
# GGUF shipped one) into a ``mtp/`` subdirectory next to the backbone.
584+
mtp_head = getattr(pkg, "mtp_head", None)
585+
if mtp_head is not None:
586+
mtp_dir = os.path.join(output_dir, "mtp")
587+
mtp_head.save(
588+
mtp_dir,
589+
external_data=args.external_data,
590+
max_workers=args.max_workers,
591+
)
592+
print(f"Saved mtp head to {os.path.join(mtp_dir, 'model.onnx')}")
593+
582594
runtime = getattr(args, "runtime", None)
583595
if runtime in ("onnx-genai", "ort-genai"):
584596
from mobius.integrations.gguf import write_gguf_runtime_package
@@ -591,6 +603,16 @@ def _cmd_build_gguf(args: argparse.Namespace) -> None:
591603
)
592604
for name, path in artifacts.items():
593605
print(f" {name}: {path}")
606+
if mtp_head is not None:
607+
from mobius.integrations.onnx_genai.inference_metadata import (
608+
write_mtp_speculator_metadata,
609+
)
610+
611+
spec_path = write_mtp_speculator_metadata(
612+
output_dir, backbone_config=getattr(pkg, "config", None)
613+
)
614+
if spec_path is not None:
615+
print(f" speculator: {spec_path}")
594616

595617

596618
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)