Skip to content

fix(rollout): release finished rollout tasks during collection - #4644

Merged
ananthsub merged 1 commit into
mainfrom
ananthsub/release-finished-rollout-tasks
Oct 15, 2026
Merged

ananthsub merged 1 commit into
mainfrom
ananthsub/release-finished-rollout-tasks

Conversation

@ananthsub

@ananthsub ananthsub commented Oct 15, 2026 •

Copy link
Copy Markdown
Contributor

What does this PR do?

Rollout collection kept every finished /run result in the driver's memory until the last rollout of the run finished, even with retain_results_in_memory=false.

The cause is in _run_examples_with_metadata in nemo_gym/rollout_collection.py, the dispatcher shared by gym eval run (through run_from_config) and by run_examples, which NeMo RL calls. When max_resident_tasks is unset, its inner generator _start_in_input_order created every rollout task up front in a list and passed that list to tqdm.as_completed. The list stayed alive in the generator frame for the whole run, and tqdm.as_completed also kept it as its fs argument. A finished asyncio task holds its result, so the consumer dropping a result did not free it.

The fix passes a generator of tasks instead of a list. _start_in_input_order was added in #3822 because asyncio.as_completed builds its tasks from a set, which would start rollouts in an arbitrary order. That property still holds: asyncio.as_completed iterates the generator in order (set(aws)) before building its set, so asyncio.ensure_future still creates the tasks in input order. After that, only asyncio.as_completed's own bookkeeping references a task, and it lets go of a task once it hands the result to the consumer. The progress bar keeps its explicit total, so it is unchanged.

The bounded admission path (_BoundedCompletionIterator, used when max_resident_tasks is set) already released finished tasks: it pops each task from its ready list before awaiting it, so it needed no change.

NeMo RL's run_examples path benefits too, since it goes through the same dispatcher.

No issue was filed; the bug and the fix are both contained in this PR.

Validation

  • A new test, test_dispatch_releases_a_taken_result_while_rollouts_are_pending, runs both run_examples and _run_examples_with_metadata, with and without max_resident_tasks. The first rollout finishes while the others are held pending. The test takes and drops the first result, then asserts through a weak reference that the result was freed before the remaining rollouts finish. On the code before this change, the cases without max_resident_tasks fail and the bounded cases pass.
  • The existing test_default_dispatch_starts_rollouts_in_input_order still passes, confirming that rollouts start in input order.
  • PYTHONPATH=. .venv/bin/python -m pytest -n 16 -q tests/unit_tests --ignore=tests/unit_tests/test_exporters.py in a venv built with uv sync --extra dev --extra telemetry. The only failures are environment-dependent ones in test_opensandbox_compose.py, test_reward_profile.py, test_dataset_orchestrator.py, and test_sandbox_stop_retry.py, which fail identically on main on the same machine.
  • pre-commit run --all-files.

Rollouts

N/A: the change only affects when the driver releases results it has already handed to the consumer. It does not change which rollouts run, in what order they start, or any agent, model, or verifier decision.

Memory evidence comes from a CPU capacity simulator with the production topology (simulated engine and tools, real Gym servers and driver). Each run collected 4,096 long-context rollouts (64 repeats, 80 history messages of 2,000 characters each) with 1,024 in flight, ++retain_results_in_memory=false, and rollout observability on. The driver's process.memory.usage came from console metric exports every 10 seconds. The table shows the highest reading taken while rollouts were still completing, with the number of completed rollouts at that sample.

Variant Repeat Peak driver memory during collection
main (974d1a9) 0 4.56 GB at 3,697 of 4,096
main (974d1a9) 1 4.52 GB at 3,652 of 4,096
this PR 0 0.70 GB at 3,726 of 4,096
this PR 1 0.82 GB at 3,235 of 4,096

On main, driver memory grew steadily with the number of completed rollouts. With this change it stayed between 0.5 and 0.8 GB for the whole collection. Both variants still jump to about 5.6 GB after the last rollout, because the no-retention mode reads the output file back into memory for aggregation. That is a separate issue and is not addressed here.

Compatibility and benchmark impact

None. Results, their order of delivery, and the progress bar are unchanged.

Checklist

  • I have read the contributing guidelines.
  • The change is focused; unrelated "drive-by" edits are tracked as separate issues/PRs.
  • Tests added or updated and pass locally, or N/A for docs-only / non-code changes (so CI unit/server checks pass when applicable).
  • Documentation added or updated, or N/A with justification. N/A: no documented behavior changes; the existing retain_results_in_memory description now holds.
  • Pre-commit checks pass locally (pre-commit run --all-files) (so CI lint/format checks pass).
  • New source files include the required Apache-2.0 SPDX header. N/A: no new files.
  • All commits have DCO sign-off (git commit -s) (so the DCO check passes).

When no resident task bound is set, the rollout dispatcher created every rollout task up front in a
list and handed that list to tqdm's as_completed. The list stayed alive in the generator frame for
the whole run, and a finished asyncio task keeps its result. Every parsed /run response therefore
stayed in memory until the last rollout finished, even with retain_results_in_memory=false.

Pass a generator instead. asyncio.as_completed drains it in order before building its set, so
tasks are still created in input order, and nothing in the dispatcher keeps a finished task once
the consumer has taken its result. The bounded admission path already released finished tasks.

This affects both gym eval run and run_examples, which NeMo RL calls.

Signed-off-by: Ananth Subramaniam <[email protected]>
@ananthsub ananthsub added bug Something isn't working area:core Shared APIs, servers, telemetry, health, and registries labels Oct 15, 2026
@nemo-automation-bot
nemo-automation-bot Bot requested a review from a team October 15, 2026 18:16
@ananthsub
ananthsub requested a review from zyzhou5 October 15, 2026 18:18
@ananthsub
ananthsub requested a review from yfw October 15, 2026 18:18
@ananthsub
ananthsub requested review from yuhezhang-ai and removed request for zyzhou5 October 15, 2026 18:47

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

LGTM. The generator removes unintended retention of consumed rollout results while preserving task start order. Verified all 461 rollout-collection tests pass, and the new release tests fail on the original implementation as expected.

@ananthsub
ananthsub added this pull request to the merge queue Oct 15, 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/38791736498

Merged via the queue into main with commit 16e8859 Oct 15, 2026
50 of 55 checks passed
@ananthsub
ananthsub deleted the ananthsub/release-finished-rollout-tasks branch October 15, 2026 19:31
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]>

This branch was previously deployed

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

Labels

area:core Shared APIs, servers, telemetry, health, and registries bug Something isn't working

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants