Repository navigation
feat(rollout): write run_examples rollouts to a run folder shard - #5359
marcromeyn wants to merge 2 commits into
Conversation
run_examples returns the raw /run result, so a training framework that dispatches through it (NeMo RL) never gets what ng_collect_rollouts records for each rollout: the model server's captured calls, the normalized ng_trajectory and ng_perf. enrich_run_result runs the collector's per-rollout steps in place: wait for capture quiescence, merge the captured model calls, project ng_trajectory and assemble ng_perf. ng_collect_rollouts now calls it, so there is one implementation and no behavior change there. run_examples gains an opt-in enrich_results (with include_model_call_payloads and delete_model_call_capture); with it off, results are exactly what /run returned. A row that never started is not joined to calls; an interrupted try keeps the calls it made. A row that names no task gets no ng_trajectory rather than a guessed task id, and deleting the capture without keeping payloads is refused. Co-authored-by: Pranav Thombre <[email protected]> Signed-off-by: Marc Romeyn <[email protected]>
A training framework that dispatches through run_examples (NeMo RL) keeps no Gym run folder, so Gym's readers (aggregation, the run health check, EvalRDL's reader) cannot read its rollouts, and RL dumps Gym state itself. RunRecordWriter writes finished rollouts the way ng_collect_rollouts lays out a run, one shard at a time: <dir>/rollouts-<shard>.jsonl with its failures sidecar beside it. A result goes to the rollouts file, a failed one to the sidecar with its attempt cap, and an interrupted or never-started try to the sidecar as an omitted-rollout row when record_omitted_rollouts is set. The caller picks the shard label (a training step, a worker); Gym owns the file names, so a folder of shards matches the glob gym eval aggregate merges. Reopening a shard replaces it, so a replayed step does not duplicate rows. run_examples(record_output_dir=..., record_shard=...) writes each enriched rollout through it; an Environment Server episode is written as the record the collector stores. The collector and the writer share the failure-row builder. Signed-off-by: Marc Romeyn <[email protected]>
|
/ok to test 7ae80de |
svcnvidia-nemo-ci
left a comment
There was a problem hiding this comment.
HOLD — two recording defects need attention: inode reuse can defeat stale-writer rejection, and missing recording indices can erase an existing shard before failing.
Reviewed both changed files and the affected dispatch, enrichment, episode-conversion, aggregation, and run-health paths. The extracted collector stamping preserves the existing assignments. This was a static review; no tests were executed.
Note: formal approval is not available for this request, so this review is posted as a comment only.
Review generated by codex. This was a full review. Request a full review with /review reset=true.
| fd, partial = tempfile.mkstemp(dir=self.rollouts_fpath.parent, prefix=f".{self.rollouts_fpath.name}.") | ||
| os.close(fd) | ||
| Path(partial).replace(self.rollouts_fpath) | ||
| self._generation = self.rollouts_fpath.stat().st_ino |
There was a problem hiding this comment.
BLOCKER — inode reuse can reactivate a superseded writer
Could we identify shard generations independently of inode numbers? This saves only st_ino, while write() accepts any file with that number. After B replaces A's shard, A retains no open descriptor keeping its old inode allocated. A later reopening C can reuse that inode, allowing A to append stale successes or failures into C's replay without raising. The lock serializes operations but does not prevent this ABA sequence. The blast radius is the replayed shard and metrics derived from its mixed records.
Correction: publish a fresh generation token in the persistent lock file and check it under that same lock before every append. Keep the inode comparison as an additional external-replacement check. A small suggested implementation is to import TextIO, change _locked() to return Iterator[TextIO], open with "a+", and yield lock. Then make these additions at its two callers:
# __init__: use `with self._locked() as lock:`.
# After replacing the rollout file and assigning self._generation:
self._writer_token = secrets.token_hex(16)
lock.seek(0)
lock.truncate()
lock.write(self._writer_token)
lock.flush()
# write: use `with self._locked() as lock:`.
# Before the existing inode check:
lock.seek(0)
if lock.read() != self._writer_token:
raise RuntimeError(
f"{self.rollouts_fpath} was replaced by another writer for the same shard"
)Never unlink or replace the lock file; all writers must lock the same object. Publish the token only after successful shard replacement. This suggestion is unexecuted and needs verification before adoption.
Preservation and acceptance: add a deterministic regression opening A, B, then C for one label while simulating recycled rollout-path inode numbers. A's success and failure appends must both raise, leaving C's files unchanged; C must remain writable. Retain the existing two-writer rejection assertion, replay replacement leaving only reward 1.0, failures-only empty-main discovery, and omitted-row routing on/off. Different labels must remain independently writable. The invariant is that every successful reopening invalidates every earlier writer, even when filesystem identity numbers recur.
| latency_tracker=latency_tracker, | ||
| **({"retry_requests": False} if not retry_requests else {}), | ||
| ) | ||
| # Opened last, once the options, the config and the rows are known good, because opening replaces the shard. |
There was a problem hiding this comment.
RISK — validate recording indices before replacing the shard
_run_examples_with_metadata() validates routing but does not require task/rollout indices. An otherwise supported row such as {"agent_ref": {"name": "my_agent"}, "responses_create_params": {"input": []}} therefore reaches this writer initialization. Opening replaces the existing main file and deletes its failures sidecar; after /run succeeds, the new stamping callback raises KeyError. The caller loses the previous shard and receives no newly recorded rollout. Unindexed dispatch is already exercised by an existing dispatcher test.
Correction: recording needs these indices for reader compatibility, so reject missing indices explicitly before constructing RunRecordWriter. Do not weaken shared stamping to use .get() or add guessed indices to all callers. Suggested guard before completions = self._run_examples_with_metadata(...):
if record_output_dir is not None:
for index, row in enumerate(examples):
missing = [
key for key in (TASK_INDEX_KEY_NAME, ROLLOUT_INDEX_KEY_NAME)
if key not in row
]
if missing:
raise ValueError(
f"Recording row {index} is missing required fields: {', '.join(missing)}"
)The invariant is that recording's mandatory stamping inputs are checked before any existing shard is replaced. Suggested code is unexecuted and must be verified.
Preservation and acceptance: using the real dispatcher with a fake HTTP client, seed both an existing main file and failures sidecar, then parameterize rows missing either or both indices. run_examples(..., record_output_dir=..., record_shard=...) should raise ValueError synchronously, leave both files byte-for-byte unchanged, and send no /run request. The same unindexed row without recording must retain its existing dispatch behavior, including enrichment-only calls. Indexed flat and materialized episode rows must still record normally; retain the enriched-record assertions and row-owned capture-ID assertions.
674a8f9 to
7b9ed8d
Compare
AdamRajfer
left a comment
There was a problem hiding this comment.
The shard writer is in #5443 as _RunRecordWriter, reached through run_examples(record_output_dir=..., record_shard=...), with the same file layout and the same replace-on-reopen rule. On top of main it writes typed failure rows, the shard's materialized inputs and a manifest built with RunManifest.create, so gym eval run +resume_from_cache=true resumes a shard, and, from your review, each shard's rollout ids are prefixed with its run id so capture keys no longer collide across shards. One thing the port turned up: the file lock alone didn't stop a superseded writer from overwriting the newer writer's status file, so the writer now carries a token that every write and status flush checks. #5443 is in the merge queue; once it lands nothing remains here and this can be closed.
|
Carried into #5443 (merged), rebased onto the failure stack with authorship kept; closing this one. |
Stacked on #5318; the diff below is this PR's commit only.
What and why
A training framework that dispatches through
run_examples(NeMo RL) keeps no Gym run folder, so Gym's readers (aggregation, the run health check, EvalRDL's reader) can't read its rollouts, and RL dumps Gym state itself (NVIDIA-NeMo/RL#4890). With this PR Gym writes those rollouts itself, in the layoutng_collect_rolloutsuses.RunRecordWriter(record_output_dir, shard, *, record_omitted_rollouts=False)writes one shard:<dir>/rollouts-<shard>.jsonlwith its failures sidecar beside it. A result goes to the rollouts file, a failed one to the sidecar with its attempt cap, and an interrupted or never-started try to the sidecar as an omitted-rollout row whenrecord_omitted_rolloutsis set.run_examples(..., record_output_dir=..., record_shard=..., record_omitted_rollouts=False)writes each rollout through it after feat(rollout): expose per-rollout enrichment to run_examples callers #5318's enrichment (and implies it). An Environment Server episode is written as the record the collector stores.gym eval aggregatemerges and the other readers already read.Shard rules:
_failuresor_materialized_inputs, which would collide with sidecars.Not in this PR: NeMo RL switching #4890 to these options; identity fields from the capture-identity design (
model_ref,weight_version, agent instance); health checks during the run (they can run on the folder afterwards).Validation
telemetryextra:pytest tests/unit_tests/test_rollout_collection.py tests/unit_tests/test_fern_docs_links.py: 652 passed.run_examplespath writing the enriched and stamped record, a refused call or a dispatch error keeping the existing shard, and a returned rollout id that differs from the row's.pre-commiton the changed files.Rollout evidence
gym env start --resources-server example_single_tool_call --model-type openai_model ++observability_enabled=true ++model_call_capture_dir=...withgpt-6-luna, then tworun_examples(rows, record_output_dir=run, record_shard="step_1" / "step_2")calls on two example rows each:rollouts-step_1.jsonlandrollouts-step_2.jsonlheld two records each, with rollout id, agent ref, captured model calls andng_trajectory.gym eval aggregate +input_glob='run/rollouts-step_*.jsonl' +output_jsonl_fpath=run/rollouts.jsonlthen merged the four records and wrote aggregate metrics and verdicts. Not run: an Environment Server pairing through this path.Compatibility
Opt-in only.
ng_collect_rolloutsoutput is unchanged; it now builds its stamping and failure rows through the shared helpers.Linear: FEP-1907 (part of FEP-1829 / GYM-1170).