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
Admit generations against the KV cache, not just the slot count (#9392)
Daniel Han6504fb56a317
diff --git a/studio/backend/core/inference/llama_admission.py b/studio/backend/core/inference/llama_admission.pyindex b893cfd4cde..6caefcefeb4 100644--- a/studio/backend/core/inference/llama_admission.py+++ b/studio/backend/core/inference/llama_admission.py@@ -32,6 +32,9 @@ ADMISSION_QUEUE_TIMEOUT_ENV = "UNSLOTH_LLAMA_ADMISSION_QUEUE_TIMEOUT"ADMISSION_KEEPALIVE_INTERVAL_ENV = "UNSLOTH_LLAMA_ADMISSION_KEEPALIVE_INTERVAL"ADMISSION_MAX_QUEUE_ENV = "UNSLOTH_LLAMA_ADMISSION_MAX_QUEUE"ADMISSION_QUEUE_PER_SLOT_ENV = "UNSLOTH_LLAMA_ADMISSION_QUEUE_PER_SLOT"+# Off restores slot-only admission. The escape hatch for a backend whose reported+# context length does not match the cache llama-server actually allocated.+ADMISSION_KV_BUDGET_ENV = "UNSLOTH_LLAMA_ADMISSION_KV_BUDGET"# The UNSLOTH_OPENAI_COMPAT_* spellings predate this queue being shared with the# Anthropic /v1/messages route (same llama-server slots). Still honored; the@@ -56,6 +59,11 @@ DEFAULT_ADMISSION_QUEUE_PER_SLOT = 16# load downshifted to fit VRAM) keeps the depth it had before scaling existed# rather than dropping to 16 and rejecting callers that used to queue.DEFAULT_ADMISSION_MIN_QUEUE = 64+# Token accounting is on by default. Slot-only admission overcommits a unified KV+# cache: llama.cpp with --parallel N --kv-unified allocates ONE cache of n_ctx but+# reports n_ctx_slot = n_ctx to every slot, so N generations are admitted against a+# cache that may hold one. When they collide, llama.cpp kills every task involved.+DEFAULT_ADMISSION_KV_BUDGET = Truedef _executor_workers() -> int:@@ -142,6 +150,7 @@ class LlamaAdmissionConfig:# Unconditional floor on the scaled line. The env path clears it when the# operator sets QUEUE_PER_SLOT, so only the default multiplier is floored.min_queue: Optional[int] = DEFAULT_ADMISSION_MIN_QUEUE+ kv_budget: bool = DEFAULT_ADMISSION_KV_BUDGETdef queue_limit(self, capacity: int) -> Optional[int]:"""How many callers may line up for a pool of ``capacity`` slots.@@ -166,6 +175,10 @@ class LlamaAdmissionSnapshot:active: intqueued: intfree: int = 0+ # KV tokens held by live leases, and the cache they are drawn from. budget 0+ # means token accounting is off, so committed carries no meaning.+ committed: int = 0+ budget: int = 0class LlamaAdmissionError(Exception):@@ -276,6 +289,7 @@ def llama_admission_config_from_env() -> LlamaAdmissionConfig:DEFAULT_ADMISSION_KEEPALIVE_INTERVAL_S,),max_queue = max_queue,+ kv_budget = _bool_env(ADMISSION_KV_BUDGET_ENV, DEFAULT_ADMISSION_KV_BUDGET),)@@ -285,15 +299,27 @@ class _Waiter:future: asyncio.Futurecancelled: bool = Falsegranted_lease: Optional["LlamaAdmissionLease"] = None+ # KV tokens this caller will occupy once admitted. Read while the head of the+ # line is considered, so a large request cannot be overtaken by small ones.+ tokens: int = 0class LlamaAdmissionLease:- __slots__ = ("_queue", "_slot", "_released", "_release_lock", "_parked", "_budgeted")+ __slots__ = (+ "_queue",+ "_slot",+ "_released",+ "_release_lock",+ "_parked",+ "_budgeted",+ "_tokens",+ )def __init__(self,queue: Optional["LlamaAdmissionQueue"],slot: Optional[int] = None,+ tokens: int = 0,):self._queue = queueself._slot = slot@@ -301,6 +327,9 @@ class LlamaAdmissionLease:self._release_lock = threading.Lock()self._parked = Falseself._budgeted = False+ # Returned to the queue on release, not on park: a parked holder has+ # stopped decoding but llama-server still holds its KV until the task ends.+ self._tokens = max(0, int(tokens or 0))@propertydef slot(self) -> Optional[int]:@@ -411,7 +440,7 @@ class LlamaAdmissionLease:if queue is not None:if parked:queue.unpark()- queue.release(self._slot)+ queue.release(self._slot, self._tokens)async def __aenter__(self) -> "LlamaAdmissionLease":return self@@ -521,6 +550,8 @@ class LlamaAdmissionQueue:"_parked","_unpark_tickets","_unpark_seq",+ "_committed",+ "_budget",)def __init__(self, key: str):@@ -541,6 +572,10 @@ class LlamaAdmissionQueue:# bare count deadlocked: every approved holder blocked every other one.self._unpark_tickets: Deque[int] = deque()self._unpark_seq = 0+ # KV tokens held by live leases, against the cache size the caller reports.+ # 0 budget disables the check, which is what every pre-existing caller gets.+ self._committed = 0+ self._budget = 0def _resize_pool_locked(self, capacity: int) -> None:# Slots past a shrunk capacity retire when their holder releases them.@@ -549,22 +584,69 @@ class LlamaAdmissionQueue:self._capacity = capacityself._free = [slot for slot in range(capacity) if not self._in_use >> slot & 1]- def _can_admit_locked(self, reserved: int) -> bool:+ def _fits_budget_locked(self, tokens: int) -> bool:+ """Whether ``tokens`` more KV may be committed.++ A caller is always admitted when nothing else holds KV, however large it is.+ Its request may still be refused by llama-server, but that refusal names both+ token counts and the setting to change, whereas refusing here would strand it+ forever.++ The escape asks whether anything is COMMITTED, not whether a slot is held.+ ``try_park`` hands a slot back while its holder waits on a tool approval, which+ drops ``_held`` to zero even though llama-server still holds that lease's KV. A+ held-slot test therefore admitted the next caller unconditionally: park a 1500+ token lease against a 2048 token budget, and the next 1500 token one sailed+ through to 3000 committed, which is the collision this accounting exists to stop.+ """+ if self._budget <= 0 or tokens <= 0:+ return True+ if self._committed == 0:+ return True+ return self._committed + tokens <= self._budget++ def _can_admit_locked(+ self,+ reserved: int,+ tokens: int = 0,+ ) -> bool:# Slots still held above a shrunk capacity keep occupying the backend, so# count every held slot against the ceiling, not just the ids below it.# ``reserved`` holds slots back for approved holders waiting to resume;# without it a stream of new arrivals took the next slot, forever.- return bool(self._free) and (self._held + reserved) < self._capacity+ if not (bool(self._free) and (self._held + reserved) < self._capacity):+ return False+ # A free slot is not enough: with --kv-unified every slot reports the full+ # n_ctx, so the pool can hand out more slots than the one cache can serve.+ return self._fits_budget_locked(tokens)- def _take_slot_locked(self, reserved: int) -> Optional[int]:- if not self._can_admit_locked(reserved):+ def _take_slot_locked(+ self,+ reserved: int,+ tokens: int = 0,+ ) -> Optional[int]:+ if not self._can_admit_locked(reserved, tokens):return Noneslot = self._free.pop()self._in_use |= 1 << slotself._held += 1+ self._committed += max(0, tokens)return slot- def reserve(self, *, capacity: int, config: LlamaAdmissionConfig) -> LlamaAdmissionReservation:+ def reserve(+ self,+ *,+ capacity: int,+ config: LlamaAdmissionConfig,+ tokens: Optional[int] = None,+ budget: Optional[int] = None,+ ) -> LlamaAdmissionReservation:+ """Take a serving slot, waiting in FIFO order when none is available.++ ``tokens`` is the KV this caller will occupy and ``budget`` the size of the+ cache it is drawn from. Leaving either unset (or ``kv_budget`` off) keeps+ the slot-only behaviour every caller had before token accounting existed.+ """capacity = max(1, int(capacity or 1))if not config.enabled:return LlamaAdmissionReservation(@@ -573,19 +655,27 @@ class LlamaAdmissionQueue:snapshot = LlamaAdmissionSnapshot(self.key, capacity, 0, 0, capacity),)+ if not config.kv_budget:+ tokens = budget = None+ cost = max(0, int(tokens or 0))+loop = asyncio.get_running_loop()with self._lock:self._resize_pool_locked(capacity)+ # Re-read every reserve: a reload can relaunch llama-server at a+ # different -c, and a stale budget would keep admitting against a+ # cache that no longer exists.+ self._budget = max(0, int(budget or 0))self._grant_waiters_locked()if not self._waiters:- slot = self._take_slot_locked(len(self._unpark_tickets))+ slot = self._take_slot_locked(len(self._unpark_tickets), cost)if slot is not None:# No snapshot here: callers read it through snapshot_now(),# which re-reads the queue, so building one per admitted# request would be pure allocation on the hot path.return LlamaAdmissionReservation(queue = self,- lease = LlamaAdmissionLease(self, slot),+ lease = LlamaAdmissionLease(self, slot, cost),)limit = config.queue_limit(self._capacity)if limit is not None and self._live_waiters_locked() >= limit:@@ -596,6 +686,7 @@ class LlamaAdmissionQueue:waiter = _Waiter(loop = loop,future = loop.create_future(),+ tokens = cost,)self._waiters.append(waiter)return LlamaAdmissionReservation(@@ -612,9 +703,18 @@ class LlamaAdmissionQueue:if slot < self._capacity:self._free.append(slot)- def release(self, slot: Optional[int]) -> None:+ def release(+ self,+ slot: Optional[int],+ tokens: int = 0,+ ) -> None:with self._lock:self._release_slot_locked(slot)+ # Floored at 0 so a double release cannot drive the pool negative and+ # let the budget admit callers the cache cannot hold. The lease's own+ # _released guard makes that unreachable; this keeps it unreachable if+ # a future caller releases by hand.+ self._committed = max(0, self._committed - max(0, int(tokens or 0)))self._grant_waiters_locked()def try_park(self, slot: Optional[int]) -> bool:@@ -713,20 +813,28 @@ class LlamaAdmissionQueue:def _grant_waiters_locked(self) -> None:# Dead waiters are skipped as they are popped, so no prune is needed here.- while self._waiters and self._can_admit_locked(len(self._unpark_tickets)):+ # The head's own cost is what is tested, not a zero: granting past a large+ # waiter whenever a small one fits would starve it for as long as traffic+ # keeps arriving. Head-of-line blocking is the fair trade here, and it+ # matches the FIFO the rest of this queue already promises.+ while self._waiters and self._can_admit_locked(+ len(self._unpark_tickets), self._waiters[0].tokens+ ):waiter = self._waiters.popleft()if waiter.cancelled or waiter.future.done():continue- slot = self._take_slot_locked(len(self._unpark_tickets))- lease = LlamaAdmissionLease(self, slot)+ slot = self._take_slot_locked(len(self._unpark_tickets), waiter.tokens)+ lease = LlamaAdmissionLease(self, slot, waiter.tokens)waiter.granted_lease = leasetry:waiter.loop.call_soon_threadsafe(self._deliver_lease, waiter, lease)except RuntimeError:# Waiter's loop is gone. Reclaim the slot; leaving the bit set- # would strand it, since _free is rebuilt from the bitmask.+ # would strand it, since _free is rebuilt from the bitmask. The+ # tokens go back with it: nothing will ever release this lease.waiter.granted_lease = Noneself._release_slot_locked(slot)+ self._committed = max(0, self._committed - max(0, waiter.tokens))def _deliver_lease(self, waiter: _Waiter, lease: LlamaAdmissionLease) -> None:# Runs on the waiter's own loop thread, which is also the only thread that@@ -778,6 +886,8 @@ class LlamaAdmissionQueue:len(self._free),max(0, self._capacity - self._held - len(self._unpark_tickets)),),+ committed = self._committed,+ budget = self._budget,)diff --git a/studio/backend/routes/inference.py b/studio/backend/routes/inference.pyindex 345294fa050..cc2147f6519 100644--- a/studio/backend/routes/inference.py+++ b/studio/backend/routes/inference.py@@ -62,6 +62,7 @@ from core.inference.audio_errors import (from core.inference.context_window import (estimate_message_tokens as _estimate_message_tokens,estimate_messages_tokens as _estimate_messages_tokens,+ estimate_messages_tokens_dense,truncate_oldest_messages as _truncate_oldest_messages,)from core.inference.stream_errors import LlamaStreamError@@ -1490,15 +1491,169 @@ def _openai_llama_admission_capacity(request: Optional[Request], llama_backend =return _positive_int_or_none(slots) or 1+def _openai_llama_admission_budget(llama_backend) -> Optional[int]:+ """KV tokens the running llama-server actually allocated, or None if unknown.++ ``_kv_cache_context_total`` is the aggregate, and is preferred where the backend+ has it. ``context_length`` is NOT that once the server has been read back:+ ``_reconcile_effective_ctx_with_server`` adopts the PER-SLOT ``n_ctx`` from+ ``default_generation_settings`` into it, and computes the total alongside as+ ``n_ctx * slots`` (slots being 1 only under ``--kv-unified``). Studio appends+ that flag only when ``n_parallel > 1`` and the binary supports it, so a build+ without it, or a user ``--no-kv-unified``, gives N private caches while+ ``context_length`` names one of them: an N-fold under-budget that collapses+ concurrency to a single generation.++ Falls back to ``context_length`` when the total is unset (nothing has been read+ back yet, in which case the two agree), and None when the backend cannot say,+ which keeps slot-only admission rather than inventing a budget.+ """+ total = _positive_int_or_none(getattr(llama_backend, "_kv_cache_context_total", None))+ return total or _positive_int_or_none(getattr(llama_backend, "context_length", None))+++def _openai_llama_admission_extra_prompt_tokens(payload) -> int:+ """Prompt the request carries OUTSIDE ``messages``, in tokens.++ OpenAI tool definitions are rendered into the llama-server prompt, and Anthropic+ keeps ``system`` and ``tools`` separate until they are translated. Sizing only the+ message list let two requests with small messages but large system instructions or+ JSON tool schemas both be admitted on a severe undercount.++ Serialised and charged at the dense rate, since a JSON schema is punctuation-heavy+ and the four-chars-per-token rule flatters it.+ """+ extra = 0+ for attribute in ("system", "tools", "tool_choice", "instructions"):+ value = getattr(payload, attribute, None)+ if value is None or isinstance(value, (bool, int, float)):+ continue+ try:+ text = value if isinstance(value, str) else json.dumps(value, default = str)+ except Exception:+ continue+ if text:+ extra += estimate_messages_tokens_dense([{"role": "system", "content": text}])+ return extra+++def _openai_llama_admission_media_tokens(payload) -> int:+ """Media the request carries in Unsloth's legacy top-level fields, in tokens.++ Studio's own composer sends every attachment as ``image_base64`` /+ ``audio_base64`` / ``video_base64``, never as ``messages`` content parts, and the+ generation path splices them into the prompt AFTER this estimate is taken+ (``_openai_messages_for_gguf_chat``, ``_inject_audio_part``,+ ``_inject_video_part``). Charging only ``messages`` therefore priced an image at+ zero while llama.cpp's mtmd embeddings occupy real KV positions, so two+ media-heavy chats with a line of text each were admitted against a cache that+ holds one.++ Sized as the same media inlined as a data URL is already sized, so the two+ spellings of one request cost the same rather than 30x apart.+ """+ extra = 0+ for attribute in ("image_base64", "audio_base64", "video_base64"):+ value = getattr(payload, attribute, None)+ if isinstance(value, str) and value:+ extra += max(1, len(value) // 4)+ return extra+++def _openai_llama_admission_tokens(+ payload, *, budget: Optional[int], capacity: int, tool_loop: bool = False+) -> Optional[int]:+ """KV a request will occupy: what is sent, plus what it may generate.++ Uses the dense estimator, not the plain one. Undercounting is the failure this+ accounting exists to prevent, and four-chars-per-token undercounts CJK by about+ 2x, which would hand out a slot the cache cannot back.++ A shape with no messages (``/completions`` takes a prompt string) falls back to+ an equal share of the cache: charging it the whole budget would serialise that+ route, and charging it nothing would restore the overcommit.+ """+ if not budget:+ return None+ messages = getattr(payload, "messages", None)+ if isinstance(messages, list) and messages:+ try:+ prompt_tokens = estimate_messages_tokens_dense(+ [m if isinstance(m, dict) else m.model_dump() for m in messages]+ )+ prompt_tokens += _openai_llama_admission_extra_prompt_tokens(payload)+ prompt_tokens += _openai_llama_admission_media_tokens(payload)+ except Exception:+ prompt_tokens = None+ else:+ prompt_tokens = None+ if prompt_tokens is None:+ return max(1, budget // max(1, capacity))+ # The same helper generation honours, not the raw field. A request that sets only+ # the supported max_completion_tokens and leaves the deprecated max_tokens unset+ # would otherwise reserve its prompt and none of its output allowance.+ cap = _positive_int_or_none(+ _effective_openai_max_tokens_from_values(+ getattr(payload, "max_tokens", None),+ getattr(payload, "max_completion_tokens", None),+ )+ )+ if cap is None:+ # No cap at all. _build_passthrough_payload then sends max_tokens = backend_ctx,+ # so generation may run until the window is full, and reserving nothing let short+ # uncapped prompts hold tiny commitments while each consumed most of the cache.+ # The honest reservation is the rest of the budget, which does serialise+ # concurrent uncapped requests. That is the true cost of not naming a cap: the+ # alternative is admitting two runs that llama.cpp will then kill.+ output_tokens = max(0, budget - prompt_tokens)+ else:+ output_tokens = cap+ # A tool loop reserves the whole cache. One lease covers up to 25 rounds, and each+ # round appends its tool results and re-sends the conversation, so a request that+ # starts small can approach the full window while its commitment stays at the+ # opening estimate. Re-costing per round would mean threading a callback through the+ # generator; reserving the upper bound is the same guarantee without that surface,+ # at the price of serialising concurrent tool requests. That price is real, and it+ # is the one this accounting exists to charge: the alternative is admitting rounds+ # the cache cannot hold and letting llama.cpp kill both.+ #+ # Keyed on the resolved execution path, NOT on payload.tools. The loop opens on+ # `enable_tools`, `mcp_enabled`, the CLI --enable-tools policy or a checkpoint+ # repair, none of which need a client `tools` array, so keying on the array+ # undercharged Studio's own tool traffic; and a passthrough or /responses request+ # that merely forwards `tools` to llama-server runs ONE generation per HTTP call,+ # so charging it the whole cache serialised the client-driven loop for nothing.+ if tool_loop:+ return budget+ # Clamped to the budget so an oversized request stays schedulable: the queue+ # admits it alone rather than stranding it, and llama-server refuses it with a+ # message naming both counts.+ return max(1, min(budget, prompt_tokens + output_tokens))++def _openai_llama_admission_reserve(- *, request: Optional[Request], llama_backend+ *,+ request: Optional[Request],+ llama_backend,+ payload = None,+ tool_loop: bool = False,) -> tuple[LlamaAdmissionReservation, LlamaAdmissionConfig]:config = llama_admission_config_from_env()capacity = _openai_llama_admission_capacity(request, llama_backend)key = str(getattr(llama_backend, "base_url", "llama-server"))+ budget = _openai_llama_admission_budget(llama_backend)reservation = get_llama_admission_queue(key).reserve(capacity = capacity,config = config,+ budget = budget,+ tokens = _openai_llama_admission_tokens(+ payload,+ budget = budget,+ capacity = capacity,+ tool_loop = tool_loop,+ )+ if payload is not None+ else None,)return reservation, config@@ -15289,6 +15444,11 @@ async def openai_chat_completions(reservation, admission_config = _openai_llama_admission_reserve(request = request,llama_backend = llama_backend,+ payload = payload,+ # This branch IS the resolved server-side loop (use_tools is true+ # here whether it came from tools, enable_tools, mcp_enabled, the+ # CLI policy or a checkpoint repair), so charge the upper bound.+ tool_loop = True,)except LlamaAdmissionQueueFull as exc:_llama_admission_log(@@ -15996,6 +16156,7 @@ async def openai_chat_completions(reservation, admission_config = _openai_llama_admission_reserve(request = request,llama_backend = llama_backend,+ payload = payload,)except LlamaAdmissionQueueFull as exc:_tracker.__exit__(None, None, None)@@ -16330,6 +16491,7 @@ async def openai_chat_completions(reservation, admission_config = _openai_llama_admission_reserve(request = request,llama_backend = llama_backend,+ payload = payload,)except LlamaAdmissionQueueFull as exc:_llama_admission_log(@@ -19539,6 +19701,10 @@ async def _responses_stream(reservation, admission_config = _openai_llama_admission_reserve(request = request,llama_backend = llama_backend,+ # chat_req, not payload: a ResponsesRequest carries `input` and+ # `max_output_tokens`, so the estimator found no `messages` and fell back to+ # one equal cache share no matter how large the request really was.+ payload = chat_req,)except LlamaAdmissionQueueFull as exc:_llama_admission_log(@@ -21530,10 +21696,13 @@ async def anthropic_messages(else:reservation.cancel()- async def _admitted_anthropic(coro):+ async def _admitted_anthropic(coro, *, tool_loop: bool = False):try:reservation, admission_config = _openai_llama_admission_reserve(- request = request, llama_backend = llama_backend+ request = request,+ llama_backend = llama_backend,+ payload = payload,+ tool_loop = tool_loop,)except LlamaAdmissionQueueFull as exc:coro.close()@@ -21795,7 +21964,9 @@ async def anthropic_messages(parse_think = _think_parsing_expected(llama_backend, payload),think_provenance = _think_prov,count_template_kwargs = _anthropic_count_template_kwargs(llama_backend, payload),- )+ ),+ # Same server-side loop the chat route runs, up to 25 rounds on one lease.+ tool_loop = True,)return await _admitted_anthropic(_anthropic_tool_non_streaming(@@ -21807,7 +21978,8 @@ async def anthropic_messages(parse_think = _think_parsing_expected(llama_backend, payload),think_provenance = _think_prov,cancel_event = cancel_event,- )+ ),+ tool_loop = True,)# ── No-tool path ──────────────────────────────────────────@@ -23741,6 +23913,7 @@ async def _openai_passthrough_stream(reservation, admission_config = _openai_llama_admission_reserve(request = request,llama_backend = llama_backend,+ payload = payload,)except LlamaAdmissionQueueFull as exc:_tracker.__exit__(None, None, None)@@ -24776,6 +24949,7 @@ async def _openai_passthrough_non_streaming(reservation, admission_config = _openai_llama_admission_reserve(request = request,llama_backend = llama_backend,+ payload = payload,)except LlamaAdmissionQueueFull as exc:_llama_admission_log(diff --git a/studio/backend/tests/test_llama_admission_kv_budget.py b/studio/backend/tests/test_llama_admission_kv_budget.pynew file mode 100644index 00000000000..81208daa08f--- /dev/null+++ b/studio/backend/tests/test_llama_admission_kv_budget.py@@ -0,0 +1,532 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""Admission must count KV tokens, not just serving slots.++The failure these cover happened live. Two chats generating at once against a model+loaded at ``-c 2048``:++ srv send_error: task id = 1101, error: Context size has been exceeded.+ slot release: id 0 | task 1101 | n_tokens = 565, truncated = 0+ srv send_error: task id = 714, error: Context size has been exceeded.+ slot release: id 1 | task 714 | n_tokens = 1485, truncated = 0++565 + 1485 = 2050 against a 2048-token cache, ``truncated = 0`` on both: neither request+was too long on its own. llama.cpp killed both tasks, taking a chat reply and a Deep+Research run with it.++The cause is that ``--parallel 4 --kv-unified`` allocates ONE cache of ``n_ctx`` and then+reports ``n_ctx_slot = n_ctx`` to every slot, so four generations can each be admitted+believing they own the whole window.+"""++import asyncio++import pytest++from core.inference.llama_admission import (+ DEFAULT_ADMISSION_KV_BUDGET,+ LlamaAdmissionConfig,+ LlamaAdmissionQueue,+)+++def _config(**overrides):+ return LlamaAdmissionConfig(**overrides)+++async def _reserve(+ queue,+ *,+ capacity,+ tokens,+ budget,+ config = None,+):+ return queue.reserve(+ capacity = capacity,+ config = config or _config(),+ tokens = tokens,+ budget = budget,+ )+++def _run(coro):+ return asyncio.run(coro)+++class TestTheBudgetIsEnforced:+ def test_two_requests_that_together_overflow_the_cache_do_not_both_run(self):+ """The live failure, in miniature. 1500 + 1500 against 2048."""++ async def scenario():+ queue = LlamaAdmissionQueue("test")+ first = await _reserve(queue, capacity = 4, tokens = 1500, budget = 2048)+ lease = first.lease_nowait()+ assert lease is not None, "the first request owns the cache"+ second = await _reserve(queue, capacity = 4, tokens = 1500, budget = 2048)+ # A slot is free, but the cache is not. Before token accounting this+ # returned a lease and llama.cpp killed both tasks.+ assert second.lease_nowait() is None+ return queue, lease, second++ queue, lease, second = _run(scenario())+ assert queue.snapshot().committed == 1500++ def test_small_requests_still_run_concurrently(self):+ """The regression guard: this must not become "one request at a time"."""++ async def scenario():+ queue = LlamaAdmissionQueue("test")+ leases = []+ for _ in range(4):+ reservation = await _reserve(queue, capacity = 4, tokens = 400, budget = 2048)+ leases.append(reservation.lease_nowait())+ return leases++ leases = _run(scenario())+ assert all(lease is not None for lease in leases), "4 x 400 fits in 2048"++ def test_a_lone_oversized_request_is_admitted_rather_than_stranded(self):+ """It will be refused by llama-server, with a message naming both counts.+ Refusing it here would strand it forever, since nothing else is running."""++ async def scenario():+ queue = LlamaAdmissionQueue("test")+ reservation = await _reserve(queue, capacity = 4, tokens = 3000, budget = 2048)+ return reservation.lease_nowait()++ assert _run(scenario()) is not None++ def test_releasing_returns_the_tokens(self):+ async def scenario():+ queue = LlamaAdmissionQueue("test")+ first = await _reserve(queue, capacity = 4, tokens = 1500, budget = 2048)+ lease = first.lease_nowait()+ assert queue.snapshot().committed == 1500+ lease.release()+ assert queue.snapshot().committed == 0+ # And the cache is available again.+ second = await _reserve(queue, capacity = 4, tokens = 1500, budget = 2048)+ return second.lease_nowait()++ assert _run(scenario()) is not None++ def test_a_double_release_returns_the_tokens_only_once(self):+ """A second subtraction would drive the pool negative and let the budget+ admit callers the cache cannot hold."""++ async def scenario():+ queue = LlamaAdmissionQueue("test")+ first = await _reserve(queue, capacity = 4, tokens = 1000, budget = 2048)+ lease = first.lease_nowait()+ lease.release()+ lease.release()+ return queue.snapshot()++ assert _run(scenario()).committed == 0+++class TestBackwardsCompatibility:+ def test_no_budget_reproduces_slot_only_admission(self):+ """Every caller that does not pass a budget must behave exactly as before."""++ async def scenario():+ queue = LlamaAdmissionQueue("test")+ leases = []+ for _ in range(4):+ reservation = queue.reserve(capacity = 4, config = _config())+ leases.append(reservation.lease_nowait())+ return leases++ leases = _run(scenario())+ assert all(lease is not None for lease in leases)++ def test_the_env_flag_off_restores_slot_only_admission(self):+ async def scenario():+ queue = LlamaAdmissionQueue("test")+ config = _config(kv_budget = False)+ first = await _reserve(+ queue,+ capacity = 4,+ tokens = 1500,+ budget = 2048,+ config = config,+ )+ assert first.lease_nowait() is not None+ second = await _reserve(+ queue,+ capacity = 4,+ tokens = 1500,+ budget = 2048,+ config = config,+ )+ return second.lease_nowait()++ assert _run(scenario()) is not None, "the escape hatch must overcommit as before"++ def test_token_accounting_is_on_by_default(self):+ assert DEFAULT_ADMISSION_KV_BUDGET is True+ assert _config().kv_budget is True++ def test_a_zero_budget_disables_the_check(self):+ async def scenario():+ queue = LlamaAdmissionQueue("test")+ first = await _reserve(queue, capacity = 4, tokens = 5000, budget = 0)+ assert first.lease_nowait() is not None+ second = await _reserve(queue, capacity = 4, tokens = 5000, budget = 0)+ return second.lease_nowait()++ assert _run(scenario()) is not None+++class TestTheRouteHelpers:+ def test_the_budget_is_the_backends_own_context_length(self):+ from types import SimpleNamespace++ import routes.inference as routes_inference++ backend = SimpleNamespace(context_length = 2048)+ assert routes_inference._openai_llama_admission_budget(backend) == 2048++ def test_an_unreadable_context_length_means_no_budget(self):+ from types import SimpleNamespace++ import routes.inference as routes_inference+ for value in (None, 0, -1, "nonsense"):+ backend = SimpleNamespace(context_length = value)+ assert routes_inference._openai_llama_admission_budget(backend) is None++ def test_the_cost_is_the_prompt_plus_the_output_allowance(self):+ from types import SimpleNamespace++ import routes.inference as routes_inference++ payload = SimpleNamespace(+ messages = [{"role": "user", "content": "x" * 4000}],+ max_tokens = 256,+ )+ cost = routes_inference._openai_llama_admission_tokens(+ payload,+ budget = 8192,+ capacity = 4,+ )+ assert cost is not None and cost > 256, "the prompt must be counted, not just the output"++ def test_the_cost_is_clamped_to_the_budget(self):+ from types import SimpleNamespace++ import routes.inference as routes_inference++ payload = SimpleNamespace(+ messages = [{"role": "user", "content": "x" * 100_000}],+ max_tokens = 4096,+ )+ cost = routes_inference._openai_llama_admission_tokens(+ payload,+ budget = 2048,+ capacity = 4,+ )+ # Clamped so the queue admits it alone rather than stranding it.+ assert cost == 2048++ def test_a_shape_with_no_messages_reserves_a_fair_share(self):+ from types import SimpleNamespace++ import routes.inference as routes_inference++ payload = SimpleNamespace(prompt = "raw completion text", max_tokens = 128)+ cost = routes_inference._openai_llama_admission_tokens(+ payload,+ budget = 2048,+ capacity = 4,+ )+ # Not the whole budget (that would serialise /completions) and not nothing+ # (that would restore the overcommit).+ assert cost == 512++ def test_no_budget_means_no_cost(self):+ from types import SimpleNamespace++ import routes.inference as routes_inference++ payload = SimpleNamespace(messages = [{"role": "user", "content": "hi"}], max_tokens = 8)+ assert (+ routes_inference._openai_llama_admission_tokens(+ payload,+ budget = None,+ capacity = 4,+ )+ is None+ )+++class TestParkedLeasesStillHoldTheirKV:+ """A parked holder gives its SLOT back, not its cache.++ `try_park` hands the slot to the pool while its holder waits on a tool approval, so+ `_held` drops to zero even though llama-server still holds that lease's KV. The+ deadlock escape used to ask whether a slot was held, which made a parked lease look+ like an empty backend and admitted the next caller unconditionally.+ """++ def test_parking_does_not_reopen_the_whole_cache(self):+ async def scenario():+ queue = LlamaAdmissionQueue("test")+ first = await _reserve(queue, capacity = 4, tokens = 1500, budget = 2048)+ lease = first.lease_nowait()+ assert lease is not None+ assert lease.park() is True, "the park budget must allow this"+ # The slot is back, the KV is not.+ assert queue.snapshot().committed == 1500+ second = await _reserve(queue, capacity = 4, tokens = 1500, budget = 2048)+ return queue, second.lease_nowait()++ queue, lease = _run(scenario())+ assert lease is None, "1500 + 1500 against 2048 must not both be admitted"+ assert queue.snapshot().committed == 1500++ def test_a_caller_is_still_admitted_when_nothing_is_committed(self):+ """The escape must survive the fix, or a large lone request deadlocks."""++ async def scenario():+ queue = LlamaAdmissionQueue("test")+ reservation = await _reserve(queue, capacity = 4, tokens = 9999, budget = 2048)+ return reservation.lease_nowait()++ assert _run(scenario()) is not None+++class TestTheOutputAllowanceIsCounted:+ def test_max_completion_tokens_is_reserved_like_max_tokens(self):+ """Generation honours max_completion_tokens through+ _effective_openai_max_tokens; admission must reserve the same allowance."""+ from types import SimpleNamespace++ import routes.inference as routes_inference++ messages = [{"role": "user", "content": "x" * 400}]+ with_deprecated = routes_inference._openai_llama_admission_tokens(+ SimpleNamespace(messages = messages, max_tokens = 512),+ budget = 8192,+ capacity = 4,+ )+ with_supported = routes_inference._openai_llama_admission_tokens(+ SimpleNamespace(messages = messages, max_tokens = None, max_completion_tokens = 512),+ budget = 8192,+ capacity = 4,+ )+ assert with_supported == with_deprecated++ def test_a_responses_shape_would_have_fallen_back_to_a_fair_share(self):+ """Why the /v1/responses site now reserves against the translated chat_req: the+ raw model has `input` and `max_output_tokens`, so nothing here can size it."""+ from types import SimpleNamespace++ import routes.inference as routes_inference++ raw = SimpleNamespace(input = "x" * 100_000, max_output_tokens = 4096)+ assert (+ routes_inference._openai_llama_admission_tokens(+ raw,+ budget = 2048,+ capacity = 4,+ )+ == 512+ )+++class TestTheWholeRenderedPromptIsCounted:+ """Two more ways the reservation undercounted, both from review.++ An uncapped request reserved no output allowance even though+ `_build_passthrough_payload` then sends `max_tokens = backend_ctx`, so short+ prompts held tiny commitments while each generation could fill the cache. And+ the estimate covered only `messages`, while OpenAI tool definitions are+ rendered into the prompt and Anthropic keeps `system` and `tools` separate+ until they are translated.+ """++ @staticmethod+ def _cost(+ payload,+ budget = 8192,+ capacity = 4,+ ):+ import routes.inference as routes_inference+ return routes_inference._openai_llama_admission_tokens(+ payload,+ budget = budget,+ capacity = capacity,+ )++ def test_an_uncapped_request_reserves_the_rest_of_the_window(self):+ from types import SimpleNamespace+ payload = SimpleNamespace(+ messages = [{"role": "user", "content": "hi"}],+ max_tokens = None,+ max_completion_tokens = None,+ )+ # Generation may run until the window is full, so the reservation says so.+ assert self._cost(payload, budget = 2048) == 2048++ def test_two_uncapped_short_prompts_do_not_both_run(self):+ """The collision this closes: tiny commitments, cache-filling generations."""+ from types import SimpleNamespace++ async def scenario():+ queue = LlamaAdmissionQueue("test")+ payload = SimpleNamespace(+ messages = [{"role": "user", "content": "hi"}],+ max_tokens = None,+ max_completion_tokens = None,+ )+ cost = self._cost(payload, budget = 2048)+ first = await _reserve(queue, capacity = 4, tokens = cost, budget = 2048)+ assert first.lease_nowait() is not None+ second = await _reserve(queue, capacity = 4, tokens = cost, budget = 2048)+ return second.lease_nowait()++ assert _run(scenario()) is None++ def test_a_capped_request_is_unaffected(self):+ from types import SimpleNamespace+ payload = SimpleNamespace(+ messages = [{"role": "user", "content": "hi"}],+ max_tokens = 128,+ max_completion_tokens = None,+ )+ assert self._cost(payload, budget = 2048) < 2048++ def test_tool_schemas_are_counted(self):+ from types import SimpleNamespace++ messages = [{"role": "user", "content": "hi"}]+ bare = self._cost(SimpleNamespace(messages = messages, max_tokens = 16))+ with_tools = self._cost(+ SimpleNamespace(+ messages = messages,+ max_tokens = 16,+ tools = [+ {+ "type": "function",+ "function": {+ "name": "lookup",+ "description": "d" * 2000,+ "parameters": {"type": "object", "properties": {}},+ },+ }+ ],+ )+ )+ assert with_tools > bare++ def test_an_anthropic_system_block_is_counted(self):+ from types import SimpleNamespace++ messages = [{"role": "user", "content": "hi"}]+ bare = self._cost(SimpleNamespace(messages = messages, max_tokens = 16))+ with_system = self._cost(+ SimpleNamespace(+ messages = messages,+ max_tokens = 16,+ system = "s" * 4000,+ )+ )+ assert with_system > bare++ def test_an_unserialisable_extra_does_not_break_admission(self):+ from types import SimpleNamespace+ payload = SimpleNamespace(+ messages = [{"role": "user", "content": "hi"}],+ max_tokens = 16,+ tools = object(),+ )+ assert self._cost(payload) is not None+++class TestToolLoopsReserveTheirUpperBound:+ """One lease covers up to 25 rounds, each larger than the last.++ `generate_chat_completion_with_tools` appends every tool result and re-sends the+ conversation, so a request that starts small can approach the full window while its+ commitment stays at the opening estimate. Another request is then admitted against a+ cache the active rounds have already grown into.+ """++ @staticmethod+ def _cost(+ payload,+ budget = 2048,+ capacity = 4,+ tool_loop = False,+ ):+ import routes.inference as routes_inference+ return routes_inference._openai_llama_admission_tokens(+ payload,+ budget = budget,+ capacity = capacity,+ tool_loop = tool_loop,+ )++ def test_a_tool_request_reserves_the_whole_cache(self):+ """Keyed on the resolved path, not on ``tools``: the loop also opens on+ ``enable_tools``, ``mcp_enabled``, the CLI policy and a checkpoint repair,+ none of which carry a client catalogue."""+ from types import SimpleNamespace+ payload = SimpleNamespace(+ messages = [{"role": "user", "content": "hi"}],+ max_tokens = 16,+ enable_tools = True,+ tools = None,+ )+ assert self._cost(payload, tool_loop = True) == 2048++ def test_two_tool_requests_do_not_run_together(self):+ from types import SimpleNamespace+ async def scenario():+ queue = LlamaAdmissionQueue("test")+ payload = SimpleNamespace(+ messages = [{"role": "user", "content": "hi"}],+ max_tokens = 16,+ enable_tools = True,+ tools = None,+ )+ cost = self._cost(payload, tool_loop = True)+ first = await _reserve(queue, capacity = 4, tokens = cost, budget = 2048)+ assert first.lease_nowait() is not None+ second = await _reserve(queue, capacity = 4, tokens = cost, budget = 2048)+ return second.lease_nowait()++ assert _run(scenario()) is None++ def test_a_request_without_tools_is_unaffected(self):+ """The serialisation is the price of a tool loop, not of every request."""+ from types import SimpleNamespace++ payload = SimpleNamespace(+ messages = [{"role": "user", "content": "hi"}],+ max_tokens = 16,+ tools = None,+ )+ assert self._cost(payload) < 2048++ def test_an_empty_tool_list_is_not_a_tool_loop(self):+ from types import SimpleNamespace+ payload = SimpleNamespace(+ messages = [{"role": "user", "content": "hi"}],+ max_tokens = 16,+ tools = [],+ )+ assert self._cost(payload) < 2048++ def test_a_forwarded_catalogue_is_not_a_tool_loop(self):+ """The passthrough and streaming /v1/responses run ONE generation per HTTP+ call; the client sends the next round itself, with its own reservation."""+ from types import SimpleNamespace+ payload = SimpleNamespace(+ messages = [{"role": "user", "content": "hi"}],+ max_tokens = 16,+ tools = [{"type": "function", "function": {"name": "lookup"}}],+ )+ assert self._cost(payload) < 2048diff --git a/studio/backend/tests/test_llama_admission_kv_budget_media_and_tools.py b/studio/backend/tests/test_llama_admission_kv_budget_media_and_tools.pynew file mode 100644index 00000000000..78ce39f10da--- /dev/null+++ b/studio/backend/tests/test_llama_admission_kv_budget_media_and_tools.py@@ -0,0 +1,173 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""Two holes in the KV reservation the estimator has to charge for.++Media: Studio's composer sends attachments in the legacy top-level ``image_base64`` /+``audio_base64`` / ``video_base64`` fields, and the generation path splices them into+the prompt AFTER admission is decided. Charging only ``messages`` priced an image at+zero while llama.cpp's mtmd embeddings take real KV positions.++Tool loop: the server-side loop opens on ``enable_tools`` / ``mcp_enabled`` / the CLI+policy / a checkpoint repair, none of which require a client ``tools`` array, so a+predicate keyed on ``payload.tools`` charged Studio's own tool traffic the opening+estimate for a lease that runs up to 25 growing rounds.+"""++import base64++from routes.inference import _openai_llama_admission_tokens+++class _Payload:+ def __init__(self, **fields):+ self.__dict__.update(fields)++ def __getattr__(self, _name):+ return None+++def _image_b64(kib: int = 200) -> str:+ return base64.b64encode(b"\x89PNG" + b"x" * (kib * 1024)).decode()+++class TestMediaIsCharged:+ def test_legacy_image_costs_what_the_same_image_inline_costs(self):+ image = _image_b64()+ legacy = _Payload(+ messages = [{"role": "user", "content": "what is this?"}],+ image_base64 = image,+ max_tokens = 128,+ )+ inline = _Payload(+ messages = [+ {+ "role": "user",+ "content": [+ {"type": "text", "text": "what is this?"},+ {+ "type": "image_url",+ "image_url": {"url": f"data:image/png;base64,{image}"},+ },+ ],+ }+ ],+ max_tokens = 128,+ )+ legacy_cost = _openai_llama_admission_tokens(legacy, budget = 4096, capacity = 4)+ inline_cost = _openai_llama_admission_tokens(inline, budget = 4096, capacity = 4)+ # Before the fix this was 139 against 4096: the same request, one spelling+ # charged the whole cache and the other charged its 13 characters of text.+ assert legacy_cost == inline_cost++ def test_two_image_chats_are_not_both_admitted(self):+ """The live failure, with images instead of text."""+ import asyncio++ from core.inference.llama_admission import LlamaAdmissionConfig, LlamaAdmissionQueue++ async def scenario():+ queue = LlamaAdmissionQueue("media")+ config = LlamaAdmissionConfig()+ image = _image_b64(4)+ leases = []+ for _ in range(2):+ payload = _Payload(+ messages = [{"role": "user", "content": "describe"}],+ image_base64 = image,+ max_tokens = 128,+ )+ reservation = queue.reserve(+ capacity = 4,+ config = config,+ budget = 2048,+ tokens = _openai_llama_admission_tokens(+ payload, budget = 2048, capacity = 4+ ),+ )+ leases.append(reservation.lease_nowait())+ return leases++ first, second = asyncio.run(scenario())+ assert first is not None, "the first image chat owns the cache"+ # A 4 KiB image is ~5.4k base64 characters, about 1365 tokens on top of a+ # 2048 cache that already holds one such request: the second must queue.+ assert second is None++ def test_audio_and_video_are_charged_too(self):+ clip = _image_b64(8)+ for field in ("audio_base64", "video_base64"):+ payload = _Payload(+ messages = [{"role": "user", "content": "transcribe"}],+ max_tokens = 64,+ **{field: clip},+ )+ cost = _openai_llama_admission_tokens(payload, budget = 65536, capacity = 4)+ assert cost > 2000, f"{field} was charged {cost}, i.e. nothing for the media"+++class TestTheToolLoopReservesTheWholeCache:+ def test_a_server_side_loop_without_client_tools_reserves_the_budget(self):+ """enable_tools / mcp_enabled / CLI policy open the loop with no `tools` array."""+ payload = _Payload(+ messages = [{"role": "user", "content": "search my notes"}],+ enable_tools = True,+ max_tokens = 128,+ )+ assert getattr(payload, "tools", None) is None+ assert (+ _openai_llama_admission_tokens(+ payload, budget = 4096, capacity = 4, tool_loop = True+ )+ == 4096+ )++ def test_a_passthrough_forwarding_tools_is_charged_its_own_round(self):+ """One HTTP call is one generation there: the client drives the rounds."""+ payload = _Payload(+ messages = [{"role": "user", "content": "hi"}],+ tools = [+ {+ "type": "function",+ "function": {"name": "shell", "parameters": {"type": "object"}},+ }+ ],+ max_tokens = 128,+ )+ cost = _openai_llama_admission_tokens(payload, budget = 4096, capacity = 4)+ assert cost < 4096, "a forwarded catalogue must not serialise the whole cache"+++class TestTheBudgetIsTheWholeCacheNotOneSlot:+ """``context_length`` stops being the total once the server has been read back.++ ``_reconcile_effective_ctx_with_server`` adopts the per-slot ``n_ctx`` into+ ``context_length`` and puts the aggregate in ``_kv_cache_context_total``. Without+ ``--kv-unified`` those differ by ``n_parallel``, and budgeting one private cache+ for the whole pool collapses concurrency to a single generation.+ """++ def test_the_partitioned_total_wins_over_one_slot(self):+ from routes.inference import _openai_llama_admission_budget++ backend = _Payload(context_length = 4096, _kv_cache_context_total = 16384)+ assert _openai_llama_admission_budget(backend) == 16384++ def test_a_unified_cache_is_unchanged(self):+ from routes.inference import _openai_llama_admission_budget++ # slots == 1 under --kv-unified, so the total IS the per-request window.+ backend = _Payload(context_length = 8192, _kv_cache_context_total = 8192)+ assert _openai_llama_admission_budget(backend) == 8192++ def test_an_unread_backend_falls_back_to_context_length(self):+ from routes.inference import _openai_llama_admission_budget++ # Nothing read back yet: the two agree, so the fallback is not a guess.+ backend = _Payload(context_length = 8192, _kv_cache_context_total = None)+ assert _openai_llama_admission_budget(backend) == 8192++ def test_a_backend_that_cannot_say_keeps_slot_only_admission(self):+ from routes.inference import _openai_llama_admission_budget++ assert _openai_llama_admission_budget(_Payload()) is None