Repository navigation
perf(eval): aggregate collected rollouts off the event loop - #4646
Merged
Merged
Conversation
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]>
yuhezhang-ai
approved these changes
Oct 15, 2026
yuhezhang-ai
left a comment
Contributor
There was a problem hiding this comment.
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.
Contributor
|
🔄 Merge queue validation started! You can track the progress here: https://github.com/NVIDIA-NeMo/Gym/actions/runs/38796058701 |
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
What changed
After the rollout loop finishes,
RolloutCollectionHelper._run_from_config(thegym eval runpath) reads several whole artifacts before it reports metrics. Withretain_results_in_memory=false, collection keeps no results in memory, so it parses the entire rollouts JSONL again with_read_jsonlfor aggregation and forcheck_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_zeroand_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:
_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.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_lineshelper, 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_metricsrequests 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.pyPYTHONPATH=. .venv/bin/python -m pytest -n 16 -q tests/unit_tests --ignore=tests/unit_tests/test_exporters.pyin a venv with thedevandtelemetryextras. The only failures are intest_opensandbox_compose.py,test_reward_profile.py,test_dataset_orchestrator.py, andtest_sandbox_stop_retry.py; they depend on the local environment and fail the same way onmain.pre-commit run --files nemo_gym/rollout_collection.py tests/unit_tests/test_rollout_collection.pytest_read_jsonl_yields_to_other_tasks_between_rowschecks 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_loopruns 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. Againstmain, the end-to-end test fails on every scan, and the reader test fails becausemain's_read_jsonlcannot 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_jsonlreturned 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'sgym.event_loop.lag_mshistogram 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.usageis the driver's peak and final sample.main, repeat 0main, repeat 1On
mainthe 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_tokensandtotal_tokens, which also differ between twomainruns, because the simulator's token counts vary from run to run.