Skip to content

fix(nemo-gym): detect context exhaustion in multi-turn hit_max_tokens - #4491

Merged
terrykong merged 6 commits into
NVIDIA-NeMo:mainfrom
linj-glitch:linj/nemo-gym-hit-max-tokens
Oct 16, 2026
Merged

terrykong merged 6 commits into
NVIDIA-NeMo:mainfrom
linj-glitch:linj/nemo-gym-hit-max-tokens

Conversation

@linj-glitch

@linj-glitch linj-glitch commented Oct 5, 2026 •

Copy link
Copy Markdown
Contributor

Gym rollouts can exhaust the context window on a final turn that generates no tokens, so counting generated tokens alone misses truncation and lets those rows bypass overlong_filtering.

This PR combines token-length evidence with Gym's terminal incomplete_details.reason=max_output_tokens signal and applies the result to the ordinary rollout and rollout-manager paths; ordinary completed responses and content-filter failures retain their existing classification.

The receipt/token-capture path remains outside this change and is tracked in #4737, which covers transport of terminal truncation metadata through receipt assembly and finalization; harnesses that synthesize a terminal response without the metadata still need an upstream signal.

Recorded validation on cf09333dfd6ab1e4532fdecdae7a0c9725a17fff is 13 focused tests passed, 123 tests passed across both affected experience modules, changed-file lint/format passed, and pyrefly reported zero shown errors; 11 tests requiring unavailable extras were deselected.

This can change the set of rows excluded from training, so the PR uses CI:L2; a live Gym/model rollout and a training comparison have not been run, and no convergence claim is made.

@copy-pr-bot

copy-pr-bot Bot commented Oct 5, 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.

@linj-glitch
linj-glitch marked this pull request as draft October 5, 2026 06:10
@linj-glitch
linj-glitch force-pushed the linj/nemo-gym-hit-max-tokens branch from 9487ebc to 7f08336 Compare October 8, 2026 00:15
linj-glitch and others added 5 commits October 12, 2026 23:24
hit_max_tokens (which feeds the truncated column, truncation_rate and
overlong_filtering) required the rollout's total token count to equal the
generation limit exactly. That almost never holds for multi-turn
rollouts: when the next prompt no longer fits, Gym's vLLM model returns
an empty finish_reason="length" completion that adds no tokens, so the
chain ends short of the limit and the rollout counts as a natural
termination. truncation_rate stays flat and overlong_filtering does
nothing for agentic rollouts.

Add nemo_gym_rollout_hit_max_tokens: a rollout is truncated if its token
count reached the limit (>=), or if the final Responses object reports
incomplete_details.reason as a length limit (Gym maps chat "length" to
"max_output_tokens"). Use it in both the batched NeMo-Gym postprocess and
RolloutManager's token-mode completion conversion.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Lin Jia <[email protected]>
nemo_gym_rollout_hit_max_tokens treats any final response whose
incomplete_details.reason is a length limit as truncated. That covers a
final turn stopped by its per-turn max_output_tokens cap as well as the
empty length-cut completion Gym returns on context overflow, because Gym
reports both with the same reason. Spell out in the docstring that this
is deliberate (the final generation was length-cut, so it belongs in
truncation_rate and is a valid overlong_filtering target) and add a
regression test for the per-turn-cap case so the behaviour is not
narrowed by accident.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Signed-off-by: Lin Jia <[email protected]>
`nemo_gym_rollout_hit_max_tokens` took `total_tokens` and
`max_total_tokens_per_sample` as two adjacent positional ints. A caller
that transposes them gets `limit >= total`, which is True for every
rollout below the limit, so `truncated` flips on for the whole batch and
`overlong_filtering` silently zeroes every sample's loss with no error.

Insert a bare `*` after `full_result` so both ints are keyword-only
(linting-and-formatting skill, "Enforce Keyword Arguments for Ambiguous
Parameters"; same shape as `shape_effort_reward` in reward_penalties.py)
and pass keywords at both production call sites and in the unit tests.
No behaviour change.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Signed-off-by: Lin Jia <[email protected]>
`test_result_to_completion_truncated_on_length_incomplete_response`
collected as `[response0-True]` / `[response1-False]` because its dict
params had no ids. Wrap them in `pytest.param(..., id=...)` so the ids
read `[length_incomplete]` / `[completed]`, matching the sibling
`test_nemo_gym_rollout_hit_max_tokens_other_endings` in test_rollouts.py.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Signed-off-by: Lin Jia <[email protected]>
Two doc-only corrections to `nemo_gym_rollout_hit_max_tokens`:

- The comment above `_LENGTH_LIMIT_INCOMPLETE_REASONS` implied `length`
  and `max_tokens` can arrive from Gym. They cannot: the pinned Gym
  (17abf2dd) normalizes chat `finish_reason="length"` and Anthropic
  `max_tokens` / `model_context_window_exceeded` to `max_output_tokens`
  (nemo_gym/responses_converter.py:806-808,
  nemo_gym/anthropic_converter.py:280-283), and the openai Responses
  schema's `IncompleteDetails.reason` Literal admits only
  `max_output_tokens` / `content_filter`. Keep both aliases as defensive
  tolerance for non-Gym producers and say so.
- The `full_result` Args entry read as if every agent carries
  `incomplete_details`. Only agents that return the model's final
  Responses object do; agents that synthesize their terminal
  `NeMoGymResponse` (e.g. the sandboxed harness agents) return no
  `incomplete_details` and fall back to the token-count check.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Signed-off-by: Lin Jia <[email protected]>
@linj-glitch
linj-glitch force-pushed the linj/nemo-gym-hit-max-tokens branch from 7f08336 to cf09333 Compare October 13, 2026 16:37
@linj-glitch
linj-glitch marked this pull request as ready for review October 13, 2026 16:39
@linj-glitch

Copy link
Copy Markdown
Contributor Author

/ok to test cf09333

@aroshanghias-nvd aroshanghias-nvd 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.

2 small process items; no code changes requested.

Thanks for the fix and for the thorough description. The root-cause walkthrough makes sense: when the overflowing turn produces no tokens, the old sum(tokens) == limit check cannot fire. The helper, the keyword-only signature and the tests look good to me. Linters (ruff check / isort / format) are clean on the 4 changed files; pyrefly was not run in this review. I could not run pytest in my environment, so I checked the helper tests by extracting the function: the new assertions pass, and 6 of 11 fail against the old == rule.

AI-1: CI label

The PR currently has no CI:* label, and the CI guide asks for exactly one. Since this changes which rollouts overlong_filtering excludes, CI:L2 may be the right level. Could you or a maintainer attach one?

AI-2: tracking issue for the receipt-mode follow-up

The description lists the receipt path (rollout_reassembler.py:786, seq_len == max_seq_len) under "Remaining gaps" with a clear plan, but "Issues: None" means the follow-up has no link. Could you open an issue and link it from the description, so receipt-mode users can find it?

Context, no action. On shipped Gym recipes stop_properly_penalty_coef is null, so reward shaping is unaffected. The per-turn max_output_tokens semantics are documented and pinned by a test.

Generated by Claude Code

@linj-glitch linj-glitch added the CI:L2 Run doctests, unit tests, functional tests, and convergence tests label Oct 15, 2026

@aroshanghias-nvd aroshanghias-nvd 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.

Code is unchanged since my previous review. CI:L2 is now attached and the receipt-mode follow-up is tracked in #4737. No further objections; my earlier validation caveats still apply.

@terrykong terrykong added CI:Lfast Runs a fast test suite and re-use nightly `main` container (but sync dependencies to PRs version) and removed CI:L2 Run doctests, unit tests, functional tests, and convergence tests labels Oct 15, 2026
@terrykong
terrykong enabled auto-merge (squash) October 15, 2026 20:17
@terrykong

Copy link
Copy Markdown
Collaborator

/ok to test 23d8264

@terrykong
terrykong merged commit a8ff9bc into NVIDIA-NeMo:main Oct 16, 2026
92 checks passed
alexandery-nvidia added a commit that referenced this pull request Oct 16, 2026
…t-metrics-hook

RL #4491 merged on main as a8ff9bc and added `nemo_gym_rollout_hit_max_tokens` to the rollouts import list in `rollout_manager.py`, where this branch adds its metrics-hook imports. Both import sets stay; the rest merged automatically.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Signed-off-by: alexandery <[email protected]>
trintamaki added a commit to trintamaki/RL that referenced this pull request Nov 23, 2026
…alizer

The token-capture finalizer still marks an ordinary row truncated only when it
fills max_seq_len, the rule the non-capture paths used before NVIDIA-NeMo#4491. NVIDIA-NeMo#4491
switched those paths (rollouts.py and the SingleController rollout manager) to
nemo_gym_rollout_hit_max_tokens, which also counts a final generation stopped
by its output-token cap, but left the finalizer unchanged. An answer cut at
max_new_tokens usually ends well short of max_seq_len, so with token capture on
overlong_filtering never masked it and truncation_rate reported 0.

The finalizer now also counts a row as truncated when its scored terminal call
finished with a length reason (length / max_tokens / max_output_tokens), the
same set the Forest receipt path already uses.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Tuomas Rintamaki <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

CI:Lfast Runs a fast test suite and re-use nightly `main` container (but sync dependencies to PRs version)

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants