Repository navigation
studio: tighten MTP reload guards and asymmetric spec flags for #5582 - #5696
Conversation
There was a problem hiding this comment.
Code Review
This pull request fixes several issues in the llama.cpp speculative decoding implementation. It prevents flag collisions in legacy builds by suppressing duplicate --draft-max flags when MTP and ngram-mod are chained. It also ensures that "none" and "disable" speculative mode aliases are correctly canonicalized to "off" and prevents server startup failures by verifying ngram-mod support before emitting flags. Furthermore, the reload logic was updated to accurately detect changes in spec_draft_n_max, including transitions to and from default values and within auto-promoted MTP sessions. A robust suite of regression tests has been added to cover these scenarios. I have no feedback to provide as there were no review comments.
Each PR ran the same staged source files before, which went stale when the upstream PR commits advanced. Refactor to one job per PR with an actions/checkout of that PR's head ref, so cross-OS validation always uses the latest commit: - PR unslothai#5603 sandbox -> studio-sandbox-hardening - PR unslothai#5620 parser parity -> studio-tools-multi-format-v2 - PR unslothai#5696 mtp reload guards -> followup-mtp-reload-guards (unslothai#5582 followup) - PR unslothai#5695 lockfile audit -> followup-lockfile-audit-regressions (unslothai#5604 followup) 4 jobs x 3 OSes = 12 runs; Windows = 4 (below the 5-concurrent cap). cancel-in-progress per (workflow, ref) keeps iteration cheap. All tests stay CPU-only and rely on the CUDA spoof harness in tests/conftest.py + tests/_zoo_aggressive_cuda_spoof.py, so no real GPU is required on any runner.
unslothai#5620 parser tests transitively import the safetensors loop, which needs the datasets package. unslothai#5696 route-guard tests import routes/inference.py, which transitively imports core/training (uses matplotlib). Add both, plus the auth deps (pyjwt/cryptography/ aiosqlite/python-multipart) needed for any test that touches the FastAPI route module so route-level imports resolve cleanly on all three OSes.
Five issues surfaced after #5582 merged. All addressed with matching pytest coverage (15 new tests, 147 total green). Bug A -- route guard compared against the requested UI mode rather than the backend's resolved spec mode. A user request setting ``spec_draft_n_max=2`` against a backend that was auto-promoted from ``auto`` -> ``draft-mtp`` saw ``requested_spec_mode == "auto"`` (not in ``("mtp", "mtp+ngram")``) and skipped the comparison, returning ``already_loaded`` with the stale value still active. Now mirrors the backend-side guard's check against ``speculative_type == "draft-mtp"``. Bug B -- both reload guards short-circuited the n_max comparison when the request value was ``None``, treating it as a wildcard. A backend loaded with an explicit override of 8 could never be cleared back to the platform default without swapping the model. Both guards now treat the ``(None vs explicit)`` flip as a difference: clear-to-default and set-from-default both bounce a reload, while ``(None == None)`` and ``(N == N)`` continue to match. Bug C -- chained MTP+ngram on a legacy llama-server (pre arg-rename) emitted ``--draft-max`` twice: once for MTP's draft length (e.g. 2), once for ngram-mod's size-N max (e.g. 64). llama-server's last-wins parsing clobbered the MTP value with 64, defeating the ``--spec-draft-n-max`` slider. ``_build_ngram_mod_flags`` now takes a ``chain_with_mtp`` kwarg that suppresses ``--draft-max`` on the legacy flavor when MTP will emit it; the post-rename flavor uses distinct ``--spec-ngram-mod-*`` names that cannot collide. Bug D -- a forced ``speculative_type="ngram"`` request emitted ``--spec-type ngram-mod`` even on binaries that did not advertise ngram-mod support, causing llama-server to refuse to start. The auto path already checked ``supports_ngram_mod`` before emitting; the forced path now mirrors that check and loads without spec (with a warning that matches the MTP-token-missing path). Bug E -- ``speculative_type="none"`` is llama.cpp's own explicit-disable spelling, and external API callers commonly use ``"disable"`` / ``"disabled"``. None of these were in the canonical spec mode set or the legacy alias map, so they fell through to ``"auto"`` and silently re-enabled MTP -- the opposite of the user's intent. Added all three to ``_LEGACY_SPEC_MODE_MAP`` as aliases for ``"off"``. Tests ----- - test_canonicalize_spec_mode_none_aliases_map_to_off (6 cases via parametrize): "none"/"None"/"NONE"/" none "/"disable"/"Disabled" all canonicalise to "off". - test_build_ngram_mod_flags_legacy_chained_omits_draft_max + test_build_ngram_mod_flags_legacy_standalone_keeps_draft_max + test_build_ngram_mod_flags_new_flavor_always_emits_distinct_names: the chain_with_mtp kwarg suppresses only the legacy flavor's --draft-max, never the new-flavor knobs. - test_build_speculative_flags_chained_mtp_ngram_legacy_no_duplicate_draft_max: end-to-end check that the assembled spec block has exactly one --draft-max carrying the MTP draft length. - test_build_speculative_flags_forced_ngram_without_support_skips_spec + test_build_speculative_flags_forced_ngram_with_support_emits_spec: forced ngram refuses on a binary lacking ngram-mod support; still emits cleanly on a supporting binary. - test_already_in_target_state_{clear,set}_explicit_n_max_*_forces_reload: backend-side guard covers both clear-to-default and set-from-default. - test_route_guard_auto_promoted_mtp_{bounces,matches,clear_*}: route guard now compares against resolved spec mode and handles the None flip symmetrically. - test_route_guard_ignores_n_max_when_resolved_spec_is_not_mtp: non-MTP resolved spec (e.g. ngram-mod) still ignores n_max. 147/147 spec/reload test suites green.
The unit-level tests in this file stub httpx so they don't pay the real-import cost. But the route-guard tests added in this PR import routes.inference -> huggingface_hub -> from httpx import Response, and the stub had no Response, so on any environment where real httpx IS installed (CI, staging) my test file was overriding it with the incomplete stub and breaking the import chain. Switch to a try: import httpx pattern: when real httpx is on the path use it; only fall back to the stub when httpx is genuinely missing. Also add Response/Request to the fallback stub as a defensive measure for future imports that might reach for them. Local: 139/139 pass.
28e70bb to
a54396a
Compare
Codex flagged that the legacy chained mtp+ngram path emits --draft-min 48 while --draft-max is suppressed and later reused for MTP (spec_draft_n_max, typically 2/3). That produces an inverted legacy ngram range (--draft-min 48 --draft-max 2/3) on affected binaries, which can break or effectively disable ngram-mod for auto CPU MTP loads and forced mtp+ngram requests. Both --draft-min and --draft-max are generic flags on legacy llama-server builds, so either one would race with MTP's own values. Gate the pair together: when chain_with_mtp=True on the legacy flavor we drop both flags and rely on MTP's emission for the chained range. Standalone ngram still emits both, preserving a valid min<=max window. Updated test_build_ngram_mod_flags_legacy_chained_omits_draft_max (now omits_draft_min_and_max) and added a min<=max guard on the standalone case. Full suite (test_llama_cpp_mtp_detection + test_llama_server_args) passes locally: 229 / 229.
|
Pushed 068e129 addressing the codex P1 on the legacy chained mtp+ngram path. Root cause: previously only Fix: gate Updated |
|
Confirmed against current main that _LEGACY_SPEC_MODE_MAP in studio/backend/core/inference/llama_cpp.py still has no entry for none, so a disable request canonicalises to auto and re-enables MTP, and the legacy ngram path still emits the generic draft flags alongside MTP's. Could you rebase this since it now conflicts, and I will get it reviewed. |
Codex Review SummaryThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 2e70eb0c91
ℹ️ 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".
|
|
||
| def _emit_ngram_mod() -> bool: | ||
| """Append --spec-type ngram-mod + flag-set knobs.""" | ||
| if not caps.get("supports_ngram_mod"): |
There was a problem hiding this comment.
Detect ngram support from the spec-type enum
When a custom or transitional llama-server advertises ngram-mod in its --spec-type enum but does not expose all three recognized tuning flags, this guard incorrectly rejects the user's forced ngram mode. probe_server_capabilities() currently derives supports_ngram_mod solely from ngram_mod_flavor, which is set only when the complete new or legacy tuning-flag trio is present, even though the already-parsed --spec-type help block is the authoritative evidence that the mode itself is accepted. Track enum support separately from knob availability so _emit_ngram_mod() can still emit --spec-type ngram-mod without optional knobs in this case.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Not taking this one. supports_ngram_mod = ngram_mod_flavor is not None predates this PR and is the same signal the auto paths already gate on (llama_cpp.py:24392, 24482, 24521, 24548); the new check in _emit_ngram_mod only makes the forced path agree with them. Splitting enum support from knob availability would let the forced path emit --spec-type ngram-mod on a binary whose ngram-mod knobs are removal stubs, which is the launch abort this PR is fixing. A build that advertises ngram-mod in --spec-type while shipping neither the --spec-ngram-mod-* trio nor the legacy --spec-ngram-size-n/--draft-min/--draft-max trio is hypothetical, and trading a real abort for it is the wrong direction.
|
Codex Review: Didn't find any major issues. Keep it up! Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
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". |
|
@codex review |
1 similar comment
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: c30852b682
ℹ️ 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".
| flags = ["--spec-ngram-size-n", str(n_match)] | ||
| if not chain_with_mtp: | ||
| flags.extend(["--draft-min", str(n_min), "--draft-max", str(n_max)]) |
There was a problem hiding this comment.
Override the legacy draft minimum when chaining
When a legacy installation has LLAMA_ARG_DRAFT_MIN set above the requested MTP depth—for example the legacy ngram tuning value 48 with spec_draft_n_max=2—omitting this flag leaves that environment value active while the emitted --draft-max 2 overrides only the maximum. The legacy help contract in test_llama_cpp_mtp_detection.py identifies LLAMA_ARG_DRAFT_MIN as the environment twin of the minimum draft-token count, and the launch scrub does not remove it, so the child receives an impossible minimum-greater-than-maximum range and the chained decoder cannot operate correctly. Override the minimum with a value compatible with MTP, or scrub the legacy minimum environment variable for this chained path.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Not taking this one, for three reasons.
There is no launch scrub to extend. LLAMA_ARG_DRAFT_MIN appears nowhere in the backend outside a fake help block in a test fixture; the only env read is LLAMA_ARG_DRAFT_MAX / LLAMA_ARG_SPEC_DRAFT_N_MAX at llama_cpp.py:18654, and it prices the VRAM rollback reserve rather than scrubbing anything. Unsloth scrubs no LLAMA_ARG_*, so an operator who exports one is overriding us the same way LLAMA_ARG_CTX_SIZE or LLAMA_ARG_BATCH would.
Without that variable there is no inverted range. --spec-draft-n-min defaults to 0 (checked against the installed llama-server's help), and the legacy --draft-min is the same knob, so omitting it leaves 0 against --draft-max 2.
With the variable set, this is not a regression. The pre-PR chained legacy path emitted --draft-min 48 --draft-max 64 and then MTP appended --draft-max 2, so last-wins produced min 48 against max 2 from our own flags, which is the inversion the earlier P1 on this PR was about. After the change that instance is gone and only the operator-set one remains.
Also worth noting the blast radius: I probed the installed llama-server and it reports the post-rename flavor, so chain_with_mtp is a no-op there and this path is reachable only on a pre-rename binary.
|
Codex Review: Didn't find any major issues. Another round soon, please! Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
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". |
…ered depth as unknown
|
Codex Review: Didn't find any major issues. Can't wait for the next one! Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
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". |
|
Codex Review: Didn't find any major issues. Keep it up! Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
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". |
|
Verified current llama.cpp command generation across 14,400 configurations and all seven modes. In the app, Draft Tokens 8 emitted I considered trimming the old-build support, but main already carries those paths and this only corrects them; removing the fixes would leave the existing legacy handling in place and broken. A future llama.cpp tuning-flag rename could disable forced ngram; Auto and drafter modes would be unaffected. CI has two failures already present on main; all other checks pass. |
Summary
Followup to #5582. Issues that surfaced after that PR landed, all with matching test coverage.
spec_draft_n_maxcomparison when the request value wasNone, treating it as a wildcard. A backend loaded with an explicit override of 8 could never be cleared back to the platform default without a model swap._runtime_matches_intentnow treats the(None vs explicit)flip as a difference, in both directions, and only where the resolved mode consumes a draft depth (draft_depth_matters).--draft-maxtwice (MTP draft length, then ngram-mod size-N max). Last-wins clobbered MTP's value with 64._build_ngram_mod_flagsnow takes achain_with_mtpkwarg that suppresses the legacy--draft-min/--draft-maxpair; the post-rename flavor uses distinct--spec-ngram-mod-*names and is unaffected. The pair is gated together, so the chained path never emits a--draft-min 48against MTP's--draft-max 2.speculative_type="ngram"emitted--spec-type ngram-modeven on binaries that did not advertise ngram-mod support, causing llama-server to refuse to start. The auto path already checkedsupports_ngram_modbefore emitting; the forced path now mirrors that check. That turns a failed launch into a resident process running without speculation, so the stand-down recordsbinary_outdatedand_runtime_matches_intentacceptsngramin its binary-retry arm: otherwiseunsloth studio updatecould never reach the resident process, because the request it would re-send is identical to the one that stood down.binary_outdatedrather thanbinary_no_mtpbecause that reason's retry rule asks_SPEC_KIND_CAPABILITYabout_spec_drafter_kind, which ngram-mod never sets.speculative_type="none"(the spelling llama.cpp itself uses for disable, plus"disable"/"disabled") fell through the canonicaliser to"auto"and silently re-enabled MTP. Added all three to_LEGACY_SPEC_MODE_MAPas aliases for"off".Two frontend halves, because
resident-config-match.tsmirrors the fields_runtime_matches_intentreloads for and the store'snormalizeSpeculativeTypemirrors_canonicalize_spec_mode. Changing only the backend leaves each mirror stale:specDraftNMaxcheck was pinned only when the pick named a count, so the model-picker adoption path returned without calling/loadand the backend fix was unreachable from the UI. It is now unconditionally pinned and compares(config ?? null) === (status ?? null). Nodraft_depth_mattersgate is needed on this side: the backend records_spec_draft_n_maxonly where a depth-consuming emitter runs, so a status carrying a count already implies the backend arm applies.residentSpeculativeNeedsRepairgated every retry onSPECULATIVE_MODES, which excludesngrambecause ngram-mod runs no drafter. The binary stand-down is admitted forngramon its own rather than by widening that set, so a forced ngram-mod repairs onbinary_outdatedand still does not ondrafter_not_foundorbinary_no_mtp.canonicalizeSpeculativeType(per-model-config.ts) is the one a stored override actually reaches, sincemodel-overrides.ts:328feedsoverride.speculative_typeintonormalizePerModelConfigand/settingspersists the field without canonicalising it. It recognised onlyoff, so the aliases fell to itsreturn null, and null there means "follow the global preference" rather than off: a persisted explicit disable became Auto and could hand the load a drafter.normalizeSpeculativeType(chat-runtime-store.ts) mirrors_canonicalize_spec_modefor the status and preset paths and is updated to match. Both now read the four spellings asoff.normalize_model_overridevalidatesspeculative_typeagainstVALID_SPECULATIVE_TYPES, which omitted the three aliases, so_clean_strdropped the field and a saved disable became no override at all. Added them there, the way that set already carriesdraft-mtp,ngram-modanddefault: aliases are stored as written and each consumer canonicalizes on read. The three layers are complementary, not redundant, since the whitelist lets the value be stored,canonicalizeSpeculativeTypereads it as off rather than as the follow-global null, and_canonicalize_spec_moderesolves it at load._spec_draft_n_maxwhile_runtime_matches_intentkeeps comparing against the count retained in_last_load_intent, so the status reports null for a load the backend still measures against an explicit depth. The comparator now treats aruntime_errorresident's depth as unknown and declines the shortcut instead of reading that null as the platform default. Taken on the UI side rather than by publishing the retained count, which would report a depth as active while speculation is off.binary_outdated, butshowSpecFallbackgated its notice on the drafter modes only, so a forced ngram stand-down showed ngram still selected with no explanation and no update button. The gate now admitsngram, andspeculativeDrafterLabelis resolved from the requested mode beforespecDrafterKind, which ngram-mod never sets, so the notice does not call a drafterless mode MTP.The route-level guard this PR originally also touched (
routes/inference.py:_request_matches_loaded_settings, the Bug A fix) no longer exists on main. Its job moved intoadopt_load_intent_if_matched, which is the backend guard changed here, so the resolved-vs-requested mode confusion it fixed is gone with it.Test plan
python -m pytestover the MTP detection, placement, reload-inheritance and native-companion suites -- 579 passed.npm test(frontend) -- 6419 passed._build_speculative_flagsover 7200 combinations of mode, slider value, ngram flavor, binary capabilities, model kind and GPU presence:_spec_draft_n_maxis recorded only alongside a depth-consumingspeculative_type, which is the invariant the UI-side comparator relies on. 0 counterexamples.chain_with_mtpis a no-op there and Bug C's change only reaches pre-rename binaries. That binary also rejects--draft-maxand--spec-ngram-size-noutright ("the argument has been removed"), which is the launch abort Bugs C and D avoid, and acceptsnonein its--spec-typeenum, which is Bug E's premise.(resident explicit, pick blank)going from adopt to reload. Every other combination, and every non-GGUF resident, is untouched.nextn_predict_layers=1, 17.9 GB): every argv shape this code emits starts llama-server and serves.--spec-type draft-mtp --spec-draft-n-max 2reportsdraft acceptance = 0.73016 (46 accepted / 63 generated), mean len 2.44, so MTP engages at the emitted depth; forced ngram-mod runs its drafter;noneandoffboth load with no speculation at all.spec_binary_fallback_can_retry()is false while the binary is unchanged and true once it is replaced, so the new repair is one reload rather than a loop.No new behaviour for users on default builds (post-rename flavor, no explicit slider use, no forced spec mode). Only the buggy edge cases change.