Repository navigation
fix(stirrup_agent): count an image as a fixed token estimate when sizing max_completion_tokens - #6140
Conversation
…ing max_completion_tokens The input-token estimator counted one token per three serialized characters, so a base64 image_url part of a few hundred KB looked like hundreds of thousands of prompt tokens and pinned every call to the completion floor. A vision model encodes an image into a bounded number of tokens, so each image_url part now counts a fixed estimate and its bytes are left out of the character count. Signed-off-by: Adam Rajfer <[email protected]>
svcnvidia-nemo-ci
left a comment
There was a problem hiding this comment.
SHIP WITH CARE
RISK — Add the required real smoke-rollout evidence
The PR reports no model rollout, but this changes agent behavior: the image estimate changes the max_completion_tokens sent to the model. The protected quality bar requires representative real smoke rollouts for behavior-changing agent work; unit tests alone aren't sufficient. The missing evidence leaves image-bearing Stirrup trajectories unvalidated through the actual model and verifier. This is a validation gap, not a demonstrated runtime failure.
Could you run a representative image-bearing Stirrup episode against a supported vision model and record the command, configuration, reviewed commit, artifact location and inspected outcome in the PR? Use a valid large base64 image that remains in context for a subsequent turn. No implementation change is requested unless that run reveals a failure, and this change alone doesn't require a benchmark-wide reward profile.
Acceptance and preservation:
- In the proposed smoke rollout, confirm that the image still reaches the model and, with sufficient context remaining, its base64 bytes no longer force subsequent requests to the completion floor. Record the requested completion limits, provider prompt-token usage, any context errors, tool progression and verifier outcome.
- Retain the image regression: adding the image increases the estimate by exactly 1536, regardless of its large payload.
- Retain the text-only budget assertion, which expects
20_000 - 3020 - 1000; the tool-argument assertion, which counts serialized arguments; and the historical-thinking regression, which expects the 64,000-token cap without changing sent or retained history.
I inspected both changed files and their affected conversion, configuration and request paths. I found no additional source-supported defects. This was a static review; I didn't execute tests or rollouts.
Review generated by codex. This was a full review. Request a full review with /review reset=true.
ffrujeri
left a comment
There was a problem hiding this comment.
SHIP WITH CARE. The fix goes the right way: base64 bytes no longer hold image-bearing turns at the 1024-token floor, and text-only estimates are unchanged.
+1 to the bot's RISK on missing smoke-rollout evidence. When you run it, could you log the provider prompt_tokens next to input_est for turns that carry images? That also answers the point below.
RISK: the fixed per-image estimate can now undercount, and the error grows with each image. Before, an image was always overcounted, so a request could not exceed the context window. Now every image counts as 1536, but a vision model may spend more than that on a large or high-resolution image. Each such image takes (real − 1536) tokens out of the single 1000-token completion_token_buffer. With a few screenshots in context, once the estimate passes ~197K tokens (where the 64000 cap stops deciding), prompt + max_completion_tokens can exceed context_window_tokens; a server that enforces that limit rejects the call and generate re-raises. Could the estimate become a config field next to completion_token_buffer (app.py:206, passed through at :414-415), or could the docs say the buffer has to cover N_images × (real − estimate)?
NOTE (suggestion): the new test imports _IMAGE_TOKEN_ESTIMATE, so setting it to 0 would still pass. A generate() case with two images, a concrete expected max_completion_tokens, and a check that the image payload is still in the sent request would protect both the budget and request preservation.
NOTE (question): input_video parts (stirrup_utils.py:337) look like they still go through the character count. If stirrup serializes them as something other than image_url, video tasks would still be held at the floor. This predates the PR; a comment saying video is out of scope would be enough.
|
|
||
| # Prompt tokens counted per image_url part: a vision model encodes an image into a bounded number of tokens, not | ||
| # one per three base64 characters; completion_token_buffer absorbs the difference. | ||
| _IMAGE_TOKEN_ESTIMATE = 1536 |
There was a problem hiding this comment.
RISK: this is the first time the estimator can undercount. If a model spends more than 1536 tokens on an image (common for high-res screenshots or tiled encoders), each image takes (real − 1536) out of the single 1000-token completion_token_buffer. With several images and a prompt past ~197K estimated tokens, prompt + max_completion_tokens can exceed the context window, and a server that enforces that rejects the call (generate re-raises). Could this become a config field next to completion_token_buffer (app.py:206 / :414), or could the docs say the buffer has to scale with the image count?
There was a problem hiding this comment.
Agreed, this is the first time the estimator can undercount. In 1e0ea6c the per-image estimate is now a config field, image_token_estimate (default 1536, so default behavior is unchanged). It sits next to completion_token_buffer in app.py and is passed to the client with it. The field description and the README both say that the buffer has to cover N_images × (real tokens per image − image_token_estimate). For high-resolution screenshots or many images, the options are to raise the estimate to the model's real per-image cost or to raise the buffer.
| for message in messages: | ||
| content = message.get("content") | ||
| if isinstance(content, list): | ||
| kept = [part for part in content if not (isinstance(part, dict) and part.get("type") == "image_url")] |
There was a problem hiding this comment.
NOTE (question): this only removes image_url parts. Stirrup also accepts input_video (stirrup_utils.py:337). If those are serialized as e.g. video_url, their base64 still counts at 1 token per 3 chars and holds calls at the floor. This predates the PR; fine to leave, but a comment saying video is out of scope would help.
There was a problem hiding this comment.
I checked how stirrup serializes video. stirrup.clients.utils.content_to_openai turns a VideoContentBlock into {"type": "file", "file": {"file_data": "data:video/mp4;base64,..."}}, not image_url. So you were right: those parts are still counted by characters, at one token per three base64 characters, and a video task is still held at the floor. 1e0ea6c adds a comment to _without_images saying video is out of scope and stating the serialization, and the README notes it too. I left the behavior alone because it predates this PR.
| count = client._count_input_tokens([{**text, "content": [*text["content"], image]}], tools={}) | ||
|
|
||
| # 900 KB of base64 would otherwise count as 300K tokens and pin every call to the completion floor. | ||
| assert count == client._count_input_tokens([text], tools={}) + _IMAGE_TOKEN_ESTIMATE |
There was a problem hiding this comment.
NOTE (suggestion): importing the production constant means setting the estimate to 0 still passes. Could you add a generate() case with two images, a concrete expected max_completion_tokens, and a check that the image payload is still in the request?
There was a problem hiding this comment.
Added in ae13015. test_two_images_budget_two_fixed_estimates_and_still_reach_the_request sends two real PNG blocks through generate() and asserts max_completion_tokens == 20_000 - (22 + 2 * 1536) - 1000, with the numbers written out literally (the text part is 66 characters, 22 tokens). It also asserts that both data:image/png;base64, URLs, each over 100K characters, are in the sent request. With the estimate set to 0 this test and test_an_image_counts_a_fixed_token_estimate_not_its_base64_length both fail; I ran that. The second test now uses the literal 1536 instead of the imported constant. I also added test_image_token_estimate_is_configurable for the new field (estimate 4000 gives 20_000 - (22 + 4000) - 1000). The stirrup agent suite passes (186 tests) and ruff check and format are clean.
An image counts as image_token_estimate tokens (default 1536, unchanged) when sizing max_completion_tokens. A model that spends more per image takes the difference out of completion_token_buffer, so document that the buffer has to cover N_images * (real - estimate). Note that input_video parts, which stirrup serializes as file parts, are not covered by the estimate. Signed-off-by: Adam Rajfer <[email protected]>
Two images yield a literal max_completion_tokens and both payloads stay in the sent request; a configured estimate changes the budget. The estimator test uses the literal 1536 instead of the production constant. Signed-off-by: Adam Rajfer <[email protected]>
|
I can't run a real image-bearing Stirrup episode right now, so this PR has no rollout evidence yet. I'll add it with the first real run: the command, config, reviewed commit and artifact location, plus the requested completion limits, the provider |
ffrujeri
left a comment
There was a problem hiding this comment.
SHIP WITH CARE.
NOTE: image_token_estimate, the two-image generate() test and the video comment close my three points. Thank you.
RISK: The PR body still says rollout evidence is N/A. AGENTS.md asks for a real smoke rollout when agent behavior changes. Can you attach one image-bearing Stirrup run before merge, not after? Please log prompt_tokens next to input_est on turns with images.
NOTE (question): ge=0 lets image_token_estimate be 0. Then each image adds no tokens, and the buffer takes the full cost. Is 0 a valid setting, or should the bound be ge=1?
ffrujeri
left a comment
There was a problem hiding this comment.
APPROVE. The code change is correct, and the tests cover the image budget.
RISK: Can you attach one image-bearing Stirrup run before merge? Please log prompt_tokens next to input_est on turns with images. The ge=0 question stays optional.
|
🔄 Merge queue validation started! You can track the progress here: https://github.com/NVIDIA-NeMo/Gym/actions/runs/43607651378 |
A clean merge. Main's NVIDIA-NeMo#6140 (the Stirrup client's per-image token estimate) changes four files this branch also changes, in other lines; neither side's changes are altered. It also brings main's repaired secrets baseline (NVIDIA-NeMo#6083). Signed-off-by: Erik Arakelyan <[email protected]> Co-Authored-By: Claude Opus 5.5 <[email protected]>
What does this PR do?
DynamicMaxTokensChatCompletionsClientsizesmax_completion_tokensper call from an estimate of the prompt: one token per three characters of the serialized messages. A message carrying a base64image_urlpart of a few hundred KB therefore counted as hundreds of thousands of tokens, which pinned every call to the completion-token floor once an image was in the context.Each
image_urlpart now counts a fixed 1536-token estimate (a vision model encodes an image into a bounded number of tokens), and its bytes are excluded from the character count.completion_token_bufferabsorbs the remaining difference. Text-only prompts are unchanged.This is independent of #5806, which lets a Stirrup run produce images; the fix matters whenever an image reaches the model's context.
Validation
cd responses_api_agents/stirrup_agent && uv run python -m pytest tests: 184 passedruff checkandruff format: cleanRollout evidence: N/A. The change only affects how the per-call output cap is computed, which the unit test asserts; no model rollout was run.