Repository navigation
Studio: reuse an identical llama-server prompt count within a tool round - #16756
Merged
Merged
Conversation
A GGUF tool round near the context window counts the fitted prompt, then counts the same conversation again for the reply-room check and the result budget. Each count is an /apply-template render plus a /tokenize round trip of the whole prompt. Keep the last few successful counts per llama-server process, keyed on everything the render sees; admission counts (prefer_native) and the text fallback are never memoised.
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. |
[skip ci]
Member
Author
|
@codex review |
|
Codex Review: Didn't find any major issues. Breezy! 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". |
danielhanchen
deleted the
studio-chat-token-count-and-stream-overheads
branch
November 5, 2026 14:48
danielhanchen
added a commit
to danielhanchen/unsloth-staging-2
that referenced
this pull request
Nov 9, 2026
…slothai#17090) ## Problem unslothai#16756 memoises Studio's llama.cpp chat token count, so a tool round that recounts the prompt it just fitted reuses one `/apply-template` + `/tokenize` render. The memo key covers the llama-server process, the model and every render input Studio sends, with an 8-entry LRU and no expiry. It does not cover the clock. llama.cpp builds `date_string` from the current time and gives Jinja templates `strftime_now`, and published templates print today's date (the Llama 3.2 template's "Today Date"). The same request rendered after midnight is a different prompt, possibly with a different token count, but the memo returns the old count for as long as the entry stays in the LRU. Reproduced with that template and a mocked server whose date moved from March 31 to April 1: the memo returned the March count (111 tokens) where a fresh render gives 112. ## Change The memo key also holds the local date (`time.strftime("%Y-%m-%d")`; llama-server is a local process on the same clock). Within a day, nothing changes: identical recounts still hit. On a new day the first count renders again. Cost: one `time.strftime` call per count, next to an HTTP round trip. ## Tests `test_a_new_day_renders_again`: two identical counts on one day render once, the same count the next day renders again. | arm | `test_llama_count_memo.py` | |---|---| | main (`a174823`) | 12 passed, 1 failed (the new test: no render on the new day) | | this PR | 13 passed | ## Not covered - A template that prints the time of day (`strftime_now("%H:%M")`) can still be off by its time string within one day. That spelling is not in the templates llama.cpp ships, and the count only sizes the context window.
danielhanchen
added a commit
to danielhanchen/unsloth-staging-2
that referenced
this pull request
Nov 23, 2026
…use the reservation's native count (unslothai#18931) A GGUF tool turn with admission on counts its whole history twice at the top of every round, one count straight after the other. The admission re-cost asks llama-server's native `/v1/chat/completions/input_tokens`, then the preflight fit renders the same conversation with `/apply-template` and counts it with `/tokenize`. On a 10 round turn that is 12 native counts (the reservation plus 11 re-costs) and 21 render counts, all of the full prompt. Two of these are pure waits: - The re-cost and the fit's first count price the same conversation and nothing runs between them that changes it, yet the second only starts when the first returns. llama-server serves both endpoints on its HTTP threads, so they can run at the same time. - The reservation count and round zero's re-cost send the identical native body a few milliseconds apart. The count memo from unslothai#16756 skips `prefer_native` calls, so round zero pays for the whole native count again before the first token. ## Change - `generate_chat_completion_with_tools`: when a round will run the preflight fit and has a re-cost to overlap with, the fit's first count starts in a worker thread just before the re-cost, with the same arguments the fit passes (the fit's count is now one helper, `_fit_count_tokens`, which both call; the round's tool list and reasoning kwargs are likewise one helper each). The thread only fills the existing count memo. The loop joins it right before the fit, which then makes its own call and reads the stored number back. If the prefetch fails or priced something different, the fit counts exactly as before. The re-cost, the iteration cap, the cancel check and every event keep their order. A cancel during the re-cost still returns at once without waiting for the thread. - `count_chat_tokens(prefer_native = True)`: a successful native count is kept in its own two entry memo keyed on the exact request body plus the llama-server process (URL, model, process object and pid, date), the same scope as the render memo. A respawn, a model switch or different messages miss. Only native answers are stored: a failed or refused native call still falls back to the render path every time, so endpoint failover is unchanged. `should_abort` is still checked before a hit. The native memo is separate so per-round re-costs (which never repeat) do not evict render counts. ## Results Colab CPU high-RAM VM (8 vCPU, load 0.8), Studio's prebuilt llama.cpp b11643 on CPU, Qwen3-0.6B Q4_K_M. One llama-server is shared by every arm. Each arm is its own process importing its own tree (merge base c7b1865, the same tree again as an A/A arm, and this branch), interleaved in 6 rotated blocks with 2 measured turns each (12 per arm per size). Each turn is a real 10 round tool loop through `_reserve_counted_gguf_chat`, `_openai_llama_admission_recost` (wired like `_gguf_recost`) and `generate_chat_completion_with_tools` with `context_overflow = "truncate_oldest"`. Only generation is faked, so the numbers are counting time. Qwen3-0.6B tops out at a 40960 token window, so the largest size is 30k tokens. Time from the reservation count to the first generation request (median, min to max): | prompt | base | base A/A | head | |---|---|---|---| | 15k tokens | 172.7 ms (168.8 to 180.6) | 170.3 ms (166.8 to 188.1) | 124.9 ms (122.3 to 131.9) | | 30k tokens | 295.6 ms (289.4 to 301.0) | 294.3 ms (290.9 to 298.9) | 211.5 ms (209.5 to 225.1) | Top of each later round, re-cost start to the fit's first count done (median of rounds 1 to 10 per turn, then median over turns): | prompt | base | base A/A | head | |---|---|---|---| | 15k tokens | 132.2 ms | 133.6 ms | 77.2 ms | | 30k tokens | 214.4 ms | 213.7 ms | 122.7 ms | Whole 10 round turn (counting only): 3748 / 3716 / 2768 ms at 30k, 2295 / 2293 / 1730 ms at 15k. On the same server a native count alone takes 81 ms at 30k, a render count 92 ms, the two back to back 172 ms and the two at once 95 ms. Server calls per turn: base 12 native + 21 render, head 11 native + 21 render (the fit never renders a prompt the prefetch already rendered). With the same inputs, the generation request bodies, the yielded events and every admission `want` are identical between base and head, on that llama-server and on a fake server with fixed counts at 30k tokens. ## Tests `tests/test_tool_round_count_reuse.py` (new, 15 tests): the prefetch fills the memo and the fit renders nothing twice; a turn with the prefetch disabled sends the same requests and events; a failed prefetch falls back to the fit's own count; no prefetch without a re-cost or a fit; a repeated native count is served from memory; a hit still honours `should_abort`; a restart, respawn, model change, different messages or tools miss; a failed native count is asked again; a server without the native endpoint keeps failing over; native counts never evict render counts. 5 of them fail on the merge base, as expected. The 162 existing test files that touch `count_chat_tokens`, `_gguf_recost`, `_fit_context`, admission or the tool loop were run on base and head and the failing test IDs compared. One test failed only on head: `test_exact_count_endpoint_failover_preserves_short_chat_concurrency[legacy]` asserted three native calls for three identical chats while the native endpoint works. Those chats now share the first answer, so that case accepts one to three calls (they race); every failure case still asserts three, which is the failover guarantee. All other failures are the same IDs on both sides (host environment, unrelated to counting). The new file, `test_llama_count_memo.py` and `test_gguf_admission_token_count.py` pass three runs in a row.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
A GGUF tool round near the context window counts the same prompt more than once. The fit counts the conversation it keeps, then the reply-room check and the result budget count the identical conversation again. Every count is an
/apply-templaterender plus a/tokenizeround trip that returns the whole token array, so each repeat costs the same as the first.This keeps the last 8 successful counts per llama-server process and returns the stored number when the next request would render exactly the same thing.
What changed
count_chat_tokensbuilds the render input (messages after neutralisation and image-turn preparation, system text, tools,tool_choice/parallel_tool_calls/response_format,chat_template_kwargs,continue_final_message) before opening the client, and keys a small LRU on its SHA-256 together withbase_url,_model_identifierand the llama-server process (object and pid). A respawn or a model switch therefore never reuses an old count.prefer_native=True) skip the memo. They run once per request and keep their existing endpoint failover behaviour.Evidence
Tool-loop probe (the existing
_make_backendharness with a recordingcount_chat_tokens, 3 tool rounds, 32K window, history at 1.2x the window): 9 counts, 5 distinct render inputs, so 4 were exact repeats. With the history below 0.8x of the window the reply-room check does not fire and there were no repeats, so this only helps long sessions near the window.Cost of one count against a real
llama-server(unsloth prebuilt, CPU, tiny Qwen3 GGUF with the real Qwen tokenizer, one tool). The base arm runs the unchanged module fromHEAD. 7 runs per arm, each arm run twice for A/A, median with [min-max]:The first count is within the base A/A spread, so hashing the key costs less than the measurement noise. A repeated count drops from 32-75 ms to under 1 ms. These numbers come from a tiny model on CPU. A large model's tokenizer pass costs about the same, because the server-side work is template rendering and tokenisation, not the model.
Tests
studio/backend/tests/test_llama_count_memo.py(12 tests): an identical recount reuses the render (fails on base: 2 round trips instead of 1); every input the render sees (messages, tools, system, template kwargs, continuation, rendering options, server process, model) causes a fresh count; failed renders and the text fallback are not remembered; admission counts are not memoised; the memo stays bounded (fails on base).count_chat_tokens(42 files) passes. In isolation the only failure istest_llama_cpp_tool_loop.py::test_gguf_over_cap_does_not_ask_for_a_retry_when_the_range_check_ends_the_loop, which fails the same way onmain.test_chat_generation_supervisor.py::test_durable_producer_preserves_monitor_originalso fails onmain.Not proven