Skip to content

Admit generations against the KV cache, not just the slot count - #9392

Merged
danielhanchen merged 10 commits into
mainfrom
studio/kv-budget-admission
Aug 20, 2026
Merged

danielhanchen merged 10 commits into
mainfrom
studio/kv-budget-admission

Conversation

@danielhanchen

Copy link
Copy Markdown
Member

Two chats generating at once killed each other. From the llama-server log:

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, so neither request was too long on its own. llama.cpp retried down the batch ladder (512, 256, 128 ... 1), failed, and killed both tasks, taking a chat reply and a Deep Research run with it.

The overcommit

--parallel 4 --kv-unified allocates ONE cache of n_ctx and then reports the whole of it to every slot:

srv load_model: initializing, n_slots = 4, n_ctx_slot = 2048, kv_unified = 'true'

core/inference/llama_admission.py gated on slot count alone. Grepping it for token, n_ctx or context returned nothing at all: _can_admit_locked tested only bool(self._free) and (self._held + reserved) < self._capacity, and capacity comes straight from --parallel. So four generations were admitted against a cache that could hold one.

Change

Leases now carry a token cost and the queue an integer budget. A caller is admitted when a slot is free and the cost fits what is left; otherwise it waits in the FIFO that already exists. Waiting instead of dying is the whole user-visible difference.

Three details matter:

  • A lone caller is always admitted, however large. 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 head waiter's own cost is tested, not zero, so a large request is not overtaken indefinitely by small ones that happen to fit. Head-of-line blocking is the fair trade, and it matches the FIFO the queue already promises.
  • Tokens are returned on release but NOT on park. A parked holder has stopped decoding, but llama-server still holds its KV until the task ends.

Sizing

The budget is the backend's own context_length, which is the whole cache in both slot modes: --kv-unified shares one n_ctx and tells every slot it owns it, and without it the same n_ctx is partitioned per slot. Either way the total is n_ctx, so no unified/partitioned branch is needed.

The cost is the dense token estimate of the prompt plus max_tokens, clamped to the budget. The dense estimator specifically: undercounting is the exact failure this prevents, and four-chars-per-token undercounts CJK by about twofold, which would hand out a slot the cache cannot back. A shape with no messages (/completions takes a prompt string) reserves an equal share, since charging it the whole budget would serialise that route and charging it nothing would restore the overcommit.

All seven reserve sites already funnel through _openai_llama_admission_reserve, so the wiring is one function plus a payload argument.

Compatibility

Passing no budget reproduces slot-only admission exactly, so any caller not updated behaves as before. UNSLOTH_LLAMA_ADMISSION_KV_BUDGET=0 restores it wholesale, for a backend whose reported context does not match the cache llama-server actually allocated.

Scope

This stops the collision. PR #9390 is what makes any residual failure explain itself instead of vanishing, and the two are independent.

Tests

tests/test_llama_admission_kv_budget.py, 15 tests:

  • the live failure in miniature: 1500 + 1500 against 2048 no longer both run
  • the regression guard that 4 x 400 against 2048 still run concurrently, so this does not quietly become one-at-a-time
  • a lone 3000-token request against 2048 is admitted rather than stranded
  • release returns the tokens, and a double release returns them only once
  • no budget, a zero budget, and the env flag off each reproduce slot-only admission
  • the route helpers: budget from context_length, unreadable values meaning no budget, cost counting the prompt and not just the output, the clamp, and the fair share for a promptless shape

3422 pass across the admission, slot-release, tool-loop and inference suites, with no failures.

danielhanchen and others added 2 commits August 20, 2026 14:24
Two chats generating at once killed each other. From the llama-server log:

  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, so
neither request was too long on its own. llama.cpp retried down the batch
ladder and then killed both tasks, taking a chat reply and a Deep Research run
with it.

The overcommit is that --parallel 4 --kv-unified allocates ONE cache of n_ctx
and then reports the whole of it to every slot:

  srv load_model: initializing, n_slots = 4, n_ctx_slot = 2048, kv_unified = 'true'

llama_admission gated on slot count alone; it contained no reference to tokens,
n_ctx or context at all. So four generations were admitted against a cache that
could hold one.

Leases now carry a token cost and the queue an integer budget. A caller is
admitted when a slot is free AND the cost fits what is left, otherwise it waits
in the FIFO that already exists. Three details matter:

- A lone caller is always admitted, however large. Its request may still be
  refused by llama-server, but that refusal names both token counts, whereas
  refusing here would strand it forever.
- The head waiter's own cost is tested, not zero, so a large request is not
  overtaken forever by small ones that happen to fit.
- Tokens are returned on release but NOT on park: a parked holder has stopped
  decoding, but llama-server still holds its KV until the task ends.

The budget is the backend's own context_length, which is the whole cache in
both slot modes: --kv-unified shares one n_ctx and tells every slot it owns it,
and without it the same n_ctx is partitioned per slot. So no unified branch is
needed. The cost is the dense token estimate of the prompt plus max_tokens,
clamped to the budget; the dense estimator because undercounting is the exact
failure this prevents and four-chars-per-token undercounts CJK about twofold. A
shape with no messages (/completions takes a prompt string) reserves an equal
share rather than the whole budget, which would serialise that route, or
nothing, which would restore the overcommit.

All seven reserve sites already funnel through one helper, so the wiring is
one function. Passing no budget reproduces slot-only admission exactly, and
UNSLOTH_LLAMA_ADMISSION_KV_BUDGET=0 restores it for a backend whose reported
context does not match its real cache.

Tests: the live failure in miniature (1500 + 1500 against 2048 no longer both
run), the regression guard that 4 x 400 still runs concurrently, the lone
oversized request, double-release idempotence, both backwards-compatible paths
and the route helpers. 3422 pass across the admission, slot-release, tool-loop
and inference suites.
chatgpt-codex-connector[bot]

This comment was marked as resolved.

All three came out of review, and the first defeats the whole change.

try_park hands a holder's slot back while it waits on a tool approval, which
decrements _held, while the lease deliberately keeps its tokens because
llama-server still holds that KV until the task ends. The deadlock escape was
written as `_held == 0`, so a parked lease read as an empty backend and the
next caller was admitted unconditionally: park 1500 against a 2048 budget,
admit another 1500, and committed reaches 3000. Exactly the collision this
accounting exists to prevent. The escape now asks whether anything is
COMMITTED, which is the condition it always meant; slot count was a proxy, and
parking is where the proxy breaks.

The cost read the raw max_tokens while generation goes through
_effective_openai_max_tokens, so a request setting only the supported
max_completion_tokens reserved its prompt and none of its output allowance. It
now calls the same helper generation uses.

Streaming /v1/responses builds chat_req with the translated messages and
max_output_tokens and then passed the raw ResponsesRequest, which carries
`input` rather than `messages`. The estimator found no messages and returned
the equal-share fallback every time, so a large or high-output Responses
request reserved a quarter of the cache regardless of its real size. It now
reserves against chat_req.

Tests: parking a 1500-token lease no longer admits a second one and committed
stays 1500; a 9999-token request is still admitted when nothing is committed,
so the escape survives; the two output-cap spellings reserve identically; and a
raw Responses shape is pinned at the fallback to record why the site changed.
3650 pass across the admission, slot-release, tool-loop, responses and
inference suites.
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

chatgpt-codex-connector[bot]

This comment was marked as resolved.

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 5a62f7f810

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment on lines +1507 to +1508
prompt_tokens = estimate_messages_tokens_dense(
[m if isinstance(m, dict) else m.model_dump() for m in messages]

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Account for ASCII-dense tokenization before admission

When message content is ASCII but tokenizes at fewer than four characters per token—common for source code, minified JSON, identifiers, and encoded data—estimate_messages_tokens_dense() still applies the plain len/4 estimate. Two such prompts can therefore each be charged far below their real KV use and admitted even though their actual token counts exceed the cache budget together, reproducing the collision this guard is meant to prevent; admission needs an actual tokenizer count or a conservative estimate for dense ASCII as well.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Pushing back on this one.

The estimator being approximate is the documented design here, not a defect. The PR body states the budget is a soft ceiling and lists estimator drift as risk 1, and PR 9390 exists so that a residual collision reports itself with both token counts rather than vanishing. Dense ASCII does tokenise below four characters per token, but "far below" overstates it: code sits nearer three, so the undercount is roughly 25 percent, not a factor that turns a fitting pair into a colliding one on its own.

The remedy proposed is the part I cannot take. An actual tokenizer count means a round trip to llama-server on every admission, on the hot path, before we know whether the caller even needs to queue. That is a real cost paid by every request to tighten a bound that is already conservative in the direction that matters: prompts are charged their full length and output is charged its full cap, both of which the request may not use.

A blanket safety factor for ASCII is the other option and I would rather not add an unexplainable constant to a budget whose whole value is that every term corresponds to something real.

If you can show a concrete pair that fits under the current estimate and collides in practice, I will take it: that would move this from drift to a reachable bug and change the answer. The other four findings on this PR were exactly that, and all four are fixed.

…ut cap

Two more undercounts from review, both of which let requests through on a
fraction of the KV they would actually use.

An uncapped request reserved no output allowance at all. _build_passthrough_payload
sets max_tokens to backend_ctx when the client names no cap, so generation may
run until the window is full, and `or 0` meant a two-token prompt held a
two-token commitment and then filled the cache. An absent cap now reserves
budget - prompt_tokens, matching what generation is permitted to do. That does
serialise concurrent uncapped requests, which is the honest trade: the
alternative is admitting two runs llama.cpp will kill. Naming a cap buys the
concurrency back. A cap of zero is unaffected, since _positive_int_or_none
already collapses it; the branch keys on None.

The estimate also covered only `messages`. OpenAI tool definitions are rendered
into the llama-server prompt, and Anthropic carries `system` and `tools`
separately until they are translated, so two requests with trivial messages and
a large JSON schema could both be admitted on a severe undercount.
_openai_llama_admission_extra_prompt_tokens now serialises system, tools,
tool_choice and instructions and charges them at the dense rate, since a JSON
schema is punctuation-heavy and four-chars-per-token flatters it. Serialisation
failures are swallowed per attribute, so an unexpected field degrades to the
previous estimate rather than refusing the request.

Tests: an uncapped request reserves the whole 2048 budget, two uncapped short
prompts no longer both run, a capped request is unchanged, and a large tool
schema, an Anthropic system block and an unserialisable extra are each covered.
4152 pass with no failures.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 9cd1b5d1c8

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment on lines +820 to +822
while self._waiters and self._can_admit_locked(
len(self._unpark_tickets), self._waiters[0].tokens
):

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Skip cancelled heads before testing their token cost

When a budgeted queue's head future is cancelled externally while its token cost does not fit the remaining budget, _can_admit_locked returns false before the cancellation check at lines 823-825 can pop it. A later live waiter whose smaller cost does fit is therefore blocked behind the dead entry until committed KV changes, potentially indefinitely when the active lease is parked on an approval prompt. Externally cancelled waiter futures are an explicitly supported path elsewhere in this queue, so prune or skip a dead head before applying the budget predicate.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Turning this one down, though not because the mechanism is imaginary.

I built the state you describe and it does deadlock: capacity 4, budget 2048, A=1000 admitted, B=1500 queued, then cancelling B's future directly and enqueuing C=500 leaves C ungranted past its timeout despite a free slot and 1500 free budget, and it stays that way with the holder parked on an approval prompt. So the shape is real.

It is not reachable. The only way I could produce it was to reach into the waiter and cancel its future by hand. Every supported abandonment goes through reservation.cancel(), and LlamaAdmissionQueue.cancel at llama_admission.py:780-797 does self._waiters.remove(waiter) under _lock BEFORE call_soon_threadsafe(waiter.future.cancel), so a cancelled waiter is never left sitting at the head. Control run: b.cancel() instead of b._waiter.future.cancel(), and C is granted immediately.

Nothing outside llama_admission.py touches a waiter or its future; I grepped routes/ and core/. Every route exit calls reservation.cancel() (_wait_for_openai_admission_non_streaming, _openai_admission_wait_stream_chunks, the anthropic finally, _close_openai_admitted_stream_iterator). The one branch that could mark a head dead in place, wait() at 501-506, needs waiter.future.cancelled(), and asyncio.shield does not propagate outer cancellation inward, so the shielded inner future keeps running and is never cancelled; the route also floors wait_s at 0.001, so wait_for's timeout <= 0 shortcut never fires.

On externally cancelled futures being an explicitly supported path elsewhere: the comment on _prune_waiters_locked does say that, and I read it as aspirational rather than describing a live caller. Testing the head's own cost rather than a zero is also deliberate, and documented at _grant_waiters_locked: granting past a large waiter whenever a small one fits would starve it for as long as traffic keeps arriving, so head-of-line blocking is the trade, matching the FIFO the rest of the queue promises.

Name a caller that can cancel a queued waiter's future without going through cancel() and I will take the guard.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Correcting myself here. I turned this down and one of my stated reasons was false.

I wrote: "Control run: b.cancel() instead of b._waiter.future.cancel(), and C is granted immediately." That is wrong. I re-ran it cleanly and C is NOT granted. The supported public path deadlocks too:

A lease: True
B granted immediately? False
C granted immediately? False
C after b.cancel(): STILL QUEUED
snapshot: capacity=4, active=1, queued=1, free=3, committed=1000, budget=2048

What I checked was true but beside the point. cancel() does remove the waiter under _lock before cancelling its future, so a dead waiter is never left at the head, and external cancellation really is unreachable. The bug is not a dead head. It is a LIVE head being removed with nothing re-running admission behind it:

release()                     :706-718  -> self._grant_waiters_locked()
try_park()                    :720-731  -> self._grant_waiters_locked()
acquire_parked_slot() finally :772-778  -> self._grant_waiters_locked()
cancel()                      :780-800  -> nothing

A cancelled waiter owns no slot and no tokens, so there is nothing to hand back, which is why the omission looks harmless. It is harmless for a mid-line waiter. For the head it is not, because _grant_waiters_locked tests the head's own cost and stops there, so a large head blocks smaller waiters and cancelling it never reopens the line. On a queue whose one active lease is parked on an approval prompt, the next reserve or release never comes.

So the reaction is flipped to agree. The fix is one _grant_waiters_locked() call inside cancel(), with a test for the deadlock and a second test that cancelling a tail waiter still must not let anyone skip the oversized head, so FIFO does not quietly become best-fit. This PR is already merged, so it is in #9415 rather than here.

Apologies for the wrong verdict. The mistake was checking the mechanism you named rather than the one your conclusion pointed at.

pre-commit-ci Bot and others added 2 commits August 20, 2026 15:52
One lease covers up to 25 rounds of generate_chat_completion_with_tools, and
each round appends its tool results and re-sends the conversation. A request
that starts small can therefore approach the full window while its commitment
stays at the opening estimate, so another request is admitted against a cache
the active rounds have already grown into.

Re-costing per round would mean threading a callback from the reservation
through the generator and into every round. Reserving the upper bound gives 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 request actually carrying tools, so an ordinary chat is unaffected
and an empty tool list is not treated as a tool loop.
chatgpt-codex-connector[bot]

This comment was marked as resolved.

@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 20, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 20, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 20, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 20, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 20, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 20, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 20, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 20, 2026
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 2b51a1c1a7

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment on lines +820 to +822
while self._waiters and self._can_admit_locked(
len(self._unpark_tickets), self._waiters[0].tokens
):

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Re-run admission when the budget-blocking head cancels

When the FIFO head is blocked only by its token cost, a normal LlamaAdmissionReservation.cancel() removes that waiter but never invokes _grant_waiters_locked(), so a smaller live waiter behind it remains queued despite free slots and sufficient KV capacity; it is reconsidered only after another reserve/release, which may never occur while the active lease is parked awaiting approval. Fresh evidence beyond the prior synthetic future-cancellation report is that this reproduces through the supported public reservation.cancel() path (for example, committed 1000/2048, cancelled head cost 1500, live tail cost 500), so cancellation should immediately re-run admission.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

You are right, and this is not the same argument as 3823100702. I rejected that one and my stated control run was false; I have retracted it on that thread.

The mechanism you name here is the live one. Every path that frees capacity ends by re-running admission except cancel():

release()                     :706-718  -> self._grant_waiters_locked()
try_park()                    :720-731  -> self._grant_waiters_locked()
acquire_parked_slot() finally :772-778  -> self._grant_waiters_locked()
cancel()                      :780-800  -> nothing

A cancelled waiter owns no slot and no tokens, which is why the omission looks harmless, and for a mid-line waiter it is. For the head it is not, because _grant_waiters_locked tests the head's own cost and stops there, so a large head blocks smaller waiters and removing it never reopens the line.

Reproduced through the ordinary public path, capacity 4, budget 2048:

A lease: True
B granted immediately? False
C granted immediately? False
C after b.cancel(): STILL QUEUED
snapshot: capacity=4, active=1, queued=1, free=3, committed=1000, budget=2048

C wants 500 with three free slots and 1048 free budget. It waits for the next reserve or release, which never arrives when the one active lease is parked on an approval prompt.

Fix is a single _grant_waiters_locked() inside cancel(), still under _lock. The cancelled waiter is already off _waiters so the loop sees the new head; in the granted_lease branch the tokens are still in _committed at that point, so granting there is conservative and the release below re-grants anyway; and it only does call_soon_threadsafe, so no re-entrant lock.

Two tests: the deadlock itself, which fails before and passes after, and one that cancelling a TAIL waiter still admits nobody early, so the head-of-line trade I defended earlier does not quietly become best-fit.

Merged already, so it is in #9415.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: cb49c853e0

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment on lines +1585 to +1588
# 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)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Bound each reservation by the per-slot context

When the backend runs with --no-kv-unified and multiple slots, _openai_llama_admission_budget() deliberately returns the aggregate n_ctx_slot * slots, but an individual generation can consume only context_length tokens from its private cache. Using that aggregate here makes every ordinary request without an explicit output cap commit the entire pool; the tool_loop branch likewise returns the entire aggregate. Consequently the first such request queues all other requests despite their independent caches and free slots, and a parked tool approval can block the backend indefinitely. Keep the aggregate as the queue budget, but use the per-slot context as the upper bound for one request.

Useful? React with 👍 / 👎.

@danielhanchen
danielhanchen merged commit 6504fb5 into main Aug 20, 2026
17 of 44 checks passed
@danielhanchen
danielhanchen deleted the studio/kv-budget-admission branch August 20, 2026 16:45
danielhanchen added a commit that referenced this pull request Aug 27, 2026
* fix(studio): bound vision media KV admission accounting

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

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

* fix(studio): make the per-image KV reservation an upper bound on both builders

Two things kept the image allowance from being the bound admission needs.

The passthrough builder spliced the legacy top-level image unconditionally,
while the GGUF chat builder skipped it when the messages already carried one.
Studio echoes the current image into both spellings, so a request with client
tools or a response_format went to llama-server with two copies of one image
against a reservation for one. Measured on llama-server b10639 with a 2048x2048
image: 4417 tokens reserved, 8466 actually charged. Across capacity x context
shapes that is a real overcommit in 12 of 30 combinations, including 4 slots at
32768 and 8 slots at 40000, which is the collision #9392 exists to stop. Both
builders now ask one shared predicate, since two copies of "does this request
already carry an image" is how they drifted apart.

The 4096 constant was also below the real ceiling. 4096 is llama.cpp's default
cap on Qwen-VL embeddings per image, but mtmd wraps them in delimiters, so a
max-resolution image measures 4098 on Qwen3-VL-4B and 258 on Gemma 3 4B. The
constant is now the embedding cap plus an explicit wrapper allowance, with the
measurements and the projector families it cannot promise anything for written
down next to it.

Also drop the unset optional fields before the dense estimate, as every other
dump of these models in this file already does. Without exclude_none a bare
{"role": "user", "content": "hi"} is priced at 34 tokens rather than 8, all of
it null padding that is never sent.

The two media equality assertions ran at a budget both sides clamped to, so
they held on the unfixed estimator too. They now run clear of the clamp, and
the new cases assert what the fix is for: every builder forwards exactly the
number of images admission charged for, and the allowance bounds the measured
cost of a real projector.

* Tighten the comments on the vision KV admission path

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

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

* Key the legacy image on distinctness, and follow the configured image cap

Two holes in the per-image reservation, both found in review.

Skipping the legacy top-level image whenever the messages carried any image was
too coarse. It deduplicates Studio's echo, which is byte-equal to a part already
in the thread, but it also silently dropped a genuinely different image attached
to the current turn through the legacy field, so llama-server answered without
the image the client just sent. Both builders and the admission estimate now key
on _legacy_image_is_distinct, which compares against the one value the composer
could have echoed. The echo is still charged and sent once; a real second image
is now charged and sent, rather than dropped.

_latest_user_image_payload reads models and plain dicts alike so that predicate
can be shared: the generation paths only ever hold models, but the estimate sees
whatever the caller passed, and the two have to agree or the reservation stops
matching the prompt.

The per-image allowance was also a hard-coded default in a place that can be
configured. --image-max-tokens is not an Unsloth-managed flag, so llama_extra_args
forwards it verbatim; measured on llama-server b10639 with --image-max-tokens 8192,
a 4096x4096 Qwen3-VL image costs 8102 against 4098 at the default, so the default
allowance would have admitted concurrent requests the cache cannot hold. The
reservation now reads the effective cap off the running backend and falls back to
the default ceiling, so lowering the cap reserves less too.

Regressions cover both: every builder forwards exactly the number of images
admission charged for, now including a history image plus a distinct legacy
attachment, and the allowance tracks a raised, lowered, absent or malformed cap.

* Tighten the comments added by the review round

* Size an image against the loaded projector, not a single default

There is no universal per-image ceiling to hard-code. llama-server documents
--image-max-tokens as "read from model" and applies it only to dynamic-resolution
projectors, and clip.cpp sets a different limit per family: 256 for lfm2, 280 for
gemma4v, 576 for minimax_m3, 1024 for pixtral and kimivl, 4096 for the qwen and
glm4v mergers, 16384 for hunyuanvl and 62500 for youtuvl. A flat 4096 bound holds
for most of those and reserves a quarter of what one hunyuanvl image costs, which
admits concurrent requests the cache cannot hold.

The mmproj already gets read at load for its capabilities, so it now also yields
clip.projector_type, and admission looks the ceiling up from a table keyed on the
strings in clip-impl.h. An unrecognised family keeps the previous default rather
than inventing a number.

Takes the LARGER of the projector ceiling and any --image-max-tokens rather than
trusting the flag. It is honoured only by dynamic-resolution projectors, so a low
cap against a fixed-resolution one is ignored by llama.cpp and believing it would
reserve less than the image costs. Over-reserving is the safe direction here.

/props carries no image-token limit, so this reads the projector file rather than
the running server.

---------

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
Co-authored-by: Daniel Han <[email protected]>
danielhanchen added a commit that referenced this pull request Aug 31, 2026
…or cache room

Simulating the first commit against a live server found that it caused the very
failure it was meant to prevent. At -c 4096 with four short tool chats, all four
were admitted and llama.cpp answered every one of them with "Context size has
been exceeded". The concurrency number looked right and the requests were not.

Three separate defects, all now covered by tests.

1. The injected tool catalogue was never priced. payload.tools is what the CLIENT
   sent, and for Unsloth's own tool loop that is usually nothing: Web Search and
   the rest are resolved server-side and rendered into the prompt after admission
   has already costed the request. Measured on Qwen3.5-4B-MTP-GGUF, the same user
   turn is 1716 prompt tokens with tools off and 2969 with them on, so roughly
   1250 tokens were invisible to the estimate. Four chats priced at an equal share
   were therefore admitted against a cache that could hold two.

   _openai_llama_admission_injected_tool_tokens now charges the resolved catalogue,
   at admission and at every re-cost, on both the OpenAI and the Anthropic tool
   paths. The catalogue is re-sent every round, so it belongs in both.

2. The opening estimate clamped its output allowance to a share. That opened a
   window #9392 had closed: a first round may generate its whole allowance before
   any re-cost can run, so four loops could overflow before the first boundary. A
   tool loop is now charged exactly what an equivalent request without tools is
   charged, with the share only as a floor.

3. recost_waiting could wait forever. release() runs from the route's teardown and
   never touches the cancel event, so a Stop that tore down before the event was
   seen left the wait spinning on a dead lease. A reparker holds the wait line shut
   for every other caller, so that did not stall one chat, it froze the pool for
   the life of the process. The loop now checks _released every pass and the wait
   is bounded by DEFAULT_RECOST_WAIT_TIMEOUT_S, after which it restores the old
   commitment and falls back to declining, which is what every release before this
   did anyway.

Also:

* on_conversation_grew moved to the END of generate_chat_completion_with_tools.
  That signature has no bare *, so every parameter is positional-or-keyword and
  inserting one in the middle silently rebinds the six arguments after it for any
  caller passing them positionally.
* ToolLoopPolicy.on_conversation_grew removed. Nothing constructed it; both live
  wirings go through llama_cpp, so it was dead surface. studio_tool_loop.py is
  back to exactly what main has.
* The docstring claimed a yielded round always stays warm in the prompt cache.
  Studio launches with --cache-ram 0 on Windows under full GPU offload (#5692) and
  --cache-idle-slots requires cache-ram, so there it may be re-prefilled. Correct
  everywhere, slower on that one platform.

Measured, Qwen3.5-4B-MTP-GGUF:UD-Q4_K_XL, --parallel 4, peak requests_processing
scraped from /metrics, every case returning 200:

  -c 32768   four tool chats that fit      1 -> 4 concurrent
  -c 32768   four larger tool chats        1 -> 4 concurrent, 11.0s -> 7.2s
  -c 4096    four tool chats               1 -> 2 concurrent (two is all 4096
                                           holds once the catalogue is counted)

Tools off is unchanged in every case.

Tests: randomised stress over the queue invariants (committed never exceeds the
cache, the queue always drains, no leaked repark counter), a matrix over the
backend shapes the budget is actually derived from (1/2/4/8 slots, unified and
non-unified KV, unknown budget, admission disabled), old-caller compatibility,
and the catalogue regression itself. 3378 pass against main's 3317 with the same
six pre-existing failures. The queue module is pure stdlib and passes on Python
3.9 through 3.14 in bare uv venvs containing only pytest.
danielhanchen added a commit that referenced this pull request Aug 31, 2026
* Let tool chats decode in parallel and wait for cache room instead of over-running it

Four chats sent together with Web Search or Tool Calling on decoded one at a time.
Measured on a 262144 cache, they reached first token at 0.1s, 2.8s, 4.6s and 8.8s
while the UI showed all four generating within 0.13s.

The cause is the reservation, not the slots. #9392 admitted generations against the
KV cache rather than the slot count, after two chats killed each other on a 2048-token
cache (565 + 1485, neither too long alone). A tool loop's final size is unknowable when
it is admitted, because each of up to 25 rounds appends its results and re-sends the
conversation, so that PR reserved the whole cache "at the price of serialising
concurrent tool requests". Any lit pill sets enable_tools, so that price fell on the
common case rather than a corner, and it scaled the wrong way: reserving all of a
2048-token cache costs a request that could not have run anyway, reserving all of
262144 costs three that comfortably could.

A tool loop now opens at an equal share and re-costs at each round boundary, which is
the alternative #9392 named and skipped for the plumbing. The opening estimate clamps
its output allowance to a share as well: Max Tokens on "Max" sends
max_tokens = context_length, which would otherwise override the floor and serialise
exactly as before.

Accounting the growth is not enough on its own. try_recost declines when the cache is
full and the run then carries on at its old figure, sending a bigger prompt than it is
charged for. Four loops opening at a share each and growing together is precisely the
failure this is meant to prevent: llama.cpp halves the batch from 1861 down to 1, gives
up, and one "Context size has been exceeded" releases and clears EVERY decoding slot,
not just the one that overflowed (server-context.cpp, whose own comment reads "TODO: try
to terminate only the largest active slot"). Under streaming it is worse to spot, since
the transport is HTTP 200 and the error arrives as the only SSE frame.

So recost_waiting makes the accounting binding: it yields the old commitment and then
waits to reclaim a bigger one. Yielding first is what makes it deadlock-free, since
blocking while still holding leaves four holders waiting on each other; _committed
strictly falls, so somebody always fits. It is called only between rounds, where the
previous round's request has finished, the slot is idle at llama-server and
--cache-idle-slots (on by default) has spilled its cells to the RAM prompt cache, so the
capacity yielded is genuinely free and the prefix stays warm.

A pending repark closes the wait line and reserve()'s fast path, so a new arrival cannot
take the room a growing conversation just released.

The Anthropic tool loop runs the same 25 rounds against the same cache and passed no
re-cost hook, so it kept its opening estimate for the whole run. It now uses the same one.

Measured on a 4096 cache with unsloth/Qwen3.5-4B-MTP-GGUF:UD-Q4_K_XL and --parallel 4,
four chats that fit together, tools on: peak llamacpp:requests_processing 1 -> 4, wall
3.3s -> 1.0s. Four that genuinely cannot fit still serialise, which is correct, and
still return 200 where the raw server returns four 500s. Tools off is unchanged.

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

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

* Charge a tool loop for the catalogue it injects, and bound the wait for cache room

Simulating the first commit against a live server found that it caused the very
failure it was meant to prevent. At -c 4096 with four short tool chats, all four
were admitted and llama.cpp answered every one of them with "Context size has
been exceeded". The concurrency number looked right and the requests were not.

Three separate defects, all now covered by tests.

1. The injected tool catalogue was never priced. payload.tools is what the CLIENT
   sent, and for Unsloth's own tool loop that is usually nothing: Web Search and
   the rest are resolved server-side and rendered into the prompt after admission
   has already costed the request. Measured on Qwen3.5-4B-MTP-GGUF, the same user
   turn is 1716 prompt tokens with tools off and 2969 with them on, so roughly
   1250 tokens were invisible to the estimate. Four chats priced at an equal share
   were therefore admitted against a cache that could hold two.

   _openai_llama_admission_injected_tool_tokens now charges the resolved catalogue,
   at admission and at every re-cost, on both the OpenAI and the Anthropic tool
   paths. The catalogue is re-sent every round, so it belongs in both.

2. The opening estimate clamped its output allowance to a share. That opened a
   window #9392 had closed: a first round may generate its whole allowance before
   any re-cost can run, so four loops could overflow before the first boundary. A
   tool loop is now charged exactly what an equivalent request without tools is
   charged, with the share only as a floor.

3. recost_waiting could wait forever. release() runs from the route's teardown and
   never touches the cancel event, so a Stop that tore down before the event was
   seen left the wait spinning on a dead lease. A reparker holds the wait line shut
   for every other caller, so that did not stall one chat, it froze the pool for
   the life of the process. The loop now checks _released every pass and the wait
   is bounded by DEFAULT_RECOST_WAIT_TIMEOUT_S, after which it restores the old
   commitment and falls back to declining, which is what every release before this
   did anyway.

Also:

* on_conversation_grew moved to the END of generate_chat_completion_with_tools.
  That signature has no bare *, so every parameter is positional-or-keyword and
  inserting one in the middle silently rebinds the six arguments after it for any
  caller passing them positionally.
* ToolLoopPolicy.on_conversation_grew removed. Nothing constructed it; both live
  wirings go through llama_cpp, so it was dead surface. studio_tool_loop.py is
  back to exactly what main has.
* The docstring claimed a yielded round always stays warm in the prompt cache.
  Studio launches with --cache-ram 0 on Windows under full GPU offload (#5692) and
  --cache-idle-slots requires cache-ram, so there it may be re-prefilled. Correct
  everywhere, slower on that one platform.

Measured, Qwen3.5-4B-MTP-GGUF:UD-Q4_K_XL, --parallel 4, peak requests_processing
scraped from /metrics, every case returning 200:

  -c 32768   four tool chats that fit      1 -> 4 concurrent
  -c 32768   four larger tool chats        1 -> 4 concurrent, 11.0s -> 7.2s
  -c 4096    four tool chats               1 -> 2 concurrent (two is all 4096
                                           holds once the catalogue is counted)

Tools off is unchanged in every case.

Tests: randomised stress over the queue invariants (committed never exceeds the
cache, the queue always drains, no leaked repark counter), a matrix over the
backend shapes the budget is actually derived from (1/2/4/8 slots, unified and
non-unified KV, unknown budget, admission disabled), old-caller compatibility,
and the catalogue regression itself. 3378 pass against main's 3317 with the same
six pre-existing failures. The queue module is pure stdlib and passes on Python
3.9 through 3.14 in bare uv venvs containing only pytest.

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

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

* Charge a re-cost for everything the reservation charged

Round re-costing priced fewer terms than the opening reservation it replaces, so
it did not merely fail to notice growth, it shrank a correctly sized lease. The
callback fires at the top of round zero, before the conversation has grown, so it
did so on a run that was still exactly the request that had been admitted, and
the room it handed back was room llama-server was already using.

- Charge the media, system and tools terms in the re-cost, the same ones the
  opening estimate charges. A vision tool request opened at 4096 and re-costed
  itself down to 1024 on round zero.
- Stop flattening "no cap named" to a zero output allowance. The reservation
  prices that as the rest of the budget; zero re-costed an uncapped loop down to
  its share on its first round, after which a newcomer was admitted beside it.
- Restore a given-up repark under the queue lock as a correction rather than a
  request. Asking through try_recost let a full cache refuse it after the lease
  had already recorded the figure, and the later release then subtracted a
  commitment that was never restored, leaving phantom room behind.
- Re-run the wait line after a reclaim drops the last repark barrier. Nothing
  else re-ran it, so a reclaim that left a free slot and free tokens behind
  stranded the queue, and a queued waiter also closes the fast path.
- Re-cost after the final synthesized pass, which was sent uncharged once the
  assistant turn and its tool results had been appended.
- Yield only where llama-server actually clears idle slots. Under --kv-unified
  the cells of a finished round stay resident until prompt_clear(), which runs
  only under --cache-idle-slots; --cache-ram 0 force-disables it and Studio emits
  exactly that on Windows under full GPU offload (#5692). There yielding freed
  nothing and would have promised the same cells twice, so re-costing declines
  instead, which is what it did before any of this existed.

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

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

* Tighten the comments around the KV re-costing

---------

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
Co-authored-by: danielhanchen <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant