Skip to content

Studio: auto-enable MTP speculative decoding for MTP GGUFs - #5527

Merged
danielhanchen merged 2 commits into
mainfrom
mtp-auto-spec-decoding
May 18, 2026
Merged

danielhanchen merged 2 commits into
mainfrom
mtp-auto-spec-decoding

Conversation

@danielhanchen

Copy link
Copy Markdown
Member

Summary

Detect Unsloth's MTP (multi-token-prediction) GGUFs and auto-emit the right --spec-type draft-mtp flags for llama-server (llama.cpp PR #22673), so users get the 1.4-2x speedup without configuration.

  • Primary signal: GGUF metadata {arch}.nextn_predict_layers > 0. Verified on the published quants:
    • unsloth/Qwen3.6-27B-MTP-GGUF (arch qwen35, qwen35.nextn_predict_layers = 1)
    • unsloth/Qwen3.6-35B-A3B-MTP-GGUF (arch qwen35moe, qwen35moe.nextn_predict_layers = 1)
  • Fallback: -MTP segment in the identifier or filename, used pre-download for HF-mode loads (the comparator runs before the GGUF is on disk) and for local-file loads where the filename still carries the marker.
  • Future quants can drop the -MTP substring from the name and detection still works because metadata is the authoritative signal.

Flag presets

Match the Unsloth MTP guide:

Hardware Emitted
GPU (NVIDIA / ROCm) --spec-type draft-mtp --spec-draft-n-max 6
CPU / Apple Silicon --spec-type draft-mtp --spec-draft-n-max 3 --spec-type ngram-mod --spec-ngram-mod-n-match 24 --spec-ngram-mod-n-min 48 --spec-ngram-mod-n-max 6
Vision GGUF nothing (spec decoding always off for vision, unchanged)
Non-MTP GGUF existing behaviour unchanged

CPU/Mac detection uses the existing _get_gpu_free_memory() probe (empty means no NVIDIA/ROCm device, which covers Apple Silicon).

User overrides win

The spec block runs before user pass-through extra_args are appended, but --spec-type is one of the few llama-server flags that accumulates when repeated (that's how the CPU MTP chain works: --spec-type draft-mtp ... --spec-type ngram-mod ...). So a user --spec-type none would compose rather than override.

Fix: _extra_args_set_spec_type scans extra_args for --spec-type / --spec-default. If the user supplied either, Studio skips the auto-emit and llama-server sees only the user's flag.

User invocation on a -MTP GGUF Behaviour
unsloth run --model unsloth/Qwen3.6-27B-MTP-GGUF auto-emit MTP preset
unsloth run ... --spec-type none suppress auto-emit; user wins
unsloth run ... --spec-type ngram-mod --draft-min 48 --draft-max 64 suppress auto-emit; user's ngram-mod wins
unsloth run ... --spec-type draft-mtp --spec-draft-n-max 8 suppress auto-emit; user's tuned MTP wins
unsloth run ... --spec-draft-n-max 8 (scalar tuning, no --spec-type) auto-emit preset, then user's scalar overrides via llama-server last-wins
LoadRequest.speculative_type = "off" explicit disable; no spec emitted

Same semantics apply through HTTP LoadRequest.llama_extra_args.

Reload comparator

_already_in_target_state mirrors the promotion so a repeat /load with speculative_type=None (or "default") against an MTP backend running draft-mtp short-circuits cleanly instead of forcing a reload. Suppressed when the caller's extra_args carries --spec-type, matching the load-time skip.

Performance

Detection cost is well below the existing GGUF-load floor:

  • _is_mtp_model_name: 0.1-2.5 us / call
  • _extra_args_set_spec_type: 0.05-0.5 us / call
  • New nextn_predict_layers entry in arch_keys: one extra dict-membership check per KV pair inside the existing header parse, plus one 4-byte read on MTP GGUFs. Below the noise floor of the 55-80 us total parse.

No new I/O on the load hot path.

llama_server_args.py

--spec-draft-n-max, --spec-draft-n-min, --spec-ngram-mod-n-match, --spec-ngram-mod-n-min, --spec-ngram-mod-n-max added to _SPEC_FLAGS so inherited llama_extra_args get stripped on speculative_type re-application (matches the existing semantics for the other spec flags). They stay pass-through (not on the hard denylist).

Test plan

  • pytest studio/backend/tests/test_llama_cpp_mtp_detection.py (38 new cases): helper detector, override detector, comparator integration (4 paths: None / "default" / "off" / user override), nextn_predict_layers capture across qwen35 / qwen35moe / qwen3moe / hypothetical future arch, zero-value falsy semantics, unload reset
  • pytest studio/backend/tests/test_llama_server_args.py (90 cases, 5 new): MTP flag pass-through, strip-shadowing for the new flag family, is_managed_flag assertions
  • pytest studio/backend/tests/test_gguf_reload_inheritance.py (8 cases): no regressions
  • pytest studio/backend/tests/test_gguf_metadata.py (12 cases): no regressions
  • Broader inference surface: test_llama_cpp_load_progress, test_llama_cpp_context_fit, test_llama_cpp_max_context_threshold, test_llama_cpp_no_context_shift, test_inference_model_validation, test_native_context_length, test_kv_cache_estimation -> 220 passed

References

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code Review

This pull request introduces auto-detection and support for Multi-Token Prediction (MTP) speculative decoding using the draft-mtp type. It implements logic to identify MTP-capable models through GGUF metadata or filename markers and automatically configures the backend with optimized presets for GPU and CPU/Mac environments. Feedback was provided regarding a discrepancy in the state-matching logic where metadata-based detection was omitted, which could cause unnecessary model reloads; a code suggestion was provided to synchronize this check with the primary loading logic.

Comment on lines +2877 to +2881
req_spec = "off"
else:
req_spec = _norm(speculative_type) or "off"
raw_spec = _norm(speculative_type)
req_spec = raw_spec or "off"
# Mirror load_model's auto-promotion to draft-mtp for MTP

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

The MTP auto-promotion logic in _already_in_target_state is missing the metadata-based signal (self._nextn_predict_layers), unlike the implementation in load_model (line 2417). This discrepancy will cause unnecessary reloads for MTP models that are identified via GGUF metadata but do not contain the -MTP fallback marker in their name or identifier. Including the metadata check ensures that repeat /load requests for these models correctly short-circuit when already running with draft-mtp.

Suggested change
req_spec = "off"
else:
req_spec = _norm(speculative_type) or "off"
raw_spec = _norm(speculative_type)
req_spec = raw_spec or "off"
# Mirror load_model's auto-promotion to draft-mtp for MTP
if (
raw_spec in (None, "default")
and (bool(self._nextn_predict_layers) or _is_mtp_model_name(model_identifier, gguf_path))
and not _extra_args_set_spec_type(extra_args)
):

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: f67fa5ceb1

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment on lines +2885 to +2888
if (
raw_spec in (None, "default")
and _is_mtp_model_name(model_identifier, gguf_path)
and not _extra_args_set_spec_type(extra_args)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Reuse metadata signal when matching MTP reloads

When an MTP GGUF is detected only from metadata and its repo/file name does not contain -MTP, this comparator never mirrors the load_model auto-promotion: raw_spec=None stays off while the running backend has _speculative_type == "draft-mtp". Because the backend still has _nextn_predict_layers from the loaded model at this point, include that signal here as well; otherwise a no-op repeat /load for such metadata-only MTP models unnecessarily kills and restarts the server even though the later command construction would auto-enable draft-mtp again.

Useful? React with 👍 / 👎.

@Mithras

Mithras commented May 18, 2026

Copy link
Copy Markdown

Just FYI, as of today mtp has almost 50% pp hit

Detect Unsloth's MTP (multi-token-prediction) GGUFs and auto-emit the
right --spec-type draft-mtp flags for llama-server (llama.cpp PR
#22673), so users get the speedup without configuration.

Detection prefers the GGUF metadata field <arch>.nextn_predict_layers
(verified on Qwen3.6-27B-MTP-GGUF / qwen35 and Qwen3.6-35B-A3B-MTP-GGUF
/ qwen35moe). Falls back to a -MTP marker in the identifier / filename
so HF-mode loads can detect MTP from the repo name before the GGUF is
downloaded.

Flag presets follow the Unsloth MTP guide:
  GPU:     --spec-type draft-mtp --spec-draft-n-max 6
  CPU/Mac: --spec-type draft-mtp --spec-draft-n-max 3 \
           --spec-type ngram-mod --spec-ngram-mod-n-match 24 \
           --spec-ngram-mod-n-min 48 --spec-ngram-mod-n-max 6

User overrides win: if the caller passes --spec-type / --spec-default
via unsloth run / unsloth studio run pass-through (or HTTP
llama_extra_args), the auto-emit steps aside so llama-server only sees
the user's flag. Scalar tuning knobs like --spec-draft-n-max compose
with the auto preset via llama-server's last-wins parsing.

_already_in_target_state mirrors the same promotion so a repeat /load
with unchanged settings against an MTP backend running draft-mtp
short-circuits cleanly instead of forcing a reload.
@danielhanchen
danielhanchen force-pushed the mtp-auto-spec-decoding branch from f67fa5c to 6599968 Compare May 18, 2026 04:36

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 105d878e59

ℹ️ About Codex in GitHub

Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

Comment on lines +2850 to +2852
raw_spec = _norm(speculative_type)
req_spec = raw_spec or "off"
# Mirror load_model's auto-promotion so repeat /load matches.

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Suppress spec comparison when extra args own spec type

load_model now explicitly lets llama_extra_args win when users pass --spec-type/--spec-default by clearing self._speculative_type, but _already_in_target_state still computes req_spec from speculative_type first. In requests that include both fields (for example a stale speculative_type="default" plus llama_extra_args=["--spec-type","none"]), the effective runtime config is unchanged, yet this comparator reports a spec mismatch and forces an unnecessary reload on every repeat /load. This is introduced by the new override behavior and should mirror the same “user owns spec type” rule during comparison.

Useful? React with 👍 / 👎.

@danielhanchen

Copy link
Copy Markdown
Member Author

@Mithras Best to open a llama.cpp issue - for now in general generation speed is definitely better.

@danielhanchen
danielhanchen merged commit 5a6e94d into main May 18, 2026
32 checks passed
@danielhanchen
danielhanchen deleted the mtp-auto-spec-decoding branch May 18, 2026 07:15
pull Bot pushed a commit to ShinnChow/unsloth that referenced this pull request May 18, 2026
* Studio: warn when llama.cpp prebuilt is too old for MTP

Layered on unslothai#5527. Adds a one-shot llama-server --help capability probe
so users get a clear signal when their prebuilt is missing MTP support,
plus a graceful fallback if they load an MTP GGUF against an outdated
binary.

What's surfaced:

1. Startup log + stderr line in main.py:lifespan() if MTP isn't
   advertised:
     WARNING: llama.cpp prebuilt is missing MTP support
     (--spec-type mtp / draft-mtp). Run `unsloth studio update` to
     refresh it. MTP GGUFs will load without speculative decoding.
2. Load-time graceful fallback in load_model's spec block: skip the
   auto-emit and log a clear warning instead of letting llama-server
   fail with an unknown-flag error.
3. /api/inference/status now returns llama_cpp_supports_mtp: bool so
   the frontend can show a banner / popup.

Probe internals:

- Class-level cache keyed on (binary_path, mtime). One subprocess call
  the first time, instant thereafter. Touching the binary (e.g. via
  `unsloth studio update`) invalidates the cache automatically because
  the mtime changes, so the new build is picked up without restarting
  the server.
- Recognises both upstream naming forms: the original draft-mtp from
  llama.cpp PR #22673 and the renamed mtp variant in later commits.
- Spec block uses whichever token the binary accepts so we emit the
  right value regardless of which release the user has.

Tests:

- 6 new cases in test_llama_cpp_mtp_detection.py covering each probe
  variant (draft-mtp, renamed mtp, pre-MTP build, missing binary,
  mtime-based cache invalidation).
- Existing 38 MTP detection cases still pass; broader 188-test
  regression suite (server args, reload inheritance, gguf metadata,
  load progress, context fit, model validation) still green.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

---------

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
@Mithras

Mithras commented May 19, 2026

Copy link
Copy Markdown

@Mithras Best to open a llama.cpp issue - for now in general generation speed is definitely better.

For agentic use pp is more important. I wouldn't default to something that halves pp

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants