Skip to content

studio: use generation usage for conversation search budgets - #9438

Merged
Imagineer99 merged 3 commits into
unslothai:mainfrom
mahiatlinux:fix/studio-conversation-search-budget
Sep 1, 2026
Merged

Imagineer99 merged 3 commits into
unslothai:mainfrom
mahiatlinux:fix/studio-conversation-search-budget

Conversation

@mahiatlinux

Copy link
Copy Markdown
Contributor

Use request-local safetensors generation usage to size conversation search results against the model context window.

  • Pass token usage from InferenceBackend.generate_stream into run_safetensors_tool_loop.
  • Charge prompt tokens plus conservative same-turn growth.
  • Return zero budget when generation usage is unavailable.
  • Isolate generation stats between concurrent requests.

Checks

  • Conversation search and generation timing tests
  • Ruff
  • Pre-push gate

@mahiatlinux

Copy link
Copy Markdown
Contributor Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Hooray!

Reviewed commit: ec062d04c3

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

Using the real prompt token count here is the right direction, but the no-usage branch drops the budget to zero and empties the search rather than falling back to the dense estimate the way the GGUF loop does at llama_cpp.py:25264; could you keep that fallback and also drop the test rewrites that are not about this change?

@Lyxot Lyxot left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Using the real prompt_tokens is the right instinct, but I think the branch has two blocking problems as written.

1. The same-turn delta is measured in bytes and spent as tokens. spent = prompt_tokens + added_cost + 64, where added_cost is a UTF-8 byte delta of the JSON-serialised conversation max'd against completion_tokens, then subtracted from a token budget. That's ~4x over on ASCII and ~3x on CJK. Reproduced against the loop with an 8K window and a model that writes a normal English preamble before calling the tool:

prompt_budget          = 7680
real prompt tokens     = 3000
real completion tokens = 1120   (4480-char preamble)
honest room            = 3496
computed budget        = 0
charged for the delta  = 4616 tokens (real: 1120)

So on a plain English turn the search is switched off with 3.5K tokens of room left — worse than the estimator it replaces. The existing tests don't catch this because their fixtures are small enough that the byte delta stays negligible.

2. Agreed on the no-usage branch, and it's the same failure the recall path already learned once: budget = 0 reaches tools.py:10255 as "There is no room left in this context to search earlier conversation", and llama_cpp.py:1034 already carries the note that flooring to zero "disabled recall on exactly the tight windows that need it."

Both problems disappear if the path measures instead of extrapolating. The safetensors backend owns the tokenizer and _apply_chat_template_for_generation, so it can count the current conversation exactly at the tool-call site the way the GGUF loop does at llama_cpp.py:25029 — exact count, estimator only as the raise-fallback. That drops the byte delta, the + 64, and the zero branch in one go.

Two smaller notes:

  • The in-process holder is reset at the top of generate_stream, but the orchestrator's stats_holder is only written on gen_done and never cleared on gen_error — same holder, two freshness contracts.
  • Deleting test_the_dense_estimate_matches_the_flat_one_on_plain_ascii removes the only parity coverage of estimate_messages_tokens_dense, which is still used by llama_cpp.py, instruction_pin.py and routes/inference.py.

Also worth rebasing before another round — main has since replaced prompt_budget here with retrieval_budget(..., reply_returns = True) and added a result_budget_tokens path, and the branch is currently conflicting.

@mahiatlinux
mahiatlinux force-pushed the fix/studio-conversation-search-budget branch from ec062d0 to 70c457e Compare August 25, 2026 22:58
@mahiatlinux

Copy link
Copy Markdown
Contributor Author

Rebased onto main at 8194d50, so the branch now sits on retrieval_budget(..., reply_returns = True) and leaves the result_budget_tokens block that landed alongside it untouched. All six points are addressed, one of them differently from the suggestion, and the reason is below.

1. Bytes spent as tokens. Gone. safetensors_agentic._spent_prompt_tokens (studio/backend/core/inference/safetensors_agentic.py:479) spends the tokenizer count the turn reported and estimates only what the loop appended after that prompt was built: prompt_tokens + max(0, dense(conversation) - prompt_dense_tokens), where prompt_dense_tokens is snapshotted at line 749 immediately before _call_single_turn. Both terms are tokens. The + 64 is gone, and so is the JSON byte delta. A snapshot rather than a message index because continue_final_message grows the last assistant message in place instead of appending one.

Same fixture as yours, 8K window, prompt_budget 7680, reported prompt 3067 tokens, a 4600-character English preamble before the call:

preamble as tokens (dense)   = 1150
preamble as UTF-8 bytes      = 4600
budget on this branch        = 3420
budget charged by bytes + 64 = 0

2. The zero floor. Gone with it. There is no else: 0 branch left. A turn that reported no usage falls through to dense(conversation) + dense(tools), which is what main does today, so the worst case is the estimate rather than "there is no room left in this context to search earlier conversation".

3. Counting exactly at the tool-call site. Not done, and the premise does not hold on the path that runs. run_safetensors_tool_loop is driven by InferenceOrchestrator.generate_chat_completion_with_tools (studio/backend/core/inference/orchestrator.py:1846) in the PARENT process, which is what routes/inference.py reaches through get_inference_backend(). InferenceOrchestrator.models is a mirror of the worker's model_info (orchestrator.py:1537) and never carries a tokenizer, so _model_info.get("tokenizer") there is None and _apply_chat_template_for_generation is not reachable. InferenceBackend.generate_chat_completion_with_tools does own a tokenizer, but nothing in the worker calls it, so wiring an exact recount into that method alone would leave the production path on the estimate.

The nearest thing to an exact count without a new worker round trip per tool call is the count the worker already makes: it tokenises each turn's prompt to run it (inputs["input_ids"].shape[1]) and ships it on gen_done, tool catalogue included. That is exact for everything up to the start of the turn, and only this turn's assistant text and any result already appended in the same batch are estimated. If you would rather have the full recount, it needs a count_tokens command on the worker protocol, which is a bigger change than this PR should carry.

4. Two freshness contracts. Fixed by giving the loop a holder that only ever describes the latest turn. In the orchestrator, turn_stats is hoisted out of _single_turn (orchestrator.py:1897) and cleared on the way IN at line 1904, so a turn that errored or was cancelled leaves it empty instead of handing the loop an earlier turn's number, and the existing fold into stats_holder at line 1958 is unchanged. InferenceBackend does the same with _turn_stats (inference.py:979, cleared at 986, written in a finally at 1008), so the _record_generation_stats and generate_stream signature changes from the first push are reverted entirely. The request-level stats_holder is never read for sizing: _summed_tool_loop_stats sums completion_tokens across turns, so it is the wrong number to charge anyway.

5. test_the_dense_estimate_matches_the_flat_one_on_plain_ascii. Restored, along with test_the_budget_charges_token_dense_text_at_its_real_rate and test_the_loop_budgets_its_search_against_this_models_context, which are back to their main form. The unrelated rewrites in test_generation_timing.py are gone too, which also covers @danielhanchen's second point.

6. Regression coverage. test_the_budget_charges_this_turns_own_output_in_tokens_not_bytes (studio/backend/tests/test_conversation_search_safetensors_loop.py:231) uses a 12K-character thread and the 4600-character preamble above, large enough that bytes and tokens land on opposite sides of the assertion. Mutation-checked against the byte delta plus + 64: it fails with assert 0 > 3000. Three more:

  • test_the_budget_spends_the_count_the_turn_reported (:250) reports 6000 prompt tokens on a thread the estimator prices at a third of that; ignoring the report gives 3840 against an asserted ceiling of 1800.
  • test_the_budget_estimates_when_no_usage_was_reported (:262) pins the estimate fallback; flooring to zero fails it.
  • test_the_orchestrator_gives_the_loop_a_holder_of_its_own (:301) pins point 4; passing the request-level stats_holder fails it.

Not changed. The result_budget_tokens block keeps estimate_messages_tokens_conservative rather than the reported count. That budget deliberately over-prices dense results and is a different policy from retrieval sizing, and it landed on main after this branch opened, so re-deriving it is out of scope here.

Verification. 760 passed across test_conversation_search_safetensors_loop.py, test_safetensors_tool_loop.py, test_safetensors_toolcall_wiring.py, test_tool_loop_controller.py, test_tool_loop_exception_contracts.py, test_conversation_recall_injection.py, test_external_tool_truncated_and_budget.py, test_safetensors_capability_advertise.py, test_studio_tool_loop.py, test_llama_cpp_tool_loop.py and the three orchestrator tests. One failure, test_safetensors_tool_loop.py::test_native_template_loads_from_base_model_for_lora, is a missing transformers in my local CPU sandbox and not related to this change. test_generation_timing.py needs torch and did not run locally for the same reason; this branch no longer touches it. No GPU here, so no CUDA, quantisation or training checks were run. ruff check clean on all four files.

@mahiatlinux
mahiatlinux force-pushed the fix/studio-conversation-search-budget branch from 2d29928 to 1b2b299 Compare August 26, 2026 03:49
@mahiatlinux

Copy link
Copy Markdown
Contributor Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

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

Reviewed commit: 1b2b299f79

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

Checked the rebase and the new _spent_prompt_tokens path in studio/backend/core/inference/safetensors_agentic.py, and the byte delta and the zero floor are both gone. The only thing left is the assert reformat in studio/backend/tests/test_health_answers_within_probe_budget.py, which is not part of this change; could you drop it so the branch is just the budget work?

@Imagineer99

Imagineer99 commented Aug 28, 2026 •

Copy link
Copy Markdown
Member

The budget fix looks good and the earlier functional concerns are addressed. Daniel’s remaining request is still outstanding: studio/backend/tests/test_health_answers_within_probe_budget.py is still in the PR diff. Please rebase onto current main, confirm only the four budget-related files remain, and rerun the focused checks.

mahiatlinux and others added 2 commits September 1, 2026 16:02
The loop priced `search_conversation` by estimating the whole thread at four
characters per token, so a turn that wrote a long preamble before calling the tool was
charged whatever its characters implied rather than what it cost. The backend already
tokenises each turn's prompt to run it and ships that count on gen_done, so spend that
and estimate only what the loop appended afterwards.

Both call sites hand the loop a holder that carries the LATEST turn only, cleared on
the way in: `InferenceOrchestrator.generate_chat_completion_with_tools` hoists its
existing per-turn `turn_stats` out of `_single_turn`, and `InferenceBackend` reads back
`last_generation_stats`. The request-level `stats_holder` sums turns for the reply's
usage report and is not what sizes a budget.

No exact recount at the tool-call site: the loop runs in the parent process and
`InferenceOrchestrator.models` mirrors the worker's model_info, which carries no
tokenizer. Without a report the dense estimate covers the whole thread, as before,
rather than reporting no room at all.

Measured on an 8K window (prompt budget 7680) with a reported prompt of 3067 tokens and
a 4600-character preamble: the search gets 3420 tokens. The same preamble charged as
its 4600 bytes leaves 0.
@mahiatlinux
mahiatlinux force-pushed the fix/studio-conversation-search-budget branch from f6189f2 to 447f339 Compare September 1, 2026 04:20
@mahiatlinux

Copy link
Copy Markdown
Contributor Author

Fixed in 447f339a28. Rebased onto current main at 3703a6678, dropped the unrelated test_health_answers_within_probe_budget.py reformat, and confirmed the PR changes only the four budget files. Ruff passes. Focused tests: 717 passed; the only local failure is the existing missing transformers dependency in test_native_template_loads_from_base_model_for_lora.

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Sep 1, 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-01T08:44:03.916066Z ef1c7c5 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.

@mahiatlinux

Copy link
Copy Markdown
Contributor Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

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

Reviewed commit: 447f339a28

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

@Imagineer99

Copy link
Copy Markdown
Member

Rechecked ef1c7c518 with a pinned A/B. Before, 6,000 reported prompt tokens were ignored and search still got 3,840 tokens. After, it correctly dropped to 1,634, kept the 3,840 fallback, and matched across 100 concurrent requests.

The diff is limited to the four intended files, the remaining red test is inherited from main, and Daniel's cleanup is addressed. Looks good from my side.

@Imagineer99
Imagineer99 merged commit 6e21a68 into unslothai:main Sep 1, 2026
33 of 34 checks passed
@mahiatlinux
mahiatlinux deleted the fix/studio-conversation-search-budget branch September 25, 2026 05:32
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