Explainer for NVIDIA-NeMo/RL #4266.
Permalinks pin the PR head 4db8f66; "before" links pin the base ed14402.
Ten pages on this stack — this one: #4266: a training step that lands while Gym is paused.
step_10, and must describe the rollout data exactly as it was when those weights were saved.
With this PR, Gym's paused agents are saved in the same snapshot, so Gym has to stop first.
Dotted words have a short explanation: hover or tap them.An attempt records the current step (10) and prepares a folder under step_10
(single_controller.py:4626).
It then closes rollout admission and asks Gym to
drain and write its state
(:4648).
The training loop is not paused, so it keeps going. Only after Gym is done does the attempt take the data-plane barrier and compare the step again
(:4664).
If step 11 finished in between, the attempt deletes the folder, aborts Gym, and logs skipped
(:4911). A skipped attempt never counts as a failure.
Which snapshot. This is the periodic snapshot, started every
snapshot_attempt_interval_s by its own loop, which runs beside training
(:801-811).
The snapshot taken at each trainer checkpoint runs inside the training loop, so training can't move during it, and it can't hit this race.
A periodic attempt only gets as far as pausing Gym while the step right after a trainer checkpoint is training; at other times it stops early, before touching Gym
(:4598).
Why it can't just finish into step_10 anyway. When step 11 commits, it deletes the rollout groups it trained on
(_cleanup_consumed_metas_unlocked).
A step_10 snapshot taken after that is missing those groups. But the step_10 weights never learned from them, so a restart from it would silently drop them.
So the check is right to throw the attempt away. The problem is that the throw-away now happens after a 70 s Gym pause, not before one.
How often. An attempt that paused Gym is wasted whenever a step finishes during the pause. In this example the pause (70 s) is longer than a step (40 s), so every attempt overlaps the end of some step, as long as the buffer holds enough finished rollouts to keep training going while new rollouts are stopped. The check before the pause only looks at whether a trainer checkpoint exists for the current step (:4598), not at whether a step is about to finish.
Nothing below is implemented or run. It is one way to do it, written against the PR head.
Where the fix lands: RL only, one file.
single_controller.py, about 30 added lines and 7 changed.
No Gym change: when Gym's prepare call is cancelled, it already resumes every agent it paused
(nemo_gym.py:1261),
and Ray delivers that cancel to an async actor as a normal asyncio cancel
(Ray 2.56.1 worker.py:3321).
The idea: the snapshot can't land once a step commits, so stop waiting for Gym the moment that happens. Training tells the snapshot "a step is starting to commit". The snapshot cancels the Gym prepare right away, and Gym resumes its agents. In the example, rollouts restart at 40 s instead of 95 s. The snapshot is still lost, but training never waits.
@@ single_controller.py L668 · SingleControllerActor.__init__ self._gym_checkpoint_rollout_permitted: asyncio.Event = asyncio.Event() self._gym_checkpoint_rollout_permitted.set() + # Set whenever a training step starts to commit. A Gym snapshot that + # began before that can no longer land. + self._optimizer_commit_started = asyncio.Event() @@ single_controller.py L1966-L1977 · _prepare_and_commit_gym_checkpoint prepare_attempted = True prepare = GymCheckpointPrepareResult.model_validate( - await gym_actor.prepare_checkpoint.remote( - checkpoint_id, - time.time() + timeout_s, - ) + await self._await_unless_step_commits( + gym_actor.prepare_checkpoint.remote( + checkpoint_id, + time.time() + timeout_s, + ) + ) ) if not prepare.ready: raise RuntimeError(...) + if self._optimizer_commit_started.is_set(): + raise _TrainerAdvancedDuringGymSnapshot() # skip the commit, abort below checkpoint = GymCheckpointCommitResult.model_validate( @@ new method, next to _prepare_and_commit_gym_checkpoint (L1949) + async def _await_unless_step_commits(self, ref: ray.ObjectRef) -> Any: + """Wait for a Gym control call, or cancel it once a training step commits.""" + call = asyncio.ensure_future(ref) + step = asyncio.ensure_future(self._optimizer_commit_started.wait()) + try: + await asyncio.wait({call, step}, return_when=asyncio.FIRST_COMPLETED) + finally: + step.cancel() + if call.done(): + return call.result() + self._cancel_gym_control_call(ref) # Gym's prepare resumes its agents + await asyncio.gather(call, return_exceptions=True) # wait for that resume + raise _TrainerAdvancedDuringGymSnapshot() + + def _cancel_gym_control_call(self, ref: ray.ObjectRef) -> None: + """Cancel one Gym control call. A method so unit tests can fake it.""" + ray.cancel(ref) @@ single_controller.py L3276 (PPO) and L3404 (GRPO) · both places a step starts to commit self._optimizer_commit_in_progress = True + self._optimizer_commit_started.set() @@ single_controller.py L4549-L4553 · _save_rollout_checkpoint_locked if self._optimizer_commit_in_progress: return _RolloutCheckpointSaveResult( saved=False, reason="optimizer_commit_in_progress", ) + # No await between the check above and this clear, so every commit that + # starts after the check sets the event again. + self._optimizer_commit_started.clear() @@ single_controller.py L4649-L4655 · _save_rollout_checkpoint_locked if self._gym_participant_checkpointing_enabled: - publication.gym_checkpoint = ( - await self._prepare_and_commit_gym_checkpoint( - checkpoint_id, - tmp_path, - ) - ) + try: + publication.gym_checkpoint = ( + await self._prepare_and_commit_gym_checkpoint( + checkpoint_id, + tmp_path, + ) + ) + except _TrainerAdvancedDuringGymSnapshot: + return _RolloutCheckpointSaveResult( + saved=False, reason="trainer_state_changed" + ) @@ new exception class, next to _GymCheckpointAbortPendingError (L257) +class _TrainerAdvancedDuringGymSnapshot(Exception): + """A training step committed while Gym was preparing its snapshot."""
What each piece does, in order: training sets the event wherever it sets _optimizer_commit_in_progress
(PPO :3276,
GRPO :3404).
The waiting prepare sees it, cancels, and waits for Gym to finish resuming. Awaiting a cancelled call on an async actor returns only after the actor's cleanup has run (measured on Ray 2.58), so Gym has already resumed its agents before RL sends its abort. The existing error path in
_prepare_and_commit_gym_checkpoint
then sends the same-ID abort. That abort does nothing, because Gym already cleared the checkpoint, and it reopens rollout admission. The attempt ends as skipped, exactly as today, just 55 s sooner.
Test that should pass once fixed: a fake Gym prepare that blocks until cancelled, a step that starts to commit, and asyncio.wait_for(..., timeout=5.0) around the attempt. It must return trainer_state_changed with Gym resumed, no commit, and rollouts reopened. Today it times out, because nothing on the RL side cancels the prepare. The cancel sits behind _cancel_gym_control_call because the unit tests' fake actor returns plain tasks, not Ray object refs.
The other option is to hold training right before its optimizer update until the snapshot's cut is taken
(before finish_train_step, and before the PPO critic update at
:3276, which the code calls "already irreversible").
That saves the snapshot, but training then waits out every Gym pause, up to prepare_timeout_s (300 s) for the drain and the same again for the write, whenever a step runs to its deadline.
Training is the part that must not wait, so the abort is the better default.
With save_period: 1. Every step is a trainer checkpoint, and each one takes the same save lock as the periodic snapshot
(:5101).
Today, step 11's checkpoint waits for the doomed periodic attempt to finish its whole Gym pause, then runs its own Gym pause, so training sits through both.
With the change above, the periodic attempt gives up as soon as step 11 commits. Step 11's checkpoint then takes the Gym snapshot itself, at the newer step, so nothing is lost.
skipped with reason trainer_state_changed. With save_period: 1, the wasted pause also holds up the next trainer checkpoint, so training waits too.