Skip to content

Studio: stop MTP forcing llama-server to a single parallel slot - #8172

Merged
danielhanchen merged 11 commits into
mainfrom
studio-mtp-parallel-slots
Aug 9, 2026
Merged

danielhanchen merged 11 commits into
mainfrom
studio-mtp-parallel-slots

Conversation

@danielhanchen

Copy link
Copy Markdown
Member

A user reported on Discord that their Studio API throughput halved on Tuesday 4 August: worksheet classification that took about a minute for 12 documents started taking 4+ minutes for 24. Their reading was that MTP had stopped engaging. It was the opposite. Throughput dropped because MTP was on.

Two of our own commits five days apart produced the swing.

Date PR Change
2026-07-28 #7455 plain unsloth studio default slots raised 1 to 4 (_PARALLEL_DEFAULT_PLAIN)
2026-07-31 #7473 saved per-model settings start applying to API loads (v0.1.511-beta, 2 Aug)
2026-08-03 #7717 --parallel clamped back to 1 whenever MTP resolves (v0.1.512-beta, 3 Aug)

So an API caller on an MTP GGUF gained four slots on 28 July and lost them on 3 August. The only signal was a logger.warning; the launched command line was the sole place it showed.

Why the clamp went in

#7717 was right about the mechanism. llama.cpp reads the nextn hidden states by raw token index while split_equal reorders the ubatch at unequal per-slot token counts, so slots read each other's rows, draft acceptance collapses, and MTP was measured slower than no speculation at all. The model cards ship -np 1.

What it got wrong was the remedy. Given "MTP and more than one slot are incompatible" it kept MTP and dropped concurrency, which is right for one interactive chat and badly wrong for a batched API client.

Why it comes out

Measured on llama.cpp b10310, unsloth/Qwen3.5-9B-MTP-GGUF Q4_K_M, one B200, 8 concurrent requests at 256 tokens each:

arm single-stream batch aggregate batch wall
1 slot, MTP (the clamp) 210.1 tok/s 226.1 tok/s 9.1 s
4 slots, MTP (this PR) 207.0 tok/s 445.6 tok/s 4.6 s
4 slots, no speculation 174.8 tok/s 345.3 tok/s 5.9 s
1 slot, no speculation 175.6 tok/s 191.0 tok/s 10.7 s

Batch throughput is 1.97x, and single-stream is unchanged at 0.98x, so nothing is taken from the interactive case the clamp was protecting. Four slots with MTP also still beats four slots without it, by 1.29x, so on a current build the premise that MTP above one slot loses to no speculation no longer holds. The clamp was paying a 2x concurrency cost to avoid a regression that is not there.

Output equivalence, greedy decoding, same 4 prompts:

comparison byte-identical
1 slot vs 4 slots, MTP on 2/4
1 slot vs 4 slots, MTP off 1/4
1 slot vs 1 slot rerun, MTP off 4/4

The divergence is ordinary batching non-determinism, since ubatch composition changes the reduction order. It is at least as bad with speculation off, so it is not attributable to MTP, which matches #7717's own point that committed text stays correct because acceptance is gated on target logits.

This is also the first time an MTP load reaches _ctx_integrity_flags at more than one slot and so emits --kv-unified. That combination is what every 4-slot arm above ran.

Changes

Both clamp sites go, along with the two restore paths that existed only to undo them and the _repatch_parallel_slots helper they were the only callers of:

  • the extras/env clamp beside the --kv-unified clamp
  • the resolved-MTP backstop after _build_speculative_flags
  • the paravirtual drafter-drop restore, and the fallback_cmd re-clamp in the startup retry

Two downgrades survive because both are real limits rather than policy: the --kv-unified capability fallback, and diffusion, which never receives --parallel at all. The VRAM-driven reduction in _slots_that_fit_on_gpu is untouched. The training-coexistence guard already sized MTP at the unclamped count, so it and the launch now agree and its comment says so.

Guard

scripts/lint_no_parallel_clamp.py is a stdlib-ast lint over studio/backend that fails CI on a slot count rebound to a literal 1 inside a function body, or on the restore shape a clamp uses to hand slots back to itself across a retry. A real limit opts out with a trailing # allow-slot-clamp: <reason>.

Parameter defaults, class-body annotations, self.<attr> assignments and max(1, ...) / getattr(..., 1) floors are structurally distinct and pass without a marker, so the false-positive surface is zero across the tree today. Run against main the rule flags all seven pre-existing sites, including both clamps and both restores.

It runs in the source-lint job of lint-ci.yml, self-test first, alongside the existing debugger scan. That workflow has no path filter, so it fires on every PR.

Testing

  • studio/backend/tests/test_parallel_slots_never_clamped.py, new: drives the real load path through the Popen capture harness and reads --parallel off the launched argv, over requested slots 1/2/4/8 x speculative auto/mtp/mtp+ngram/ngram/off, plus extras-owned --spec-type draft-mtp and an inherited LLAMA_ARG_SPEC_TYPE. 17 of its 29 cases fail against the unpatched loader.
  • tests/test_lint_no_parallel_clamp.py, new: positive, allowlisted and one case per structural false-positive class.
  • Removed the 15 tests and helpers in test_metal_paravirtual_guard.py and test_batch_sizes_per_load.py that existed to pin the clamp and its restores, and corrected the stale comments left behind in test_parallel_slots_per_load.py.
  • Studio backend suite: 77 failed, 18675 passed on this branch against 77 failed, 18659 passed on main, same failing-file set. Those failures are the usual missing optional deps for the rag, video, mcp, auth and stt suites in this environment and are untouched by this change. The llama.cpp, MTP, speculative, placement, batch-size and parallel-slot suites are 726 passed.
  • compileall and ruff check clean on unsloth unsloth_cli studio tests cli.py unsloth-cli.py.

danielhanchen and others added 2 commits August 8, 2026 12:12
#7717 clamped --parallel to 1 whenever MTP resolved, six days after #7455
raised the default slot count from 1 to 4. Anyone serving an MTP GGUF went
from four concurrent slots to one, with a logger.warning as the only signal.

Measured on b10310 with Qwen3.5-9B-MTP-GGUF Q4_K_M, 8 concurrent requests:
four slots with MTP is 1.97x the batch throughput of one and 1.29x four slots
without MTP, so the acceptance collapse the clamp was avoiding no longer
outweighs the concurrency it cost.

Removes both clamp sites and the two restore paths that existed only to undo
them. The --kv-unified and diffusion downgrades stay: those are real limits,
and they now carry an allow-slot-clamp marker. A new stdlib-ast lint plus a
launch-argv test matrix keep a silent downgrade from coming back.

@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: 5d219e4e6a

ℹ️ 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 +9399 to +9401
# MTP does not clamp the slots. #7717 did, for a draft-acceptance
# collapse above one slot, but on b10310 four slots with MTP measured
# 1.97x the batch throughput of one, and still beat four without it.

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 Gate multi-slot MTP on a confirmed compatible build

When Studio selects an older or custom MTP-capable binary through LLAMA_SERVER_PATH, UNSLOTH_LLAMA_CPP_PATH, or PATH, this now enables multiple slots unconditionally. The evidence cited here covers only b10310, while the removed guard documents that affected builds mix per-slot MTP hidden states and collapse draft acceptance; probe_server_capabilities() only detects MTP and --kv-unified support, not whether that defect is fixed. Preserve the requested concurrency by disabling MTP on unconfirmed builds, or gate this behavior on a build known to support multi-slot MTP.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

The mechanism is real in llama.cpp master (llm_arch_is_hybrid covers QWEN35/QWEN35MOE, those memories split_equal unconditionally, and MTP reads the target nextn rows by raw token index), and ggml-org/llama.cpp#26031 is open. But it did not reproduce here in four attempts with a unique-identifier leak detector: dense qwen35 at 16 concurrent; the same with unequal prefill lengths and staggered arrival so per-slot token counts differ, which is the condition split_equal needs; and the exact reported model, Qwen3.6-35B-A3B Q8_0 with mmproj at the reporter's sampling, 24 concurrent. Every arm returned its own identifier, leaked no foreign identifier and produced no garbling, and the MTP and no-speculation arms gave identical anomaly sets. The remedy as written is also unsatisfiable: there is no upstream fix, so there is no build number to gate on, and probe_server_capabilities parses --help only. Recorded #26031 in a comment at 905fb5b so the open report is discoverable from the code. Reconsider if it is confirmed upstream or reproduces on a supported configuration.

danielhanchen added a commit to shimmyshimmer/unsloth-staging-4 that referenced this pull request Aug 8, 2026
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

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

ℹ️ 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 +6117 to 6119
# Size with the count that will actually launch, or a load that fits gets a 409.
# An unclassified GGUF keeps the ask.
if is_gguf and 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 Account for per-slot MTP memory in the training guard

When an MLA-based MTP model is loaded with multiple slots while training is running, _estimate_gguf_required_gb() still charges only the main KV cache and drafter file; the loader additionally reserves a duplicated target context per slot, draft KV, and draft compute. The old single-slot launch left the guard's extra main-KV slots as compensating headroom, but now all estimated slots are real, so the actual MTP footprint can be roughly twice the guarded KV footprint and the guard may admit a chat load that consumes memory reserved for training. Add the same MTP overhead calculation used by load_model() before treating n_parallel as the complete launched footprint.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

The compensation this describes does not exist, so removing the clamp does not remove it. Under --kv-unified the guard's KV term is slot-independent for the same reason as above; the only slot-dependent part of the estimate is the compute buffer's out_buffer * (slots - 1), about 1 GB between 1 and 4 slots. For a non-MLA MTP model the unmodelled reserve is ~0.7 GB, smaller than that accidental slack and far inside required * 1.15 + 4.0. For an MLA MTP model the guard has always under-modelled by roughly 10 GB, so the deleted comment's claim that spare slots stood in for it was wrong by an order of magnitude when it was written; this PR moves a pre-existing gap by about 9 percent and changes no code in the guard. The loader also re-checks live free VRAM after the guard and shrinks context or falls back to --fit rather than over-committing.

Comment on lines +9399 to +9400
# MTP does not clamp the slots. #7717 did, for a draft-acceptance collapse, but on
# b10310 four MTP slots hit 1.97x the batch throughput of one, beating four without.

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 Recompute the MTP reserve for each slot-fit candidate

For a multi-slot MTP load that does not fully fit on the selected GPUs, the newly reachable _slots_that_fit_on_gpu() path evaluates smaller slot counts, but _base_footprint includes _mtp_bytes(effective_ctx) from a closure whose _np and micro-batch were bound to the original requested count. Every candidate therefore retains the original-slot draft KV and, for MLA, duplicated target KV, so a smaller count that really fits can be rejected; the helper then leaves --fit enabled at the original count and may offload layers to CPU, causing the decode slowdown this slot-reduction path is intended to avoid. Make the candidate calculation resize the MTP reserve alongside the main KV and compute buffers.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

The MTP reserve does not vary with the slot count, so it cancels out of the candidate comparison. Studio emits --kv-unified whenever n_parallel > 1, and under kv_unified _kv_cache_cell_layout returns streams=1 and cells_per_stream=pad(n_ctx) regardless of slots. Both terms named here ride on that layout: _mtp_draft_kv_bytes uses it directly, and the MLA target_ctx_copy is _estimate_kv_cache_bytes(..., n_parallel=n_parallel). Evaluated numerically against the code at head, the reserve is byte-identical at 1, 2, 4 and 8 slots, so a 4 to 2 candidate is over-charged by 0. Reachability is also weaker than stated: only the extras-owned route was gated before, since the auto/mtp backstop ran after the fit, so that path already ran with an MTP _base_footprint.

`n_parallel: int = 1` in a function body is an ast.AnnAssign, which the lint
never visited, so the exact regression it exists to block could be reintroduced
past a green gate. Handle both nodes, with self-test and pytest cases for the
annotated form, its allow-slot-clamp opt-out, and a non-literal annotated
assignment.
It reports concurrent MTP garbling on hybrid architectures. It did not
reproduce on qwen35 or qwen35moe here, so the slots stay, but a reader
weighing this code should find the open report from it.
chatgpt-codex-connector[bot]

This comment was marked as resolved.

danielhanchen and others added 2 commits August 8, 2026 13:59
The reserve is not slot-independent after all: compact SWA scales its window
allowance by the slot count under kv_unified, and an MLA target with recurrent
KDA layers charges per slot. _base_footprint carried it at the originally
requested count, so every reduced candidate was over-charged and one that really
fits could be rejected, leaving the load on --fit with layers offloaded to host.

_slots_that_fit_on_gpu now takes mtp_bytes_for_slots and re-prices the reserve
alongside the KV and compute buffer; the base footprint drops it. Passing None
keeps the non-MTP path byte-identical.

Also catch a clamp spelled as an expression: min(n_parallel, 1) and a
conditional with a literal 1 branch both pinned the count past a green gate.
A real bound like min(n, cap) and a conditional between two live counts stay
clean.
chatgpt-codex-connector[bot]

This comment was marked as resolved.

…t gaps

The slot re-pricing added last commit only overrode the slot count. A reduced
candidate also lowers the batch floor, so its micro-batch shrinks, and compact
SWA adds one micro-batch to its window allowance. The reserve kept the ubatch
captured for the original request, so it was still over-priced. The callback
now takes (slots, ubatch) and the fit passes the candidate pair.

The lint missed two shapes it should have caught from the start. Tuple targets
were only tested at the outer ast.Tuple, so `gpu_indices, use_fit, n_parallel =
gi, False, 1` -- the very style load_model uses for the VRAM fit -- passed a
green gate. Targets are flattened and paired positionally with a tuple value
now; an unpairable right-hand side says nothing and is still skipped. And the
route resolves the request into `_n_parallel` before the load paths see it, so
that alias counts as a slot variable too.
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

danielhanchen added a commit to shimmyshimmer/unsloth-staging-4 that referenced this pull request Aug 8, 2026
danielhanchen added a commit to shimmyshimmer/unsloth-staging-4 that referenced this pull request Aug 8, 2026
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

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

ℹ️ 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".

from pathlib import Path

REPO_ROOT = Path(__file__).resolve().parents[1]
DEFAULT_SCAN_DIR = REPO_ROOT / "studio" / "backend"

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 Scan the CLI slot handoff as well

A downgrade in the primary CLI still bypasses this gate because the scan stops at studio/backend. Both the plain unsloth studio flow and unsloth studio run hold the requested count in the local parallel variable in unsloth_cli/commands/studio.py and pass it to run_server(llama_parallel_slots=parallel), so inserting parallel = 1 before either handoff silently serializes those users while CI remains green; scan these focused CLI entry points and cover their slot alias with a self-test.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Declining this one, on where the rule's line sits rather than on the facts, which are right. The lint guards a per-load downgrade: a load that asked for N slots being launched with fewer. The CLI parallel variable is the other thing, the server-wide default a user chooses at startup, and the module docstring and a self-test already assert that configuration is out of scope (module-scope n_parallel = 1 is deliberately not flagged). Changing that default is visible in --help and in the CLI's own tests rather than silent at load time, which is the failure mode #7717 had. Extending the scan into unsloth_cli to track a name as generic as parallel also widens the false-positive surface for a path the original defect never took. llama_parallel_slots is in, per the sibling item, because the resolver hands it straight back as a per-load count.

- _compute_buffer_pipeline
+ _mtp_bytes(effective_ctx)
+ _cc_bytes(effective_ctx)
model_size_fit - _compute_buffer_pipeline + _cc_bytes(effective_ctx)

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 Reprice context compute for each slot-fit candidate

For an extras-owned MTP load with an explicitly small n_batch, this change newly allows the multi-slot fit path to run, but _base_footprint evaluates _cc_bytes(effective_ctx) with the original request's _effective_ubatch. Although _slots_that_fit_on_gpu() derives a smaller micro-batch for each reduced-slot candidate, that candidate value reaches only the flat compute, KV, and MTP terms; the context-linear compute term and its split-device reserve remain priced at the larger batch. At high context or with quantized KV this can make every smaller candidate appear too large, leaving --fit enabled and unnecessarily offloading layers to CPU, so pass the candidate micro-batch through the context-compute calculation too.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

The mechanism is real: _compute_buffer_ctx_bytes takes n_ubatch, the _cc_bytes closure passes the request's _effective_ubatch, and the fit does not re-price it per candidate. Two things make it a different call from the two re-pricing items I did take. It is not something this PR froze: _cc_bytes(effective_ctx) already sat in _base_footprint at the merge-base and this change did not touch it, unlike the MTP reserve, which I moved and then had to finish moving. And the direction is safe: it over-reserves, so the worst case is a --fit fallback, whereas re-pricing it correctly requires threading the candidate micro-batch through the base footprint, the per-device overhead and the split reserve all at once, and any term I get wrong there tightens a VRAM estimate that exists to stop a decode-time OOM. Trading a possible OOM for a possible offload is the wrong way round on a fit function this heavily relied upon. Worth its own change with its own testing rather than a fourth re-pricing on this one; happy to file it.

A request that names no count resolves to llama_parallel_slots, so a clamp on
that name reduces the same user-facing slots the rule exists to protect. The
existing bindings are keyword arguments rather than assignments, so the tree
stays clean; self-test and pytest cover both the clamp and the handoff.
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 8, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 8, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 8, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 8, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 8, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 8, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 8, 2026
@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. What shall we delve into next?

Reviewed commit: a4379286d7

ℹ️ 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".

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. 🎉

Reviewed commit: cd3e622409

ℹ️ 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".

@oobabooga

Copy link
Copy Markdown
Member

Tested at cd3e622:

  • Loaded unsloth/gemma-4-E4B-it-GGUF:UD-Q4_K_XL on CUDA with MTP and --parallel 4.
  • Ran a Playwright smoke test with 4 separate Flappy Bird chats for HTML, JavaScript, Rust, and Python. All 4 generated concurrently and completed cleanly.
  • Repeated the same test manually in Studio and visibly confirmed all 4 chats were generating at the same time.
  • Confirmed in the server log that llama.cpp used slots 0 through 3 concurrently. All 4 requests returned 200 with coherent output and no cross-chat mixing or garbling.
  • Confirmed the pre-fix base used --parallel 1 for the same load and serialized the requests.
  • All 101 focused regression tests pass.

This confirms the original Gemma 4 parallel-chat regression is fixed. I do not see any blocker.

@danielhanchen
danielhanchen merged commit dc49ff6 into main Aug 9, 2026
8 of 55 checks passed
@danielhanchen
danielhanchen deleted the studio-mtp-parallel-slots branch August 9, 2026 04:10
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