Skip to content

fix(studio): count rendered GGUF prompts before shared-KV admission - #10794

Merged
danielhanchen merged 14 commits into
unslothai:mainfrom
Imagineer99:fix/gguf-admission-token-count
Sep 25, 2026
Merged

danielhanchen merged 14 commits into
unslothai:mainfrom
Imagineer99:fix/gguf-admission-token-count

Conversation

@Imagineer99

Copy link
Copy Markdown
Member

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:

  • Identical local A/B at 30,000 context, 3 slots, Qwen3-1.7B UD-Q4_K_XL, max_tokens=1024: baseline 3/3 shared-context errors; fixed 3/3 completions without errors, with large requests waiting for available capacity.
  • Short-prompt control: 3/3 complete, all three start generating before any completes.
  • Related admission, recost, media, and route tests: 277 passed, 5 skipped.
  • Worktree and pre-push checks pass. Post-fix audit flags only module-private test fixture names shared with unrelated test modules; manually reviewed as harmless.

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.

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Sep 11, 2026 •

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-09-14T16:12:03.298529Z d95cf1e New commits
ℹ️ 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" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@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: 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".

Comment thread studio/backend/routes/inference.py Outdated
Comment on lines +2258 to +2260
counted = await asyncio.to_thread(
_count_gguf_admission_prompt, llama_backend, payload, messages, injected_tools
)

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 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 👍 / 👎.

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.

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.

Comment on lines +23697 to 23701
reservation, admission_config = await _reserve_counted_gguf_chat(
messages = gguf_messages,
request = request,
llama_backend = llama_backend,
payload = payload,

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 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 👍 / 👎.

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.

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.

Comment on lines +23697 to 23701
reservation, admission_config = await _reserve_counted_gguf_chat(
messages = gguf_messages,
request = request,
llama_backend = llama_backend,
payload = payload,

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 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 👍 / 👎.

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.

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.

Comment on lines +2335 to +2338
if count_prepared_prompt:
prompt_tokens = _count_gguf_admission_prompt(
llama_backend, payload, conversation, injected_tools
)

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 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 👍 / 👎.

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.

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.

Comment on lines +2335 to +2338
if count_prepared_prompt:
prompt_tokens = _count_gguf_admission_prompt(
llama_backend, payload, conversation, injected_tools
)

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 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 👍 / 👎.

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.

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.

@danielhanchen

Copy link
Copy Markdown
Member

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?

@danielhanchen

Copy link
Copy Markdown
Member

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?

Copy link
Copy Markdown
Member Author

@danielhanchen Updated in 58ac6f2, now included in d95cf1e after merging current main (#10673), to prefer llama-server's native /v1/chat/completions/input_tokens endpoint for text chats. This renders and counts in one server request. If that endpoint is unsupported, times out, or returns an invalid count, admission falls back to the existing strict /apply-template + /tokenize path. Both paths use an exact rendered-prompt count; neither falls back to the character estimate.

Measured on Qwen3-1.7B UD-Q4_K_XL, WSL / RTX 5070 Ti, llama-server build 10840 (58670d128), with thinking disabled:

Per-request counting cost Samples Median p95
Existing two-request path 100 8.69 ms 10.75 ms
Native single-request path 100 8.30 ms 9.49 ms

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:

Injected condition Before After
Healthy 3 concurrent completions 3 concurrent completions
Legacy counting endpoints return 503 Chats run one at a time 3 concurrent completions using native count
Native count times out 3 concurrent completions using legacy path 3 concurrent completions using legacy fallback
Native endpoint returns 404 3 concurrent completions using legacy path 3 concurrent completions using legacy fallback
Native endpoint returns an invalid count 3 concurrent completions using legacy path 3 concurrent completions using legacy fallback

“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.

@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: 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".

Comment thread studio/backend/routes/inference.py Outdated
chat_template_kwargs = llama_backend._request_reasoning_kwargs(
payload.enable_thinking, payload.reasoning_effort, payload.preserve_thinking
),
continue_final_message = _continue_final_message(payload),

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 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 👍 / 👎.

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.

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.

@Imagineer99

Copy link
Copy Markdown
Member Author

@codex review

1 similar comment
@Imagineer99

Copy link
Copy Markdown
Member Author

@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.
@shimmyshimmer

Copy link
Copy Markdown
Member

pre-commit.ci run

@shimmyshimmer

shimmyshimmer commented Sep 25, 2026 •

Copy link
Copy Markdown
Member

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 480e697e7 (no equivalent commit found on this PR)

chatgpt-codex-connector[bot] on studio/backend/routes/inference.py (on the mirror)

@@ -2403,6 +2416,87 @@ def _openai_llama_admission_reserve(
     return reservation, config
 
 
+def _count_gguf_admission_prompt(
+    llama_backend,
+    payload,
+    messages,
+    tools = None,
+    cancel_event = None,
+) -> int:
+    """Exact prompt count plus media allowance; the whole pool if counting fails
+    (the character estimate undercounts numeric text, #10671)."""
+    from core.inference.chat_template_helpers import trailing_assistant_text
+
+    budget = _openai_llama_admission_budget(llama_backend) or 0
+    try:
+        text_messages, images = _openai_llama_admission_messages_for_estimate(
+            messages, vision = bool(getattr(llama_backend, "is_vision", False))
+        )
+        count = llama_backend.count_chat_tokens(
+            text_messages,
+            tools = tools,
+            strict = True,
+            prefer_native = images == 0,
+            chat_template_kwargs = llama_backend._request_reasoning_kwargs(
+                payload.enable_thinking, payload.reasoning_effort, payload.preserve_thinking
+            ),
+            continue_final_message = _continue_final_message(payload)
+            and bool(trailing_assistant_text(messages)),
+            **({"should_abort": cancel_event.is_set} if cancel_event is not None else {}),
+        )
+        if type(count) is not int or count <= 0:
+            raise ValueError("Invalid prompt token count")
+        return count + _openai_llama_admission_media_tokens(
+            payload,
+            message_image_parts = images,
+            image_tokens = _openai_llama_admission_image_tokens(llama_backend),
+            message_video_clips = _conversation_video_clips(messages),
+        )
+    except Exception:
+        logger.debug("Prompt count unavailable; reserving the context pool", exc_info = True)
+        return budget
+
+
+async def _reserve_counted_gguf_chat(
+    *,
+    request,
+    llama_backend,
+    payload,
+    messages,
+    injected_tools = None,
+    tool_loop: bool = False,
+):
+    config = llama_admission_config_from_env()
+    if not (config.enabled and config.kv_budget):
+        return await _openai_llama_admission_reserve_async(
+            request = request,
+            llama_backend = llama_backend,
+            payload = payload,
+            tool_loop = tool_loop,
+            injected_tools = injected_tools,
+        )
+    identity = (
+        getattr(llama_backend, "base_url", None),
+        _openai_llama_admission_budget(llama_backend),
+    )
+    counted = await asyncio.to_thread(
+        _count_gguf_admission_prompt, llama_backend, payload, messages, injected_tools
+    )

P2 Badge Register cancellation before counting GGUF prompts

When this helper is called from the tool-loop or standard non-streaming paths, _TrackedCancel is not entered until after this await returns, and no cancel_event is passed into _count_gguf_admission_prompt. Consequently, a stop by session ID or a disconnect during a slow /input_tokens → /apply-template → /tokenize sequence cannot interrupt the count and may delay cancellation for multiple 10-second HTTP timeouts; only the standard streaming branch currently registers its tracker before calling this helper. Register those other paths before counting and propagate their event here so should_abort can stop the fallback calls.

Useful? React with 👍 / 👎.

Rejected on the mirror

Reply from shimmyshimmer:

Same as the earlier round: this is cancel latency before admission, not a correctness bug. The count is one llama-server round trip of about 8 to 13 ms measured live (count endpoints bypass the slot task queue), so only a hung server stretches it, and the request still exits without running anything. Moving tracker registration ahead of admission on two more paths is a larger change than this PR should carry.

chatgpt-codex-connector[bot] (on the mirror)

🛡️ Codex Security Review

Here are some automated security review suggestions for this pull request.

Reviewed commit: 480e697e7b

No triage reaction was recorded on the mirror

chatgpt-codex-connector[bot] on studio/backend/routes/inference.py (on the mirror)

@@ -2403,6 +2416,87 @@ def _openai_llama_admission_reserve(
     return reservation, config
 
 
+def _count_gguf_admission_prompt(
+    llama_backend,
+    payload,
+    messages,
+    tools = None,
+    cancel_event = None,
+) -> int:
+    """Exact prompt count plus media allowance; the whole pool if counting fails
+    (the character estimate undercounts numeric text, #10671)."""
+    from core.inference.chat_template_helpers import trailing_assistant_text
+
+    budget = _openai_llama_admission_budget(llama_backend) or 0
+    try:
+        text_messages, images = _openai_llama_admission_messages_for_estimate(
+            messages, vision = bool(getattr(llama_backend, "is_vision", False))
+        )
+        count = llama_backend.count_chat_tokens(
+            text_messages,
+            tools = tools,
+            strict = True,
+            prefer_native = images == 0,
+            chat_template_kwargs = llama_backend._request_reasoning_kwargs(
+                payload.enable_thinking, payload.reasoning_effort, payload.preserve_thinking
+            ),
+            continue_final_message = _continue_final_message(payload)
+            and bool(trailing_assistant_text(messages)),
+            **({"should_abort": cancel_event.is_set} if cancel_event is not None else {}),
+        )
+        if type(count) is not int or count <= 0:
+            raise ValueError("Invalid prompt token count")
+        return count + _openai_llama_admission_media_tokens(
+            payload,
+            message_image_parts = images,
+            image_tokens = _openai_llama_admission_image_tokens(llama_backend),
+            message_video_clips = _conversation_video_clips(messages),
+        )
+    except Exception:
+        logger.debug("Prompt count unavailable; reserving the context pool", exc_info = True)
+        return budget
+
+
+async def _reserve_counted_gguf_chat(
+    *,
+    request,
+    llama_backend,
+    payload,
+    messages,
+    injected_tools = None,
+    tool_loop: bool = False,
+):
+    config = llama_admission_config_from_env()
+    if not (config.enabled and config.kv_budget):
+        return await _openai_llama_admission_reserve_async(
+            request = request,
+            llama_backend = llama_backend,
+            payload = payload,
+            tool_loop = tool_loop,
+            injected_tools = injected_tools,
+        )
+    identity = (
+        getattr(llama_backend, "base_url", None),
+        _openai_llama_admission_budget(llama_backend),
+    )
+    counted = await asyncio.to_thread(
+        _count_gguf_admission_prompt, llama_backend, payload, messages, injected_tools
+    )

🛡️ Codex Security Review

P2 Badge Security: Admit requests before running prompt counts

When shared-KV accounting is enabled (the default) and a GGUF model is loaded, an authenticated or explicitly enabled keyless chat caller can run this to_thread count before LlamaAdmissionQueue.reserve(). The queue therefore cannot reject excess requests until each has rendered/tokenized the attacker-controlled prompt through llama-server. These synchronous jobs use the same bounded executor as GGUF stream iteration and can make multiple 10-second HTTP calls, so a burst can exhaust workers and stall existing inference even when the excess requests are later rejected. Acquire a bounded count permit or provisional reservation first, then recost with the exact result and cancel counting on disconnect.

Useful? React with 👍 / 👎.

Rejected on the mirror

Reply from shimmyshimmer:

Not changing: the count runs only for authenticated callers and holds a worker for about 10 ms per request on a live llama-server (measured), the same pre-reservation worker pattern main already uses for the replayed-image estimate and audio decode. A burst of 1000 requests occupies the executor for well under a second, far less than what the same caller can cause by simply sending large prompts.

Verdict

The round did not reach a clean review on the mirror before it closed.

This is the review as it stood at that commit. Anything pushed to this PR afterwards was not part of it.

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.
@danielhanchen
danielhanchen merged commit 3480890 into unslothai:main Sep 25, 2026
45 of 48 checks passed
shaojun pushed a commit to shaojun/unsloth that referenced this pull request Sep 29, 2026
…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]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants