unsloth/studio/backend/tests/test_parallel_slots_per_load.py
Kirelos Namroud 150b5ba25a
feat(studio): adjustable llama-server parallel slots from the web UI (#7447)
* feat(studio): share the llama-server --parallel bounds as PARALLEL_MIN/MAX

The per-load parallel-slots field needs the same 1..64 range the CLI flag
validates, but models/inference.py cannot import run.py (run.py builds the
app that imports routes that import models). Promote the bounds into this
dependency-free module, which already owns the -np/--parallel semantics, and
record the deliberate mirrors that cannot import it (run.py, the unsloth CLI,
the web UI). The denylist entry stays: the first-class field is now the single
write path for the slot count, so a pass-through would still desync the
committed bookkeeping from llama-server.

* feat(studio): note the per-load override in the --parallel help text

--parallel is now the server-wide default that a per-load n_parallel (the
Studio Parallel Slots run setting) can override, not the definitive slot
count. Point at the new control so a user does not conclude a restart is the
only way to change slots, and record the shared PARALLEL_MIN/MAX mirror
alongside the existing CLI one.

* feat(studio): add n_parallel to LoadRequest and echo the slot counts

LoadRequest.n_parallel (optional, PARALLEL_MIN..PARALLEL_MAX) lets a load pick
its own llama-server --parallel count; omitted, the server-wide launch default
applies. ValidateModelRequest carries it too so the training-coexistence
estimate sizes the KV cache like the follow-up load rather than passing on a
smaller footprint.

LoadResponse and InferenceStatusResponse gain both requested_parallel_slots
(what the load was invoked with) and parallel_slots (what llama-server
actually runs after the fitter's slot reduction), so a client can tell an
honored request from a reduced one. Both are None where --parallel has no
meaning: non-GGUF loads and the diffusion runner.

* feat(studio): record the requested parallel-slot count on the backend

The auto GPU-memory fit may launch fewer slots than requested to keep the
model fully on GPU, so the committed effective count cannot answer "is the
live server what this request asked for?". Store the invoked count separately
(mirroring the _requested_n_ctx pattern) from the pre-reduction pending
kwargs, expose it as requested_parallel_slots, and have _already_in_target_state
compare requested-vs-requested: comparing against the effective count would
reload -- and re-reduce -- forever on an identical Apply.

The comparison sits in the non-diffusion branch, since the diffusion runner
ignores --parallel entirely. The requested value shares the effective count's
lifecycle, so every unload/kill path clears it and a stale count cannot
poison the next load's dedupe.

* feat(studio): honor a per-load parallel-slot count in /load and /validate

Resolve the slot count once per load -- the request field if set, else the
server-wide launch default -- and feed it to every consumer that must agree:
the training-coexistence guard, the llama-server load kwargs, and the reload
dedupe. Without the dedupe comparison a changed slot count would be swallowed
as already_loaded; it compares requested-vs-requested and skips the diffusion
runner, which ignores --parallel.

app.state.llama_parallel_slots is deliberately never written: it stays the
launch intent and the admission-queue fallback, so one load's override cannot
leak into later loads. /validate resolves the same way so its estimate cannot
undercount what the load then allocates.

Both /load returns and /status echo the counts through one helper, which
reports None for diffusion -- its load never commits a count, so echoing the
reset placeholder would fabricate an "invoked with 1 slot".

* feat(studio): accept nParallel in the chat-preset load config

ChatPresetLoadConfig is extra="forbid", so a preset carrying the new parallel
slots knob would 422 the whole settings sync without this field. Bounds come
from the shared PARALLEL_MIN/MAX rather than literals, so a future range
change cannot start rejecting presets the UI still allows.

* test(studio): cover the per-load parallel-slots knob

Pins the behaviors a regression would silently break: the requested-vs-effective
dedupe (comparing against the reduced count would reload forever), the diffusion
skip and its None echo, the requested count's reset lifecycle, and its commit
from the pre-reduction pending kwargs.

Also pins the three bounds mirrors that cannot import PARALLEL_MIN/MAX (run.py,
the unsloth CLI, the web UI) plus the preset model that can, so a range change
cannot leave one of them clamping or rejecting at the old limit.

* test(studio): refresh the --parallel denylist comments for the UI knob

The pinned rationale said the typer flag owns the slot count and pointed users
at a Studio restart. Parallel Slots / LoadRequest.n_parallel is now the other
managed writer, and the 1..64 guard is the shared PARALLEL_MIN/MAX -- a reader
following the old comments would conclude the UI control does not exist.

* feat(studio): note the per-load override in the CLI --parallel help

Both the plain-serve and `unsloth studio run` flags now describe a server-wide
default the Studio Parallel Slots run setting can override per load, matching
the backend help text.

* feat(studio): remember a per-model Parallel Slots override

nParallel joins the per-model config with the same null-means-follow-the-default
convention as the other knobs: null keeps the server-wide --parallel count, so
a blank control never pins a number and isDefaultConfig still deletes an
otherwise-untouched config instead of storing it.

The value is re-clamped to N_PARALLEL_MIN/MAX on every localStorage read and
write (the store is user-editable), and listing it in STORED_CONFIG_FIELDS
keeps it from being dropped as an unknown key. Legacy blobs predate the knob,
so their migration carries null. No schema-version bump: an additive optional
field, like the GPU fields before it.

* feat(studio): bridge nParallel between the per-model config and the store

The config->store, store->config and equality helpers all need the new field:
without the equality arm a slots-only edit reads as unchanged, so Apply is
dropped and the dirty state never lights up.

* feat(studio): track the parallel-slot override in the chat runtime store

nParallel holds the editable override and loadedNParallel the value the last
successful load sent, which the failed-switch rollback re-sends. Both are
per-model: they clear on unload and on a model switch, unlike the standing
preferences (GPU memory mode, speculative type) that survive one.

There is deliberately no backend-echo field for the control: the echo is the
resolved count, so adopting it would pin a blank "follow the server default"
input to an explicit number.

* feat(studio): type n_parallel and the slot-count echoes

The load request gains the optional per-load slot count, and both the load
response and the status payload gain requested_parallel_slots (invoked) and
parallel_slots (actually running after the fitter's reduction). Keys stay
snake_case: the payload is serialized as-is, with no case conversion.

* feat(studio): forward n_parallel to the validate preflight

validateModel builds its own body rather than forwarding the load payload, so
the slot count has to be listed explicitly. Slots scale the KV estimate, and
the preflight exists to refuse a load the training guard would then 409 -- an
unforwarded count would validate a smaller footprint than the load allocates.

* feat(studio): include nParallel in the active model's config

The sidebar assembles the active model's config from individually subscribed
store fields; an unsubscribed field would leave the form showing a stale value
after any external change.

* feat(studio): add the Parallel Slots control to the run settings

A numeric input in the GGUF advanced section, blank meaning "follow the server
default". It clamps on change like the Draft Tokens field rather than using
NumericValueInput, so there is no blur-draft to lose when the user types a
value and immediately clicks Load.

hasNonDefaultAdvanced counts it too, so a remembered override reopens the
advanced section instead of hiding the setting that is actually in effect.

* feat(studio): key the sidebar config form on nParallel too

The signature drives the remount that re-seeds the form; without the new field
an externally changed slot count would leave the sidebar showing the old one.

* feat(studio): send the Parallel Slots override on load

performLoad snapshots the slot count at click time (staged run-settings config
first, else the store) and sends it on both the validate preflight and the
load, so the two size the same footprint. A cross-model switch re-baselines it
like the other per-model knobs -- the previous model's count must not follow
onto the next one -- and the failed-switch rollback re-sends the previous
model's value so a rescue reload cannot silently drop to the server default.

The success path keeps the click-time value rather than the response echo: the
echo is the count the fitter resolved, so adopting it would turn a blank
"follow the server default" control into an explicit pin. Slots are GGUF-only,
so a transformers load sends and records null instead of a phantom override.

* feat(studio): carry the slot override through the compare-pane load

The compare pane builds its own load request, so it needs the field explicitly
or a pane with a remembered override would load at the server default. Its
validate preflight sends the same count, matching the comment above it that
promises validation is sized exactly as the load below.

GGUF-gated on both calls, and the store adopts the pane's own click-time value
rather than the resolved echo, mirroring the single-model path.

* feat(studio): honor the remembered slot override on startup auto-load

The auto-load path reads the per-model config and forwards every other
remembered knob, so a remembered Parallel Slots value was the one setting lost
on the "load last used model" path: llama-server came back at the server-wide
default with the control showing blank, and the first manual Apply afterwards
then forced a needless reload because the counts disagreed.

* feat(studio): seed the slot baseline from the status echo

Only the rollback baseline is seeded, never the editable control: the echo is
the resolved count, so adopting it would pin a blank "follow the server
default" input to a number. Without the seed, loadedNParallel stayed null
after a tab reload or a second tab adopting the running model, and a failed
switch then rolled the previous model back at the server default while every
other knob was restored.

* feat(studio): capture Parallel Slots in chat presets

The knob joins the preset load config end to end: captured from the store,
re-clamped when read back (persisted presets are untrusted input), applied on
switch, and summarized in the preset chip. Its default is null, so
coalesceDefaultLoadKnobs keeps a default-only preset empty rather than
persisting a no-op override.

* feat(studio): re-derive the preset state when Parallel Slots changes

Both preset memos snapshot the store through capturePresetLoadConfig, so
without the new dependency a slots-only edit left the unsaved-changes flag and
the load summary showing the previous value.

* test(studio): pin the Parallel Slots wiring end to end

Source-contract coverage for the hops a refactor can silently drop: the three
/load builders (interactive, compare pane, startup auto-load) and their
validate preflights, per-model persistence and clamping, the UI row, and the
status seed -- including the negative assertion that hydration seeds only the
rollback baseline, never the control, so the resolved echo cannot pin a blank
"server default" input.

* test(studio): pin nParallel in the preset load config

Covers capture, clamped read-back and apply on the frontend, plus the backend
field itself: ChatPresetLoadConfig is extra="forbid", so a missing or drifted
field 422s every settings sync that carries a preset.

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

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

* Fall back to one slot when llama-server lacks --kv-unified for PR #7447

Without --kv-unified an explicit --parallel N makes llama-server give each slot -c/N, so on a build without the flag choosing N slots silently shrinks every context window for a feature that build cannot serve. Clamp to one slot and log why, placed after the requested count is captured so the echo still reports it and before the KV estimates so the fit matches what actually launches.

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

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

* Clear the slot control on load paths that never send it, and size the training guard for diffusion

Four review findings on the per-load Parallel Slots knob.

The editable nParallel control means "follow the server default" when null, so
any success path that does not send a slot count has to clear it. Three paths
kept a value staged for a different model:

- chat-adapter.ts, cached non-GGUF auto-load: the interactive and compare
  builders already clear both fields for a non-GGUF response, this third one
  did not. The field never renders for a non-GGUF target, so the stale count
  was invisible and unclearable from the UI yet still persisted, and it flips
  isDefaultConfig so a user with no overrides silently gets a stored entry.
- chat-adapter.ts, fresh-model fallback: its request omits n_parallel but its
  success state resynced every other knob and left the slots alone, so a staged
  edit survived against a server running the default and the next Apply
  reloaded at a count that load never sent.
- apply-inference-status-to-store.ts: on a model change underneath the tab
  every sibling knob adopts the new model's status, but nParallel updated only
  its baseline, so the previous model's explicit count followed onto the new
  model and saving or reloading there pinned it. Clear the control and keep
  seeding the baseline for the rollback.

The training-coexistence guard sized a diffusion GGUF with the requested slot
count. _estimate_kv_cache_bytes scales the SWA cache with slots
(swa_limit = swa * slots + ubatch), but load_model hands a diffusion target to
_start_diffusion_server before the slot plumbing, so that runner is always
single-slot. At the new default of 4 this inflated the estimate and could 409 a
load that fits. An unclassified GGUF keeps the requested count.

Backend base KV depends on -c alone, not on --parallel, which is why only the
SWA term is affected: llama.cpp PR 14363 and discussion 4130.

Tests: three training-guard cases in test_parallel_slots_per_load.py and one
source contract in test_model_picker_contracts.py, each mutation-checked.
174 passed across the backend slot/admission/training suites, 56 across the
frontend contract suites.

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

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

* Keep the slot control when re-adopting the running model, and never record slots for a diffusion load

Two follow-ups from the latest review round.

The first is a regression from c796393. That commit cleared the slot control
whenever hydratingExistingModel was set, to stop model A's count following onto
model B. But that flag is also set on the resident-model adopt path: when the
store checkpoint is an external provider id and the user re-picks the still
loaded local model, applyActiveModelStatusToStore is called with the external
id as previousCheckpoint, so the flag is unconditionally true. The clear then
wiped the config applyPerModelConfigToRuntime had restored two lines earlier,
and it was the only knob that did, because the siblings re-adopt the status
echo while this one cleared. Gate the clear on the tab's own baseline no longer
matching the running count: a genuine A to B swap still clears, re-adopting the
same model keeps its value.

The second revises an earlier call of mine. I rejected the diffusion phantom as
cosmetic because the backend ignores the value on every send. The sharpened
report is right and my rejection was wrong: capturePresetLoadConfig records
nParallel with no model gate, a Preset carries no model id, and applying one
writes nParallel for whatever model is current. So a count recorded against a
diffusion model, which the backend never applied, rides a saved preset onto a
text GGUF and becomes a real override the user never chose. Record slots only
when the load actually committed them, on all three load builders.

Tests: two source contracts in test_model_picker_contracts.py, both mutation
checked. Frontend typecheck clean, 58 passed across the contract and preset
suites.

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

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

* Clear the slot baseline when status reports a model without slots

Hydrating from a GGUF to a slotless model left loadedNParallel at the previous
model's count: the seed only runs when the echo is non-null, and the control
clear added earlier touches nParallel alone. The stale baseline is what a
failed-switch rollback re-sends, and preset capture reads it, so it could claim
slots for a model that never used them.

Clear it when status describes a model that cannot have slots. /status omits
the echo entirely for non-GGUF and sends an explicit null for the diffusion
runner, so keying on is_gguf === false or an explicit null covers both while an
absent field on a GGUF, which is how an older backend reports one, still leaves
the baseline alone.

Test mutation checked; frontend typecheck clean against a fresh npm ci.

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

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

* Distinguish a same-model re-adopt from a model swap, and size the training guard at the slots that launch for PR #7447

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

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

* Keep the blank slot control across a failed-switch rollback for PR #7447

* Restore a remembered slot override when hydrating a fresh store for PR #7447

* Tighten comments for PR #7447

* Restore a remembered slot override on a model switch too for PR #7447

* Tighten comments and docstrings for PR #7447

* Take the rollback slot intent from the picker's pre-switch snapshot for PR #7447

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

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

---------

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
Co-authored-by: danielhanchen <danielhanchen@gmail.com>
Co-authored-by: danielhanchen <unslothai@gmail.com>
2026-07-28 18:03:28 -07:00

517 lines
20 KiB
Python

# SPDX-License-Identifier: AGPL-3.0-only
# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
"""Backend contract for the per-load parallel-slots knob.
An optional ``n_parallel`` (llama-server ``--parallel``) rides on LoadRequest;
omitted, the server-wide launch default (``run.py --parallel``) applies. These
tests pin the pydantic contract and the shared PARALLEL_MIN/MAX mirrors, the
``requested_parallel_slots`` lifecycle, the ``_already_in_target_state``
requested-vs-requested reload branch with its diffusion skip, and the route
wiring behind the /load, /validate and /status echoes.
"""
from __future__ import annotations
import inspect
import re
import struct
import sys
import types as _types
from pathlib import Path
import pytest
_BACKEND_DIR = str(Path(__file__).resolve().parent.parent)
if _BACKEND_DIR not in sys.path:
sys.path.insert(0, _BACKEND_DIR)
# Same external-dep stubs as the other llama_cpp unit tests.
_loggers_stub = _types.ModuleType("loggers")
_loggers_stub.get_logger = lambda name: __import__("logging").getLogger(name)
sys.modules.setdefault("loggers", _loggers_stub)
_structlog_stub = _types.ModuleType("structlog")
_structlog_stub.get_logger = lambda *a, **k: __import__("logging").getLogger("stub")
sys.modules.setdefault("structlog", _structlog_stub)
# Real httpx: a stub would poison a combined run (routes/inference reads its
# attrs at def time).
import httpx # noqa: F401
from core.inference import llama_cpp as llama_cpp_module
from core.inference.llama_server_args import PARALLEL_MAX, PARALLEL_MIN
from core.inference.llama_cpp import LlamaCppBackend
from models.inference import (
InferenceStatusResponse,
LoadRequest,
LoadResponse,
ValidateModelRequest,
)
class _FakeProcess:
def terminate(self):
pass
def wait(self, timeout = None):
return 0
def kill(self):
pass
def poll(self):
return 0
# ── Pydantic contract ────────────────────────────────────────────────
def test_load_request_defaults_n_parallel_none():
assert LoadRequest(model_path = "owner/repo").n_parallel is None
@pytest.mark.parametrize("value", [PARALLEL_MIN, 4, PARALLEL_MAX])
def test_load_request_accepts_in_range_n_parallel(value):
assert LoadRequest(model_path = "owner/repo", n_parallel = value).n_parallel == value
@pytest.mark.parametrize("value", [0, -1, PARALLEL_MAX + 1])
def test_load_request_rejects_out_of_range_n_parallel(value):
with pytest.raises(ValueError):
LoadRequest(model_path = "owner/repo", n_parallel = value)
def test_load_request_round_trips_json_key():
req = LoadRequest.model_validate({"model_path": "owner/repo", "n_parallel": 8})
assert req.n_parallel == 8
assert req.model_dump()["n_parallel"] == 8
def test_validate_request_n_parallel_contract():
# /validate sizes like /load, so it carries the same field and bounds.
assert ValidateModelRequest(model_path = "owner/repo").n_parallel is None
assert (
ValidateModelRequest(model_path = "owner/repo", n_parallel = PARALLEL_MAX).n_parallel
== PARALLEL_MAX
)
with pytest.raises(ValueError):
ValidateModelRequest(model_path = "owner/repo", n_parallel = PARALLEL_MAX + 1)
@pytest.mark.parametrize("model_cls", [LoadResponse, InferenceStatusResponse])
def test_response_models_emit_parallel_slot_fields(model_cls):
kwargs = (
dict(status = "loaded", model = "owner/repo", display_name = "repo", inference = {})
if model_cls is LoadResponse
else {}
)
empty = model_cls(**kwargs).model_dump()
assert empty["requested_parallel_slots"] is None
assert empty["parallel_slots"] is None
dumped = model_cls(**kwargs, requested_parallel_slots = 8, parallel_slots = 4).model_dump()
assert dumped["requested_parallel_slots"] == 8
assert dumped["parallel_slots"] == 4
# ── Shared bounds and their deliberate mirrors ───────────────────────
def _mirrored_bounds(source_path: Path) -> tuple[int, int]:
src = source_path.read_text(encoding = "utf-8")
low = re.search(r"^_PARALLEL_MIN\s*=\s*(\d+)$", src, re.MULTILINE)
high = re.search(r"^_PARALLEL_MAX\s*=\s*(\d+)$", src, re.MULTILINE)
assert low and high, f"{source_path} must define _PARALLEL_MIN/_PARALLEL_MAX"
return int(low.group(1)), int(high.group(1))
def test_run_py_mirror_matches_shared_bounds():
assert _mirrored_bounds(Path(_BACKEND_DIR) / "run.py") == (PARALLEL_MIN, PARALLEL_MAX)
def test_cli_mirror_matches_shared_bounds():
cli = Path(_BACKEND_DIR).parent.parent / "unsloth_cli" / "commands" / "studio.py"
assert _mirrored_bounds(cli) == (PARALLEL_MIN, PARALLEL_MAX)
def test_frontend_mirror_matches_shared_bounds():
# The UI clamps with its own copy; a bumped PARALLEL_MAX that skips it would
# leave the UI silently capping lower.
src = (
Path(_BACKEND_DIR).parent
/ "frontend"
/ "src"
/ "features"
/ "model-picker"
/ "model-config"
/ "per-model-config.ts"
).read_text(encoding = "utf-8")
low = re.search(r"^export const N_PARALLEL_MIN = (\d+);$", src, re.MULTILINE)
high = re.search(r"^export const N_PARALLEL_MAX = (\d+);$", src, re.MULTILINE)
assert low and high, "per-model-config.ts must export N_PARALLEL_MIN/MAX"
assert (int(low.group(1)), int(high.group(1))) == (PARALLEL_MIN, PARALLEL_MAX)
def test_preset_model_reuses_shared_bounds():
# Bounds drifting from PARALLEL_MIN/MAX would 422 valid presets on every sync.
from routes.chat_history import ChatPresetLoadConfig
field = ChatPresetLoadConfig.model_fields["nParallel"]
bounds = {type(m).__name__: getattr(m, "ge", getattr(m, "le", None)) for m in field.metadata}
assert bounds.get("Ge") == PARALLEL_MIN
assert bounds.get("Le") == PARALLEL_MAX
# ── requested_parallel_slots lifecycle ───────────────────────────────
@pytest.fixture
def backend(monkeypatch):
monkeypatch.setattr(LlamaCppBackend, "_kill_orphaned_servers", lambda self: 0)
monkeypatch.setattr(llama_cpp_module.atexit, "register", lambda *_args, **_kwargs: None)
return LlamaCppBackend()
def test_requested_parallel_slots_initial_value_is_one(backend):
assert backend.requested_parallel_slots == 1
def test_requested_parallel_slots_reflects_field(backend):
backend._requested_n_parallel = 8
assert backend.requested_parallel_slots == 8
@pytest.mark.parametrize("value", [None, 0, -2, "not-an-int"])
def test_requested_parallel_slots_invalid_value_falls_back_to_one(backend, value):
backend._requested_n_parallel = value
assert backend.requested_parallel_slots == 1
def test_reset_effective_parallel_slots_also_resets_requested(backend):
backend._requested_n_parallel = 8
backend._commit_effective_parallel_slots(4)
backend._reset_effective_parallel_slots()
assert backend.requested_parallel_slots == 1
assert backend.effective_parallel_slots == 1
def test_unload_resets_requested_parallel_slots(backend):
backend._process = _FakeProcess()
backend._requested_n_parallel = 8
backend.unload_model()
assert backend.requested_parallel_slots == 1
def test_load_model_commits_requested_from_pending_kwargs():
# n_parallel may be reduced before the commit, so the requested value must
# come from the pre-reduction pending snapshot.
src = inspect.getsource(LlamaCppBackend.load_model)
commit = src.find(
'self._requested_n_parallel = max(1, int(_pending_load_kwargs["n_parallel"]))'
)
healthy = src.find("self._healthy = True\n", 0, commit if commit != -1 else None)
snapshot = src.find("self._last_load_kwargs = _pending_load_kwargs")
assert commit != -1, "load_model must commit the requested slot count"
assert healthy != -1 and healthy < commit < snapshot
# ── _already_in_target_state requested-vs-requested branch ───────────
def _loaded_backend() -> LlamaCppBackend:
backend = LlamaCppBackend()
backend._process = _FakeProcess() # is_loaded only checks "is not None"
backend._healthy = True
backend._model_identifier = "owner/repo"
backend._hf_variant = "Q4_K_M"
backend._requested_n_ctx = 8192
backend._cache_type_kv = None
backend._requested_spec_mode = "auto"
backend._chat_template_override = None
backend._is_vision = False
backend._extra_args = None
backend._gguf_path = None
return backend
def _target_state(backend: LlamaCppBackend, n_parallel: int) -> bool:
return backend._already_in_target_state(
gguf_path = None,
model_identifier = "owner/repo",
hf_variant = "Q4_K_M",
n_ctx = 8192,
cache_type_kv = None,
speculative_type = "auto",
chat_template_override = None,
extra_args = None,
is_vision = False,
n_parallel = n_parallel,
)
def test_already_in_target_state_matches_same_slots():
backend = _loaded_backend()
backend._requested_n_parallel = 4
assert _target_state(backend, 4) is True
def test_already_in_target_state_reloads_on_slots_change():
backend = _loaded_backend()
backend._requested_n_parallel = 4
assert _target_state(backend, 8) is False
def test_already_in_target_state_compares_requested_not_effective():
# An identical re-Apply must dedupe even after the fitter reduced the slots.
backend = _loaded_backend()
backend._requested_n_parallel = 8
backend._commit_effective_parallel_slots(4)
assert _target_state(backend, 8) is True
def test_already_in_target_state_ignores_slots_for_diffusion():
# The diffusion runner ignores --parallel, so a slots change must not reload.
backend = _loaded_backend()
backend._is_diffusion = True
backend._requested_n_parallel = 1
assert _target_state(backend, 8) is True
# ── Route wiring (source contract, mirroring test_gpu_memory_mode) ───
def _route_source() -> str:
return (Path(_BACKEND_DIR) / "routes" / "inference.py").read_text(encoding = "utf-8")
def _load_impl_source() -> str:
"""Body of _load_model_impl only, so positional assertions can't be
satisfied by a later function in the module."""
src = _route_source()
body = src[src.index("async def _load_model_impl") :]
return body[: body.index("\n@router.")]
def test_route_resolves_slots_once_before_dedupe_guard_and_load():
load_impl = _load_impl_source()
resolve = load_impl.index("request.n_parallel")
fallback = load_impl.index('getattr(_app_state, "llama_parallel_slots", 1)')
dedupe = load_impl.index("requested_parallel_slots = _n_parallel")
guard = load_impl.index("_guard_chat_load_against_training")
# The GGUF launch kwargs, not the guard's own kwarg (which shares the spelling).
load_kwargs = load_impl.index("_common_load_kwargs = dict(")
assert resolve < dedupe, "resolution must precede the reload dedupe"
assert fallback < dedupe
assert resolve < guard < load_kwargs
# Guard and load kwargs share the resolved value; app.state is read once.
assert load_impl.count("n_parallel = _n_parallel") == 2
assert "n_parallel = _n_parallel" in load_impl[load_kwargs : load_kwargs + 800]
assert load_impl.count('getattr(_app_state, "llama_parallel_slots", 1)') == 1
# getattr, so a direct caller without an app cannot raise, and no re-read.
assert "fastapi_request.app.state" not in load_impl
def test_route_dedupe_compares_requested_slots_and_skips_diffusion():
match_impl = _route_source()[_route_source().index("def _request_matches_loaded_settings") :]
match_impl = match_impl[: match_impl.index("\ndef ")]
assert "requested_parallel_slots is not None" in match_impl
assert "not llama_backend.is_diffusion" in match_impl
assert "llama_backend.requested_parallel_slots" in match_impl
def test_route_echoes_requested_and_effective_slots():
route_src = _route_source()
# Both /load returns plus the /status GGUF branch, via the shared helper.
assert route_src.count("**_parallel_slot_echo(llama_backend)") == 3
def test_parallel_slot_echo_reports_none_for_diffusion():
# Diffusion never commits a count, so echoing the reset placeholder 1 would lie.
from routes.inference import _parallel_slot_echo
backend = _loaded_backend()
backend._requested_n_parallel = 8
backend._commit_effective_parallel_slots(4)
assert _parallel_slot_echo(backend) == {"requested_parallel_slots": 8, "parallel_slots": 4}
backend._is_diffusion = True
assert _parallel_slot_echo(backend) == {
"requested_parallel_slots": None,
"parallel_slots": None,
}
def test_validate_route_prefers_request_n_parallel():
validate_impl = _route_source()[_route_source().index("async def validate_model") :]
resolve = validate_impl.index("request.n_parallel")
fallback = validate_impl.index('"llama_parallel_slots",')
guard = validate_impl.index("_guard_chat_load_against_training")
assert guard < resolve and guard < fallback, "the guard call resolves the slots inline"
def _load_model_source() -> str:
return inspect.getsource(LlamaCppBackend.load_model)
def test_slots_fall_back_to_one_without_kv_unified():
# Without --kv-unified llama-server gives each slot -c/N, so an explicit
# --parallel N shrinks every context window.
src = _load_model_source()
clamp = src.find("supports_kv_unified")
assert clamp != -1, "load_model must check for --kv-unified before honouring the slots"
block = src[clamp : clamp + 700]
assert (
"n_parallel > 1" in src[clamp - 300 : clamp]
), "only an explicit multi-slot load is clamped"
assert "n_parallel = 1" in block
def test_clamp_sits_between_the_echo_and_the_fit():
# The echo reports the ask and the fit uses what launches, so the clamp
# belongs between the two.
src = _load_model_source()
pending = src.index("_pending_load_kwargs")
clamp = src.index("supports_kv_unified")
estimate = src.index("_estimate")
commit = src.index("_commit_effective_parallel_slots")
assert pending < clamp, "the requested count is captured before the clamp"
assert clamp < estimate, "the fit must be estimated from the effective slot count"
assert clamp < commit, "the committed effective count is the clamped one"
# ── Training-guard sizing ────────────────────────────────────────────
def _write_swa_gguf(path: Path) -> str:
"""Smallest DiffusionGemma-shaped header the KV estimator can size: the
canvas marker routing it to the diffusion runner, plus the sliding-window
dims that make llama.cpp's SWA cache slot-scaled."""
def _kv_str(key: str, value: str) -> bytes:
kb, vb = key.encode(), value.encode()
return (
struct.pack("<Q", len(kb)) + kb + struct.pack("<I", 8) + struct.pack("<Q", len(vb)) + vb
)
def _kv_u32(key: str, value: int) -> bytes:
kb = key.encode()
return struct.pack("<Q", len(kb)) + kb + struct.pack("<I", 4) + struct.pack("<I", value)
arch = "diffusion-gemma"
kvs = [
_kv_str("general.architecture", arch),
_kv_u32("diffusion.canvas_length", 256),
_kv_u32(f"{arch}.context_length", 32768),
_kv_u32(f"{arch}.block_count", 30),
_kv_u32(f"{arch}.attention.head_count", 16),
_kv_u32(f"{arch}.attention.head_count_kv", 8),
_kv_u32(f"{arch}.attention.key_length", 512),
_kv_u32(f"{arch}.attention.value_length", 512),
_kv_u32(f"{arch}.attention.sliding_window", 1024),
_kv_u32(f"{arch}.attention.key_length_swa", 256),
_kv_u32(f"{arch}.attention.value_length_swa", 256),
]
path.write_bytes(struct.pack("<IIQQ", 0x46554747, 3, 0, len(kvs)) + b"".join(kvs))
return str(path)
def _guard_required_gb(
monkeypatch,
gguf_path: str,
*,
n_parallel: int,
diffusion,
caps = None,
) -> float:
"""Run the training guard over a local GGUF and return the size it budgeted."""
import routes.inference as inf
seen = {}
core_training = _types.ModuleType("core.training")
core_training.get_training_backend = lambda: _types.SimpleNamespace(
is_training_active = lambda: True
)
def _can_load(**kwargs):
seen.update(kwargs)
return True, {"mode": "single_device"}
training_vram = _types.ModuleType("routes.training_vram")
training_vram.can_load_chat_during_training = _can_load
monkeypatch.setitem(sys.modules, "core.training", core_training)
monkeypatch.setitem(sys.modules, "routes.training_vram", training_vram)
monkeypatch.setattr(inf, "_classify_diffusion_gguf", lambda _config: diffusion)
monkeypatch.setattr(LlamaCppBackend, "_is_vulkan_backend", staticmethod(lambda *a, **k: False))
monkeypatch.setattr(LlamaCppBackend, "_effective_gpu_count", staticmethod(lambda *a, **k: 1))
monkeypatch.setattr(LlamaCppBackend, "_diffusion_gpu_arg", staticmethod(lambda *a, **k: "0"))
# Pin the --kv-unified probe so the estimate cannot depend on a locally
# installed llama-server. Default "no binary found" leaves the count alone.
monkeypatch.setattr(
LlamaCppBackend,
"probe_server_capabilities",
classmethod(lambda cls, binary = None: dict(caps or {})),
)
inf._guard_chat_load_against_training(
_types.SimpleNamespace(is_gguf = True, gguf_file = gguf_path, identifier = "local/model"),
model_identifier = "local/model",
hf_token = None,
load_in_4bit = False,
max_seq_length = 8192,
requested_gpu_ids = None,
n_parallel = n_parallel,
gpu_memory_mode = "auto",
)
return seen["required_override_gb"]
def test_training_guard_sizes_a_diffusion_gguf_at_one_slot(monkeypatch, tmp_path):
# Diffusion ignores --parallel, so slots must not inflate the estimate and 409
# a load that would have fitted beside training.
gguf = _write_swa_gguf(tmp_path / "diffusion.gguf")
one = _guard_required_gb(monkeypatch, gguf, n_parallel = 1, diffusion = True)
many = _guard_required_gb(monkeypatch, gguf, n_parallel = 8, diffusion = True)
assert one == many
def test_training_guard_still_sizes_slots_for_an_ordinary_gguf(monkeypatch, tmp_path):
# llama-server does allocate per-slot SWA cells, so the reduction above must
# be scoped to diffusion and not flatten every GGUF to one slot.
gguf = _write_swa_gguf(tmp_path / "chat.gguf")
one = _guard_required_gb(monkeypatch, gguf, n_parallel = 1, diffusion = False)
many = _guard_required_gb(monkeypatch, gguf, n_parallel = 8, diffusion = False)
assert many > one
def test_training_guard_sizes_one_slot_when_the_binary_has_no_kv_unified(monkeypatch, tmp_path):
# load_model clamps a multi-slot request to 1 on such a build, where each slot
# carries its own SWA stream, so sizing the asked count would 409 a load that fits.
gguf = _write_swa_gguf(tmp_path / "chat.gguf")
old = {"found": True, "supports_kv_unified": False}
one = _guard_required_gb(monkeypatch, gguf, n_parallel = 1, diffusion = False, caps = old)
many = _guard_required_gb(monkeypatch, gguf, n_parallel = 8, diffusion = False, caps = old)
assert one == many
def test_training_guard_sizes_every_slot_when_kv_unified_exists(monkeypatch, tmp_path):
# The clamp is scoped to binaries that cannot serve the slots; a capable one
# really does allocate the SWA window per slot.
gguf = _write_swa_gguf(tmp_path / "chat.gguf")
new = {"found": True, "supports_kv_unified": True}
one = _guard_required_gb(monkeypatch, gguf, n_parallel = 1, diffusion = False, caps = new)
many = _guard_required_gb(monkeypatch, gguf, n_parallel = 8, diffusion = False, caps = new)
assert many > one
def test_training_guard_keeps_slots_for_an_unclassified_gguf(monkeypatch, tmp_path):
# None = inconclusive header, so keep the larger estimate rather than
# under-size against training.
gguf = _write_swa_gguf(tmp_path / "unknown.gguf")
one = _guard_required_gb(monkeypatch, gguf, n_parallel = 1, diffusion = None)
many = _guard_required_gb(monkeypatch, gguf, n_parallel = 8, diffusion = None)
assert many > one