Repository navigation
fix(studio): count rendered GGUF prompts before shared-KV admission - #10794
Conversation
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: bf1dd15594
ℹ️ 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".
| counted = await asyncio.to_thread( | ||
| _count_gguf_admission_prompt, llama_backend, payload, messages, injected_tools | ||
| ) |
There was a problem hiding this comment.
Bound prompt counting before the admission queue
When many native GGUF chat requests arrive concurrently, every request reaches this to_thread call before reserve() can enforce the configured capacity or maximum queue depth. Since count_chat_tokens performs up to two llama-server HTTP operations over the full rendered prompt, a burst can enqueue an unbounded number of executor jobs and overload the same server that admission control is intended to protect, rather than rejecting excess callers with 429; place the counting stage behind an equivalent bounded gate.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
The pre-admission count is real, but the reported overload is not established. With capacity 1 and queue depth 1 already occupied, a completed count is followed by LlamaAdmissionQueueFull; generation capacity and the 429 path remain enforced. A separate bounded counting stage may be useful hardening, but this review has not reproduced a server failure from a supported workload.
| reservation, admission_config = await _reserve_counted_gguf_chat( | ||
| messages = gguf_messages, | ||
| request = request, | ||
| llama_backend = llama_backend, | ||
| payload = payload, |
There was a problem hiding this comment.
Exit the tracker when prompt counting is cancelled
If a streaming request task is cancelled while awaiting this newly asynchronous count, CancelledError bypasses the following except LlamaAdmissionQueueFull, and the _TrackedCancel entered immediately above is never exited because the response cleanup has not been constructed yet. This permanently leaves the request in _CANCEL_REGISTRY and active_generations, so later model load/unload operations continue to see a phantom active generation until process restart; ensure cancellation unwinds the tracker around this await.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in 2c112d8. Cancelling the streaming route during prompt counting reproduced two stale cancellation keys and one active-generation entry. The pre-response exception path now exits the tracker and re-raises; the full-route regression verifies both registries are empty afterward.
| reservation, admission_config = await _reserve_counted_gguf_chat( | ||
| messages = gguf_messages, | ||
| request = request, | ||
| llama_backend = llama_backend, | ||
| payload = payload, |
There was a problem hiding this comment.
Start streaming before waiting on prompt counting
For streaming GGUF requests, this await now completes before _SameTaskStreamingResponse is returned, so the route cannot send headers or the existing admission keepalive comments while count_chat_tokens runs. That method can spend nearly 20 seconds across its two 10-second llama-server calls, meaning a slow tokenizer or large prompt can trip client/proxy response-header or idle timeouts even though the subsequent admission wait is explicitly kept alive; move the count into a stream-aware phase or emit keepalives while it runs.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Counting does precede response headers. The claimed client/proxy timeout remains unproven: no failing supported client configuration was demonstrated. The existing route also awaits asynchronous estimation before constructing its streaming response. Keeping this as a latency concern rather than a confirmed correctness defect; it can be revisited with a concrete failing client/server case.
| if count_prepared_prompt: | ||
| prompt_tokens = _count_gguf_admission_prompt( | ||
| llama_backend, payload, conversation, injected_tools | ||
| ) |
There was a problem hiding this comment.
Skip exact recosting when KV admission is disabled
When UNSLOTH_LLAMA_ADMISSION_CONTROL=0 or UNSLOTH_LLAMA_ADMISSION_KV_BUDGET=0, the opening helper correctly skips exact counting, but every native tool-loop round still enters this branch because count_prepared_prompt is set unconditionally. The resulting /apply-template and /tokenize calls cannot affect admission—the disabled reservation has no queue or the queue has a zero budget—yet they add two synchronous llama-server round trips before every tool generation, so the documented escape hatches no longer remove the costly accounting path; gate this count on the active admission configuration.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in 2c112d8. Tool-round recosting now returns when admission control or KV accounting is disabled. Regression tests exercise both environment switches with real reservations and verify no count is issued.
| if count_prepared_prompt: | ||
| prompt_tokens = _count_gguf_admission_prompt( | ||
| llama_backend, payload, conversation, injected_tools | ||
| ) |
There was a problem hiding this comment.
Abort tool-round counts when the request is cancelled
When Stop or another cancellation arrives between tool rounds, generate_chat_completion_with_tools invokes on_conversation_grew before checking cancel_event, and this branch synchronously performs the rendered-prompt count without checking or forwarding that event. A cancelled tool generation can therefore remain blocked for nearly 20 seconds across /apply-template and /tokenize before the loop observes the cancellation; check the event before counting and pass it through the counter's existing should_abort hook.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in 2c112d8. Recosting checks cancellation before counting, forwards the event through should_abort, and skips recost after cancellation. Tests cover Stop before the round and during native-count failure, verifying no fallback HTTP call starts. An already-running HTTP call still finishes or reaches its existing timeout.
|
Confirmed the character estimate at studio/backend/routes/inference.py:2098 is still what prices admission today, so the undercount you describe is real. This does add two llama-server round trips per native GGUF chat and reserves the whole pool whenever the count fails, so could you share what the added latency looks like on a short prompt and what happens on a backend where count_chat_tokens is unavailable? |
|
Confirmed the character estimate is still what admission uses in studio/backend/routes/inference.py, so the undercount is real, but this now puts a strict count_chat_tokens call on every native GGUF chat and falls back to reserving the whole pool when it fails. Could you confirm the added per-request counting cost and that a tokenizer hiccup will not serialise chats that run concurrently today? |
|
@danielhanchen Updated in 58ac6f2, now included in d95cf1e after merging current main (#10673), to prefer llama-server's native Measured on Qwen3-1.7B UD-Q4_K_XL, WSL / RTX 5070 Ti, llama-server build 10840 (
The same 20-token prompt was used for both, alternating the order of the two methods in the same process. This includes client setup and the production admission-count helper. The speedup is modest; the main improvement is avoiding serialization when one counting endpoint path fails. For concurrency, I ran identical before/after probes with real generation, 30,000 shared KV tokens and 3 slots:
“Concurrent” means all three emitted content before any finished. The injected timeout included a 50 ms delay, and the event loop remained responsive. The dense numeric prompt counted 22,511 tokens identically through both methods. Three such requests were still admitted one at a time and all completed without context errors. Counts also matched for a short prompt, Unicode, tool schemas, and assistant continuation. Media keeps its existing counting and embedding allowance path. The remaining limit is a complete counting outage: if neither exact path succeeds, the full-pool fallback still applies. This change preserves concurrency for an endpoint-level hiccup; it cannot promise unchanged concurrency when all exact counting is unavailable. Validation on the merged branch: 1,046 passed, 6 skipped, including the new approval-context-release tests, plus passing lint, worktree and pre-push checks. The live concurrency and numeric-prompt probes also pass on this merged version. The live probes exercise production counting/admission helpers and direct llama-server generation, not the entire Studio HTTP/UI flow. |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: d95cf1e419
ℹ️ 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".
| chat_template_kwargs = llama_backend._request_reasoning_kwargs( | ||
| payload.enable_thinking, payload.reasoning_effort, payload.preserve_thinking | ||
| ), | ||
| continue_final_message = _continue_final_message(payload), |
There was a problem hiding this comment.
Recheck continuation before recosting tool rounds
When a tool-enabled request starts with continue_final_message=true, this keeps passing that original flag after the loop appends a tool result, even though the live generation path only enables continuation while the current conversation still ends in assistant text. Subsequent counts therefore render with add_generation_prompt=false while the actual round uses the normal generation prompt, causing an undercount; if llama-server rejects that invalid continuation shape instead, the helper falls back to the entire KV budget and unnecessarily serializes the loop. Derive this flag from the current messages, as the generation path does.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in 7ad5594. Admission counting now rechecks the current conversation for trailing assistant text, matching generation after tool results. The regression fails before the fix and passes afterward; 470 focused and dependent tests passed, with 5 skipped.
|
@codex review |
1 similar comment
|
@codex review |
Reuse one SSL context for the count client (httpx loaded the CA bundle on every admission, ~15 ms of a ~24 ms count), drop a repeated enabled check, and skip the character estimate in a counted recost since the count replaces it.
|
pre-commit.ci run |
|
Review record for #10794, carried over from the mirror it was reviewed on: danielhanchen/unsloth-staging-review#106. Findings are quoted as posted and attributed to the account that posted them. The reactions shown are the triage recorded on the mirror; none were re-applied here. Commits are named as the mirror's, with this PR's equivalent where one was found. Round 1 — reviewed mirror
|
The route now counts the prompt before reserving, so the test double needs a count and the spy moves to the token sizing both paths share.
A test elsewhere in the suite can replace sys.modules["httpx"], after which a fresh `import httpx` no longer reaches the client llama_cpp builds, and seven count tests fail only when they share an xdist worker with it.
…thai#10794) * fix(studio): count GGUF prompts before shared KV admission * fix(studio): use native GGUF counts with exact failover * test(studio): retain asynchronous admission and counting recovery * fix: recheck GGUF continuation when counting tool rounds * fix: honor cancellation and disabled GGUF admission * Tighten admission count docstrings * Cut per-request admission count overhead Reuse one SSL context for the count client (httpx loaded the CA bundle on every admission, ~15 ms of a ~24 ms count), drop a repeated enabled check, and skip the character estimate in a counted recost since the count replaces it. * Tighten moved recost comments * Price the audio admission test through the counted GGUF path The route now counts the prompt before reserving, so the test double needs a count and the spy moves to the token sizing both paths share. * Trim recost comments * Patch the httpx module llama_cpp uses in the count tests A test elsewhere in the suite can replace sys.modules["httpx"], after which a fresh `import httpx` no longer reaches the client llama_cpp builds, and seven count tests fail only when they share an xdist worker with it. --------- Co-authored-by: Daniel Han <[email protected]>
Concurrent native GGUF chats can overflow a shared KV cache because the character-based admission estimate undercounts numeric text. In the local reproduction, a prompt estimated at 5,687 tokens actually evaluates 22,560 tokens; three such requests are admitted together into a 30,000-token pool and all fail.
Count the prepared chat through llama-server's strict rendered-prompt tokenizer before reserving KV capacity, including injected system text and tool schemas. Count off the event loop and retain the existing output and media allowances. Use the same count for native tool-loop recosting; if counting fails, reserve the full pool so the request runs alone.
Validation:
Scope: native Studio GGUF chat admission. Other protocol passthrough paths, the existing uncapped-output policy, and media embedding estimates are unchanged. This does not establish a fix for the separate MTP batch-index or tool-permission reports. Reproduced on WSL with an RTX 5070 Ti and a cached Qwen3-1.7B model, not the reporter's Windows desktop/Nemotron/5090 setup.
Related to #10671.