Skip to content

perf(eval): aggregate collected rollouts off the event loop - #4646

Merged
ananthsub merged 1 commit into
mainfrom
ananthsub/aggregate-off-event-loop
Oct 15, 2026
Merged

ananthsub merged 1 commit into
mainfrom
ananthsub/aggregate-off-event-loop

Conversation

@ananthsub

Copy link
Copy Markdown
Contributor

What changed

After the rollout loop finishes, RolloutCollectionHelper._run_from_config (the gym eval run path) reads several whole artifacts before it reports metrics. With retain_results_in_memory=false, collection keeps no results in memory, so it parses the entire rollouts JSONL again with _read_jsonl for aggregation and for check_completion, as #3497 designed. It also reads the failure sidecar in _failure_rows_counted_as_zero, the materialized inputs in _missing_rollout_rows_counted_as_zero and _fill_task_fields, the upload spool, and the materialized inputs again to count the expected rollouts.

All of these reads ran on the asyncio event loop without yielding. For a large run the loop served nothing else until they finished, so telemetry sampling, any remaining tasks, and shutdown all waited. Rollouts were not slowed, because the reads start after collection ends.

This change takes two approaches, depending on what each read keeps:

  • The two reloads that keep every row, the rollouts JSONL and the upload spool, go through an async _read_jsonl. It parses on the event loop thread and yields to other tasks every few milliseconds. It stays on the loop thread on purpose: a worker thread allocates from its own malloc arena, so it cannot reuse the memory the loop thread freed during collection, and the driver would hold both copies. A worker-thread version of this reload raised the simulator driver's memory from about 6 GB to about 10 GB.
  • The scans that keep only a small result run in a worker thread through asyncio.to_thread: the failure sidecar scan, the missing-rollout scan, the task-field fill, and the expected-count read. The expected-count read moves into a small _count_lines helper, which also closes the file it opens.

The functions, their inputs, and their order are unchanged, so the aggregate metrics, the counted failure and missing rows, the uploaded rows, the returned value, and the raised errors stay the same. Sorting and the /aggregate_metrics requests stay as they were. A full cyclic garbage collection while the reload builds many objects can still pause the loop briefly, as it would in any thread holding the GIL. Peak memory during the reload is unchanged, because the whole rollouts file is still loaded for aggregation, as #3497 documented.

No issue: this is a focused fix for an event-loop stall found with the CPU capacity simulator.

Validation

  • PYTHONPATH=. .venv/bin/python -m pytest -n 16 -q tests/unit_tests/test_rollout_collection.py
  • PYTHONPATH=. .venv/bin/python -m pytest -n 16 -q tests/unit_tests --ignore=tests/unit_tests/test_exporters.py in a venv with the dev and telemetry extras. The only failures are in test_opensandbox_compose.py, test_reward_profile.py, test_dataset_orchestrator.py, and test_sandbox_stop_retry.py; they depend on the local environment and fail the same way on main.
  • pre-commit run --files nemo_gym/rollout_collection.py tests/unit_tests/test_rollout_collection.py

test_read_jsonl_yields_to_other_tasks_between_rows checks that a coroutine on the same loop runs between parsed rows and that the parsed rows are unchanged. test_run_from_config_non_retaining_reads_artifacts_off_the_event_loop runs a non-retaining collection with one success, one sidecar failure counted as zero, one missing rollout counted as zero, and upload enabled. Each scan waits for a coroutine on the loop to advance before it starts. On the loop thread that wait blocks the coroutine, so the scan is recorded as stalling the loop. Against main, the end-to-end test fails on every scan, and the reader test fails because main's _read_jsonl cannot be awaited. The end-to-end test also checks the rows sent to aggregation, including the task field filled into the counted zeros, and the rows sent to the exporter.

On one simulator run's 4.8 GB rollouts file, the new _read_jsonl returned the same rows as the previous synchronous reader.

Rollout evidence

N/A: this change only changes how the driver reads its own artifacts after collection. It does not change agent, model, or verifier behavior, so no model rollouts were run.

The CPU capacity simulator compared main (974d1a921b) with this branch on the production topology: a long-context eval with 4,096 rollouts, 1,024 in flight, 80 history messages of 2,000 characters each, rollout observability on, console metrics export, and ++retain_results_in_memory=false, with two interleaved repeats per variant. The driver's gym.event_loop.lag_ms histogram is cumulative, so its max in the final export includes any end-of-run stall, and the export before it covers only collection. process.memory.usage is the driver's peak and final sample.

Run Lag max before the final export Lag max in the final export Driver memory, peak / end
main, repeat 0 1,747 ms 8,400 ms 5.99 / 5.55 GB
main, repeat 1 1,701 ms 6,073 ms 5.99 / 5.52 GB
this branch, repeat 0 2,244 ms 2,244 ms 5.99 / 5.56 GB
this branch, repeat 1 1,143 ms 1,143 ms 5.99 / 5.74 GB

On main the end-of-run read raises the lag max by 4 to 7 seconds. On this branch the max does not move after collection; the values in the table were reached during collection and are unaffected by this change. Driver memory is the same. Throughput was within run-to-run noise (median 51.0 versus 48.8 rollouts per second, with overlapping ranges).

The aggregate metrics files agree between variants on every reward metric. They differ only in input_tokens and total_tokens, which also differ between two main runs, because the simulator's token counts vary from run to run.

After the rollout loop finishes, `gym eval run` reads several whole artifacts before it reports
metrics.
With `retain_results_in_memory=false` this includes the entire rollouts JSONL, which it parses
again for aggregation and the completion check.
It also reads the failure sidecar, the materialized inputs (for counted zeros, their task fields,
and the expected rollout count), and the upload spool.
All of these ran on the event loop without yielding, so for a large run the loop served nothing
else until they finished: telemetry sampling, the remaining tasks, and shutdown all waited.

The two reloads that keep every row, the rollouts JSONL and the upload spool, now go through an
async `_read_jsonl` that parses on the event loop thread and yields to other tasks every few
milliseconds.
They stay on the loop thread on purpose.
A worker thread allocates from its own malloc arena, so it cannot reuse the memory the loop thread
freed during collection, and the process would hold both copies.

The scans that keep only a small result now run in a worker thread through `asyncio.to_thread`:
the failure sidecar scan, the missing-rollout scan, the task-field fill, and the expected-count
read, which moves into a small `_count_lines` helper that also closes its file.

The functions, their inputs, and their order are unchanged, so the aggregate metrics, the counted
failure and missing rows, the uploaded rows, the returned value, and the errors are the same.

Signed-off-by: Ananth Subramaniam <[email protected]>
@ananthsub ananthsub added bug Something isn't working area:evaluation Evaluation, rollout collection, reward profiling, comparison, and exporters labels Oct 15, 2026
@nemo-automation-bot
nemo-automation-bot Bot requested a review from a team October 15, 2026 18:20
@yaoyu-33 yaoyu-33 added complexity:low Localized change in one scope with a small, straightforward review surface needs-review PR is ready for code review and waiting on a reviewer labels Oct 15, 2026

@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. One nonblocking note for the record: the PR body’s “memory unchanged” wording is broader than what was validated. Counted judge-failure rows can retain full generated responses, so memory behavior with many such failures remains unverified. No regression was identified, and no change is requested.

@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/38796058701

Merged via the queue into main with commit 58b3240 Oct 15, 2026
52 of 57 checks passed
@ananthsub
ananthsub deleted the ananthsub/aggregate-off-event-loop branch October 15, 2026 19:58
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 — 8522ac8b Deployed Oct 15, 2026 by copy-pr-bot[bot] via release / finalize / notify #5546
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area:evaluation Evaluation, rollout collection, reward profiling, comparison, and exporters bug Something isn't working complexity:low Localized change in one scope with a small, straightforward review surface needs-review PR is ready for code review and waiting on a reviewer

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants