Skip to content

fix(agent): sum token usage across every model call in four loop agents - #4753

Merged
qiaochuz-nv merged 1 commit into
mainfrom
qiaochuz/nvb-6900411-loop-agents-usage
Oct 22, 2026
Merged

qiaochuz-nv merged 1 commit into
mainfrom
qiaochuz/nvb-6900411-loop-agents-usage

Conversation

@qiaochuz-nv

Copy link
Copy Markdown
Contributor

What does this PR do?

Makes four more multi-call agents report the token usage of the whole rollout. Each of them returned
response.usage from a single model call, so per-rollout input_tokens/output_tokens/total_tokens, and every
token aggregate built from them, were under-counted:

Agent Calls per rollout (shipped config) response.usage before this PR
proof_refinement_agent (math_formal_lean multi-turn) up to 3 (max_correction_turns: 2) last turn only
conversational_tool_use_domain_generation 2 (followup_count: 1) last phase only
conversational_tool_use_policy_tool_generation 4 policy calls + 7 judge calls per attempt final tools completion only
conversational_tool_use_scenario_generation 20 (request_count) the one completion chosen as the artifact

It also fixes a second bug in proof_refinement_agent that the live smoke surfaced: correction turns dropped the
caller's output cap.

Follow-up to #4716 (same defect in aviary_agent and toolsandbox_agent), NVBug
6900411. No separate issue: the 6900411 retro's sweep of loop agents
found these agents, and the review of this PR found policy_tool_generation.

Cause

  • proof_refinement_agent.run() returns the last /verify result. math_formal_lean echoes the request body, so
    response is the last turn's model response.
  • domain_generation reassigns final_response each phase and converts only it.
  • policy_tool_generation converts only final_completion.
  • scenario_generation converts only last_artifact_completion.

None of them sums usage. nemo_gym/reward_profile.py copies response.usage into each rollout row. The
documented contract (rollout-evidence.mdx) is the sum over model responses that finished.

Output cap: since #563, correction turns copy ["temperature", "max_tokens", "top_p"] from
responses_create_params. Responses requests have no max_tokens (the params model forbids extra fields), so
max_output_tokens was dropped on every turn after the first.

Fix

  • New public helper chat_completion_usage_to_response_usage in nemo_gym/responses_converter.py, extracted
    unchanged from chat_completion_to_response, which now calls it.
  • Each agent sums every policy-model call with accumulate_response_usage (as fix(aviary): sum token usage across every model call in an episode #4716 does) and sets the sum on the
    response it returns. The response text and other fields still come from the same call as before.
    • Proof refinement sums each turn's Responses usage.
    • Domain and scenario generation sum each chat completion's converted usage.
    • Scenario generation also counts completions whose text failed to parse: they spent tokens. Such a completion now
      stays on its failure outcome. It is never picked as the artifact, because selection still requires parsed scenarios.
    • Policy/tool generation counts role == "policy" calls only. Judge calls go to an auxiliary model, and Gym
      keeps those out of rollout usage (rollout-health "Binding Policy-Model Calls"; switchyard.mdx). A rejected
      attempt's policy calls are counted, since their tokens were spent.
  • Proof refinement correction turns copy max_output_tokens instead of max_tokens.
  • Tests: one per agent with distinct per-call usage, including cached and reasoning details, asserting the exact
    sum. Scenario generation also has a test where every completion fails to parse. The proof refinement test checks
    that a correction turn keeps max_output_tokens/temperature/top_p, plus a direct test for the helper. One
    existing scenario test pinned the old value (5/3/8, one of 19 completions); it now expects 95/57/152.

Before the fix

This branch's tests run against main's (d3205cd89) agent code:

proof_refinement_agent 2 failed, 2 passed | domain_generation 1 failed, 9 passed
policy_tool_generation 1 failed, 13 passed | scenario_generation 3 failed, 16 passed
proof_refinement_agent:      usage {'input_tokens': 1818, ..., 'total_tokens': 1842} != {'input_tokens': 2118, ..., 'total_tokens': 3542}
                             correction turn: KeyError: 'max_output_tokens'
domain_generation:           usage 1818/24/1842 != 2118/1424/3542
policy_tool_generation:      usage 20/6/26 (final tools call) != 2148/1435/3583 (4 policy calls)
scenario_generation:         usage 1818/... != 2218/1474/3692;  existing test 95 expected, 5 reported;
                             all-unparseable test: empty response carries no usage

Live, with model-call capture on (inference provider, Nemotron-3-Nano-30B-A3B, shipped config, one example row
each). response.usage is one captured call:

proof-refinement   3 turns   usage 221/5415/5636        sum 645/7619/8264      output per turn 1024 -> 1180 -> 5415 (cap 1024)
domain-generation  2 calls   usage 451/6764/7215        sum 589/9970/10559
scenario-gen       3 calls   usage 577/3413/3990        sum 1731/5057/6788
policy-tool-gen    4 policy  usage 5300/9760/15060      sum 85871/29857/115728   (7 judge calls excluded)

After the fix

Gym d80b6a404 (this branch, then rebased without conflicts onto 4ced0d735 as 4ca8744c9; the unit counts below
were rerun on 4ca8744c9), same commands:

proof_refinement_agent 4 passed | domain_generation 17 passed | policy_tool_generation 29 passed | scenario_generation 24 passed
proof-refinement   3 turns   usage 556/3072/3628 == sum    output per turn 1024 -> 1024 -> 1024
domain-generation  2 calls   usage 633/7961/8594 == sum
scenario-gen       3 calls   usage 1731/2349/4080 == sum
policy-tool-gen    4 policy  usage 84337/22794/107131 == sum of policy calls (11 captured, 7 judge calls excluded)

Validation

  • gym env test +entrypoint=responses_api_agents/<agent> +should_validate_data=true for all four: 4, 17, 29, and 24
    passed. Every new assertion fails on main.
  • Core: tests/unit_tests/test_responses_converter.py + test_openai_utils.py: 460 passed. Full tests/unit_tests
    on the Mac: 36 failed with the fix vs 37 on a pristine main tree; the fix's failures are a subset of main's
    (pre-existing sandbox/telemetry failures on this host).
  • pre-commit run --all-files: passed.
  • Rollout evidence: the live runs above, before and after on main and this branch. No registered QA case covers
    these agents. Proof refinement ran the shipped math_formal_lean_multi_turn config without a Lean sandbox: the
    sandbox client turns the connection error into a failed compile, so every turn asks for a correction. Rewards in
    that run are meaningless; only the agent loop and its usage were checked. scenario_generation ran with
    request_count=3 and scenarios_per_request=2, and policy_tool_generation with max_retries lowered, to bound
    cost.

Compatibility

  • Token metrics for these four agents go up. Rollouts now report every policy-model call: correction turns, the
    follow-up phase, all policy calls including rejected attempts, and all returned scenario completions. Earlier
    numbers under-count and are not comparable. Judge calls in policy/tool generation remain excluded.
  • proof_refinement_agent correction turns now honor max_output_tokens. Before, they generated uncapped, up to
    45k tokens in one smoke turn against a 1024 cap. That changes generation length and cost for any run that sets a
    cap.
  • chat_completion_usage_to_response_usage is a new public helper; chat_completion_to_response output is unchanged.
  • Correction turns still don't carry reasoning/instructions/top_logprobs; no shipped caller sets them. Left as is.

🤖 Generated with Claude Code

proof_refinement_agent and three conversational_tool_use generation agents
(domain, policy_tool, scenario) returned a rollout response whose usage
came from one model call: the last correction turn, the last domain phase,
the final tools completion, or the one completion chosen as the scenario
artifact. reward_profile copies response.usage into the rollout token
fields, so those under-counted every multi-call rollout.

Sum every policy-model call's usage with accumulate_response_usage, as
#4716 does for aviary_agent and toolsandbox_agent. Chat agents convert
each completion's usage with a new chat_completion_usage_to_response_usage
helper, which chat_completion_to_response now uses too. Scenario
generation also counts completions whose text failed to parse;
policy_tool_generation leaves its judge calls out, as rollout usage covers
the policy model.

proof_refinement_agent correction turns also copied max_tokens, which
Responses requests don't have, so the caller's max_output_tokens cap was
dropped on every turn after the first. Copy max_output_tokens instead.

Follow-up to NVBug 6900411.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: qiaochuz <[email protected]>
@qiaochuz-nv qiaochuz-nv added bug Something isn't working QA_fix Fix implemented by a QA team member area:agent Agent harnesses and Responses API agent behavior needs-review PR is ready for code review and waiting on a reviewer complexity:medium Single-domain change with interacting parts or a moderate review surface labels Oct 19, 2026
@qiaochuz-nv
qiaochuz-nv requested a review from yaoyu-33 October 19, 2026 18:25
@copy-pr-bot

copy-pr-bot Bot commented Oct 19, 2026

Copy link
Copy Markdown

This pull request requires additional validation before any workflows can run on NVIDIA's runners.

Pull request vetters can view their responsibilities here.

Contributors can view more details about this message here.

@qiaochuz-nv

Copy link
Copy Markdown
Contributor Author

/ok to test 4ca8744

@yaoyu-33 yaoyu-33 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Thanks for this, @qiaochuz-nv. I reviewed the diff at 4ca8744c9c with a team of reviewers (core library, agent harness, bug hunt, tests) plus an independent second pass, and had every finding challenged before posting.

Verdict: no blocking issues, no inline findings.

What I checked:

  • chat_completion_usage_to_response_usage is behavior-identical to the block it replaced in chat_completion_to_response, with annotations and a docstring.
  • Each of the four agents counts every policy-model call exactly once. That includes parse failures, rejected attempts, and every exit path of the proof-refinement loop. Judge calls in policy_tool_generation stay excluded.
  • Nothing is shared or mutated: accumulate_response_usage deep-copies, and the summed usage is set on a response the agent owns. Accumulation is serial in scenario_generation and policy_tool_generation, so there is no race.
  • A parse-failed scenario completion now carries usage but can never be picked as the artifact, because selection still requires parsed scenarios.
  • max_output_tokens is the correct key: the Responses params model has no max_tokens and forbids extras, and the new test asserts it on the correction request.
  • The new tests fail when the usage assignment is removed (checked per agent), and the PR's tests pass on this head.

Optional follow-ups, none blocking:

  • A test for a turn that reports no usage (the code handles it).
  • A test for a rejected-then-accepted attempt in policy_tool_generation, to pin that earlier attempts' policy calls stay counted.
  • NeMoGymResponseUsage.model_validate(turn_usage) in proof_refinement_agent is new strict validation on raw model JSON. A malformed usage block would now fail the rollout. The model servers already validate upstream, so I think this is fine as is.

PR hygiene: title, body, validation list, rollout evidence and compatibility notes all match the AGENTS.md bar. CI has not run yet (/ok to test is posted), and the PR is currently BLOCKED pending required checks and review.

@yaoyu-33 yaoyu-33 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Approving after the team review above: no blocking issues at the reviewed head.

@github-actions github-actions Bot removed the sla:review-overdue Review response is over the one-business-day SLA label Oct 22, 2026
@qiaochuz-nv
qiaochuz-nv added this pull request to the merge queue Oct 22, 2026
@github-actions

Copy link
Copy Markdown
Contributor

🔄 Merge queue validation started! You can track the progress here: https://github.com/NVIDIA-NeMo/Gym/actions/runs/39829650997

Merged via the queue into main with commit ea60272 Oct 22, 2026
53 of 58 checks passed
@qiaochuz-nv
qiaochuz-nv deleted the qiaochuz/nvb-6900411-loop-agents-usage branch October 22, 2026 18:39
@yaoyu-33 yaoyu-33 added the ready-to-merge PR is approved, current, and waiting for final CI or merge label Oct 22, 2026
@yaoyu-33 yaoyu-33 removed the needs-review PR is ready for code review and waiting on a reviewer label Oct 22, 2026

This branch was previously deployed

1 inactive deployment
public — 4ca8744c Deployed Oct 19, 2026 by copy-pr-bot[bot] via release / finalize / notify #5807
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area:agent Agent harnesses and Responses API agent behavior bug Something isn't working complexity:medium Single-domain change with interacting parts or a moderate review surface QA_fix Fix implemented by a QA team member ready-to-merge PR is approved, current, and waiting for final CI or merge

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants