Skip to content

Stop charging a chat the whole cache because Max Tokens says "Max" - #10070

Merged
danielhanchen merged 10 commits into
mainfrom
fix/studio-unstated-max-tokens
Aug 31, 2026
Merged

danielhanchen merged 10 commits into
mainfrom
fix/studio-unstated-max-tokens

Conversation

@danielhanchen

Copy link
Copy Markdown
Member

What

Studio ships Max Tokens: Max, and Max sends max_tokens = the context length. A client that names nothing arrives the same way, because _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 the whole time. llama-server had free slots and never saw requests 2 to 4, because Studio was holding them.

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

How

An absent cap and a cap of the whole window are the same statement, and neither is a promise to fill the cache. Both are now charged _OPENAI_LLAMA_ADMISSION_UNSTATED_OUTPUT_TOKENS, which is 1024, clamped to what is left of the budget and overridable with UNSLOTH_LLAMA_ADMISSION_UNSTATED_OUTPUT_TOKENS.

Only "the whole window" reads as unstated. A caller that deliberately asks for nearly all of it has said something, and is charged for it.

The opening estimate and the round re-cost call one helper, so a re-cost cannot read "Max" literally and put the run back on the whole cache at its first round boundary, undoing at round zero exactly what the opening stopped doing.

Before and after

Measured through _openai_llama_admission_tokens on a 32768 cache with four slots, before and after on the same tree:

request before after four fit at once
Max Tokens = Max 32768 1032 no to yes
no cap named 32768 1032 no to yes
max_tokens = 512 520 520 unchanged

A request that states a real cap is priced exactly as it was.

The trade, stated plainly

This is an estimate where the rest of that function is a bound. A run that generates more than the allowance is undercharged until something re-costs it. A tool loop does that at every round boundary (#10046). A plain chat has no round boundary yet, so on a genuinely full cache a long uncapped generation can still overrun, which is the hazard the old "reserve the window" behaviour was closing.

It was closing it by making the default chat un-runnable concurrently, which is too high a price for a case almost nothing hits. The env knob is there for a deployment where it does, and mid-turn preemption is what removes the caveat properly.

Tests

New test_llama_admission_unstated_max_tokens.py: what counts as unstated (absent, equal to the window, above it, and the boundary case one below it, which stays a real cap), that the allowance never exceeds what is left on a small cache, that four default chats now fit in one cache, that max_completion_tokens is read the same way, and that an unknown budget still declines to price.

Two existing tests pinned the old policy and are updated rather than deleted, since the policy is what changed:

  • test_an_uncapped_request_reserves_the_rest_of_the_window becomes ..._reserves_a_bounded_allowance.
  • test_round_zero_keeps_an_uncapped_loop_s_output_allowance keeps the invariant it exists for, that the re-cost must not shrink the opening lease, and drops its assumption that the opening is the whole cache. It now asserts the two sides agree rather than asserting a number, which is the property that actually matters.

test_two_uncapped_short_prompts_do_not_both_run still passes, but for a different reason than before, and its docstring now says so: on a 2048 cache two of them simply do not fit. On a larger cache they now do both run, which is the point.

Affected suites: test_llama_admission*.py, test_anthropic_admission.py, test_llama_cpp_tool_loop.py -> 384 passed, 5 skipped.

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.
@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-31T14:13:38.577935Z 4a5c96a Manual request
ℹ️ 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.

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@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: 4244c5fddc

ℹ️ 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 +1733 to +1734
if cap is not None and cap < budget:
return cap

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 Compare Max against the per-request context window

When llama-server uses --parallel N --no-kv-unified, _openai_llama_admission_budget intentionally returns the aggregate of the private caches (context_length * N), while Studio's Max setting sends the per-slot context_length. Consequently cap < budget classifies that default Max value as a real cap; adding any prompt tokens makes each reservation cost more than one slot's share, so all N default chats cannot run concurrently (for four 4096-token caches, at most three fit). Detecting Max needs the per-request context window rather than the aggregate admission budget.

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.

Confirmed and fixed. Reproduced exactly as described: a backend reporting per-slot context_length 4096 with _kv_cache_context_total 16384 (four private caches) priced a Max chat at 4104, so four of them came to 16416 against 16384 and only three fit.

The units were the bug. cap is per request and budget is the aggregate, so comparing them only happens to agree under --kv-unified, where the two are the same number. _openai_llama_admission_output_allowance now 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. Same backend now prices that chat at 1032 and all four fit.

Covered by TestMaxIsPerRequestNotPerCache: Max unstated against the per-request window, four default chats fitting four private caches, a real cap under the window still being a cap, and the unknown-window fallback.

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

Copy link
Copy Markdown
Member Author

@codex review

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@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: 8f1eef26f1

ℹ️ 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
window = context_window or budget
if cap is not None and cap < window:
return cap
return min(_OPENAI_LLAMA_ADMISSION_UNSTATED_OUTPUT_TOKENS, max(0, budget - prompt_tokens))

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 Clamp the allowance to the per-request window

Under --parallel N --no-kv-unified, this subtracts the prompt from the aggregate cache budget rather than the per-slot window. For example, with four 4096-token private caches and a 3500-token prompt, the default allowance remains 1024 and the request is charged 4524 tokens, so only three such chats fit in the 16384-token aggregate even though each slot can occupy at most 4096 KV positions. Clamp the unstated allowance against window - prompt_tokens so long default prompts do not reintroduce the concurrency loss this change is intended to fix.

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.

Confirmed and fixed. Reproduced: four private 4096 caches with a 3500-token prompt gave a flat 1024 allowance and charged 4524, which is more KV than one slot can physically hold, and four of those came to 18096 against the 16384 aggregate so only three fit.

The clamp was the second half of the same units mistake as the cap comparison: it subtracted the prompt from the aggregate budget rather than from the window. It now clamps against window - prompt_tokens, so the same case gives an allowance of 596, a charge of exactly 4096, and all four fit. Identical under --kv-unified, where window and budget are one number.

Covered by TestTheAllowanceCannotExceedOneSlot: a long prompt shrinking the allowance to fit its slot, four such chats still fitting, a prompt that fills the slot getting nothing, a short prompt still getting the full allowance, and the unified case being unchanged arithmetic.

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

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Already looking forward to the next diff.

Reviewed commit: ed47e0bcac

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

@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: 7839ba0262

ℹ️ 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 +1734 to +1735
if cap is not None and cap < window:
return cap

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 Preserve explicit full-window caps for Anthropic requests

When /v1/messages supplies max_tokens equal to or greater than the backend context window, this branch treats that explicit Anthropic output cap as Studio's implicit “Max” setting and reserves only the 1024-token estimate. anthropic_messages passes the same payload.max_tokens through to generation, so several such requests can be admitted even though each may consume nearly the full context, defeating KV admission and potentially causing context-size failures. Restrict this sentinel interpretation to request surfaces that actually synthesize the Studio/OpenAI “Max” value.

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 premise is right and the conclusion is backwards, so I am leaving this as is.

The premise checks out: /v1/messages does reach this code, via the reservation at inference.py:27949, so an Anthropic request with max_tokens >= context_length is charged the unstated allowance.

The conclusion does not. max_tokens is a required field on the Messages API, and it is documented as "the maximum number of tokens to generate before stopping ... this parameter only specifies the absolute maximum". A client there has no way to express "no limit" other than a large value, so a full-window max_tokens on that surface is the same non-statement as Studio synthesising "Max" on the OpenAI one. If anything it is weaker evidence of intent, since the OpenAI caller could have omitted the field and chose not to.

There is also no signal to key the suggested restriction on. Studio sends max_tokens = context_length for "Max", _build_passthrough_payload sends max_tokens = backend_ctx when the client names none, and a deliberate client cap of the window arrives byte-identical to both. "Restrict this to surfaces that synthesize the Max value" is not implementable without inventing a new marker, and a request that names the whole window is not meaningfully capped whoever sent it.

The undercharge you describe is real, but it is the documented trade of the change rather than a property of the Anthropic surface: the allowance is an estimate where the rest of the sizing is a bound, a tool loop re-costs at every round boundary and a plain chat cannot yet, and UNSLOTH_LLAMA_ADMISSION_UNSTATED_OUTPUT_TOKENS is the escape hatch. Closing it properly is mid-turn preemption, not a per-surface exception.

Comment thread studio/backend/routes/inference.py Outdated
if cap is not None and cap < window:
return cap
# Clamped to the WINDOW: a request cannot occupy more KV than its own slot holds.
return min(_OPENAI_LLAMA_ADMISSION_UNSTATED_OUTPUT_TOKENS, max(0, window - prompt_tokens))

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 Bound the default allowance by a slot's fair share

On a small unified cache, the fixed 1024-token allowance can itself consume an entire slot's nominal share before prompt tokens are added. For example, with the repository's four-slot unified 4096-token configuration, every default short chat costs slightly more than 1024 tokens, so the aggregate budget admits only three of the four advertised slots; at a 2048-token context it can admit only one. Clamp the unstated allowance against budget // capacity - prompt_tokens so the concurrency fix also works for smaller context windows.

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.

Confirmed and fixed in 4a5c96a. Reproduced the arithmetic first: at budget 4096 with capacity 4 a default chat cost 1032 against a 1024 share, so three of four ran, and at 2048 only one did, which meant the fix delivered nothing on exactly the small caches that need it most.

The allowance is now clamped to share - prompt_tokens as well as to the window, so an unstated request costs at most its fair share and capacity of them always fit:

budget=   2048 share=   512 cost=  512 fit=4
budget=   4096 share=  1024 cost= 1024 fit=4
budget=   8192 share=  2048 cost= 1032 fit=7
budget=  32768 share=  8192 cost= 1032 fit=31
budget= 262144 share= 65536 cost= 1032 fit=254

The clamp only bites where the share is the tighter of the two, so every cache from 8192 up is unchanged, and a named cap ignores it entirely.

One deliberate departure from the suggestion: a prompt already past its share keeps the flat allowance rather than being clamped to zero. max(0, share - prompt) would admit a long-prompt chat with no room to generate at all, which hides the overrun instead of pricing it.

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Keep them coming!

Reviewed commit: 4a5c96a14d

ℹ️ 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
danielhanchen merged commit 6416393 into main Aug 31, 2026
47 of 52 checks passed
@danielhanchen
danielhanchen deleted the fix/studio-unstated-max-tokens branch August 31, 2026 21:19
DhruvaMyakeri added a commit to DhruvaMyakeri/unsloth that referenced this pull request Sep 1, 2026
…cache

Conflict was two signature hunks on _openai_llama_admission_tokens: this
branch added extra_prompt_tokens, main added context_window in unslothai#10070. They
do unrelated jobs, so both are kept. The body had already auto-merged
correctly, applying extra_prompt_tokens to the reservation and passing
context_window into the new output-allowance helper. No fix code changed.

test_the_unresolved_reservation_was_the_whole_cache asserted the pre-unslothai#10070
baseline, where an unstated cap reserved the whole cache. unslothai#10070 removed
that, so it now asserts the current baseline and keeps its contrast purpose.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant