Skip to content

fix(nemo-gym): mark incomplete terminal responses as truncated - #4449

Closed
alexandery-nvidia wants to merge 4 commits into
mainfrom
alexandery/gym-sample-truncated-by-status
Closed

alexandery-nvidia wants to merge 4 commits into
mainfrom
alexandery/gym-sample-truncated-by-status

Conversation

@alexandery-nvidia

@alexandery-nvidia alexandery-nvidia commented Oct 3, 2026 •

Copy link
Copy Markdown
Contributor

What does this PR do?

A NeMo-Gym sample counted as truncated only when its message log filled the generation engine's window exactly (max_total_tokens_per_sample). A rollout cut by the per-call output budget rather than by the window never fills the window, but its terminal response carries the Responses API's cause field, incomplete_details.reason: "max_output_tokens", which a Gym model server sets for a completion cut at the budget. Such a sample counted as a natural termination.

_nemo_gym_sample_truncated in nemo_rl/experience/rollouts.py now marks a sample truncated on either signal: the window-fill rule as before, or incomplete_details.reason == "max_output_tokens" on the terminal response. The response's status: "incomplete" alone is not the signal: Gym's agents also set that status for an agent-level stop (an EOS with no assistant message or tool call, or a harness that did not finish), with incomplete_details unset, and counting those as length cuts would take away, under grpo.overlong_filtering or stop_properly_penalty_coef, the only gradient against producing them. Every budget cut at the pinned Gym carries the reason field. The verdict feeds the hit_max_tokens metrics (truncation_rate, natural_termination_rate) and the batch's truncated column, which grpo.overlong_filtering reads to give those samples a zero loss weight; both the batched and the single-controller readers use the same helper. A result without a response is not truncated by this rule.

Issue

No issue filed; observed while training agent harnesses whose sessions end at the per-call output cap long before the context window: the truncation rate read zero while the rebuilt responses carried the budget-cut reason.

Validation

  • tests/unit/experience/test_rollouts.py and tests/unit/experience/test_rollout_manager.py: 104 passed on this branch. The group test postprocesses a budget-cut response, an agent stop-token response (status: "incomplete", no incomplete_details), and a completed response and checks truncated == [True, False, False], truncation_rate == 1/3, and natural_termination_rate == 2/3, that the window-fill rule still truncates, and that a result without a response is not truncated; the single-controller reader's parametrized test carries the same three cases.
  • pre-commit run --files <changed files>: ruff, ruff-format, end-of-file, trailing-whitespace, and the recipe minimize check pass; the pyrefly hook cannot build its environment in this checkout (no submodules), so pyrefly check was run directly on the touched modules with the project interpreter: the same 9 pre-existing findings as main, none new.
  • Rollout evidence: this change has run for weeks in a downstream fork's GRPO training with NeMo-Gym agent environments on Slurm clusters; the truncation rate tracks the sessions cut at the output budget, and with overlong_filtering on those samples get a zero loss weight. The fork's harness sets both status and incomplete_details together, so the narrower rule keeps its behavior.

🤖 Generated with Claude Code

Maintainer validation

Team review covered RL correctness, an independent bug/API scan, test/design perspective, existing discussion, and an independent devil’s-advocate challenge. Reviewed Gym truncation from terminal response status in both standard and SingleController readers; no blocking findings remain on the final reviewed head.

Addressed the existing reviewer request by using the same truncation helper in SingleController and adding completed/incomplete regression cases.

Validation: 3 focused CPU tests passed. All formatting, lint, TOML, and recipe-minimization hooks passed. The pinned pyrefly0.24.2 check reports the same 34 diagnostics on main and this branch, from unavailable optional/native dependencies; there are no new diagnostics. No local GPU/model run was performed. Required repository CI remains the merge gate.

@copy-pr-bot

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

@nidhishs

nidhishs commented Oct 3, 2026

Copy link
Copy Markdown

I think the SingleController path has the same check: AsyncNemoGymRolloutImpl._results_to_completions (rollout_manager.py#L1439-L1449) only compares total tokens against max_seq_len, so responses stopped at max_new_tokens stay truncated=False. Could this PR apply _nemo_gym_sample_truncated there too?

@linj-glitch linj-glitch changed the title fix(nemo_gym): count a Gym sample as truncated when its response status is incomplete fix(nemo-gym): mark incomplete terminal responses as truncated Oct 5, 2026
@linj-glitch linj-glitch added the CI:L0 Run doctests and unit tests label Oct 5, 2026
@linj-glitch
linj-glitch marked this pull request as ready for review October 5, 2026 17:46

@linj-glitch linj-glitch 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.

Team review covered RL correctness, an independent bug/API scan, test/design perspective, existing discussion, and an independent devil’s-advocate challenge. Reviewed Gym truncation from terminal response status in both standard and SingleController readers; no blocking findings remain on the final reviewed head.

Addressed the existing reviewer request by using the same truncation helper in SingleController and adding completed/incomplete regression cases.

Validation: 3 focused CPU tests passed. All formatting, lint, TOML, and recipe-minimization hooks passed. The pinned pyrefly0.24.2 check reports the same 34 diagnostics on main and this branch, from unavailable optional/native dependencies; there are no new diagnostics. No local GPU/model run was performed. Required repository CI remains the merge gate.

@linj-glitch

Copy link
Copy Markdown
Contributor

/ok to test 1b3dce4

@linj-glitch

Copy link
Copy Markdown
Contributor

/ok to test 366983c

linj-glitch
linj-glitch previously approved these changes Oct 6, 2026

@linj-glitch linj-glitch 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.

Rechecked the final head after updating against main f04e61b. Author history is preserved by additive main merges. No blocking logical issues remain in the reviewed changes.

Local validation: 3 terminal truncation regression tests passed. Formatting, lint, TOML, and recipe-minimization hooks passed. Pinned pyrefly has the same 13 diagnostics as current main in this local environment, with no introduced diagnostics. No fresh GPU/model training was run. Required repository CI is awaiting test-environment approval; this approval does not bypass that merge gate.

@aroshanghias-nvd

aroshanghias-nvd commented Oct 8, 2026 •

Copy link
Copy Markdown
Contributor

The change correctly distinguishes output-budget truncation from agent-level incomplete termination and applies the same logic to both rollout paths. I verified the existing overlong-filtering behavior and ran the four targeted tests locally; all passed. No blocking findings.

cc: @terrykong

@alexandery-nvidia

Copy link
Copy Markdown
Contributor Author

/ok to test 0e51655

alexandery-nvidia and others added 3 commits October 12, 2026 12:18
…us is incomplete

A NeMo-Gym sample counted as truncated only when its message log filled the
generation engine's window exactly. A rollout cut by the per-call output
budget rather than by the window carries the Responses API's own truncation
status on its terminal response, status "incomplete" with
incomplete_details.reason "max_output_tokens", which a Gym model server sets
for a completion cut at the budget, and such a sample counted as a natural
termination.

_nemo_gym_sample_truncated now marks a sample truncated on either signal.
The verdict feeds the hit_max_tokens metrics (truncation_rate,
natural_termination_rate) and the batch's truncated column, which
grpo.overlong_filtering reads to give those samples a zero loss weight.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Signed-off-by: alexandery <[email protected]>
…are incomplete status

status: "incomplete" is not length truncation by itself. Gym's agents
set that status for agent-level stops too: an EOS with no assistant
message or tool call (simple_agent, simple_agent_with_compaction) and
a harness that did not finish (hermes_agent), all with
incomplete_details unset. Counting those as length cuts put a natural
stop with no answer into truncation_rate, and under
grpo.overlong_filtering or stop_properly_penalty_coef removed its loss
weight or reward, which is the only gradient against producing such
outputs.

The predicate now reads the Responses API's cause field,
incomplete_details.reason == "max_output_tokens", which every budget
cut at the pinned Gym carries; the window-fill rule is unchanged. The
fixtures carry the cause field on the length-cut cases and the agent
stop-token case asserts False on both paths.

Co-Authored-By: Claude Fable 5 <[email protected]>
Signed-off-by: alexandery <[email protected]>
@alexandery-nvidia

Copy link
Copy Markdown
Contributor Author

/ok to test ee7a6b0

@alexandery-nvidia
alexandery-nvidia force-pushed the alexandery/gym-sample-truncated-by-status branch from 0e51655 to ee7a6b0 Compare October 12, 2026 19:40
@alexandery-nvidia

Copy link
Copy Markdown
Contributor Author

Done, thanks for catching it, and sorry for the late reply. Commit 5409f91 applies _nemo_gym_sample_truncated on the single-controller path too, in _results_to_completions (rollout_manager.py#L1456), so a response stopped at max_new_tokens reads truncated=True there as well. ee7a6b0 then narrowed the rule on both paths to incomplete_details.reason == "max_output_tokens", because Gym also writes a bare status: "incomplete" for its agent-level stops.

linj-glitch added a commit to linj-glitch/Gym that referenced this pull request Oct 15, 2026
…VIDIA-NeMo#3973)

## What does this PR do?

Three related changes in `nemo_gym/token_id_capture`, so that a consumer
of a rollout record can tell a trajectory that ended at the output-token
budget from one that ended on its own.

1. **Each locally captured record carries its call's finish reason.**
`TokenEntry` gains `finish_reason`, usually in the Chat Completions
vocabulary (`stop`, `length`, `tool_calls`, `content_filter`; other
engine values pass through unchanged). `response_finish_reason` in
`records.py` derives it from either served payload shape: a chat payload
states it directly as `choices[0].finish_reason`; a Responses payload
carries no finish reason, so `incomplete_details.reason` is mapped back
through the converter's own mapping (`max_output_tokens` to `length`,
`content_filter` to itself), and a completed Responses payload stopped
at a tool call (`tool_calls`) or at the end of its text (`stop`).
`capture_tokens` in `sink.py` stamps it on every record written by the
local capture path. A record written without the field reads as `None`,
so existing stores stay readable, and the conformance kit's entry
carries a non-default finish reason so a store that drops the field
fails the round trip.
2. **The rebuilt response reports a cut terminal as incomplete.**
`project_main_chain_response` in `builder.py` sets `status:
"incomplete"` with `incomplete_details.reason: "max_output_tokens"` when
the delivered chain's terminal call stopped for `length`, and
`incomplete_details.reason: "content_filter"` when it stopped for
`content_filter`: the verdicts the Responses converter already gives a
served chat completion that ended the same way. Only the terminal call
decides: an earlier `length` stop was extended by a later call and does
not end the chain. Any other finish reason leaves the status unset, as
before. When terminal attribution chose the terminal call among
token-identical retries by call-id order alone and those twins recorded
different finish reasons, the verdict is withheld too
(`TerminalAttribution.finish_reason_resolved`, passed to
`project_main_chain_response`): the delivered tokens are the same either
way, but the status would otherwise depend on which twin drew the
smaller id. A witness that singles out one serving (an explicit id, or a
response id, item id or content fingerprint matching exactly one entry)
keeps that serving's verdict.
3. **Delivery carries that verdict onto the rollout record.**
`finalize_rollout_token_capture` in `delivery.py` replaced only
`response.output`, so the builder's verdict never reached the record. It
now also sets the harness response's `status` and `incomplete_details`
from the rebuilt response when the harness reported `completed` or no
status; a harness that already reported `incomplete` or `failed` keeps
its own, more specific, verdict. The readers that see it without any
change are Gym's own aggregate-metrics path, which reads
`response.incomplete_details`, and the downstream NeMo RL fork, whose
agent harness finalizes the capture in-process and reads the verdict
there. Upstream NeMo RL does not see this verdict yet: at
NVIDIA-NeMo/RL#4449's head, `NemoGym` runs capture in receipt mode
(`external_staging: true`, `rebuild_response: false`) and collects
through `run_examples`, so `finalize_rollout_token_capture` never runs
for it and NVIDIA-NeMo#4449 counts only a status the harness set itself. Upstream
RL gets the verdict once NVIDIA-NeMo#4366 carries the finish reason through
worker-custody staging and RL's receipt consumer applies it.

### Scope

The finish reason is recorded on the local capture path only. Under
external staging (worker custody) `capture_tokens` returns before
building a record, and the staged `CallRecord`, the ledger, and
`staging/rebuild.py` carry no finish reason, so a chain rebuilt from
staged records reports no verdict. Carrying the finish reason through
the staging record is the follow-up NVIDIA-NeMo#4366, stacked on this branch.

## Issue

No issue filed; the missing status was found while training with agent
harnesses under token-id capture, where a session cut at the output
budget was indistinguishable from a completed one in the rebuilt
response.

## Validation

- `tests/unit_tests/test_terminal_attribution.py`,
`tests/unit_tests/test_trajectory_builder.py`: 97 passed, including the
new tests for the `content_filter` verdict and for delivery with a
harness status that is absent, `completed`, `failed` (left untouched),
and `incomplete` for the harness's own reason (left untouched); the
earlier tests for `response_finish_reason` on both payload shapes, the
recorded reason on the `/v1/responses` and `/v1/chat/completions`
capture routes, the store round trip with an older record lacking the
field, and the terminal-versus-earlier `length` rule stay.
- Full `tests/unit_tests` and every `responses_api_models/*/tests` suite
on this branch: the only failures (opensandbox, telemetry, and the two
servers that import `vllm`) are the same as on `main` f128d43 in the
same environment.
- `ruff check` and `ruff format --check` on the changed files: clean.
- Rollout evidence: these changes have run for several weeks in a
downstream fork training with OpenCode and Codex harnesses under
token-id capture; the rebuilt responses of sessions cut at the output
budget carry `status: "incomplete"`, and the trainer's truncation count
reflects them.

### Review follow-up

Rebased onto `main` f128d43. The dependency edits that the validation
merges had added to this branch live in NVIDIA-NeMo#4362 now.

yaoyu-33's follow-up of 2026-10-12 (744e198): the finish-reason rule
for token-identical retries described in item 2, with regression tests
at the attribution level (both id orders; the explicit and response-id
witnesses), through `_assemble` (both orders; twins that agree keep the
verdict), and on the builder.
`tests/unit_tests/test_terminal_attribution.py`,
`test_trajectory_builder.py`, `test_token_id_capture.py`: 290 passed.

ananthsub's notes of 2026-10-15 (5ed1608): item 3 now names the
readers that see the delivered verdict and the one that does not
(upstream NeMo RL's receipt mode, which needs NVIDIA-NeMo#4366 plus a
receipt-consumer change on the RL side), the Scope section links NVIDIA-NeMo#4366,
and a delivery test where the harness reports `incomplete` for its own
reason (`result_missing`) pins the second half of the guard.
`tests/unit_tests/test_terminal_attribution.py`: 65 passed.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Signed-off-by: alexandery <[email protected]>
Signed-off-by: Lin Jia <[email protected]>
Co-authored-by: Claude Fable 5.1 <[email protected]>
Co-authored-by: Lin Jia <[email protected]>
…-truncated-by-status

RL #4435 merged on main as c30bbd4 and appended a test to the rollouts unit-test file where
this branch had appended its own; both sides stay.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Signed-off-by: alexandery <[email protected]>
@alexandery-nvidia

Copy link
Copy Markdown
Contributor Author

Merged main after #4435's squash (c30bbd4) as 6271642: both sides had appended tests to tests/unit/experience/test_rollouts.py (and, where this branch touches it, the neighboring file), and both stay. A merge commit, not a rebase, so the review history stands and the head is current with main. Local gate on the merge head: pre-commit clean on the changed files; tests/unit/experience/test_rollouts.py and test_rollout_manager.py 116 passed.

@alexandery-nvidia

Copy link
Copy Markdown
Contributor Author

/ok to test 6271642

@alexandery-nvidia

Copy link
Copy Markdown
Contributor Author

Closing: #4491 (merged as a8ff9bc) landed this rule on main. Its nemo_gym_rollout_hit_max_tokens counts a rollout truncated when the token count reaches the budget or the terminal response is incomplete for a length reason (max_output_tokens, plus the length and max_tokens aliases), on both rollout paths, and a bare status: incomplete still does not count, which is what this PR asked for. After merging main here, the branch's own code reduced to a dangling import, and its two tests cover cases #4491's tests already cover. Thanks @linj-glitch; @terrykong, nothing left to review here.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

CI:L0 Run doctests and unit tests

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants