Skip to content

studio: engage MTP on *-MTP vision GGUF repos (temporary mmproj/vision bypass) - #5559

Closed
mmathew23 wants to merge 2 commits into
unslothai:mainfrom
mmathew23:fix/studio-mtp-bypass-vision-mmproj
Closed

mmathew23 wants to merge 2 commits into
unslothai:mainfrom
mmathew23:fix/studio-mtp-bypass-vision-mmproj

Conversation

@mmathew23

Copy link
Copy Markdown
Contributor

Summary

llama.cpp MTP speculative decoding (--spec-type draft-mtp) does not support --mmproj or -np > 1 (llama.cpp #22673; the Qwen3.6 MTP guide). Unsloth's *-MTP GGUF repos (for example unsloth/Qwen3.6-27B-MTP-GGUF) still ship an mmproj-*.gguf projector. On a normal load, LlamaCppBackend.load_model resolves that mmproj, sets effective_is_vision=True, and the existing draft-mtp auto-promotion (gated not effective_is_vision) is therefore suppressed.

Net effect today: the headline MTP speedup never engages out of the box for exactly the repos that advertise MTP. --spec-type draft-mtp is wired and tested, but for these vision-capable MTP repos the mmproj wins the gate and MTP is silently never used.

Change

Add a narrowly-scoped, explicitly temporary shim. In load_model, right after effective_is_vision is computed and before the command is built: when we positively detect an MTP GGUF, the bundled llama-server actually advertises the MTP spec type, and the caller has not taken over speculative decoding, fall back to text-only for that session so draft-mtp can auto-enable:

  • launch_mmproj_path = None
  • effective_is_vision = False
  • n_parallel = 1

A clear logger.warning states image input is unavailable for the session and that this is temporary until upstream supports mmproj + MTP together.

The decision is factored into a pure module-level helper _mtp_should_force_text_only(...) (same pattern as the existing _is_mtp_model_name / _extra_args_set_spec_type) so the contract is unit-testable without standing up a server.

Why this cannot regress anything else

The helper returns True only when all of these hold, so it is inert outside the exact broken case:

  • mtp_detected is true (nextn_predict_layers GGUF metadata or -mtp in the name). Non-MTP GGUFs short-circuit immediately and are never touched.
  • effective_is_vision is true. If no usable mmproj would be attached there is nothing to bypass; the existing draft-mtp auto-promotion already handles that case unchanged.
  • supports_mtp is true (probed from the bundled binary's --help). An outdated prebuilt keeps today's exact behavior (mmproj/vision preserved, existing outdated-binary warning still fires) rather than sacrificing image input for an MTP path the binary cannot run.
  • The caller has not set --spec-type/--spec-default via extra_args, and speculative_type is one of auto/empty/default/draft-mtp. An explicit user spec choice, any non-MTP speculative_type (for example ngram-mod), or "off" opts out and preserves vision/mmproj.

Testing

  • 17 new gating cases in studio/backend/tests/test_llama_cpp_mtp_detection.py covering engage, the three skip conditions (non-MTP model, not effective-vision, binary lacks MTP), and the opt-outs (off, explicit non-MTP spec, user-managed --spec-type/--spec-default via extra args, plus unrelated extra args passing through).
  • Full existing test_llama_cpp_mtp_detection.py + test_llama_server_args.py suites still green: 151 passed. py_compile clean.
  • The exact llama-server command this shim produces (-m <mtp.gguf> ... -np 1 --spec-type draft-mtp --spec-draft-n-max 6, no --mmproj) was separately verified end to end on the bundled prebuilt binary (llama.cpp b9190) with unsloth/Qwen3.6-27B-MTP-GGUF:UD-Q4_K_XL on a B200: the server log confirms creating MTP draft context / adding speculative implementation 'draft-mtp' with draft acceptance around 0.93 and a measured decode-throughput gain over the baseline.

Notes

This is deliberately a temporary shim (it disables image input for MTP vision repos). It should be removed once upstream llama.cpp supports --mmproj together with MTP. The scope is intentionally minimal so a future revert is a clean delete of one helper and one guarded block.

Test plan

  • New unit tests pass on Python 3.13
  • Existing MTP + llama_server_args suites pass (151 passed), py_compile clean
  • Produced command verified to engage MTP end to end on the bundled binary with the Qwen3.6 MTP GGUF
  • Maintainer review of the temporary-shim approach vs. a longer-term mmproj-aware MTP toggle

…n bypass)

llama.cpp MTP speculative decoding (--spec-type draft-mtp) cannot run
with --mmproj or -np > 1 (llama.cpp #22673; Qwen3.6 MTP guide). Unsloth's
*-MTP GGUF repos (e.g. unsloth/Qwen3.6-27B-MTP-GGUF) still ship an mmproj
projector, so load_model resolves it, sets effective_is_vision=True, and
the existing draft-mtp auto-promotion (gated `not effective_is_vision`)
is suppressed. Net: the headline MTP speedup never engages out of the
box for exactly the repos that advertise it.

Add a narrowly-scoped, temporary shim: when we positively detect an MTP
GGUF (nextn_predict_layers metadata or -mtp name), the bundled
llama-server actually advertises the MTP spec type, and the caller has
not taken over speculative decoding, fall back to text-only (drop
mmproj, effective_is_vision=False, single slot) so draft-mtp can
auto-enable.

Decision is a pure helper _mtp_should_force_text_only so it is unit
testable. Scoped so it cannot regress anything else:
- non-MTP GGUFs: never affected (mtp_detected False short-circuits).
- outdated binary without MTP: unchanged (keeps mmproj/vision).
- explicit user --spec-type / --spec-default via extra_args: respected.
- speculative_type "off" or any non-MTP value (e.g. ngram-mod):
  opt-out, vision/mmproj preserved.

Remove once upstream llama.cpp supports mmproj + MTP together.

Tests: 17 new gating cases in test_llama_cpp_mtp_detection.py covering
engage/skip/opt-out branches; full existing MTP + llama_server_args
suites still green (151 passed).

@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: a782fa5836

ℹ️ 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 +2627 to +2628
effective_is_vision = False
n_parallel = 1

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Keep load dedupe consistent after forcing text-only mode

Setting effective_is_vision = False here makes MTP vision repos report as non-vision while requests still come in with is_vision=True, which breaks the duplicate-load short-circuit logic: load_model._already_in_target_state() coerces request spec to "off" when is_vision is true, but backend spec is now "draft-mtp", so identical follow-up loads no longer match and trigger unnecessary reloads; the route-level matcher in studio/backend/routes/inference.py (_request_matches_loaded_settings) similarly compares request spec against backend spec based on llama_backend.is_vision, so this mismatch can repeatedly restart an already-loaded model.

Useful? React with 👍 / 👎.

)
launch_mmproj_path = None
effective_is_vision = False
n_parallel = 1

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 Recalculate VRAM/context fit after overriding parallel slots

The shim forces n_parallel = 1 only after GPU selection and context fitting have already used the original n_parallel in KV-cache estimates, so for requests that started with n_parallel > 1 the selected effective_ctx, use_fit, and max_available_ctx can be needlessly conservative and remain reduced even though the launched server now runs one slot; this introduces avoidable context/performance regression specifically in the new MTP-vision path.

Useful? React with 👍 / 👎.

@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 a temporary shim, _mtp_should_force_text_only, to enable MTP (Multi-Token Prediction) in llama.cpp for GGUF models that bundle vision projectors, which would otherwise prevent MTP from engaging. The shim forces a text-only, single-slot configuration when an MTP model is detected. Reviewers identified a potential infinite reload loop caused by state mismatches in _already_in_target_state and recommended extending the shim to handle the n_parallel > 1 limitation for all MTP models, not just vision-enabled ones. Additional tests were suggested to cover these scenarios.

Comment on lines +2609 to +2618
if _mtp_should_force_text_only(
mtp_detected = bool(self._nextn_predict_layers)
or _is_mtp_model_name(model_identifier, model_path),
effective_is_vision = effective_is_vision,
supports_mtp = bool(
self.probe_server_capabilities(binary).get("supports_mtp")
),
speculative_type = speculative_type,
extra_args = extra_args,
):

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.

high

This shim will cause an infinite reload loop for MTP vision models because _already_in_target_state (lines 3185-3186) is not aware of it. When the shim engages, it sets self._is_vision = False and self._speculative_type = "draft-mtp". However, _already_in_target_state checks the original request's is_vision=True and forces req_spec = "off", creating a mismatch with the running backend. You should update _already_in_target_state to use _mtp_should_force_text_only to determine the expected state correctly.

                if _mtp_should_force_text_only(
                    mtp_detected = bool(self._nextn_predict_layers)
                    or _is_mtp_model_name(model_identifier, model_path),
                    effective_is_vision = effective_is_vision,
                    n_parallel = n_parallel,
                    supports_mtp = bool(
                        self.probe_server_capabilities(binary).get("supports_mtp")
                    ),
                    speculative_type = speculative_type,
                    extra_args = extra_args,
                ):

Comment on lines +488 to +515
def _mtp_should_force_text_only(
*,
mtp_detected: bool,
effective_is_vision: bool,
supports_mtp: bool,
speculative_type: Optional[str],
extra_args: Optional[Iterable[str]],
) -> bool:
"""Temporary shim: should an MTP GGUF drop mmproj/vision to engage MTP?

llama.cpp MTP speculative decoding (``--spec-type draft-mtp``) does not
support ``--mmproj`` or ``-np > 1`` (llama.cpp #22673; the Qwen3.6 MTP
guide). Unsloth's ``*-MTP`` GGUF repos still ship an mmproj projector,
which pins ``effective_is_vision=True`` and therefore suppresses the
draft-mtp auto-promotion in ``load_model`` -- so the headline MTP
speedup never engages out of the box for those repos.

Return True only when we positively detect an MTP GGUF that would
otherwise be forced into vision mode, the bundled llama-server actually
advertises the MTP spec type, and the caller has not taken over
speculative decoding. Deliberately narrow so non-MTP GGUFs are never
affected, an explicit user ``--spec-type`` (or ``speculative_type``
other than auto/default/draft-mtp, including ``"off"``) opts out, and
an outdated binary falls back to today's behavior. Remove once
upstream llama.cpp supports mmproj + MTP together.
"""
if not (mtp_detected and effective_is_vision and supports_mtp):
return False

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 llama.cpp MTP implementation also lacks support for multiple parallel slots (-np > 1). While the docstring mentions this, the current logic only triggers the shim if effective_is_vision is True. Non-vision MTP models loaded with n_parallel > 1 will still attempt to engage MTP and likely fail to start. I suggest updating the shim to also engage when n_parallel > 1.

def _mtp_should_force_text_only(
    *,
    mtp_detected: bool,
    effective_is_vision: bool,
    n_parallel: int,
    supports_mtp: bool,
    speculative_type: Optional[str],
    extra_args: Optional[Iterable[str]],
) -> bool:
    """Temporary shim: should an MTP GGUF drop mmproj/vision to engage MTP?

    llama.cpp MTP speculative decoding (``--spec-type draft-mtp``) does not
    support ``--mmproj`` or ``-np > 1`` (llama.cpp #22673; the Qwen3.6 MTP
    guide). Unsloth's ``*-MTP`` GGUF repos still ship an mmproj projector,
    which pins ``effective_is_vision=True`` and therefore suppresses the
    draft-mtp auto-promotion in ``load_model`` -- so the headline MTP
    speedup never engages out of the box for those repos.

    Return True only when we positively detect an MTP GGUF that would
    otherwise be forced into vision mode or multiple slots, the bundled
    llama-server actually advertises the MTP spec type, and the caller
    has not taken over speculative decoding. Deliberately narrow so
    non-MTP GGUFs are never affected, an explicit user ``--spec-type``
    (or ``speculative_type`` other than auto/default/draft-mtp,
    including ``"off"``) opts out, and an outdated binary falls back to
    today's behavior. Remove once upstream llama.cpp supports mmproj +
    MTP together.
    """
    if not (mtp_detected and supports_mtp and (effective_is_vision or n_parallel > 1)):
        return False

Comment on lines +503 to +514
def _shim(**over):
"""Base = the case the shim exists for: MTP GGUF whose repo also
ships an mmproj, recent binary, no caller spec override."""
kw = dict(
mtp_detected = True,
effective_is_vision = True,
supports_mtp = True,
speculative_type = None,
extra_args = None,
)
kw.update(over)
return _mtp_should_force_text_only(**kw)

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

Update the test helper to include n_parallel.

Suggested change
def _shim(**over):
"""Base = the case the shim exists for: MTP GGUF whose repo also
ships an mmproj, recent binary, no caller spec override."""
kw = dict(
mtp_detected = True,
effective_is_vision = True,
supports_mtp = True,
speculative_type = None,
extra_args = None,
)
kw.update(over)
return _mtp_should_force_text_only(**kw)
def _shim(**over):
"""Base = the case the shim exists for: MTP GGUF whose repo also
ships an mmproj, recent binary, no caller spec override."""
kw = dict(
mtp_detected=True,
effective_is_vision=True,
n_parallel=1,
supports_mtp=True,
speculative_type=None,
extra_args=None,
)
kw.update(over)
return _mtp_should_force_text_only(**kw)

Comment on lines +566 to +567
def test_shim_passes_through_unrelated_extra_args():
assert _shim(extra_args = ["--threads", "8", "--no-warmup"]) is True

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

Add a test case for the n_parallel > 1 limitation.

Suggested change
def test_shim_passes_through_unrelated_extra_args():
assert _shim(extra_args = ["--threads", "8", "--no-warmup"]) is True
def test_shim_passes_through_unrelated_extra_args():
assert _shim(extra_args=["--threads", "8", "--no-warmup"]) is True
def test_shim_engages_for_multi_slot_non_vision_mtp_model():
# MTP does not support -np > 1 even without vision.
assert _shim(effective_is_vision=False, n_parallel=4) is True

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.

1 participant