At the deadline, the rollout snapshot waits for the model to reach disk, though it never reads the model

NVIDIA-NeMo/RL #5056, review comment C9. Permalinks pin the PR head a97d8342.

Two pages on this PR, one question each. This one: why the last save takes longer than it needs to.

This PR
When the deadline hits, the run saves a trainer checkpoint and waits until it is fully on disk. Only then does it take the rollout snapshot, and then it stops.
C9 asks
Take the snapshot inside the trainer save, while the model is still being written to disk. One rename then publishes both.
Status
Proposed, not implemented. Nothing below is in the PR, and nothing here has been run or timed.
The deadline. checkpointing.checkpoint_must_save_by is a time budget such as 00:03:45:00 (days:hours:minutes:seconds), counted from when the job started. When the run is close enough to it that one more step would not fit (seconds_until_save), the next step saves a checkpoint and the run exits on its own, before the cluster’s time limit kills it mid-step. “At the deadline” means that last save.
Background: the two saves. A trainer checkpoint (folder step_N) holds the model, optimizer, and training progress. A rollout snapshot holds what the trainer checkpoint lacks: the environment’s unfinished conversations and a newer copy of the rollout queue. A snapshot is not a separate checkpoint: it lives inside the trainer checkpoint’s folder, at step_N/rollout_snapshots/snapshot_000001. Dotted words have a short explanation: hover or tap them.

The trainer save copies the model off the GPU and returns. The disk write keeps going in the background, and tmp_step_N is renamed to step_N when it finishes (_publish_when_policy_write_done). The snapshot then waits for that rename twice: in finalize_pending, and again in _resolve_anchor, which skips the snapshot unless step_N exists. Nothing in the snapshot reads the model. It needs the folder only as a place to live.

saves training state Gym paused background disk write idle, waiting This PR: one after the other controller policy workers cut ATQ + counters modelGPU โ†’ CPU waits for the model on disk and the rename to step_N L627 rollout snapshotpause Gym ยท cut B ยท TQ save publishsnapshot model + optimizer โ†’ disk single_controller.py L4226 rename โ†’ step_N run stops C9: snapshot while the model is written controller policy workers cut ATQ + counters modelGPU โ†’ CPU rollout snapshotinto tmp_step_N, same steps publishsnapshot model + optimizer โ†’ disk one rename โ†’ step_N, snapshot inside single_controller.py L3280 run stops saved โ‰ˆ the shorter of the two Time runs left to right. Not to scale: no GPU timings yet.

๐ŸŸ  review comment C9 โ€” single_controller.py:3272

What each save writes, and what it waits on

ItemTrainer checkpointRollout snapshot
Model weights, optimizer, tokenizer (and the PPO value model)yes: copied off the GPU, then written to disk in the backgroundno
Training counters: step, model version, epoch, samples seenyesstep and version only, in its manifest, to match its trainer checkpoint
Loader position, sampler position, next Gym task, spare promptsyesyes, a newer copy
Rollout queue: finished rollouts waiting for training, and their index (capture)yesyes, a newer copy
The environment’s unfinished conversations (Gym snapshot)noyes
Stopsnew queue changes, briefly (cut A). Rollouts keep running.Gym: no new turns start and live ones are parked. Then a brief cut B.
Waits onthe previous checkpoint’s background writetoday: this checkpoint’s model on disk and the rename to step_N. It needs only the folder.

The two saves write different things. The only thing they share is the folder, so the only real order is that the snapshot goes in before the rename.

The proposed change, not in the PR

Where it lands: RL only, two files. single_controller.py (the trainer save and the deadline branch) and snapshots.py (save_snapshot takes a folder). No Gym change: Gym writes wherever it is pointed. No restore change: resolve_latest_snapshot only looks for step_N/rollout_snapshots/snapshot_* with a matching manifest.

@@ single_controller.py L3189-L3193 ยท _train_pump, the save call
                        await self._save_checkpoint(
                            step_metrics,
                            is_policy_training_step=is_policy_training_step,
                            is_final_checkpoint=is_last_step,
+                           snapshot_rollouts=should_save_by_timeout,
                        )
@@ single_controller.py L3272-L3277 ยท _train_pump, the deadline branch
             if should_save_by_timeout:
-                if self._master_config.checkpointing["enabled"]:
-                    # The trainer checkpoint holds no environment state, and no
-                    # later step will wake the pump to snapshot it.
-                    await self._finish_pending_save(blocking=True)
-                    await self._rollout_snapshots.save_at_deadline()
                 print("Timeout has been reached, stopping training early", flush=True)
@@ single_controller.py L4105-L4128 ยท _save_checkpoint and _save_checkpoint_impl
         is_final_checkpoint: bool,
+        snapshot_rollouts: bool = False,
     ) -> None:
         ...
             await self._save_checkpoint_impl(
                 step_metrics,
                 is_policy_training_step=is_policy_training_step,
                 is_final_checkpoint=is_final_checkpoint,
+                snapshot_rollouts=snapshot_rollouts,
             )
     ...
         is_final_checkpoint: bool,
+        snapshot_rollouts: bool = False,
     ) -> None:
@@ single_controller.py L4237-L4243 ยท _save_checkpoint_impl, after the model save returns
         )
+        if snapshot_rollouts:
+            # Runs while the model is still being written to disk. It must finish
+            # before the publish below starts the rename.
+            await self._rollout_snapshots.save_at_deadline(Path(checkpoint_path))
         await write_controller_sidecars(checkpoint_path, captured)
         # Keep this last: the rename it leads to waits only for the policy's async
@@ snapshots.py L604-L608, L625-L633 ยท save_snapshot
     async def save_snapshot(
-        self, *, force: bool = False
+        self, *, force: bool = False, anchor: Optional[Path] = None
     ) -> RolloutCheckpointSaveResult:
         """Publish one rollout-only snapshot anchored to durable trainer state."""
-        async with self._save_lock:
+        # Inside a trainer save, which already holds the lock; taking it again hangs.
+        async with contextlib.nullcontext() if anchor else self._save_lock:
             ...
             save_started = time.monotonic()
-            await asyncio.to_thread(self._checkpointer.finalize_pending)
-            anchor = await self._resolve_anchor()
-            if anchor is None:
+            if anchor is None:
+                await asyncio.to_thread(self._checkpointer.finalize_pending)
+                resolved = await self._resolve_anchor()
+            else:
+                resolved = (anchor, None)  # tmp_step_N; past step 0, so no fingerprint
+            if resolved is None:
                 return RolloutCheckpointSaveResult(
                     saved=False,
                     reason="missing_trainer_anchor",
                 )
-            anchor_path, snapshot_fingerprint = anchor
+            anchor_path, snapshot_fingerprint = resolved
@@ snapshots.py L949, L962 ยท save_at_deadline
-    async def save_at_deadline(self) -> None:
+    async def save_at_deadline(self, anchor: Path) -> None:
         ...
-            result = await self.save_snapshot(force=True)
+            result = await self.save_snapshot(force=True, anchor=anchor)

In order:

  1. The train loop already knows at the save whether the deadline is due (should_save_by_timeout, L3110), so it passes that flag into the save.
  2. After the model leaves the GPU, the snapshot runs into tmp_step_N, while the policy workers write the model to disk. It must finish before the rename starts (L4240-L4242).
  3. The step’s optimizer window has already closed (L3057, before the save at L3189), so the snapshot does not skip itself.
  4. The deadline branch keeps only print and break. The _finish_pending_save after the loop publishes both at once, with or without deferred finalize.
  5. save_at_deadline keeps its failure rule. A failed snapshot deletes its own tmp folder and warns, and the trainer checkpoint still publishes.

About +10 lines net. It also makes C6 (the test for _finish_pending_save) unnecessary, because the branch it covers goes away.

So what. The last save takes about the longer of the two saves instead of their sum. The saving is the shorter of the model’s disk write and the snapshot. Both write to the same file system, so the real saving may be smaller. The C4 GPU run should time the deadline save before and after this change. The snapshot could start even earlier, next to the GPU-to-CPU copy, but C9 keeps it after that copy so the steps stay simple.