Skip to content

Let tool chats decode in parallel instead of one at a time - #10046

Merged
danielhanchen merged 7 commits into
mainfrom
fix/studio-kv-preemption
Aug 31, 2026
Merged

danielhanchen merged 7 commits into
mainfrom
fix/studio-kv-preemption

Conversation

@danielhanchen

@danielhanchen danielhanchen commented Aug 31, 2026 •

Copy link
Copy Markdown
Member

Four chats sent together with Web Search or Tool Calling on decode one at a time. Measured on a 262144 cache they reach first token at 0.1s, 2.8s, 4.6s and 8.8s, while the UI shows all four as generating within 0.13s, which is why it reads as broken rather than queued.

Where it comes from

The slots are fine. The reservation is the serialiser.

#9392 moved admission from the slot count to the KV cache, after two chats killed each other on a 2048-token cache (565 + 1485, neither too long on its own). A tool loop's final size cannot be known when it is admitted, because each of up to 25 rounds appends its results and re-sends the whole conversation, so that PR reserved the entire cache, explicitly "at the price of serialising concurrent tool requests".

That price landed on the common case rather than a corner: any lit pill sets enable_tools. And it scales 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.

What this does

A tool loop opens at the same figure an equivalent request without tools is charged, with an equal share of the cache as a floor, and re-costs at each round boundary. That is the alternative #9392 named and left for the plumbing.

Two things make the accounting honest rather than decorative.

The injected catalogue is 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. The same user turn is 1716 prompt tokens with tools off and 2969 with them on, so about 1250 tokens were invisible. Missing them is not a rounding error, it is the difference between four chats fitting and four chats dying together.

Growth that does not fit waits. try_recost declines when the cache is full and the run continues at its old figure, sending a larger prompt than it is charged for. Enough of those is:

decode: failed to find a memory slot for batch of size 1861
srv  decode: failed to find free space in the KV cache, retrying with smaller batch size, n_batch = 1024
...
srv  decode: Context size has been exceeded. off = 0, n_batch = 1, ret = 1

llama.cpp halves the batch to 1, gives up, and then releases and clears every processing slot, not just the one that overflowed. Upstream's own comment there reads TODO: try to terminate only the largest active slot/sequence and continue with the rest. Under streaming it is harder to spot, because the transport is HTTP 200 and the failure arrives as the only SSE frame.

So recost_waiting yields the old commitment first and then waits to reclaim a bigger one. Yielding first is what makes it deadlock-free: blocking while still holding leaves four holders waiting on one another, whereas here _committed strictly falls so somebody always fits. It is called only between rounds, where the previous round's request has completed and the slot is idle at llama-server, so the capacity handed back is genuinely free. The wait is bounded, because a waiter holds the line shut for every other caller and an unbounded one would turn a single stuck run into a frozen pool; on expiry it restores the old commitment and falls back to declining, which is what every release before this did.

Measured

unsloth/Qwen3.5-4B-MTP-GGUF:UD-Q4_K_XL, --parallel 4, four chats sent together, peak llamacpp:requests_processing scraped from /metrics. Every case returns 200 on both sides.

context case before after
32768 four tool chats that fit 1 concurrent 4 concurrent
32768 four larger tool chats 1 concurrent, 11.0s 4 concurrent, 7.2s
4096 four tool chats 1 concurrent 2 concurrent
any tools off unchanged unchanged

Two rather than four at -c 4096 is the correct answer, not a shortfall: once the ~1250-token catalogue is counted, a third chat does not fit in 4096.

Not breaking

  • Single-slot backends are untouched. capacity 1 makes the share the whole cache, so a CPU-only load or one downshifted to fit VRAM is charged exactly what Admit generations against the KV cache, not just the slot count #9392 charged it.
  • Unknown budget is untouched. When the context length cannot be read back, budget is None and admission stays slot-only, as it was before Admit generations against the KV cache, not just the slot count #9392. UNSLOTH_LLAMA_ADMISSION_KV_BUDGET=0 still overcommits on purpose.
  • No frontend files change, and no route, SSE shape or status code changes, so there is no browser surface.
  • No new environment variable, no persisted state, no migration. An existing install upgrades into this with nothing to do.
  • on_conversation_grew is appended to the end of generate_chat_completion_with_tools. That signature has no bare *, so inserting it anywhere else would silently rebind the arguments after it for any caller passing them positionally.

Tests

  • Randomised stress over the queue invariants: committed never exceeds the cache, the queue always drains, the repark counter never leaks, across 18 seeded interleavings of concurrent growth, cancellation and release.
  • A matrix over the shapes the budget is actually derived from: 1/2/4/8 slots, unified and non-unified KV, unknown budget, admission disabled, and the env escape hatch.
  • Old-caller compatibility, including that the hook stays last in the signature.
  • The catalogue regression itself, which a live run caught and every unit test had missed.

3378 tests 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.

Scope

This covers tool loops, which have a safe point between rounds to wait at. Plain chats have no round boundary, so the second and independent cause of the same staircase (Max Tokens on "Max" reserving budget - prompt) is left alone here; it needs mid-generation preemption rather than this.

…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.
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Aug 31, 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-08-31T07:46:45.134477Z 77b40e1 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: 70a8ef5631

ℹ️ 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 +27850 to +27852
if on_conversation_grew is not None:
try:
on_conversation_grew(conversation)

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 Preserve the opening share through the first tool round

When Studio sends its common “Max” setting (max_tokens equal to the context window), this callback runs at iteration == 0, before the conversation has grown, and _openai_llama_admission_recost immediately requests the full KV budget. With four leases initially admitted at quarter shares, they all yield and only one can reclaim the full budget, so the chats still decode serially exactly as before this change. The initial conversation must retain its clamped opening allowance rather than being recosted as a grown round.

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.

Checked this one closely and the mechanism does not hold, so leaving it. The premise is four leases admitted at quarter shares, but with Max Tokens equal to the context window that is not what happens: the opening estimate is max(share, prompt_tokens + output_tokens) clamped to the budget, and with output_tokens equal to the window it resolves to the whole budget, not to a share. Measured on a 32768 budget with four slots: share 8192, opening 32768, round-zero re-cost 32768. The re-cost is the opening formula minus the media and non-message terms, so at round zero it is structurally never larger than the opening. Any serialisation in that configuration comes from the opening reservation and predates this callback, and it is honest: a run that may generate the whole window does occupy it. The real round-zero defect was the opposite sign, and that is 3891868398 and 3891868403, both now fixed.

Comment thread studio/backend/routes/inference.py Resolved
Comment thread studio/backend/routes/inference.py Resolved
danielhanchen and others added 2 commits August 31, 2026 06:07
…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.

@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: 1049bf1795

ℹ️ 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 +505 to +506
held, self._tokens = self._tokens, 0
queue.yield_commitment(held)

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 Make the failed recost-to-yield transition atomic

A release can grant a queued newcomer between the failed self.recost(want) and this later yield_commitment call, because no repark is registered during that gap. For example, with two 2000-token holders on a 4096 budget and a queued 2000-token arrival, a holder growing to 3000 can fail its recost, the other holder can release and admit the newcomer, and only then can the grower yield—leaving it unable to reclaim until the newcomer finishes despite the stated in-flight priority. Transitioning from the failed recost to the yielded/reparking state under one queue lock avoids this overtaking race.

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.

Leaving this one. The gap is a priority inversion at worst, not an overcommit: the lease still holds its old commitment across it, so nothing is handed to another caller on the strength of room that is not free. The stall that was genuinely reachable through that path is 3891868424, which is fixed in 3049990.

Comment thread studio/backend/routes/inference.py Outdated
Comment on lines +2031 to +2033
prompt_tokens = estimate_messages_tokens_dense(
_openai_llama_admission_messages_for_estimate(conversation)[0]
)

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 Price dense ASCII correctly during round re-costing

When a conversation contains long base64, hex, minified JSON, or similar dense ASCII in tool arguments or results, estimate_messages_tokens_dense still charges ASCII at four characters per token. The repository's context_window.py explicitly records measured costs near 1.13–2.75 characters per token and provides estimate_messages_tokens_conservative for this case. Several loops can therefore reclaim commitments far below the KV their next prompts actually occupy and be admitted together past the shared cache budget; use the conservative estimator or an exact backend token count for live re-costing.

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.

Leaving this one, since it is not something this change introduces. estimate_messages_tokens_dense is the estimator the opening reservation already uses, unchanged by this PR, so the re-cost using it is what keeps the two sides of the same lease priced the same way. Pricing a re-cost differently from the reservation it replaces is exactly the class of bug 3891868398 and 3891868403 turned out to be. If dense is the wrong default it is wrong at admission too and should change in both places together, which is a separate change with its own measurements.

return self._give_up_repark(queue, held, cancelled = True)
if deadline is not None and time.monotonic() >= deadline:
return self._give_up_repark(queue, held, cancelled = False)
time.sleep(poll_s)

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 Avoid blocking the shared executor while waiting to repark

Each tool stream advances its synchronous generator through asyncio.to_thread(next, gen), so this polling sleep occupies a worker in the event loop's shared default executor. On an 8-slot backend in a low-CPU container with fewer than eight executor workers, simultaneous growth can leave one reparker holding the reclaimed budget while the remaining workers block here; queued reparking calls consume the worker released after the winner's next yielded event, leaving no worker to advance that winner to completion and release its commitment. The pool then stalls until the 300-second timeout (after which callers may proceed under stale accounting), so the wait needs an async/non-shared mechanism or a dedicated executor.

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.

Leaving this one. recost_waiting sleeps inside the generator existing to_thread(next, gen) call, so a reparker consumes no worker it did not already own while decoding. The number of reparkers is bounded by the slot count, the winner keeps its own worker throughout, and the wait is bounded by the 300s timeout regardless.

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

Copy link
Copy Markdown
Member Author

@codex review

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. 🎉

Reviewed commit: 3049990e93

ℹ️ 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".

@danielhanchen

Copy link
Copy Markdown
Member Author

Confirmed this hits studio/backend/routes/inference.py where a tool loop still reserves the entire cache, so any second chat with a tools pill lit is queued behind the first, and the missing server-side catalogue tokens explain the slot-wide clears. Will get this reviewed.

@mahiatlinux
mahiatlinux self-requested a review August 31, 2026 08:50
@mahiatlinux mahiatlinux self-assigned this Aug 31, 2026
@danielhanchen

Copy link
Copy Markdown
Member Author

Before/after screenshots for this PR, from two isolated installs built from the merge base (da3c85c05) and the head (77b40e145). Four chat threads in four independent browser contexts, sent together, photographed 8s in and tiled.

Posting these with a clear caveat: they do not demonstrate the fix. Both sides look the same, and the measurements agree with the picture. I would rather show the run than describe it.

four parallel chats, merge base vs head

Three bursts of four chats per side, ctx 32768, --parallel 4 --kv-unified, tools on and maxTokens pinned to 512 (both asserted at runtime rather than assumed):

merge base head
median time for the last of four to produce text 6.20s 5.87s
median spread across the four 3.23s 3.02s

The same on both sides, and the composite shows one pane with prose and the rest on "Generating..." either way.

This is not evidence that the change does nothing. The base's tool-loop branch is a bare return budget, the whole cache, which would serialise strictly if it were reached, and at 6.20s for the last of four it plainly was not. The reservation under test was never taken on either side: the browser path did not set enable_tools. Pinning the pills through PUT /api/chat/settings turns out not to prove the request carried them, and an admission decision that is never made cannot be photographed.

What would settle it is a measurement below the SPA: four concurrent posts to /v1/chat/completions carrying tools, scraping llamacpp:requests_processing off the llama-server port (peak 1 means serialised, peak 4 means not). Only once the base serialises there is there a difference worth photographing.

Two notes for anyone reproducing this, since both produced confident-looking numbers that were wrong. The first-token probe initially counted Generating... as text; it is rendered before any token exists, so every pane appeared to start within 0.2s on both sides. And run-to-run spread on this box is the same size as the effect being claimed: single pairs gave base 1 pane / head 2, then base 4 / head 2, on the same two builds. Any version of this needs repeats rather than one pair.

The unit and integration evidence for the actual fixes is unchanged: 463 passed, 5 skipped across the admission, tool-loop and Anthropic suites.

@danielhanchen
danielhanchen merged commit 044cdb8 into main Aug 31, 2026
49 of 52 checks passed
@danielhanchen
danielhanchen deleted the fix/studio-kv-preemption branch August 31, 2026 09:26
danielhanchen added a commit that referenced this pull request Aug 31, 2026
…10070)

* Stop charging a chat the whole cache because Max Tokens says "Max"

Studio ships "Max Tokens: Max", and Max sends max_tokens = the context length.
A client that names nothing arrives the same way, since _build_passthrough_payload
fills in max_tokens = backend_ctx. So the overwhelmingly common request claims it
may write the entire window, and admission believed it: one chat committed the
whole KV cache before generating a token, and the next was refused however little
either actually wrote.

That is the reservation, not the hardware. Measured on a 262144 cache with
--parallel 4 --kv-unified, four chats reached first token at 0.1 / 2.8 / 4.6 /
8.8s with llamacpp:requests_deferred flat at 0 throughout, meaning llama-server
had free slots the whole time and never saw requests 2 to 4.

#10046 fixed the tool-loop half of this (`if tool_loop: return budget`). This is
the other half, and it covers every plain chat.

An absent cap and a cap of the whole window are the same statement, and neither
is a promise to fill the cache, so both are now charged
_OPENAI_LLAMA_ADMISSION_UNSTATED_OUTPUT_TOKENS (1024, clamped to what is left,
overridable with UNSLOTH_LLAMA_ADMISSION_UNSTATED_OUTPUT_TOKENS). On a 32768
cache with four slots:

  Max Tokens = Max   32768 -> 1032   four fit
  no cap named       32768 -> 1032   four fit
  max_tokens = 512     520 ->  520   unchanged

The opening estimate and the round re-cost share one helper, so a re-cost cannot
read "Max" literally and put the run back on the whole cache at its first round
boundary.

This is an estimate where the rest of that function is a bound, which is the
trade. A run that generates more than the allowance is undercharged until
something re-costs it; a tool loop does that at every round boundary, a plain
chat has no round boundary yet, so on a genuinely full cache a long uncapped
generation can still overrun. The knob is there for a deployment where that
matters, and mid-turn preemption is what removes the caveat.

Two existing tests pinned the old policy and are updated rather than deleted:
the uncapped reservation is now bounded instead of the whole window, and the
round-zero re-cost test keeps the invariant it exists for (the re-cost must not
shrink the opening lease) while dropping its assumption that the opening is the
whole cache.

* Tighten the comments on the Max Tokens budgeting change

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

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

* Compare Max against the per-request window, not the aggregate budget

Under --parallel N --no-kv-unified the admission budget is the aggregate of N
private caches, while Studio's Max still sends one slot's context_length. The two
are in different units, and comparing them only happens to agree under
--kv-unified, where they are the same number.

Measured on a backend reporting context_length 4096 with _kv_cache_context_total
16384: Max was read as a real cap, each chat cost 4104, and four came to 16416
against 16384, so only three fit. The same backend now prices it at 1032 and all
four fit.

The allowance takes the per-request window, read off the backend by
_openai_llama_admission_context_window, and falls back to the budget when it is
unknown, which is the unified case anyway.

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

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

* Clamp the unstated allowance to the slot, not to the whole cache

Second half of the same units mistake as the cap comparison: the clamp subtracted
the prompt from the aggregate budget rather than from the per-request window, so
under --parallel N --no-kv-unified it charged a request for more KV than its own
slot can hold.

Measured on four private 4096 caches with a 3500-token prompt: a flat 1024
allowance charged 4524 for something that can only ever occupy 4096, and four of
those came to 18096 against the 16384 aggregate, so three fit. Clamped against
the window it gives 596, a charge of exactly 4096, and all four fit.

Identical under --kv-unified, where window and budget are one number.

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

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

* Trim the comments on the unstated max_tokens sizing

* Clamp the unstated allowance to a slot's fair share

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

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

---------

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

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants