Skip to content

feat(nemo-gym): opt-in straggler cutoff for synchronous Gym rollouts - #4482

Open
linj-glitch wants to merge 14 commits into
NVIDIA-NeMo:mainfrom
linj-glitch:linj/nemo-gym-straggler-cutoff
Open

linj-glitch wants to merge 14 commits into
NVIDIA-NeMo:mainfrom
linj-glitch:linj/nemo-gym-straggler-cutoff

Conversation

@linj-glitch

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

Copy link
Copy Markdown
Contributor

Adds an opt-in straggler cutoff for synchronous NeMo Gym GRPO training so slow rollouts do not hold an entire step open. After the completion-fraction grace period or maximum wall time, it preserves completed outcomes, propagates failures, and returns zero-loss placeholders only for remaining rows, with RL-owned deadline records and per-shard metrics.

Iterators close on every exit and wait for local client tasks; server cancellation and sandbox cleanup depend on the agent. The pinned Gym 3f6f2059 includes merged Gym #4029's aclose_and_drain() support. Older Gym versions and token-capture mode warn and run uncut.

This branch now integrates main through 0e36f2e6, including merged #4160 (which incorporates #4490). Zero-loss cutoff placeholders are excluded from baseline statistics under both masked-reward policies in the legacy and data-plane trainers. Cutoff selection can still affect the training distribution; no convergence-neutrality claim is made.

Validation refreshed October 28 on 6c776943: 81 cutoff unit tests and 17 interoperability tests against the actual pinned Gym passed. All lint/format/pre-commit hooks except pyrefly passed. Full pyrefly reports the same 44 diagnostics as pristine main in this local environment (including the missing transfer-queue dependency), with no new diagnostics. No training A/B was run.

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

@github-actions github-actions Bot added the Documentation Improvements or additions to documentation label Oct 5, 2026
@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-straggler-cutoff branch from 23a81fb to fa89e60 Compare October 8, 2026 00:15
linj-glitch and others added 10 commits October 12, 2026 23:36
Why: a synchronous GRPO step waits for the slowest rollout of its batch.
With hour-long sandboxed agent sessions the tail dominates. In one run with
768 sessions per step, a single session ran to the agent's 3600 s CLI
timeout while every other rollout was back much earlier, so the step took
4058 s and all of the job's GPUs sat idle for most of that time. Nothing on
the synchronous Gym path bounds this. The single-controller path has
per-group deadlines and asynchronous admission, and validation must not drop
rollouts.

What (off unless env.nemo_gym.straggler_cutoff.enabled is true):
- NemoGym._stream_rollouts drives Gym's run_examples iterator with a
  deadline. Once done_fraction of the call's rows are back and min_elapsed_s
  has passed, it arms. grace_s later, or at max_wall_s (an absolute cap), it
  calls the iterator's aclose(), which cancels every rollout still running
  and closes its /run request. Each cut row comes back as a text-only,
  zero-reward placeholder (prompt + one EOS token, logprob 0) marked
  _ng_straggler_cut. With a Gym whose run_examples result has no aclose(),
  it logs once and runs uncut.
- Only callers that opt in can be cut: run_rollouts(allow_straggler_cutoff=),
  run_async_nemo_gym_rollout / run_nemo_gym_rollout_sync(allow_straggler_cutoff=),
  SyncRolloutActor.rollout_to_tq(allow_straggler_cutoff=). The synchronous
  GRPO training call sites (legacy and data-plane) pass True. Validation,
  async GRPO, distillation, PPO and the single controller do not.
- _postprocess_single_nemo_gym_group zeroes loss_multiplier for cut rows
  regardless of env.should_mask_flagged_samples, ORs them into the
  mask_sample column, and keeps them out of the per-agent full-result
  means. Placeholders get no media re-attached.
- The last row of the call carries straggler_cutoff/{num_cut, armed,
  armed_at_s, cut_at_s, done_fraction_at_cut, cut_by_max_wall}.
- The block is validated on the driver (unknown keys and out-of-range values
  raise) and never forwarded to Gym's global config.

Tests: tests/unit/environments/test_nemo_gym_straggler_cutoff.py (38: config
parsing, decision and wait tables, the cancelling stream with
grace/min_elapsed/max_wall/failure, placeholder shape, run_rollouts end to
end incl. opt-out and old-Gym fallback, batch loss masking and metrics).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Lin Jia <[email protected]>
_parse_straggler_cutoff converted each env.nemo_gym.straggler_cutoff value
with float() and then range-checked it, but NaN compares false against every
bound, so {grace_s: .nan} (or the string "nan") was accepted. Once armed, a
NaN grace collapses the wait to zero and the decision never trips, so the
cutoff never fires; an infinite timer never fires either. Reachable only
with a Gym whose run_examples result has aclose(), since the pinned Gym
falls back first, but a misconfiguration that silently disables the feature
should fail at setup.

Every supplied value now goes through _finite_straggler_cutoff_value, which
rejects non-numeric, NaN and infinite values with the offending key in the
message, before the existing range checks. The driver-side validation in
_build_gym_actor_config gets the same treatment for free.

Tests: non-finite floats and strings for each key, a non-numeric value, and
the driver-side rejection.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Signed-off-by: Lin Jia <[email protected]>
Reconciles the straggler cutoff with what main gained on the NeMo-Gym
rollout path since the branch was cut: reward penalties and effort shaping
(NVIDIA-NeMo#4099), per-prompt-group length penalties (NVIDIA-NeMo#4553) and per-agent token
metrics (NVIDIA-NeMo#4379).

- A cut placeholder is not a model output. _postprocess_single_nemo_gym_group
  now runs effort shaping and the reward-penalty checks over the scored rows
  only, and reports the penalty rates over that population, so an empty
  placeholder response is not counted as an "empty final answer". Cut rows
  also stay out of main's new per-agent token/truncation metrics, alongside
  the existing exclusion from the per-agent full_result means. Length
  penalties need no change: they only adjust rows with a positive reward.
- Token-capture (receipt) mode is unsupported: a cancelled rollout has no
  receipt for the finalizer to rebuild. The actor now logs once and runs the
  batch uncut, the same fallback as a Gym without aclose(); the warning text
  names the reason.

Tests: receipt-mode fallback; penalty rate and rewards with a cut row under
penalize_empty_final_answer; per-agent gen-token mean excludes the cut row.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Signed-off-by: Lin Jia <[email protected]>
The straggler cutoff needs the iterator returned by
RolloutCollectionHelper.run_examples to have an async aclose(), which
NVIDIA-NeMo/Gym#4029 adds. The pinned Gym (17abf2dd) returns a plain map,
so with it the actor warns once and runs uncut; the pin follows once the
Gym change is on main. Also spells out what cancellation does on the Gym
side, the per-actor scope under sharding, the receipt-mode fallback, and
how cut rows are treated statistically: zero loss, excluded from the
rollout-level statistics over model outputs, but a reward of 0 that still
enters the group baseline/std on current main until the masked-reward
participation policy (NVIDIA-NeMo#4490 / NVIDIA-NeMo#4160) lands. The timing replay is an
estimate of wall time saved, not a convergence result.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Signed-off-by: Lin Jia <[email protected]>
find_gym_config_entries treats every dict-shaped top-level env.nemo_gym key
that is not a known NeMo RL setting as an inherited Gym overlay. The new
straggler_cutoff block was not registered, so with two or more shards
parse_shard_plan rejected it as an unowned overlay ("Inherited Gym overlays
['straggler_cutoff'] have no owner"), and claiming it under one shard, as that
message instructs, left every other shard's actor without the block and
running uncut.

Register the key in NEMO_RL_DICT_CONFIG_KEYS next to external_service_readiness
so the block stays in the shared base and reaches every shard's
_build_gym_actor_config, which already pops and validates it. Mirror
test_external_service_readiness_reaches_every_shard for the cutoff.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Signed-off-by: Lin Jia <[email protected]>
…d any

The actor appends its batch-level straggler_cutoff/* stats to the last row's
timing metrics, and the driver rolled them up with _merge_nemo_gym_timing_metrics,
whose rule is max per key. That is right for concurrent durations but wrong for
these: with shards cutting 2, 3 and 0 rows the batch reported num_cut = 3 instead
of 5, and done_fraction_at_cut and cut_by_max_wall could each come from a
different shard, describing an event that never happened.

Sum num_cut, set armed and cut_by_max_wall if any shard set them, and report the
per-event values (armed_at_s, cut_at_s, done_fraction_at_cut) per shard only,
under straggler_cutoff/shard/<instance>/ rather than under the timing namespace.
Unsharded runs are unchanged. Adds a three-shard roll-up test.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Signed-off-by: Lin Jia <[email protected]>
The result stream yields Optional[dict] now that a cut row carries None, but
the finished-row branches of _stream_rollouts passed it straight into
_postprocess_receipt_mode and _postprocess_nemo_gym_to_nemo_rl_result, both
typed dict (two new per-file pyrefly diagnostics; nemo_gym.py is outside the
CI gate's project-includes). Assert the result is present once the cut branch
is excluded, and annotate _raise_typed_gym_failure -> NoReturn so the rows it
guards are provably bound.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Signed-off-by: Lin Jia <[email protected]>
…ver paths

Nothing asserted the per-call-site opt-in: that grpo_train_sync passes
allow_straggler_cutoff=True on every rollout_to_tq call (mirrors the
apply_length_penalty analog), that the legacy validate() never opts in, that
run_nemo_gym_rollout_sync forwards the flag, and that the shard merge sends it
to each actor as a keyword only when enabled (the router fakes could not even
accept it). Also cover the two driver branches in run_async_nemo_gym_rollout:
the returns_entire_batch guard and the media-skip for a cut placeholder, which
would otherwise receive pixel tensors with no image placeholder tokens.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Signed-off-by: Lin Jia <[email protected]>
…utoff

Drive _iter_gym_results_with_straggler_cutoff, as imported, against the
installed NeMo Gym's real RolloutCollectionHelper.run_examples through a fake
server client whose /run handlers finish after a delay or hang until cancelled.
Three scenarios (unbounded grace cut, bounded grace cut, bounded max_wall cut
with unadmitted rows) check that the hanging handlers observe CancelledError,
finished rows come first and cut rows after them with no result, the iterator
is closed, no task is left pending, and nothing finishes or is admitted late.

Marked nemo_gym and skipped until the installed Gym's iterator has aclose()
(NVIDIA-NeMo/Gym#4029), so the pin bump makes the cutoff path run in the
nemo_gym CI shard without further changes. Passes against the Gym#4029 head
(dbefd8679) and skips on the pinned 17abf2dd.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Signed-off-by: Lin Jia <[email protected]>
…olicy notes

NeMo RL calls run_examples without Gym's max_resident_tasks, so the cutoff
always acts on in-flight /run requests; drop the claim that unadmitted rows
never start and say that max_resident_rollout_tasks does not bound this path.
Describe the sharded roll-up (num_cut summed, flags any-shard, per-event
values per shard) and that the block stays in every shard's config. Hedge the
masked-reward note to what RL NVIDIA-NeMo#4490 does today (legacy grpo.py only; the
data-plane trainer still needs the same valid mask) with NVIDIA-NeMo#4160 tracking the
policy. Point at the in-repo interop test, and list the cutoff among the
SingleController guide's unsupported features.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Signed-off-by: Lin Jia <[email protected]>
@linj-glitch

linj-glitch commented Oct 13, 2026 •

Copy link
Copy Markdown
Contributor Author

Dependency update for 778a9d7: cutoff activation requires the public aclose_and_drain() API from NVIDIA-NeMo/Gym#4029 and a subsequent Gym pin update. A Gym with only aclose() is insufficient because it can discard completed outcomes; older versions warn once and run uncut. Closing waits for local client tasks, not server or sandbox cleanup. Placeholder baseline bias is documented and still needs #4490 or equivalent exclusion in both trainers. Full CI remains outstanding.

@linj-glitch

Copy link
Copy Markdown
Contributor Author

/ok to test 2cc6682

@ananthsub

Copy link
Copy Markdown
Contributor

I reviewed the Gym side in NVIDIA-NeMo/Gym#4029, and a few points from that review land here instead.

  • Close the iterator on every exit path. aclose() runs only when the cutoff fires. If _raise_typed_gym_failure raises, or the consumer stops iterating early, the finally cancels next_completion but leaves every other /run request running until the actor's event loop ends. Calling await completions.aclose() in the finally (it returns immediately after the first call) would cover both.
  • What aclose() waits for. The PR body says aclose() "waits for the cancellations to land" and that an agent "releases its sandbox". aclose() returns once the rollout tasks in the actor have ended. The server cancels its handler after it sees the disconnect, so agent cleanup happens after aclose() returns, and several agents on Gym main keep running when cancelled (the local CLI agents, the Ray-based agents, and terminus_2_sandboxed). The sandbox savings depend on which agent the run uses, and the body should say that. I asked for the same correction on the Gym side.
  • Key prefix. _ng_straggler_cut uses the _ng_ prefix that Gym's rollout collector reserves for its own fields. A key that Gym does not own should use a different prefix, so a later Gym field cannot collide with it or strip it.
  • Recording the cutoff. A cut row is a time limit the trainer enforced, not a failure of the rollout. It would help to record it as one: its own failure kind, distinct from cancelled, with the limit that fired (done_fraction with grace_s, or max_wall_s) and the elapsed time. That keeps cut rows separable from real failures when someone later reads the scores, and it matches the failure event shape we are converging on in Gym.
  • Group baseline bias. The placeholder gets reward 0 and a zero loss multiplier, so it never trains, but if it still enters the group's reward mean, it lowers the baseline for the other rows in that group. The cut rows are the slowest tasks, which tend to be the hardest, so the bias is systematic rather than random. Until fix(grpo): exclude masked rows from the GRPO baseline/std #4490 excludes masked rows from the baseline, it would be worth either excluding cut rows from the group statistics here or saying in the docs that the cutoff shifts advantages.

@terrykong
terrykong requested a review from macandro96 October 15, 2026 05:34
Close Gym completions on every actor-stream exit and drain pending completion waiters. Record RL-owned trainer cutoff events with the fired deadline and elapsed time, separately from genuine Gym failures. Clarify client-task cleanup and the baseline exclusion dependency on both synchronous trainers. Add fail-before lifecycle regressions and real Gym iterator compatibility coverage.

Signed-off-by: Lin Jia <[email protected]>
@linj-glitch linj-glitch added the CI:L2 Run doctests, unit tests, functional tests, and convergence tests label Oct 15, 2026
@linj-glitch

Copy link
Copy Markdown
Contributor Author

@ananthsub Addressed the cleanup and documentation points in d51702d and 778a9d7.

Recorded validation: 81 cutoff unit tests and 17 real-Gym iterator interoperability cases passed. Activation still requires Gym#4029's stop-and-drain API plus a Gym pin update; full CI and the baseline follow-up remain outstanding.

khazic pushed a commit to khazic/Gym-lao that referenced this pull request Oct 17, 2026
…ht (NVIDIA-NeMo#4029)

`run_examples()` now exposes `aclose()` so direct callers and collection
owners can cancel unfinished client work. `aclose_and_drain()` stops
admission before suspending and preserves completed, unconsumed outcomes
for deadline consumers such as [RL
NVIDIA-NeMo#4482](NVIDIA-NeMo/RL#4482). Completed failures
remain observable; consumed payloads are released; outcomes are
delivered once.

Concurrent eager consumers now use one queue notification per finished
rollout. Drain wakes every parked consumer. A deterministic public-API
regression at 1,024 individually arriving outcomes measures 1,024
consumer resumptions, versus 524,800 with the shared event. Tests also
cover cancelled notified consumers, multiple parked drain consumers,
completed backlogs, exception retrieval, and result lifetime.

Both lifecycle methods wait for local client tasks. They do not
acknowledge server/agent cleanup or guarantee sandbox release. Existing
sequential use remains compatible; no configuration or benchmark-score
behavior changes.

Main `c2000f79f6bea21e9b21f7f021d57a06f6082974` is integrated
additively. The remaining test import conflict is resolved by retaining
`signal`, `sys`, and `time`; NVIDIA-NeMo#4646's asynchronous artifact reads are
preserved. Collector cleanup retains main's timing tasks, SIGTERM
restoration, and report, while closing both iterator modes. Its
capture-write barrier and reward telemetry are preserved. The
queue-based iterator also preserves NVIDIA-NeMo#4644's consumed-result release; all
four new upstream weak-reference cases pass unchanged.

Validation on head `f28029f5b359858b09596c45a476fc1dd5b52596`:

```bash
python3 -m pytest -o addopts= -q \
  tests/unit_tests/test_rollout_collection.py \
  tests/unit_tests/test_server_utils.py \
  tests/unit_tests/telemetry/test_observer.py \
  tests/unit_tests/test_run_timing.py \
  tests/unit_tests/test_base_responses_api_model.py \
  tests/unit_tests/telemetry/test_rollout_reward.py \
  tests/unit_tests/test_rollout_health.py \
  tests/unit_tests/test_rollout_observability.py \
  tests/unit_tests/test_rollout_correlation.py \
  tests/unit_tests/test_token_id_capture.py \
  tests/unit_tests/test_trajectory_builder.py
# 1,244 passed (including all 498 rollout tests)

pre-commit run --all-files
# All applicable hooks passed; no files modified. The guardwords hook retains its catalog-availability guard.
```

RL NVIDIA-NeMo#4482 at `778a9d7ee3c8811174745137519748a6b9443271`: all 17 native
real-Gym interoperability cases passed again against Gym head
`f28029f5b359858b09596c45a476fc1dd5b52596` after the main integration.
The original three performance regressions failed before the queue fix
and passed afterward. Disabling drain shutdown also makes the new
parked-consumer regression fail. Real HTTP client cancellation remains
covered.

Model rollout evidence: N/A for this shared-library lifecycle repair. No
training A/B was run. A separate issue is unnecessary because this
addresses the [P2 feedback on this
PR](NVIDIA-NeMo#4029 (comment)).

[NVIDIA-NeMo#3302](NVIDIA-NeMo#3302) should follow this
change and retain both lifecycle methods. RL activation needs a
subsequent Gym pin update. Ananth's concrete review requests are
addressed. Full mirrored CI and the repository's required approval
remain outstanding.

---------

Signed-off-by: Lin Jia <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
…er-cutoff

# Conflicts:
#	docs/guides/single-controller.md
@linj-glitch

Copy link
Copy Markdown
Contributor Author

Merged current main into the branch (merge commit 966ca24; one docs conflict in single-controller.md, resolved by keeping main's drain-gate wording plus this PR's straggler-cutoff note). NVIDIA-NeMo/Gym#4029 (aclose_and_drain) has merged, so the Gym-side dependency for cutoff activation is now on Gym main.

Local run: tests/unit/environments/test_nemo_gym_straggler_cutoff.py tests/unit/environments/test_nemo_gym_shards.py tests/unit/experience/test_rollouts.py tests/unit/environments/test_nemo_gym.py → 299 passed; test_grpo.py::test_grpo_train_sync_lets_training_rollouts_cut_stragglers passes. Pre-commit (ruff, ruff-format) clean on the touched files.

@linj-glitch

Copy link
Copy Markdown
Contributor Author

Follow-up to the cleanup and baseline questions, verified at 6c776943: the iterator closes in finally, local client tasks are drained, RL-owned markers use _nrl_, and cutoff rows record failure_kind=trainer_cutoff with deadline/elapsed data. The documentation distinguishes local cleanup from agent-dependent server cancellation and sandbox cleanup.

The actual Gym pin 3f6f2059 already provides aclose_and_drain() via merged Gym #4029. This revision integrates merged #4160, so zero-loss cutoff placeholders are excluded from baseline statistics under both policies in both legacy and data-plane trainers. The stale activation/baseline dependency paragraphs are corrected; cutoff selection can still change the training distribution.

Validation: 81 cutoff unit tests and 17 interoperability cases against the actual pinned Gym passed. No training A/B or convergence-neutrality claim is made. Lint/format hooks passed; the full local pyrefly run has the same 44 diagnostics as pristine main and no new diagnostics.

@linj-glitch

Copy link
Copy Markdown
Contributor Author

/ok to test 6c77694

@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 Nov 5, 2026
@terrykong terrykong removed the Documentation Improvements or additions to documentation label Nov 28, 2026

This branch has not been deployed

No deployments
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