Repository navigation
Conversation
Replace the per-rollout Gym log and the train-dump gym_full_result column
from the two previous commits with async_rl.gym_results_log:
- Every row carries a unique _ng_rollout_id (the token-capture gate id, or
<group_id>_g<i>_a<attempt>) and the dispatch weight version, so Gym's
model-call capture never falls back to its repeating "{task}-{rollout}"
key and every log line has a join key.
- Each NemoGym actor appends gym_results.<pid>.jsonl: the raw /run result
before RL post-processing (raw reward; token arrays still present on the
legacy path), with the rollout's model-server calls merged in through
Gym's enrich_run_result on a copy, so nothing extra travels to the
trainer. A failed /run or post-processing step writes an error line.
- rl_outcomes.<pid>.jsonl records buffered/evicted groups (replay buffer)
and trained/masked samples (advantage stage); buffered lines map the
per-attempt TQ group id to the Gym group id.
- Setup rejects the log on a non-Gym run, and model calls without Gym's
observability_enabled + absolute model_call_capture_dir.
The TQ object column is dropped (along with its warm-up, resume and
modified-reward issues); the train dump joins the log by sample id. The
LoggerConfig fix for log_full_train_data is kept.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: Pranav Prashant Thombre <[email protected]>
Each logged Gym result now omits what it repeats, keeping every captured model call's entry and metadata (async_rl.gym_results_log.compact, default on): - identity keys enrich_run_result stamps on full_result (the line carries them at top level), - ng_model_call_capture.calls (the same calls as ng_trajectory.model_calls; metrics and gaps stay), - null-valued fields, - a call's request.input / request.tools / response.output / response.tools equal to the agent's own field, replaced by a "=full_result...." reference. Bodies that differ (intermediate turns, subagents, judges) stay in full. Done on the logged copy without mutating the result RL post-processes. Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: Pranav Prashant Thombre <[email protected]>
…is on Every Gym row carried _ng_dispatch_weight_version even with the log off, and agents that echo their input row (multichallenge_simple_agent) copied it into their results. RolloutManager now passes the weight-version reader to the NeMo-Gym impl only when async_rl.gym_results_log.enabled, so a run with the log off sends Gym the same rows as before. Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: Pranav Prashant Thombre <[email protected]>
| except (OSError, ValueError, RuntimeError) as error: | ||
| # A debug log must not fail the rollout it describes; say why the | ||
| # line has no merged calls instead. | ||
| logged["_nrl_enrich_error"] = f"{type(error).__name__}: {error}" |
There was a problem hiding this comment.
_nrl_enrich_error never reaches the log when compact=true (the default).
added_keys=set(logged) - set(result) on the next lines includes _nrl_enrich_error, and compact_gym_result drops every added key that is not in _ENRICHMENT_KEYS ({ng_model_call_capture, ng_trajectory, ng_perf}, gym_results_log.py:105,159-161). A failed enrich therefore produces a line with no merged calls and no reason.
Repro:
result = {"response": {"output": []}, "reward": 0.0}
logged = {**result, "_nrl_enrich_error": "KeyError: x"}
out = compact_gym_result(logged, added_keys=set(logged) - set(result))
assert "_nrl_enrich_error" in out # failsSuggested fix: drop the try/except and let enrich errors raise. The log is opt-in debug output, and its failures are code or version bugs that a retry or a swallowed error won't fix; failing loudly is easier to notice than a missing marker. That also removes the marker, so the compaction allowlist needs no special case.
If you'd rather keep the rollout alive, the minimal alternative is added_keys=set(logged) - set(result) - {"_nrl_enrich_error"}, plus a compact=True test that asserts the marker survives.
|
I checked out this PR with Gym #5023 and ran it locally: unit tests plus GRPO toy runs (Qwen3-0.6B) on 1. Let enrichment errors raise, and fix the stale setup test
2. NaN/inf in the log lines (raised by @mikhailshilkov on #4855) Gym pin (left to you): with the log on, Still open from #4855's review, now in this PR's code (@mikhailshilkov): a writer chosen by target (they write to Iceberg), and logging rows the controller re-dispatches or gives up on after a timeout or transport failure. Only Gym Patch (on top of 9ebe1ab)diff --git a/nemo_rl/environments/nemo_gym.py b/nemo_rl/environments/nemo_gym.py
index 77d3777a3..6308a2a28 100644
--- a/nemo_rl/environments/nemo_gym.py
+++ b/nemo_rl/environments/nemo_gym.py
@@ -1286,19 +1286,16 @@ Depending on your data shape, you may want to change these values."""
):
from nemo_gym.rollout_collection import enrich_run_result
- try:
- await enrich_run_result(
- row,
- logged,
- capture_dirs=capture_dirs,
- observability_enabled=self._gym_observability_enabled,
- include_payloads=self._gym_results_cfg["include_payloads"],
- delete_capture=self._gym_results_cfg["delete_capture_after_merge"],
- )
- except (OSError, ValueError, RuntimeError) as error:
- # A debug log must not fail the rollout it describes; say why the
- # line has no merged calls instead.
- logged["_nrl_enrich_error"] = f"{type(error).__name__}: {error}"
+ # No try: the log is opt-in, and an enrichment failure is a code or
+ # Gym-version bug that should surface, not a marker on the line.
+ await enrich_run_result(
+ row,
+ logged,
+ capture_dirs=capture_dirs,
+ observability_enabled=self._gym_observability_enabled,
+ include_payloads=self._gym_results_cfg["include_payloads"],
+ delete_capture=self._gym_results_cfg["delete_capture_after_merge"],
+ )
if isinstance(logged, dict) and self._gym_results_cfg["compact"]:
logged = compact_gym_result(logged, added_keys=set(logged) - set(result))
self._gym_results_log.append(
diff --git a/nemo_rl/utils/gym_results_log.py b/nemo_rl/utils/gym_results_log.py
index b8b36e2fe..2dc80846e 100644
--- a/nemo_rl/utils/gym_results_log.py
+++ b/nemo_rl/utils/gym_results_log.py
@@ -35,6 +35,8 @@ from collections.abc import Iterable, Mapping
from concurrent.futures import Future, ThreadPoolExecutor
from typing import Any, Optional, TextIO
+from nemo_rl.utils.train_data_dump import json_safe_nonfinite
+
GYM_RESULTS_SUBDIR = "gym_results"
GYM_RESULTS_PREFIX = "gym_results"
RL_OUTCOMES_PREFIX = "rl_outcomes"
@@ -79,7 +81,11 @@ class JsonlAppender:
def append(self, record: Mapping[str, Any]) -> Future:
"""Queue one record; the returned future resolves once it is written."""
- line = json.dumps(record, separators=(",", ":"), default=str) + "\n"
+ # NaN/inf (e.g. a reward) would otherwise be written as invalid JSON.
+ line = (
+ json.dumps(json_safe_nonfinite(record), separators=(",", ":"), default=str)
+ + "\n"
+ )
return self._executor.submit(self._write, line)
def flush(self) -> None:
diff --git a/tests/unit/single_controller/test_gym_results_log.py b/tests/unit/single_controller/test_gym_results_log.py
index 6a2f05cc1..6eb404e36 100644
--- a/tests/unit/single_controller/test_gym_results_log.py
+++ b/tests/unit/single_controller/test_gym_results_log.py
@@ -60,6 +60,20 @@ def test_appender_snapshots_the_record_when_appended(tmp_path):
appender.close()
+def test_appender_writes_nonfinite_values_as_valid_json(tmp_path):
+ appender = JsonlAppender(str(tmp_path), GYM_RESULTS_PREFIX)
+ appender.append({"reward": float("nan"), "scores": [float("inf"), 1.0]})
+
+ appender.flush()
+ # json.loads accepts NaN; the strict parse is what a non-Python reader does.
+ line = Path(appender.path).read_text().strip()
+ assert json.loads(line, parse_constant=pytest.fail) == {
+ "reward": None,
+ "scores": [None, 1.0],
+ }
+ appender.close()
+
+
def test_appender_survives_being_shipped_to_another_process(tmp_path):
# The replay buffer holding the outcome appender is built in the driver and
# pickled into the controller actor's args.
diff --git a/tests/unit/single_controller/test_setup.py b/tests/unit/single_controller/test_setup.py
index 09b892677..3ef155bb7 100644
--- a/tests/unit/single_controller/test_setup.py
+++ b/tests/unit/single_controller/test_setup.py
@@ -2096,6 +2096,7 @@ class TestSetup:
# The vLLM server's bearer token, handed to the Gym model server.
policy_api_key=patched_factories["fake_gen"].http_server_api_key,
token_capture=None,
+ gym_results_log=None,
)
mock_validate.assert_called_once_with(
fake_gym_shards, |
ZhiyuLi-Nvidia
left a comment
There was a problem hiding this comment.
Suggested changes for the proposal in #4890 (comment); each one can be applied from its thread.
One change can't be a suggestion because test_setup.py isn't in this PR's diff. test_nemo_gym_wires_env_handle fails without it:
--- a/tests/unit/single_controller/test_setup.py
+++ b/tests/unit/single_controller/test_setup.py
@@ -2096,6 +2096,7 @@
policy_api_key=patched_factories["fake_gen"].http_server_api_key,
token_capture=None,
+ gym_results_log=None,
)The Gym pin is left to you, after Gym #5023 merges.
| try: | ||
| await enrich_run_result( | ||
| row, | ||
| logged, | ||
| capture_dirs=capture_dirs, | ||
| observability_enabled=self._gym_observability_enabled, | ||
| include_payloads=self._gym_results_cfg["include_payloads"], | ||
| delete_capture=self._gym_results_cfg["delete_capture_after_merge"], | ||
| ) | ||
| except (OSError, ValueError, RuntimeError) as error: | ||
| # A debug log must not fail the rollout it describes; say why the | ||
| # line has no merged calls instead. | ||
| logged["_nrl_enrich_error"] = f"{type(error).__name__}: {error}" |
There was a problem hiding this comment.
Drop the try/except: compact_gym_result strips _nrl_enrich_error under the default compact=true, so the marker never reaches the log anyway.
| try: | |
| await enrich_run_result( | |
| row, | |
| logged, | |
| capture_dirs=capture_dirs, | |
| observability_enabled=self._gym_observability_enabled, | |
| include_payloads=self._gym_results_cfg["include_payloads"], | |
| delete_capture=self._gym_results_cfg["delete_capture_after_merge"], | |
| ) | |
| except (OSError, ValueError, RuntimeError) as error: | |
| # A debug log must not fail the rollout it describes; say why the | |
| # line has no merged calls instead. | |
| logged["_nrl_enrich_error"] = f"{type(error).__name__}: {error}" | |
| # No try: the log is opt-in, and an enrichment failure is a code or | |
| # Gym-version bug that should surface, not a marker on the line. | |
| await enrich_run_result( | |
| row, | |
| logged, | |
| capture_dirs=capture_dirs, | |
| observability_enabled=self._gym_observability_enabled, | |
| include_payloads=self._gym_results_cfg["include_payloads"], | |
| delete_capture=self._gym_results_cfg["delete_capture_after_merge"], | |
| ) |
| import time | ||
| from collections.abc import Iterable, Mapping | ||
| from concurrent.futures import Future, ThreadPoolExecutor | ||
| from typing import Any, Optional, TextIO |
There was a problem hiding this comment.
For the NaN/inf fix below. nemo_gym.py already imports torch, so train_data_dump costs nothing extra here.
| from typing import Any, Optional, TextIO | |
| from typing import Any, Optional, TextIO | |
| from nemo_rl.utils.train_data_dump import json_safe_nonfinite |
|
|
||
| def append(self, record: Mapping[str, Any]) -> Future: | ||
| """Queue one record; the returned future resolves once it is written.""" | ||
| line = json.dumps(record, separators=(",", ":"), default=str) + "\n" |
There was a problem hiding this comment.
json.dumps writes NaN/Infinity, which is invalid JSON (raised by @mikhailshilkov on #4855).
| line = json.dumps(record, separators=(",", ":"), default=str) + "\n" | |
| # NaN/inf (e.g. a reward) would otherwise be written as invalid JSON. | |
| line = ( | |
| json.dumps(json_safe_nonfinite(record), separators=(",", ":"), default=str) | |
| + "\n" | |
| ) |
| appender.close() | ||
|
|
||
|
|
||
| def test_appender_survives_being_shipped_to_another_process(tmp_path): |
There was a problem hiding this comment.
A test for the NaN/inf fix.
| def test_appender_survives_being_shipped_to_another_process(tmp_path): | |
| def test_appender_writes_nonfinite_values_as_valid_json(tmp_path): | |
| appender = JsonlAppender(str(tmp_path), GYM_RESULTS_PREFIX) | |
| appender.append({"reward": float("nan"), "scores": [float("inf"), 1.0]}) | |
| appender.flush() | |
| # json.loads accepts NaN; the strict parse is what a non-Python reader does. | |
| line = Path(appender.path).read_text().strip() | |
| assert json.loads(line, parse_constant=pytest.fail) == { | |
| "reward": None, | |
| "scores": [None, 1.0], | |
| } | |
| appender.close() | |
| def test_appender_survives_being_shipped_to_another_process(tmp_path): |
|
Some ideas to make this smaller while keeping both features: the outcome log and compaction. Roughly in order of how much they remove. 1. Join outcomes on
On the legacy path the id is 2. Compaction: drop a fixed set of identity keys instead of 3. Fewer knobs
4. Error lines: keep 5. Small cleanups in
Possible improvement, not a simplification: with token capture off, a line is about 144 KB, and 78% of that is Unrelated change to check: |
|
From poolside's side (Mikhail, Slack): they join Gym's records to the train dump and would like |
|
/ok to test 9ebe1ab |
Signed-off-by: Christian Muertz <[email protected]>
…m API Signed-off-by: Christian Muertz <[email protected]>
|
/ok to test 6e5faa9 |
What and why
#4855 logs each agent's own
/runresult. How much that holds depends on the agent: many return only their final answer. Gym's model server already records every call a rollout makes (subagents, summarizers, judge calls throughServerClient), but RL never turns that on and never reads it. This PR replaces #4855's two outputs withasync_rl.gym_results_log, which logs that full record for every rollout, plus RL's decision about each one, without repeating anything within a line.How Gym records and RL outcomes are written
Unique
_ng_rollout_idon every row (rollout_manager._build_inputs). It's the token-capture gate id, or<group_id>_g<i>_a<attempt>when token capture is off. Previously capture-off rows had none: feat(sc): dump Gym results with train data, and log every Gym result separately #4855 loggedrollout_id: null, and Gym fell back to a"{task}-{rollout}"capture key that repeats across steps. Rows also carry_ng_dispatch_weight_version.Gym-actor log,
<log_dir>/gym_results/gym_results.<pid>.jsonl.resultline per Gym result, before RL post-processing, so the reward is Gym's raw reward and the legacy path's token arrays are still present.enrich_run_resulton a shallow copy, so nothing extra travels to the trainer./runwrites anerrorline naming the rollouts still pending. A result RL can't post-process writes one naming that rollout. feat(sc): dump Gym results with train data, and log every Gym result separately #4855 logged neither.Compact lines (
compact: true, the default). Each line drops only what it repeats:enrich_run_resultstamps onfull_result, which the line carries at top level;ng_model_call_capture.callswhen every captured call also appears inng_trajectory.model_calls(metricsandgapsstay);request.input,request.tools,response.outputorresponse.toolsthat equals the agent's own field, which becomes a reference such as"=full_result.responses_create_params.input".Every captured call keeps its entry, timing, TTFT, status,
finish_reasonand token counts. Bodies that differ (intermediate turns, subagents, summarizers, judges) stay in full.compact: falselogs Gym's record unchanged.rl_outcomes.<pid>.jsonl.bufferedandevictedlines per group.bufferedmaps the per-attempt TQ group id to the Gym group id and attempt; with token capture off these differ, and without the mapping outcomes couldn't be joined to Gym lines.trainedandmaskedlines per sample, with the final reward, numbered liketrain_data_step<N>.jsonl.Config:
async_rl.gym_results_log(enabled,include_model_calls,include_payloads,delete_capture_after_merge,compact), a BaseModel with defaults on its fields. Setup rejects the log on a non-Gym run, and rejectsinclude_model_callswithout Gym'sobservability_enabledand an absolutemodel_call_capture_dir.Removes feat(sc): dump Gym results with train data, and log every Gym result separately #4855's
gym_full_resultTQ object column. That also removes its open review findings (schema warm-up, resume with the column missing, modified values with token capture off). The train dump joins the log by sample id. Kept from feat(sc): dump Gym results with train data, and log every Gym result separately #4855: thelogger.log_dircrash fix and its regression test.Docs: a "Gym rollout logs" section in
docs/guides/single-controller.md, plus the exemplar YAMLs.What a line holds
full_result.response+reward, verifier fieldsng_trajectory.invocations[]ng_trajectory.turns[],tool_calls[]ng_trajectory.model_calls[]agent,dispatch_weight_version,token_capturerl_outcomeslinesCompared with #4855:
ng_trajectory.model_callsis always[]there, and the agent-side fields only appear if Gym observability happened to be on. The RL-side fields,errorlines andrl_outcomesare new.Issues
Stacked on #4855.
Convergence / perf / functionality proof
On the updated base, 984 tests passed locally: 366 setup, 246 controller, 180 advantage-stage and replay-buffer, 107 rollout-manager, 68 Gym actor, and 17 Gym logging tests. The logging tests exercised the real pinned Gym capture and enrichment APIs, with and without a task index. CI for this revision.
errorlines, merged calls staying out of the trainer-bound result), rollout id stamping, the replay-buffer and advantage-stage outcomes, compaction (every call kept, only identical fields referenced, input never mutated), and pickling the appender. That last one matters because setup ships the replay buffer to the controller actor; the first live run caught that it was unpicklable.nemo.lenshas nospan_attributes), because of dependency drift. CI will run them here.test_gym_results_log.py,test_tq_replay_buffer.py,test_advantage_stage.py,test_rollout_manager.py,test_nemo_gym.py,test_single_controller_actor.pyandtest_train_data_dump.py.ruff checkandruff formatare clean.resultlines, all identity fields setrollout_id<group>_g<i>_a0)trained/maskedlines joined to Gym linesbufferedThat run then crashed in the step-0 optimizer step: every sequence over
seq_logprob_error_thresholdwith token capture off, and a NaN grad norm with it on. The port's base lacked the leader-broadcast layout fix (#4263), which this PR's base already has. A rerun of the compacted format with that fix is in progress, and this section will be updated with it.🤖 Generated with Claude Code
Needs upstream changes
None. The parent already pins a Gym revision with rollout enrichment and the model-call capture helpers. Pinned Gym source.