Repository navigation
Studio: enforce the KV reservation on the wire, not just in the ledger - #10120
danielhanchen wants to merge 71 commits into
Conversation
An unstated "Max Tokens: Max" is charged a bounded allowance at admission, but the request sent to llama-server still asked for the whole window. The two disagreed by the entire cache. Under `--parallel N --kv-unified -c N` there is ONE pool of N cells while every slot reports `n_ctx = N`, so four chats each admitted at their fair share were all free to generate into the same pool. When it overflowed, llama-server called `send_error` on every processing slot at once: four conversations lost together, not one. Send the figure that was charged. The bound is the fair share rather than the smaller charged estimate: the charge is deliberately optimistic so more chats fit, while the bound only has to be physically safe. At most `capacity` requests hold a slot at once and each is held to `prompt + (share - prompt) == share`, so the total cannot pass `capacity * share <= budget`. Clamping to the charge instead would cut a lone chat to about a thousand tokens for no safety gain. The allowance is carried BESIDE the caller's cap, never folded into it. `_loop_budget_left` reads `max_tokens` as "what the caller allowed" and stops continuing once it is spent, so assigning it there would trade the crash for a silent truncation at one share. Overrun now ends as a plain `length` finish that the existing continuation path already resumes. A client that names its own cap is already honest and is never clamped. `/v1/completions` takes no lease and is left alone.
Codex Review SummaryThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 80ff261698
ℹ️ 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".
| ) | ||
| # What admission actually reserved. Applied to the wire only: `max_tokens` stays |
There was a problem hiding this comment.
Continue plain chats that hit the enforced allowance
When an ordinary GGUF chat has no tool loop, generate_chat_completion sends only this one capped request and returns its finish_reason="length"; the continuation logic cited by this change exists only in generate_chat_completion_with_tools. Consequently, with unified KV and multiple configured slots, even a lone uncapped standard chat is now truncated at roughly one slot's share instead of completing beyond that boundary. Add equivalent continuation handling for this path or avoid applying the hidden per-share cap here.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Right that generate_chat_completion has no continuation of its own; _continuation_max_tokens in the tool loop is the only one in the backend, and I removed the claim to the contrary from the helper docstring in f5834a8. Neither remedy holds up, though. A continuation carries the partial in its own prompt, so share - prompt shrinks with every resumption and converges on the one-token floor: the share bounds prompt plus output for the conversation, not one request, so no amount of continuation gets past it. And leaving the plain path unclamped is the overcommit this change exists to close, on the path the reproduction used. Bounding a chat to its share rather than letting all P chats reach for the full window is the stated tradeoff here, with request-granularity preemption as the follow-up; a length stop is the honest signal for it and the frontend already offers Continue on one (studio/frontend/src/features/chat/utils/continuation.ts).
The bound was the fair share while the charge stayed the smaller of the share and the flat unstated allowance. The reasoning was that the charge should stay optimistic so more chats fit, and that a prompt past its share is charged more than a share so fewer are admitted. That second part holds on its own but not in company. A SMALL prompt was charged `prompt + 1024` and still permitted its whole share. Mixed with a large-prompt request, the permitted total passes the cache while the charged total fits. Measured on a 262144 cache over four slots: prompts of 1 / 65537 / 189139 / 1 charged 258774 and were permitted 385750, over by 123606. Charge the whole share instead. `sum(charged) <= budget` then implies `sum(prompt + permitted) <= budget`, because the two are the same number. This costs no concurrency: `capacity * share <= budget` by construction, so a full capacity of unstated requests still fit. The flat allowance never admitted more than that, it only undercharged the ones it did admit. A randomised search over 60000 mixed admission sets falls from a 123606-token worst case to a single token, in the one case where a prompt fills the entire cache on its own and llama-server refuses it before generating anything. `test_the_bound_is_not_the_charge` asserted the unsafe property directly and is replaced by `test_the_bound_is_exactly_the_charge`.
|
Pushed The first revision bounded each request at its fair share while charging it the smaller of the share and the flat unstated allowance, and I justified the gap by noting that a prompt past its share is charged more than a share, so the queue admits fewer than A small prompt was charged The fix is to charge the whole share, so the charged and permitted figures are the same number and It costs no concurrency. A solo chat is unaffected and still gets its share rather than a flat thousand tokens.
Admission suite: 102 passed, 5 skipped. |
Two tests from the unstated-max-tokens suite pinned the mechanism this branch replaces: a flat allowance that a known share could only lower. One asserted the charge stayed within 100 tokens of that constant, the other that a large cache left it unchanged. The charge is now the whole share, because charging less than the wire permits is what made the reservation unsafe, so both are false by construction. The properties each class exists to protect are untouched and still asserted: a default chat never reserves the cache, capacity of them always fit at every cache size, and a named cap is priced as before. The scaling test now says the charge follows the share, since a large cache priced as though it were small would admit far more than it holds.
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: d5a11e9b42
ℹ️ 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".
| prompt_tokens = _openai_llama_admission_prompt_tokens( | ||
| payload, | ||
| image_tokens = _openai_llama_admission_image_tokens(llama_backend), | ||
| injected_tools = injected_tools, | ||
| ) |
There was a problem hiding this comment.
Base the wire cap on a bounded prompt-token count
With multiple unified-KV slots, this only enforces share - estimated_prompt, but _openai_llama_admission_prompt_tokens uses estimate_messages_tokens_dense, whose own implementation prices ordinary ASCII at four characters per token even though its documentation records English near 3.27 characters per token; it also does not render the active chat template. Thus several ordinary prompts can each occupy more KV than prompt_tokens reports, while all are charged one share and allowed enough output to reach one estimated share, so their real combined occupancy can still exceed the cache and kill the slots this change is meant to protect. Use a tokenizer/template-derived count or a genuine upper bound before deriving the wire allowance.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
The numbers are right: estimate_messages_tokens_dense prices ASCII at four characters per token and the same module measures English prose at 3.27 (context_window.py). It does not separate the charge from the bound, though. The wire cap comes from _openai_llama_admission_prompt_tokens, the helper the ledger charges from, which is what ae174d5 added for exactly this reason, so estimator error moves both figures together and they cannot drift. Estimator precision belongs to the accounting #9392 introduced rather than to this change, and enforcement only ever lowers permitted occupancy from the whole window to one estimated share, so no configuration ends up worse than main. A tokenizer or template-derived count means a count_chat_tokens round trip to llama-server on the admission path of every request, which is a redesign of that accounting rather than a fix to this diff.
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 784bcfb776
ℹ️ 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".
| ) | ||
| # After the wait, not before: a round that waited for room is bounded by the | ||
| # conversation it waited on. | ||
| return _openai_llama_admission_enforced_max_tokens( |
There was a problem hiding this comment.
Stop the round when its re-cost is refused
When lease.recost_waiting(...) returns False—notably with idle_slot_clearing_active=False when the pool has no room for a growing tool prompt, or after its timeout—the lease explicitly retains its old token commitment, but this newly added return still supplies a cap and the loop proceeds. Once the prompt itself exceeds that old commitment/share, even the one-token floor cannot make the request fit; several such rounds can therefore exceed the unified-KV budget and reproduce the all-slot context failure. Check the boolean result and do not send the round until its larger commitment has actually been acquired.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Declining and continuing is what recost_waiting is specified to do: "Giving up restores the old commitment and the decline-and-continue behaviour that predates this", and with allow_yield False it "degrades to plain recost, which declines rather than overcommits". That path exists for Studio on Windows under full GPU offload (--cache-ram 0 plus --kv-unified, #5692), where yielding would hand the same cells to a second caller; refusing to send the round there would stall every growing tool run instead. Nothing in this change made it worse either: before it the round carried a cap frozen at share - opening_prompt, which permits strictly more than the share - current_prompt it now carries. What is left is the one-token floor on a prompt already past its share, which the helper documents as deliberate. Reworking a refused re-cost into a hard stop is a change to the admission contract #9392 and #10070 set, not to this diff.
|
Codex Review: Didn't find any major issues. 👍 Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
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". |
|
Codex Review: Didn't find any major issues. 🚀 Reviewed commit: ℹ️ About Codex in GitHubCodex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you
If Codex has suggestions, it will comment; otherwise it will react with 👍. When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback". |
|
Codex Review: Didn't find any major issues. Keep them coming! Reviewed commit: ℹ️ About Codex in GitHubCodex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you
If Codex has suggestions, it will comment; otherwise it will react with 👍. When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback". |
|
@codex review |
|
To use Codex here, create a Codex account and connect to github. |
|
This PR fixes a mismatch between reserved cache capacity and permitted generation. It also introduces an output-length policy that can stop answers while cache capacity remains unused. Current behaviorAssume a 16K shared cache, four workers, and no explicit For a short prompt, this PR effectively budgets one quarter of the cache: One request, no other traffic:
[ prompt + answer: about 4K ][ about 12K unused ]
^
The answer cannot borrow this space.Larger prompts can receive larger reservations, which is useful. But once a prompt is too large for its share, the default output allowance switches to 1,024 tokens, less the safety margin: Estimated prompt: 10,000 tokens
[ prompt: 10,000 ][ answer: up to 960 ][ safety: 64 ]
Total reservation: 11,024 tokens
The answer stops even if the rest of the cache is unused.For a direct API client, that means a partial answer with The concern is the connection between worker count, prompt size, and answer length. Four workers is the default, so this output cap affects users who have not changed any concurrency setting. The obvious alternatives also lose somethingSimply reserving the whole available window for an uncapped request would make arrival order determine concurrency: A arrives first: [ A reserves the whole 16K ]
B arrives next: waits
C arrives next: waits
D arrives next: waits
Even if A's actual answer turns out to be short.Switching to non-unified cache gives predictable isolation, but loses the ability to serve larger prompts: [ A: fixed 4K ][ B: fixed 4K ][ C: fixed 4K ][ D: fixed 4K ]
A 10K prompt cannot fit, even when all other workers are idle.Dividing the cache by the number of active requests on each arrival is not sufficient either: A has already used 10K: [ A: 10K ][ free: 6K ]
B arrives.
Two 8K allocations are no longer possible:
A already occupies more than its proposed new share.Alternative: manage memory pressure during generationAllocating cache as requests grow, with pausing and resuming when the pool fills, could preserve larger prompts and longer answers without reserving the entire window upfront. This requires generation-time scheduling support; it is not implemented by this PR. A arrives alone
-> Allow it to grow beyond one quarter of the cache.
B arrives while space remains
-> Admit it without reserving every possible future token for A.
The shared cache approaches capacity
-> Pause a request and make its cache space reusable.
-> Let another request progress.
-> Restore or rebuild the paused request's state and resume it.Pausing alone does not free memory. This would require support for saving/restoring cached state or rebuilding it from retained text, while preserving generation state and tool-call correctness. The feasibility depends on the bundled llama.cpp's support for these operations. Existing server scheduling capabilities should be evaluated before adding a separate scheduler in Studio. This cannot make finite memory unlimited. If all four requests grow large, something must wait, and moving or rebuilding state adds latency. The desired tradeoff is: Under memory pressure:
Prefer: slower progress, with requests eventually completing
Over: shorter answers because of an implicit per-worker output capValidation needed before choosing the policyThe relevant cases for comparing scheduling approaches are:
The design target is automatic behavior: retain large-prompt support, allow concurrent requests, and handle memory pressure through scheduling instead of an implicit answer-length cutoff. Whether the bundled server can support this remains unverified. An interim reservation policy needs an explicit account of which behavior it sacrifices. |
…nd beside main's exact prompt count, and keep a Stop a cancel
|
@codex review |
1 similar comment
|
@codex review |
|
Codex Review: Didn't find any major issues. Bravo. Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
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". |
What happens today
Four parallel chats on one GGUF model all die together with:
Reproduced on
unsloth/Qwen3.8-27B-GGUFat-c 16384 --parallel 4 --kv-unified: four tool chats on the default "Max Tokens: Max", all four lost at the same instant.Why
Studio launches llama-server with
--parallel N --kv-unified -c N. That is ONE pool of N cells, but every slot reportsn_ctx = N. The server polices onlyprompt_tokens < slot.n_ctx, never "is there room right now", so requests that each fit individually are all admitted and then collide. On overflowserver-context.cppcallssend_erroron every processing slot, which is why one overrun kills all four rather than one.Admission already charges an unstated "Max Tokens: Max" a bounded allowance. The problem is that the reservation was pure accounting and was never enforced on the request. Studio reserved a share and simultaneously told llama-server the request could write the whole window. A client-stated cap was the only case that was both charged and enforced, which is why setting an explicit Max Tokens was the workaround.
What happens after
The charged figure is what gets sent, so
sum(prompt_i + allowance_i) <= budgetbecomes an invariant instead of a hope. An overrun ends as a plainfinish_reason="length", which the existing length-continuation path already resumes, so a long answer still completes.The bound is the share, not the charge
At most
capacityrequests hold a slot at once, and each is held toprompt + (share - prompt) == share, so the total cannot exceedcapacity * share <= budget. For the configuration above that is4 * (8 + 4088) = 16384exactly.Bounding by the smaller charged estimate would also be safe but would cut a lone chat to about a thousand tokens for no gain. The charge stays optimistic so more chats fit; the bound only has to be physically safe.
The trap this deliberately avoids
The allowance is carried beside the caller's cap, never folded into it.
_loop_budget_leftreadsmax_tokensas "what the caller allowed" and refuses to continue once it is spent. Assigning the allowance there would have replaced the crash with a silent truncation at one share. It travels as a separateadmission_output_allowanceand is applied only where the outgoing payload is built, including after the continuation override so every attempt, first or resumed, fits the share it was admitted on. A test asserts the symbol never appears in_loop_budget_left.A declined re-cost ends the turn
A tool round that grows its prompt re-costs its lease first. When
recost_waitingdeclines the growth (no room and no way to yield), the lease still holds the previous round's figure, so the larger prompt is not covered by it. The route used to ignore that answer and hand back a freshly priced cap anyway: four 4096-cell leases in a 16384-cell pool, one round growing to 4999 prompt tokens, committed stays at 16384 and the round still got an allowance of 1024, a permitted aggregate of 18311.A refusal is now
LlamaAdmissionRecostRefused, raised past the accounting handler that swallows everything else. Both consumers, the tool round and each final-answer attempt, end the turn on it: the partial stays, the finish islength, so the UI offers Continue rather than an error box, and the request is never sent. Where yielding is possible the wait still happens first; this only fires once waiting cannot help.The re-cost itself prices what the opening prices for a conversation it is handed (the messages and catalogue sent, media from the compaction count, transport), not the payload's raw
systemandtoolsagain, which a translating route has already folded in. It runs below the round's compaction, so a refusal is for the prompt the request is built from. A Stop or a release during the wait is a cancel, not a refusal, and ends the turn as a Stop does. A refused ending reports the prompt of the last attempt that ran beside the accumulated generation.What is left alone
max_tokens/max_completion_tokensbelow the window is already honest and is never clamped. A stated cap at or above the window is the same as no cap and is enforced as unstated.--no-kv-unified, where the aggregate is N times the window, so a share IS the window./v1/completions, which takes no lease at all, and the audio and video transcription requests, whose output cannot be priced. Out of scope and noted as such: the invariant holds for the priced chat surfaces.Scope
This is the safety floor, not the end state. It bounds each chat to its share rather than letting all P chats use the full N. Request-granularity preemption, which is what actually gives every chat the full window, is the follow-up.
Upstream has the same TODO in the overflow handler:
Tests
15 new tests in
test_llama_admission_enforced_max_tokens.pyplus, for the declined re-cost, the audit scenario against the real queue and lease (the refusal, the lease keeping its share, committed equal to the budget), a refused round sending nothing, a refused final continuation keeping its partial, and a stated cap at or above the window enforced as unstated, covering the invariant at 2048/4096/8192/16384/65536/262144 and at 2/3/4/8 slots, the pass-through cases, the edges, and that the allowance reaches the wire without becoming the caller's cap.Verified against clean
mainat3703a6678with an identical test selection: same 14 pre-existing failures on both sides, name for name (a local environment missingpeftand a diffusers pin), 6645 passing here against 6630 on main, the difference being these new tests.