Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.
Python agentaichatgptdeepseekfine-tuninggemmaimage-generationllamallmllmsopenaipythonqwenreinforcement-learningself-hostedstable-diffusiontext-to-speechttsuiunsloth
Studio: stop MTP forcing llama-server to a single parallel slot (#8172)
Daniel Handc49ff6b56d4
diff --git a/.github/workflows/lint-ci.yml b/.github/workflows/lint-ci.ymlindex 1696cad8fa1..32e1a5d8443 100644--- a/.github/workflows/lint-ci.yml+++ b/.github/workflows/lint-ci.yml@@ -158,6 +158,15 @@ jobs:python scripts/verify_import_hoist.py \--before "$MERGE_BASE" --after "$HEAD_SHA" "${CHANGED[@]}"+ - name: No silent llama-server parallel-slot downgrades+ # #7717 clamped --parallel to 1 whenever MTP resolved, costing batched+ # callers 4x throughput. Launch fewer slots only for a real capability+ # or VRAM limit, marked '# allow-slot-clamp: <reason>'. Self-test first,+ # so a regression in the rule fails before we trust it on the tree.+ run: |+ python scripts/lint_no_parallel_clamp.py --self-test+ python scripts/lint_no_parallel_clamp.py+- name: No leftover debugger / pdb / breakpoint calls# Catches the "I'll just stick a breakpoint() here" mistake# before it ships. AST-based so commented-out debuggerdiff --git a/scripts/lint_no_parallel_clamp.py b/scripts/lint_no_parallel_clamp.pynew file mode 100644index 00000000000..f64f60e3653--- /dev/null+++ b/scripts/lint_no_parallel_clamp.py@@ -0,0 +1,228 @@+#!/usr/bin/env python3+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.++"""Refuse silent llama-server parallel-slot downgrades.++#7717 clamped `--parallel` to 1 whenever MTP resolved, so a batched API caller+lost 4x throughput with nothing but a log line to show for it. The slot count is+a user-facing setting: a load may launch fewer slots only when a real resource+or capability limit forces it, and never as a policy choice.++Flagged inside `studio/backend` (tests excluded):++1. `n_parallel = 1` in a function body, annotated or not -- a downgrade, not a+ default.+2. `n_parallel = <name>` where the name is a saved pre-clamp count, which is+ how a clamp hands slots back to itself across a retry.+3. the same clamp spelled as an expression -- `min(n_parallel, 1)`, or a+ conditional with a literal 1 branch.++Tuple unpacking is flattened, and the aliases the same count travels under -- the+route's `_n_parallel` and the server-wide `llama_parallel_slots` -- count too.++Parameter defaults, class-body annotations, `self.<attr>` assignments and+`max(1, ...)` / `getattr(..., 1)` floors are structurally distinct and pass.++A genuine capability or resource limit is allowed with a trailing+`# allow-slot-clamp: <reason>` comment on the assignment line.++Exit codes: 0 = clean, 1 = findings, 2 = usage error.+Run from repo root: python3 scripts/lint_no_parallel_clamp.py+"""++from __future__ import annotations++import argparse+import ast+import sys+from pathlib import Path++REPO_ROOT = Path(__file__).resolve().parents[1]+DEFAULT_SCAN_DIR = REPO_ROOT / "studio" / "backend"++# Aliases the same count travels under: the route resolves a request into `_n_parallel`,+# and a request that names no count resolves to `llama_parallel_slots`, so a clamp on+# either reduces the user's slots under a different name.+SLOT_NAMES = frozenset({"n_parallel", "_n_parallel", "llama_parallel_slots"})+ALLOW_MARKER = "# allow-slot-clamp:"+SKIP_PARTS = frozenset({"tests", ".venv", "venv", "build", "dist", "node_modules", "__pycache__"})+++def _is_slot_target(node: ast.AST) -> bool:+ """A bare `n_parallel`, not `self._n_parallel` or `d["n_parallel"]`."""+ return isinstance(node, ast.Name) and node.id in SLOT_NAMES+++def _restores_a_saved_count(value: ast.AST) -> bool:+ """`n_parallel = _mtp_clamped_slots`: only a clamp saves a pre-clamp count."""+ return isinstance(value, ast.Name) and value.id.endswith("_clamped_slots")+++def _is_one(node: ast.AST) -> bool:+ return isinstance(node, ast.Constant) and node.value == 1+++def _forces_one(value: ast.AST) -> bool:+ """A clamp spelled as an expression rather than a literal: `min(n_parallel, 1)`+ or `1 if mtp else n_parallel`. Both pin the count to 1 on some path."""+ if isinstance(value, ast.IfExp):+ return _is_one(value.body) or _is_one(value.orelse)+ return (+ isinstance(value, ast.Call)+ and isinstance(value.func, ast.Name)+ and value.func.id == "min"+ and any(_is_one(a) for a in value.args)+ )+++def _target_value_pairs(node: ast.AST) -> list[tuple[ast.AST, ast.AST]]:+ """(target, value) per assignment, flattening the two spellings a clamp can hide in:+ AnnAssign, and tuple unpacking, which load_model already uses for the VRAM fit.+ An unpairable right-hand side says nothing about the value, so it is skipped."""+ if isinstance(node, ast.AnnAssign):+ return [(node.target, node.value)] if node.value is not None else []+ if not isinstance(node, ast.Assign):+ return []+ pairs: list[tuple[ast.AST, ast.AST]] = []+ for target in node.targets:+ if isinstance(target, (ast.Tuple, ast.List)):+ if isinstance(node.value, (ast.Tuple, ast.List)) and len(target.elts) == len(+ node.value.elts+ ):+ pairs.extend(zip(target.elts, node.value.elts))+ else:+ pairs.append((target, node.value))+ return pairs+++def _findings_for_tree(+ tree: ast.AST, lines: list[str], filename: str+) -> list[tuple[str, int, str]]:+ found: list[tuple[str, int, str]] = []+ for func in ast.walk(tree):+ if not isinstance(func, (ast.FunctionDef, ast.AsyncFunctionDef)):+ continue+ for node in ast.walk(func):+ for target, value in _target_value_pairs(node):+ if not _is_slot_target(target):+ continue+ if isinstance(value, ast.Constant) and value.value == 1:+ what = "clamped to a single slot"+ elif _restores_a_saved_count(value):+ what = f"restores the pre-clamp count `{value.id}`"+ elif _forces_one(value):+ what = "pinned to a single slot by an expression"+ else:+ continue+ if ALLOW_MARKER in lines[node.lineno - 1]:+ continue+ found.append((filename, node.lineno, what))+ return found+++def scan_source(source: str, filename: str) -> list[tuple[str, int, str]]:+ """(file, line, reason) per finding. Unparseable files are left to compileall."""+ try:+ tree = ast.parse(source, filename = filename)+ except SyntaxError:+ return []+ return _findings_for_tree(tree, source.splitlines(), filename)+++def scan_paths(root: Path) -> tuple[list[tuple[str, int, str]], int]:+ found: list[tuple[str, int, str]] = []+ scanned = 0+ for path in sorted(root.rglob("*.py")):+ if SKIP_PARTS & set(path.parts):+ continue+ scanned += 1+ try:+ source = path.read_text(encoding = "utf-8", errors = "replace")+ except OSError:+ continue+ rel = path.relative_to(REPO_ROOT) if path.is_relative_to(REPO_ROOT) else path+ found += scan_source(source, str(rel))+ return found, scanned+++_SELF_TEST_CASES: tuple[tuple[str, int], ...] = (+ # (source, expected finding count)+ ("def load():\n n_parallel = 1\n", 1),+ ("def load():\n n_parallel: int = 1\n", 1),+ ("def load():\n n_parallel: int = 1 # allow-slot-clamp: ok\n", 0),+ ("def load(x):\n n_parallel: int = x\n", 0),+ ("def load():\n n_parallel = 1 # allow-slot-clamp: no --kv-unified\n", 0),+ ("def load():\n n_parallel = _mtp_clamped_slots\n", 1),+ ("def load(n):\n n_parallel = min(n, 1)\n", 1),+ ("def load(n, mtp):\n n_parallel = 1 if mtp else n\n", 1),+ ("def load(n):\n n_parallel = min(n, 1) # allow-slot-clamp: ok\n", 0),+ ("def load(n, cap):\n n_parallel = min(n, cap)\n", 0),+ ("def load(n, hi):\n n_parallel = n if n < hi else hi\n", 0),+ ("def load(gi):\n gpu_indices, use_fit, n_parallel = gi, False, 1\n", 1),+ ("def load(gi):\n gi, uf, n_parallel = gi, False, 1 # allow-slot-clamp: ok\n", 0),+ ("def load(gi, s):\n gpu_indices, use_fit, n_parallel = gi, False, s\n", 0),+ ("def load(f):\n gi, use_fit, n_parallel = f()\n", 0),+ ("def load():\n _n_parallel = 1\n", 1),+ ("def load(r, s):\n _n_parallel = _resolve(r, s)\n", 0),+ ("def serve():\n llama_parallel_slots = 1\n", 1),+ ("def serve(a):\n run(llama_parallel_slots = a.parallel)\n", 0),+ ("def load(n_parallel: int = 1):\n return n_parallel\n", 0),+ ("class A:\n n_parallel: int = 1\n", 0),+ ("def load():\n self._requested_n_parallel = 1\n", 0),+ ("def load(x):\n n_parallel = max(1, x)\n", 0),+ ("def load(s):\n n_parallel = getattr(s, 'llama_parallel_slots', 1)\n", 0),+ ("def load(r):\n n_parallel = r.n_parallel\n", 0),+ ("n_parallel = 1\n", 0), # module scope is configuration, not a launch decision+)+++def _self_test() -> int:+ failures = 0+ for source, expected in _SELF_TEST_CASES:+ got = len(scan_source(source, "<self-test>"))+ if got != expected:+ failures += 1+ print(+ f"self-test: expected {expected} finding(s), got {got} for:\n{source}",+ file = sys.stderr,+ )+ if failures:+ print(f"self-test FAILED ({failures} case(s))", file = sys.stderr)+ return 1+ print(f"self-test passed ({len(_SELF_TEST_CASES)} cases)")+ return 0+++def main() -> int:+ parser = argparse.ArgumentParser(description = __doc__)+ parser.add_argument("--self-test", action = "store_true", help = "check the rule, scan nothing")+ parser.add_argument("--path", type = Path, default = DEFAULT_SCAN_DIR, help = "directory to scan")+ args = parser.parse_args()++ if args.self_test:+ return _self_test()++ if not args.path.is_dir():+ print(f"ERROR: {args.path} is not a directory", file = sys.stderr)+ return 2++ found, scanned = scan_paths(args.path)+ if not scanned:+ print(f"ERROR: no Python files under {args.path}", file = sys.stderr)+ return 2+ if found:+ for filename, lineno, what in found:+ print(+ f"::error file={filename},line={lineno}::parallel slots {what}. The slot count is "+ f"a user setting: launch fewer only for a real capability or VRAM limit, and mark "+ f"it '{ALLOW_MARKER} <reason>'.",+ )+ print(f"{len(found)} silent parallel-slot downgrade(s)", file = sys.stderr)+ return 1+ print(f"no silent parallel-slot downgrades (scanned {scanned} files)")+ return 0+++if __name__ == "__main__":+ sys.exit(main())diff --git a/studio/backend/core/inference/llama_cpp.py b/studio/backend/core/inference/llama_cpp.pyindex 3e62d4edaa0..7623f5734ef 100644--- a/studio/backend/core/inference/llama_cpp.py+++ b/studio/backend/core/inference/llama_cpp.py@@ -2776,25 +2776,6 @@ def _emitted_n_batch(n_batch: Optional[int], n_parallel: int) -> Optional[int]:return max(int(n_batch), max(2, int(n_parallel or 1)))-def _repatch_parallel_slots(argv: list[str], n_parallel: int, n_batch: Optional[int]) -> bool:- """Point ``--parallel`` at ``n_parallel``, re-raising ``--batch-size`` to match.-- The batch flag is emitted from the slot count as it stood then, so a later- restore that hands slots back would leave the batch under the new floor and- abort the very fallback the restore exists to make work. Returns whether- ``--parallel`` was found (callers rebind their own n_parallel on that).- """- try:- _at = argv.index("--parallel")- except ValueError:- return False- argv[_at + 1] = str(n_parallel)- _batch = _emitted_n_batch(n_batch, n_parallel)- if _batch is not None and "--batch-size" in argv:- argv[argv.index("--batch-size") + 1] = str(_batch)- return True--def _extra_args_n_ubatch(extra_args: Optional[Iterable[str]],env: Optional[Mapping[str, str]] = None,@@ -6456,11 +6437,12 @@ class LlamaCppBackend:flash_attn: bool = True,split_extra_bytes: int = 0,ubatch_for_slots: Optional[Callable[[int], Optional[int]]] = None,+ mtp_bytes_for_slots: Optional[Callable[[int, Optional[int]], int]] = None,) -> tuple[Optional[list[int]], bool, int]:"""Largest serving-slot count in [1, n_parallel) whose fully-on-GPU footprint fits,so Unsloth keeps the model on GPU (-ngl -1) instead of --fit on, which offloads layersto host and collapses decode ~3x (oobabooga #6718). ``base_footprint_bytes`` is the- slot-independent footprint (weights + soft overhead + MTP + context-linear compute,+ slot-independent footprint (weights + soft overhead + context-linear compute,minus the folded compute buffer); each candidate re-adds the slot-sized compute bufferand KV, then re-selects GPUs like the explicit-context path -- ``split_extra_bytes``included, so a multi-GPU candidate is re-checked at the split rate. Returns@@ -6470,7 +6452,14 @@ class LlamaCppBackend:--batch-size is raised to max(slots, 2), and llama.cpp caps the micro-batchagainst it, so a batch below the requested slot count shrinks as the candidatesdo. Holding it at the requested count made a fitting candidate look too big and- dropped the load to --fit offload."""+ dropped the load to --fit offload.+ ``mtp_bytes_for_slots(slots, ubatch)`` does the same for the MTP reserve, which is+ NOT slot-independent: compact SWA scales its window allowance by the slot count+ under kv_unified and adds one micro-batch, and an MLA target with recurrent (KDA)+ layers charges per slot. It takes the candidate micro-batch as well as the slot+ count, since a reduced candidate lowers the batch floor and so the ubatch too;+ pricing the reserve at the requested pair over-charged every candidate, so one that+ fits could be rejected and the load kept --fit."""for slots in range(n_parallel - 1, 0, -1):_ub = ubatch_for_slots(slots) if ubatch_for_slots else n_ubatchcb = self._estimate_compute_buffer_bytes(@@ -6481,6 +6470,7 @@ class LlamaCppBackend:total = (base_footprint_bytes+ cb+ + (mtp_bytes_for_slots(slots, _ub) if mtp_bytes_for_slots else 0)+ self._estimate_kv_cache_bytes(effective_ctx,cache_type_kv,@@ -9413,33 +9403,12 @@ class LlamaCppBackend:n_parallel,n_parallel,)- n_parallel = 1-- # MTP is documented as single-slot: the model cards ship "-np 1" and say- # "-np > 1 [...] not yet supported with MTP". The MTP state is per sequence,- # so what breaks at more slots is the draft: unequal per-slot token counts- # make split_equal reorder the ubatch while the nextn hidden states are- # still read by raw token index, so slots read each other's rows, acceptance- # collapses and MTP ends up slower than no speculation. Clamped beside the- # --kv-unified clamp so the KV fit matches.- # The env counts: llama.cpp appends spec types rather than replacing them- # (--spec-type inserts, --spec-default push_backs, enablement is a find over- # the vector), so an inherited LLAMA_ARG_SPEC_TYPE=draft-mtp really does- # launch MTP and no later flag can clear it.- _pv_extras_clamped_slots = 0- if n_parallel > 1 and _extra_args_requests_mtp(- extra_args, env = _child_spec_env(extra_args)- ):- # Kept so the paravirtual drafter drop can hand the slots back if it- # strips the very spec group this clamped for.- _pv_extras_clamped_slots = n_parallel- logger.warning(- "MTP speculative decoding (--spec-type draft-mtp) does not support "- "%d parallel slots; using 1. Load without MTP to serve chats in "- "parallel.",- n_parallel,- )- n_parallel = 1+ n_parallel = 1 # allow-slot-clamp: the build cannot serve more++ # 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.+ # llama.cpp#26031 reports concurrent MTP garbling on hybrid archs; it did not+ # reproduce here (qwen35 and qwen35moe on CUDA, 24 staggered uneven requests).# ── Vulkan-ordinal preflight (BEFORE the Phase 1 kill) ────────# An explicit Vulkan pin the ggml probe never enumerated cannot be honored.@@ -10258,8 +10227,21 @@ class LlamaCppBackend:)return v if v is not None else 0- def _mtp_bytes(ctx: int) -> int:- return mtp_overhead_fn(ctx) if mtp_overhead_fn is not None else 0+ def _mtp_bytes(+ ctx: int,+ slots: Optional[int] = None,+ ubatch: Optional[int] = None,+ ) -> int:+ # slots/ubatch override the closure's requested pair: the reserve+ # scales with both for compact SWA and MLA+recurrent, so the slot+ # fit re-prices it per candidate.+ if mtp_overhead_fn is None:+ return 0+ if slots is None:+ return mtp_overhead_fn(ctx)+ return mtp_overhead_fn(+ ctx, _np = slots, _n_ubatch = ubatch if ubatch else _effective_ubatch+ )def _kv_bytes(ctx: int) -> int:return self._estimate_kv_cache_bytes(@@ -10807,13 +10789,10 @@ class LlamaCppBackend:and self._can_estimate_kv()and effective_ctx > 0):- # Slot-independent footprint (folded compute buffer swapped out so the- # helper re-adds a slot-sized one per candidate).+ # Slot-independent footprint (folded compute buffer and the MTP+ # reserve swapped out so the helper re-prices both per candidate)._base_footprint = (- model_size_fit- - _compute_buffer_pipeline- + _mtp_bytes(effective_ctx)- + _cc_bytes(effective_ctx)+ model_size_fit - _compute_buffer_pipeline + _cc_bytes(effective_ctx))_gi_slots, _uf_slots, _slots = self._slots_that_fit_on_gpu(n_parallel,@@ -10831,6 +10810,7 @@ class LlamaCppBackend:flash_attn = planned_flash_attn,split_extra_bytes = _cc_split_extra(effective_ctx),ubatch_for_slots = _ubatch_for_slots,+ mtp_bytes_for_slots = lambda s, ub: _mtp_bytes(effective_ctx, s, ub),)if not _uf_slots:logger.info(@@ -11289,19 +11269,6 @@ class LlamaCppBackend:strip_template = False,strip_split_mode = False,)- # The slots were clamped for an MTP that just went away, so give- # them back. Restored before the spec flags are rebuilt, so the- # backstop below re-clamps if Unsloth's own resolution is MTP.- if _pv_extras_clamped_slots > 1 and not _extra_args_requests_mtp(- extra_args, env = _child_spec_env(extra_args)- ):- n_parallel = _pv_extras_clamped_slots- _repatch_parallel_slots(cmd, n_parallel, n_batch)- logger.info(- "Restoring %d parallel slots: the drafter drop left a "- "non-MTP server.",- n_parallel,- )spec_flags = self._build_speculative_flags(speculative_type = speculative_type,spec_draft_n_max = spec_draft_n_max,@@ -11381,37 +11348,6 @@ class LlamaCppBackend:if _paravirtual_cpu_forced:_pv_split_mode_pin = _paravirtual_split_mode_pin(extra_args)- # Backstop for the MTP clamp above, which only sees an explicit- # --spec-type in extra_args; speculative_type="auto"/"mtp" is not- # resolved until _build_speculative_flags runs, here. The KV fit was- # sized for more slots, so this over-reserves, never under-reserves.- # Skipped when the user's extras own --spec-type: _build_speculative_flags- # emits nothing then, and judging the empty flag list would fall through- # to LLAMA_ARG_SPEC_TYPE and clamp a launch that is not MTP at all.- _mtp_clamped_slots = 0- if (- n_parallel > 1- and not _extra_args_set_spec_type(extra_args)- and _extra_args_requests_mtp(spec_flags, env = _child_spec_env(extra_args))- ):- if "--parallel" in cmd:- logger.warning(- "%s resolved to MTP speculative decoding, which does not "- "support %d parallel slots; using 1.",- model_identifier,- n_parallel,- )- # Through the same helper as the restores: the floor is meant to- # be the smallest legal batch, so dropping to one slot must undo- # a raise the old count forced. Leaving it launched -b 64 for a- # requested -b 1 and made the recorded micro-batch, derived from- # the clamped count, describe a graph 32x smaller than the child's.- _repatch_parallel_slots(cmd, 1, n_batch)- # _commit_effective_parallel_slots reports what launched, so- # rebind rather than only patching cmd.- _mtp_clamped_slots = n_parallel- n_parallel = 1-# Apply custom chat template override if provided.self._chat_template_override = chat_template_overrideif chat_template_override:@@ -12417,26 +12353,7 @@ class LlamaCppBackend:strip_template = False,strip_split_mode = False,)- # The extras owned --spec-type, so the clamp that took the slots- # was the extras one and _mtp_clamped_slots stayed 0. The strip- # above makes this retry genuinely non-MTP, so hand those back- # too, or --parallel 1 sticks and the requested-vs-requested- # dedupe keeps every later load on the same one-slot server.- # Only where no GPU had to admit them: that clamp runs before the- # slot fit, so on a GPU box the count was never budgeted and the- # retry would size buffers nothing approved.- if not _detected_gpus:- _mtp_clamped_slots = max(_mtp_clamped_slots, _pv_extras_clamped_slots)fallback_cmd = cmd[:_spec_start] + ["--spec-default"] + _fb_tail- # fallback_cmd inherits the MTP slot clamp, but this retry is not- # MTP: hand back the slots the KV fit was sized for, or --parallel N- # silently serves one chat at a time (and the requested-vs-requested- # dedupe makes that stick). Later retries derive from this argv, so- # rebind n_parallel now.- if _mtp_clamped_slots > 1 and _repatch_parallel_slots(- fallback_cmd, _mtp_clamped_slots, n_batch- ):- n_parallel = _mtp_clamped_slotshealthy = _spawn_and_wait(fallback_cmd, label = "-retry")if healthy:self._speculative_type = "default"diff --git a/studio/backend/routes/inference.py b/studio/backend/routes/inference.pyindex 890fbf87d45..9a17d1bddd7 100644--- a/studio/backend/routes/inference.py+++ b/studio/backend/routes/inference.py@@ -6150,25 +6150,16 @@ def _guard_chat_load_against_training(requested_gpu_ids, vulkan_gpu_memory, tensor_parallel = guard_tensor_parallel)- # Size with the count that will actually launch, or a load that fits gets a- # 409: diffusion never receives --parallel, load_model clamps to 1 on an- # llama-server without --kv-unified, and it clamps MTP to 1 as well. An- # unclassified GGUF keeps the ask.+ # 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:if diffusion_kind is True:- n_parallel = 1- # MTP is deliberately NOT clamped here even though the launch clamps it to one- # slot. _estimate_gguf_required_gb counts the drafter file and the main KV, but- # not the draft KV, the duplicated target context MLA keeps, or the draft compute- # reserve, all of which load_model does budget. Sizing for one slot would drop- # the slot KV without replacing it with those, and a guard that under-sizes- # evicts the training run it exists to protect: the spare slots stand in for- # what is not modelled.+ n_parallel = 1 # allow-slot-clamp: diffusion never receives --parallelelse:try:caps = LlamaCppBackend.probe_server_capabilities()if caps.get("found") and not caps.get("supports_kv_unified"):- n_parallel = 1+ n_parallel = 1 # allow-slot-clamp: mirrors the load_model clampexcept Exception as e:logger.warning("Could not probe llama-server slots for chat-load guard: %s", e)diff --git a/studio/backend/tests/test_batch_sizes_per_load.py b/studio/backend/tests/test_batch_sizes_per_load.pyindex 366ed79e8f2..417cc6a4012 100644--- a/studio/backend/tests/test_batch_sizes_per_load.py+++ b/studio/backend/tests/test_batch_sizes_per_load.py@@ -35,7 +35,6 @@ from core.inference.llama_cpp import (LlamaCppBackend,_emitted_n_batch,_extra_args_n_ubatch,- _repatch_parallel_slots,)from core.inference.llama_server_args import BATCH_MAX, BATCH_MIN, strip_shadowing_flagsfrom models.inference import LoadRequest, ValidateModelRequest@@ -403,36 +402,6 @@ def test_emitted_batch_clears_both_llama_server_floors(n_batch, n_parallel, expeassert _emitted_n_batch(None, n_parallel) is None-def test_restoring_slots_re_raises_the_batch_flag():- """Two paths hand slots back after --batch-size was emitted: the paravirtual- drafter drop, which restores the slots the extras-MTP clamp took, and the- non-MTP fallback retry, which restores them in its own argv. Both patched only- --parallel, so an explicit small batch emitted at one slot met a restored eight- and aborted the very fallback the restore exists to make work."""- # emitted at 1 slot, restored to 8: the floor moves with it- argv = ["llama-server", "--parallel", "1", "--batch-size", "2", "--ubatch-size", "64"]- assert _repatch_parallel_slots(argv, 8, 2) is True- assert argv[argv.index("--parallel") + 1] == "8"- assert argv[argv.index("--batch-size") + 1] == "8"- # the micro-batch is not raised: llama.cpp caps it against the batch itself- assert argv[argv.index("--ubatch-size") + 1] == "64"-- # a batch already above the restored floor is left alone- argv = ["llama-server", "--parallel", "1", "--batch-size", "4096"]- assert _repatch_parallel_slots(argv, 8, 4096) is True- assert argv[argv.index("--batch-size") + 1] == "4096"-- # llama.cpp defaults emit no flag, and the restore must not invent one- argv = ["llama-server", "--parallel", "1"]- assert _repatch_parallel_slots(argv, 8, None) is True- assert "--batch-size" not in argv-- # no --parallel to patch: report it so the caller does not rebind n_parallel- argv = ["llama-server", "--batch-size", "2"]- assert _repatch_parallel_slots(argv, 8, 2) is False- assert argv[argv.index("--batch-size") + 1] == "2"--def test_budgets_use_the_raised_batch_not_the_requested_one():"""llama.cpp caps the micro-batch against the batch it is GIVEN(cparams.n_ubatch = min(cparams.n_batch, n_ubatch or n_batch)), and the loader@@ -616,10 +585,9 @@ def test_the_local_guard_charges_diffusion_nothing_for_the_batch_flags():def test_the_recorded_micro_batch_is_derived_from_the_slots_that_launched():"""self._n_ubatch is recorded next to _commit_effective_parallel_slots and the two are- read together later (the slot save re-estimates the KV from both). Both slot RESTORES- (the paravirtual drafter drop and the non-MTP retry) raise the count after the sizing- pass ran, so recording the sizing pass's value would pair the launched slots with a- micro-batch derived at the clamped count and under-state that cache. Pinned on the+ read together later (the slot save re-estimates the KV from both). The fit-time reduction+ moves the count after the sizing pass, so recording that pass's value would pair the launched+ slots with a micro-batch derived at the old count and under-state that cache. Pinned on thesource, since reaching the record needs a real spawn."""import astimport inspect@@ -642,7 +610,7 @@ def test_the_recorded_micro_batch_is_derived_from_the_slots_that_launched():assert "_launched_ubatch=_ubatch_for_slots(n_parallel)" in compact# and it is derived after the last thing that can move the slot countassert compact.index("_launched_ubatch=_ubatch_for_slots") > compact.index(- "n_parallel=_mtp_clamped_slots"+ "gpu_indices,use_fit,n_parallel=_gi_slots,False,_slots")diff --git a/studio/backend/tests/test_metal_paravirtual_guard.py b/studio/backend/tests/test_metal_paravirtual_guard.pyindex e3c0344d394..ce3fe247af1 100644--- a/studio/backend/tests/test_metal_paravirtual_guard.py+++ b/studio/backend/tests/test_metal_paravirtual_guard.py@@ -692,9 +692,6 @@ def _drafter_gate("_extra_args_requests_mtp": llama_cpp._extra_args_requests_mtp,"_child_spec_env": llama_cpp._child_spec_env,"strip_shadowing_flags": llama_cpp.strip_shadowing_flags,- # The slot restore rides in this block; 0 = nothing clamped, so it stays out of- # the way of the drafter cases these helpers cover.- "_pv_extras_clamped_slots": 0,"n_parallel": 1,"cmd": ["--parallel", "1"],"logger": log,@@ -877,21 +874,6 @@ def test_a_managed_spec_block_clears_the_inherited_spec_env():assert "_pv_draft_unpinnable" in gate-def test_the_drafter_drop_hands_back_the_slots_it_no_longer_needs():- """The extras-MTP clamp cuts a multi-slot request to one. If the drop then strips- that very spec group the server is not speculating at all, and would serve one chat- at a time forever: the dedupe records the original ask, so no Apply restores it."""- src = _load_model_source()- clamp_at = src.index("_pv_extras_clamped_slots = n_parallel")- restore_at = src.index("n_parallel = _pv_extras_clamped_slots")- assert clamp_at < restore_at- # Restored before the spec flags are rebuilt, so the backstop can re-clamp if- # Unsloth's own resolution turns out to be MTP.- assert restore_at < src.index("spec_flags = self._build_speculative_flags(")- # And it only fires once the stripped extras really are non-MTP.- assert "not _extra_args_requests_mtp(" in src[restore_at - 400 : restore_at]--def test_the_training_guard_sizes_the_cpu_pin_not_the_raw_request():"""load_model rewrites a GGUF placement to CPU here, so a guard sizing the raw Autorequest could refuse a chat load for VRAM it never takes."""@@ -1036,15 +1018,14 @@ def test_a_load_with_no_separate_drafter_is_unaffected():def test_mtp_detection_reads_every_accumulated_type():"""llama.cpp inserts each --spec-type rather than replacing, and applies the env- first, so MTP is on if ANY source names it. Reading only the last left the slot clamp- off for a launch that really does run MTP."""+ first, so MTP is on if ANY source names it. The VRAM budget rides on reading them all."""f = llama_cpp._extra_args_requests_mtpenv = {"LLAMA_ARG_SPEC_TYPE": "draft-mtp"}assert f(["--spec-type", "ngram-mod"], env) is Trueassert f(["--spec-type", "draft-mtp", "--spec-type", "ngram-mod"], {}) is Trueassert f(["--spec_type=draft-mtp"], {}) is Trueassert f([], env) is True- # Negatives: nothing names MTP, so nothing clamps.+ # Negatives: nothing names MTP.assert f(None, {}) is Falseassert f(["--spec-type", "ngram-mod"], {}) is Falseassert f(["--spec-default"], {}) is False@@ -1186,16 +1167,15 @@ def test_the_split_mode_override_outlives_the_pass_through_extras():assert pin_at > extras_at, "the split-mode override is emitted before the user extras"-# ── the MTP slot clamp must follow the flags that actually launch ─────+# ── MTP detection must read the flags that actually launch ────────────-def test_the_clamp_judges_the_env_the_child_will_actually_get():+def test_the_mtp_read_judges_the_env_the_child_will_actually_get():"""An inherited draft-mtp does launch MTP, but the launch scrubs it whenever Unsloth- owns the spec block, so the slots must survive rather than clamp for a server that- will not run MTP. The env counts only when the extras own --spec-type, the one case- it reaches the child."""+ owns the spec block, so reading os.environ would describe a server that will not run MTP.+ The env counts only when the extras own --spec-type, the one case it reaches the child."""env = {"LLAMA_ARG_SPEC_TYPE": "draft-mtp"}- # Managed block: scrubbed, so nothing to clamp for.+ # Managed block: scrubbed, so the env says nothing about this launch.assert llama_cpp._child_spec_env([]) == {}assert llama_cpp._extra_args_requests_mtp([], llama_cpp._child_spec_env([])) is False# Extras own the spec type: their flags and the env accumulate and both launch.@@ -1209,11 +1189,8 @@ def test_the_clamp_judges_the_env_the_child_will_actually_get():def test_the_training_guard_does_not_shrink_itself_for_mtp():- """The launch clamps MTP to one slot, but the guard's estimate counts only the drafter- file and the main KV: not the draft KV, the duplicated target context under MLA, or- the draft compute reserve. Sizing for one slot would drop the slot KV without adding- those back, and a guard that under-sizes evicts the training run it protects; the- unclamped slots stand in for the difference."""+ """MTP launches at the slots it asked for, and a guard that under-sizes evicts the+ training run it protects."""route_src = inspect.getsource(_routes())assert "_extra_args_requests_mtp(llama_extra_args" not in route_src# The diffusion and kv-unified clamps stay: neither drops a modelled term.@@ -1221,17 +1198,7 @@ def test_the_training_guard_does_not_shrink_itself_for_mtp():assert 'caps.get("supports_kv_unified")' in route_src-def test_the_backstop_defers_to_a_user_owned_spec_type():- """_build_speculative_flags emits nothing when the user owns --spec-type, and judging- that empty list would fall through to the env and clamp anyway."""- env = {"LLAMA_ARG_SPEC_TYPE": "draft-mtp"}- assert llama_cpp._extra_args_requests_mtp([], env) is True # why the guard is needed- assert llama_cpp._extra_args_set_spec_type(["--spec-type", "ngram-mod"]) is True- src = _load_model_source()- assert "not _extra_args_set_spec_type(extra_args)" in src---# ── ...and give the slots back when MTP never launches ────────────────+# ── ...and drop the spec group the startup retry cannot keep ──────────def _if_block(predicate, tree = None):@@ -1249,116 +1216,10 @@ def _names(node) -> set:return {n.id for n in ast.walk(node) if isinstance(n, ast.Name)}-def _is_mtp_clamp(test) -> bool:- return "spec_flags" in _names(test) and "n_parallel" in _names(test)---def _is_slot_restore(test) -> bool:- return "_mtp_clamped_slots" in _names(test)--def _is_retry_spec_strip(test) -> bool:return "_launch_spec_env" in _names(test)-def _run_clamp_then_fallback(- *,- n_parallel,- extra_args,- spec_flags,- cmd,- asked_for = None,- n_batch = None,-):- """Run the real clamp block, rebuild fallback_cmd the way the MTP retry does, then run- the real restore block. Returns the two argvs and the slot count- _commit_effective_parallel_slots would receive."""- scope = {- "n_parallel": n_parallel,- "extra_args": extra_args,- "spec_flags": spec_flags,- "cmd": list(cmd),- "_mtp_clamped_slots": 0,- "model_identifier": "owner/repo",- "logger": llama_cpp.logger,- "n_batch": n_batch,- "_extra_args_set_spec_type": llama_cpp._extra_args_set_spec_type,- "_extra_args_requests_mtp": llama_cpp._extra_args_requests_mtp,- "_child_spec_env": llama_cpp._child_spec_env,- "_repatch_parallel_slots": llama_cpp._repatch_parallel_slots,- # The pre-fit ask, which the restore must NOT reach for.- "_pending_load_kwargs": {"n_parallel": n_parallel if asked_for is None else asked_for},- }- exec(ast.unparse(_if_block(_is_mtp_clamp)), scope)- clamped = list(scope["cmd"])- # The retry swaps the spec slice for --spec-default; it sits at this argv's tail.- spec_at = len(clamped) - len(spec_flags)- scope["fallback_cmd"] = clamped[:spec_at] + ["--spec-default"]- exec(ast.unparse(_if_block(_is_slot_restore)), scope)- return clamped, scope["fallback_cmd"], scope["n_parallel"]---def _cmd(slots: int, spec_flags: list) -> list:- return ["llama-server", "-m", "/m.gguf", "--parallel", str(slots), "--kv-unified", *spec_flags]---def test_the_mtp_fallback_gets_the_requested_slots_back():- """MTP aborts at startup and the retry drops speculative decoding entirely, so that- server must not inherit the single slot MTP needed. The KV fit was sized for the full- count."""- spec = ["--spec-type", "draft-mtp"]- clamped, fallback, slots = _run_clamp_then_fallback(- n_parallel = 4,- extra_args = ["--top-k", "40"],- spec_flags = spec,- cmd = _cmd(4, spec),- )- assert clamped[clamped.index("--parallel") + 1] == "1" # MTP itself still gets one- assert fallback[fallback.index("--parallel") + 1] == "4"- # _commit_effective_parallel_slots reads this, and /status echoes it.- assert slots == 4---def test_the_fallback_raises_the_batch_flag_with_the_slots():- """--batch-size is emitted from the slot count as it stands then, and llama-server- aborts below it, so handing 4 slots back to an argv carrying an explicit -b 2 would- abort the very retry the restore exists to make work."""- spec = ["--spec-type", "draft-mtp"]- cmd = ["llama-server", "-m", "/m.gguf", "--parallel", "4", "--batch-size", "2", *spec]- clamped, fallback, slots = _run_clamp_then_fallback(- n_parallel = 4,- extra_args = ["--top-k", "40"],- spec_flags = spec,- cmd = cmd,- n_batch = 2,- )- assert fallback[fallback.index("--parallel") + 1] == "4"- assert fallback[fallback.index("--batch-size") + 1] == "4"- assert slots == 4- # the clamped argv keeps what it launched with: one slot needs no raise- assert clamped[clamped.index("--batch-size") + 1] == "2"---def test_the_mtp_backstop_lowers_the_batch_with_the_slots():- """The floor is the SMALLEST legal batch, not merely a sufficient one. This clamp runs- after --batch-size is emitted, so dropping to one slot has to undo the raise the old- count forced: -b 1 with 64 slots emits 64, and leaving it there launched MTP at a- 64-token micro-batch for a request of 1 (a much larger compute buffer), while the- recorded micro-batch, derived from the clamped count, said 2."""- spec = ["--spec-type", "draft-mtp"]- cmd = ["llama-server", "-m", "/m.gguf", "--parallel", "64", "--batch-size", "64", *spec]- clamped, _fallback, _slots = _run_clamp_then_fallback(- n_parallel = 64,- extra_args = ["--top-k", "40"],- spec_flags = spec,- cmd = cmd,- n_batch = 1,- )- assert clamped[clamped.index("--parallel") + 1] == "1"- # max(1, max(2, 1)) = 2, which is what _ubatch_for_slots(1) records- assert clamped[clamped.index("--batch-size") + 1] == "2"--def test_the_startup_retry_drops_the_mtp_the_extras_and_the_env_carry():"""A trailing --spec-default cannot override MTP or DSpark that extras or the envsupplied: llama.cpp applies the env first and appends types rather than replacing@@ -1386,36 +1247,6 @@ def test_the_startup_retry_drops_the_mtp_the_extras_and_the_env_carry():) == ["--top-k", "40"]-def test_the_retry_only_hands_back_slots_no_gpu_had_to_admit():- """The extras clamp cuts n_parallel to 1 before the GPU slot fit, whose gate needs >1,- so on a GPU box that count is never admitted and restoring it would size buffers- nothing approved. Off GPU there is nothing to budget, so the slots come back."""-- def _restored(detected_gpus):- scope = {- "cmd": ["llama-server", "--parallel", "1", "--spec-type", "draft-mtp"],- "_spec_start": 3,- "spec_flags": [],- "_fb_tail": ["--spec-type", "draft-mtp"],- "extra_args": ["--spec-type", "draft-mtp"],- "_launch_spec_env": {},- "env": {},- "n_parallel": 1,- "_pv_extras_clamped_slots": 4,- "_mtp_clamped_slots": 0,- "_detected_gpus": detected_gpus,- "_extra_args_requests_mtp": llama_cpp._extra_args_requests_mtp,- "strip_shadowing_flags": llama_cpp.strip_shadowing_flags,- "_SPEC_ENV_VARS": llama_cpp._SPEC_ENV_VARS,- "logger": llama_cpp.logger,- }- exec(ast.unparse(_if_block(_is_retry_spec_strip)), scope)- return scope["_mtp_clamped_slots"]-- assert _restored([]) == 4, "a CPU launch must get its slots back"- assert _restored([(0, 8 << 30)]) == 0, "a GPU launch must not restore unbudgeted slots"--def test_the_startup_fallback_records_the_extras_it_actually_launched():"""The success path stores extra_args as the launched list, but the fallback launchedwithout the spec group. Leaving the MTP list there means the next Apply that omits@@ -1432,116 +1263,6 @@ def test_the_startup_fallback_records_the_extras_it_actually_launched():assert src.index("_mtp_active_for_launched_server = False", 0, swap_at) < swap_at-def test_the_extras_own_clamp_comes_back_from_the_startup_retry_too():- """Extras owning --spec-type park the displaced slots in _pv_extras_clamped_slots and- leave _mtp_clamped_slots at 0. The retry strips that MTP for real now, so a restore- reading only _mtp_clamped_slots would leave --parallel 1 forever: _requested_n_parallel- still holds the original ask, so every later identical load dedupes onto it."""- scope = {- "cmd": ["llama-server", "--parallel", "1", "--spec-type", "draft-mtp"],- "_spec_start": 3,- "spec_flags": [],- "_fb_tail": ["--spec-type", "draft-mtp"],- "extra_args": ["--spec-type", "draft-mtp"],- "_launch_spec_env": {},- "env": {"LLAMA_ARG_SPEC_TYPE": "draft-mtp"},- "n_parallel": 1,- # What the extras clamp displaced, and what the Unsloth-resolved clamp holds.- "_pv_extras_clamped_slots": 4,- "_mtp_clamped_slots": 0,- "_detected_gpus": [], # CPU launch: nothing had to budget the slots- "n_batch": None,- "_extra_args_requests_mtp": llama_cpp._extra_args_requests_mtp,- "_repatch_parallel_slots": llama_cpp._repatch_parallel_slots,- "strip_shadowing_flags": llama_cpp.strip_shadowing_flags,- "_SPEC_ENV_VARS": llama_cpp._SPEC_ENV_VARS,- "logger": llama_cpp.logger,- }- exec(ast.unparse(_if_block(_is_retry_spec_strip)), scope)- assert scope["env"] == {}, "the child kept the spec env the retry dropped"- scope["fallback_cmd"] = ["llama-server", "--parallel", "1", "--spec-default"]- exec(ast.unparse(_if_block(_is_slot_restore)), scope)- assert scope["fallback_cmd"][scope["fallback_cmd"].index("--parallel") + 1] == "4"- assert scope["n_parallel"] == 4---def test_the_fallback_gets_back_what_the_fit_sized_not_what_the_user_asked():- """_slots_that_fit_on_gpu can already have cut the count before the clamp, so restoring- the raw ask would launch a server the VRAM budget never covered."""- spec = ["--spec-type", "draft-mtp"]- _, fallback, slots = _run_clamp_then_fallback(- n_parallel = 4,- extra_args = None,- spec_flags = spec,- cmd = _cmd(4, spec),- asked_for = 8,- )- assert fallback[fallback.index("--parallel") + 1] == "4"- assert slots == 4---def test_a_single_slot_mtp_load_stays_single_slot_on_the_fallback():- """The negative that matters most: nothing was clamped, so nothing is owed."""- spec = ["--spec-type", "draft-mtp"]- clamped, fallback, slots = _run_clamp_then_fallback(- n_parallel = 1,- extra_args = None,- spec_flags = spec,- cmd = _cmd(1, spec),- )- assert clamped[clamped.index("--parallel") + 1] == "1"- assert fallback[fallback.index("--parallel") + 1] == "1"- assert slots == 1---def test_a_user_owned_spec_type_is_not_handed_slots_it_never_asked_to_lose():- """The pre-flight clamp already reduced this load before the KV fit, so the fit is- sized for one slot and the backstop never records a debt."""- clamped, fallback, slots = _run_clamp_then_fallback(- n_parallel = 1,- extra_args = ["--spec-type", "draft-mtp"],- spec_flags = [],- cmd = _cmd(1, []),- )- assert clamped[clamped.index("--parallel") + 1] == "1"- assert fallback[fallback.index("--parallel") + 1] == "1"- assert slots == 1---def test_a_non_mtp_resolution_keeps_its_slots_end_to_end():- """No clamp, so the restore must not touch a count that was already correct."""- spec = ["--spec-default"]- clamped, fallback, slots = _run_clamp_then_fallback(- n_parallel = 4,- extra_args = None,- spec_flags = spec,- cmd = _cmd(4, spec),- )- assert clamped[clamped.index("--parallel") + 1] == "4"- assert fallback[fallback.index("--parallel") + 1] == "4"- assert slots == 4---def test_the_restore_is_scoped_to_the_retry_that_actually_drops_mtp():- """A successful MTP launch, and the FA-off retry that keeps MTP, both stay at one- slot: the restore belongs to the --spec-default retry alone."""- tree = _load_model_tree()- restore = _if_block(_is_slot_restore, tree)- owners = [- node- for node in ast.walk(tree)- if isinstance(node, ast.If)- and any(restore in ast.walk(stmt) for stmt in node.body)- and "_spec_requested_mtp" in _names(node.test)- ]- assert len(owners) == 1, "the slot restore left the MTP-fallback branch"- assert "healthy" in _names(owners[0].test), "the restore must only run on a failed MTP start"- # ...and after the retry argv exists, or it would rewrite nothing.- src = _load_model_source()- assert src.index("fallback_cmd = cmd[:_spec_start]") < src.index("_mtp_clamped_slots > 1")- assert src.index("_mtp_clamped_slots > 1") < src.index("_spawn_and_wait(fallback_cmd")--# ── a suppressed drafter must not churn the server it left healthy ───diff --git a/studio/backend/tests/test_parallel_slots_never_clamped.py b/studio/backend/tests/test_parallel_slots_never_clamped.pynew file mode 100644index 00000000000..7ebc4349e8a--- /dev/null+++ b/studio/backend/tests/test_parallel_slots_never_clamped.py@@ -0,0 +1,98 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""The launched --parallel must equal the requested slot count.++#7717 clamped it to 1 whenever MTP resolved, costing batched API callers up to 4x+throughput. These drive the real load path and read the slots off the launched argv.+"""++from __future__ import annotations++import sys+from pathlib import Path++import pytest++_TESTS_DIR = str(Path(__file__).resolve().parent)+if _TESTS_DIR not in sys.path:+ sys.path.insert(0, _TESTS_DIR)++# Reuses the only harness in the suite that yields a real launched argv.+from test_llama_cpp_placement import _backend, _launch, _write_gguf # noqa: E402++_MEMORY = [(0, 40 * 1024**3, 48 * 1024**3)]++# Everything the MTP branch of _build_speculative_flags probes for.+_CAPS = {+ "found": True,+ "supports_kv_unified": True,+ "supports_mtp": True,+ "mtp_token": "draft-mtp",+ "spec_draft_n_max_flag": "--spec-draft-n-max",+}+++def mtp_backend(tmp_path, monkeypatch):+ backend, _ = _backend(tmp_path, vulkan = False, memory = _MEMORY)+ monkeypatch.setattr(+ type(backend), "probe_server_capabilities", classmethod(lambda cls, binary = None: _CAPS)+ )+ # The name is what _is_mtp_model_name reads, so this GGUF resolves to MTP.+ return backend, _write_gguf(tmp_path / "Qwen3.5-9B-MTP.gguf")+++def _slots(cmd: list[str]) -> int:+ return int(cmd[cmd.index("--parallel") + 1])++[email protected]("requested", [1, 2, 4, 8])[email protected]("speculative", ["auto", "mtp", "mtp+ngram", "ngram", "off"])+def test_the_launch_serves_the_slots_that_were_asked_for(mtp_backend, requested, speculative):+ backend, gguf = mtp_backend+ cmd = _launch(backend, gguf, n_parallel = requested, speculative_type = speculative)["cmd"]+ assert _slots(cmd) == requested++[email protected]("requested", [2, 4, 8])+def test_extras_owned_mtp_keeps_the_slots_too(mtp_backend, requested):+ """The other route into MTP: --spec-type in the user's own extra args."""+ backend, gguf = mtp_backend+ cmd = _launch(+ backend,+ gguf,+ n_parallel = requested,+ extra_args = ["--spec-type", "draft-mtp"],+ )["cmd"]+ assert _slots(cmd) == requested++[email protected]("requested", [2, 4, 8])+def test_an_inherited_spec_env_does_not_take_the_slots(mtp_backend, monkeypatch, requested):+ """LLAMA_ARG_SPEC_TYPE cannot be cleared by a later flag, so it used to clamp."""+ backend, gguf = mtp_backend+ monkeypatch.setenv("LLAMA_ARG_SPEC_TYPE", "draft-mtp")+ cmd = _launch(backend, gguf, n_parallel = requested)["cmd"]+ assert _slots(cmd) == requested++[email protected]("requested", [2, 8])+def test_the_batch_floor_follows_the_slot_count(mtp_backend, requested):+ """llama-server aborts below the slot count, so -b rises with an MTP load too."""+ backend, gguf = mtp_backend+ cmd = _launch(backend, gguf, n_parallel = requested, n_batch = 1, speculative_type = "mtp")["cmd"]+ assert _slots(cmd) == requested+ assert int(cmd[cmd.index("--batch-size") + 1]) >= max(2, requested)+++def test_a_build_without_kv_unified_still_falls_back_to_one_slot(tmp_path, monkeypatch):+ """The one downgrade that survives: more slots would split the context window."""+ backend, gguf = _backend(tmp_path, vulkan = False, memory = _MEMORY)+ monkeypatch.setattr(+ type(backend),+ "probe_server_capabilities",+ classmethod(lambda cls, binary = None: {**_CAPS, "supports_kv_unified": False}),+ )+ cmd = _launch(backend, gguf, n_parallel = 4, speculative_type = "mtp")["cmd"]+ assert _slots(cmd) == 1diff --git a/studio/backend/tests/test_parallel_slots_per_load.py b/studio/backend/tests/test_parallel_slots_per_load.pyindex 3af788ad299..e6c4d1e2b96 100644--- a/studio/backend/tests/test_parallel_slots_per_load.py+++ b/studio/backend/tests/test_parallel_slots_per_load.py@@ -519,11 +519,8 @@ def test_training_guard_sizes_every_slot_when_kv_unified_exists(monkeypatch, tmpdef test_training_guard_keeps_the_asked_slots_for_an_explicit_mtp_load(monkeypatch, tmp_path):- # load_model does clamp MTP to a single slot, but this estimate counts only the- # drafter file and the main KV: not the draft KV, the duplicated target context MLA- # keeps, or the draft compute reserve. Sizing for one slot would drop the slot KV- # without adding those back, and a guard that under-sizes evicts the training run it- # protects, so it keeps the larger number.+ # MTP launches at the slots asked for, and this estimate under-counts it (no draft KV, no MLA+ # duplication, no compute reserve), so under-sizing here evicts the training run it protects.gguf = _write_swa_gguf(tmp_path / "chat.gguf")mtp = ["--spec-type", "draft-mtp"]new = {"found": True, "supports_kv_unified": True}diff --git a/studio/backend/tests/test_slot_offload_fit.py b/studio/backend/tests/test_slot_offload_fit.pyindex 60900f04195..bf8bd63231a 100644--- a/studio/backend/tests/test_slot_offload_fit.py+++ b/studio/backend/tests/test_slot_offload_fit.py@@ -194,3 +194,56 @@ class TestSlotsThatFitOnGpu:assert _fit(ubatch_for_slots = ubatch_for_slots) == (([0], False, 3), [3])# held at the requested count's micro-batch, the same card loses a slotassert _fit() == (([0], False, 2), [64, 64])+++class TestMtpReserveIsRepricedPerCandidate:+ """The MTP reserve is not slot-independent: compact SWA scales its window allowance by+ the slot count under kv_unified, and an MLA target with recurrent (KDA) layers charges+ per slot. Holding it at the requested count over-charged every candidate, so a smaller+ one that fits was rejected and the load kept --fit and offloaded to host (PR #8172)."""++ def _fit(+ self,+ mtp_for_slots,+ base_mib = 22000,+ ):+ return _backend()._slots_that_fit_on_gpu(+ 4,+ CTX,+ [(0, 24576)],+ {0: 24576},+ int(base_mib * MIB),+ "q8_0",+ FRAC,+ 0,+ 1,+ n_ubatch = 512,+ mtp_bytes_for_slots = mtp_for_slots,+ )++ def test_a_slot_scaled_reserve_shrinks_with_the_candidate(self):+ # 500 MiB per slot: par3 (22000+1162+1500) over 23839, par2 (22000+604+1000) fits.+ gi, use_fit, slots = self._fit(lambda s, _ub: int(500 * s * MIB))+ assert use_fit is False and gi == [0] and slots == 2++ def test_holding_the_reserve_at_the_requested_count_would_reject_them_all(self):+ # The old behaviour: every candidate charged the 4-slot reserve, so even one slot+ # (22000+46+2000) looked too big and the load stayed on --fit.+ gi, use_fit, slots = self._fit(lambda _s, _ub: int(500 * 4 * MIB))+ assert use_fit is True and gi is None and slots == 4++ def test_no_reserve_callable_matches_a_zero_reserve(self):+ assert self._fit(None) == self._fit(lambda _s, _ub: 0)++ def test_the_candidate_micro_batch_reaches_the_reserve(self):+ """Compact SWA adds one micro-batch to its window allowance, and a reduced+ candidate lowers the batch floor, so the reserve has to see the candidate ubatch+ and not the one the original request was sized at (PR #8172)."""+ seen = []+ # base 24000: no candidate fits, so every one is priced and observed.+ self._fit(lambda s, ub: seen.append((s, ub)) or 0, base_mib = 24000)+ assert seen, "the reserve callback was never consulted"+ # ubatch_for_slots is None here, so n_ubatch passes through; what matters is that+ # it travels with the slot count instead of being dropped.+ assert all(ub == 512 for _s, ub in seen), seen+ assert [s for s, _ub in seen] == [3, 2, 1]diff --git a/tests/test_lint_no_parallel_clamp.py b/tests/test_lint_no_parallel_clamp.pynew file mode 100644index 00000000000..0b3edd2f385--- /dev/null+++ b/tests/test_lint_no_parallel_clamp.py@@ -0,0 +1,88 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.++"""Regression suite for scripts/lint_no_parallel_clamp.py.++The lint is what stops #7717 coming back: a rule that flags `max(1, n)` gets+disabled, and one that misses `n_parallel = 1` protects nothing.+"""++from __future__ import annotations++import importlib.util+import sys+from pathlib import Path++import pytest++REPO_ROOT = Path(__file__).resolve().parents[1]+_SCRIPT = REPO_ROOT / "scripts" / "lint_no_parallel_clamp.py"++_spec = importlib.util.spec_from_file_location("lint_no_parallel_clamp", _SCRIPT)+lint = importlib.util.module_from_spec(_spec)+sys.modules["lint_no_parallel_clamp"] = lint+_spec.loader.exec_module(lint)+++CLAMPS = (+ "def load():\n n_parallel = 1\n",+ # The annotated spelling of the same clamp: a different AST node, same regression.+ "def load():\n n_parallel: int = 1\n",+ "async def load():\n n_parallel: int = 1\n",+ # Spelled as an expression rather than a literal.+ "def load(n):\n n_parallel = min(n, 1)\n",+ "def load(n, mtp):\n n_parallel = 1 if mtp else n\n",+ # Tuple unpacking, the shape load_model already uses for the VRAM fit.+ "def load(gi):\n gpu_indices, use_fit, n_parallel = gi, False, 1\n",+ # The route resolves the request into this alias before the load paths see it.+ "def load():\n _n_parallel = 1\n",+ # A request that names no count resolves to the server-wide default.+ "def serve():\n llama_parallel_slots = 1\n",+ "def load():\n n_parallel = _mtp_clamped_slots\n",+ "async def load():\n n_parallel = 1\n",+ "def load():\n if mtp:\n n_parallel = 1\n",+)++ALLOWED = (+ # The two shapes that survive: a real capability limit, and a real resource limit.+ "def load():\n n_parallel = 1 # allow-slot-clamp: no --kv-unified\n",+ "def load():\n n_parallel: int = 1 # allow-slot-clamp: no --kv-unified\n",+ "def load(fit):\n n_parallel = fit.slots\n",+ "def load(n):\n n_parallel = min(n, 1) # allow-slot-clamp: no --kv-unified\n",+ # A real bound, and a conditional between two live counts: neither pins to 1.+ "def load(n, cap):\n n_parallel = min(n, cap)\n",+ "def load(n, hi):\n n_parallel = n if n < hi else hi\n",+ "def load(gi, s):\n gpu_indices, use_fit, n_parallel = gi, False, s\n",+ "def load(f):\n gi, use_fit, n_parallel = f()\n",+ "def load(r, s):\n _n_parallel = _resolve(r, s)\n",+ "def serve(a):\n run(llama_parallel_slots = a.parallel)\n",+ "def load(x):\n n_parallel: int = x\n",+ # Structurally distinct, so no marker is needed for any of these.+ "def load(n_parallel: int = 1):\n return n_parallel\n",+ "class A:\n n_parallel: int = 1\n",+ "def load():\n self._requested_n_parallel = 1\n",+ "def load(x):\n n_parallel = max(1, x)\n",+ "def load(s):\n n_parallel = getattr(s, 'llama_parallel_slots', 1)\n",+ "def load(r):\n n_parallel = r.n_parallel\n",+ "n_parallel = 1\n",+)++[email protected]("source", CLAMPS)+def test_a_silent_downgrade_is_flagged(source):+ assert lint.scan_source(source, "<test>")++[email protected]("source", ALLOWED)+def test_a_legitimate_slot_count_is_not_flagged(source):+ assert lint.scan_source(source, "<test>") == []+++def test_the_scripts_own_self_test_passes():+ assert lint._self_test() == 0+++def test_the_studio_backend_is_clean():+ found, scanned = lint.scan_paths(lint.DEFAULT_SCAN_DIR)+ assert scanned, "no backend source files were scanned"+ assert found == [], f"silent parallel-slot downgrade(s): {found}"