Why the trainer warm-up crashes at startup when CUDA graphs are on

NVIDIA-NeMo/RL #5001. Permalinks pin the PR head 5223071, Megatron-LM 3e95097 (the copy pinned inside Megatron-Bridge), and Transformer Engine 2.18 27486e0.

Before
There was no warm-up. Step 1 was the first time the trainer ran.
This PR
Adds NRL_TRAINER_WARMUP=1. The warm-up saves the trainer's random-number state, runs a fake step, then puts the state back. It saves that state with .clone() unless the tracker has a use_cudagraphable_rng flag.
Status
Open: not fixed in this PR. It only hits runs with the warm-up on and Megatron CUDA graphs on. The fix below is proposed in review comment C1 (pending), not implemented.

Three pages on this PR. Read page 1 first for what the warm-up is. Page 3 proposes a simpler way for setup to start it.

Background. Megatron keeps a few named random-number streams, one per kind of parallel group, in an RNG tracker. There are two kinds of tracker. Megatron's own stores each state as a tensor. Transformer Engine's (TE's) stores each state as a torch.Generator object, so that CUDA graphs can read it. NeMo RL switches to TE's tracker whenever cuda_graph_impl is not "none". Dotted words have a short explanation: hover or tap them.
mainthis PRafter the review's fix (proposed in C1)
v1 (driver loops)no warm-upno warm-upno warm-up
v2 (single controller)no warm-upwarm-up + CUDA graphs โ†’ AttributeError before step 1warm-up skips CUDA-graph runs. Every tracker kind is saved and restored in place.

The crash, one config line to the error

With NRL_TRAINER_WARMUP=1, on every Megatron rank policy.megatron_cfg: cuda_graph_impl: local use_te_rng_tracker = True NeMo RL forces it: setup.py TECudaRNGStatesTracker Megatron picks TE's class rng_tracker.get_states() โ†’ {"model-parallel-rng": <torch.Generator>, ...} TE stores Generators this PR asks: getattr(tracker, "use_cudagraphable_rng", False) โ†’ False (TE's class has no such flag) megatron_policy_worker.py L2744-L2748 Megatron's own check says: is_graph_safe_cuda_rng_tracker(tracker) โ†’ True (isinstance TE tracker) random.py L604-L612 (not used) {n: s.clone() for n, s in ...} AttributeError: 'torch._C.Generator' object has no attribute 'clone' This runs before the try: block, so nothing catches it. The warm-up fails, and the run stops before step 1. The error itself was reproduced on CPU with torch 2.13; no GPU run.
  1. A run sets cuda_graph_impl: local (or any value other than "none"), or sets use_te_rng_tracker: true in model_overrides. The shipped example configs use "none", so they do not hit this.
  2. Megatron builds TE's tracker. In TE 2.18 each saved state is a torch.Generator from clone_state().
  3. The PR's check looks for a flag that only Megatron's own tracker has, so it takes the .clone() branch. torch.Generator has get_state/set_state but no clone.
  4. One more problem waits behind the crash. With cuda_graph_impl: local, the warm-up's forward/backward is the call that captures Megatron's CUDA graphs, so they are captured on the fake batch's shapes. A real batch that matches none of them hits "no matching cudagraph runners were found".

The fix: proposed in C1, not in the PR

Where the fix lands: RL only, one file, megatron_policy_worker.py, plus one row in the docs table. No Megatron or TE change: both already expose get_state/set_state on each generator.

Nothing below is implemented or run. The - lines exist at the PR head.

@@ megatron_policy_worker.py L2693-L2695 ยท _trainer_warmup_skip_reason
         if self.optimizer is None:
             return "no optimizer"
+        # The warm-up's fwd/bwd would capture CUDA graphs on the synthetic batch's shapes.
+        if get_model_config(self.model).cuda_graph_impl != "none":
+            return "CUDA graphs would be captured on the synthetic batch"
         if self._router_replay_enabled:
@@ megatron_policy_worker.py L2741-L2749 ยท warmup_first_pass, save
         rng_tracker = get_cuda_rng_tracker()
-        # Graph-safe trackers hold generators that CUDA graphs may have registered;
-        # replacing them with copies would detach those graphs.
-        tracker_states = (
-            None
-            if getattr(rng_tracker, "use_cudagraphable_rng", False)
-            else {name: s.clone() for name, s in rng_tracker.get_states().items()}
-        )
+        # TE's tracker and graph-safe trackers hold torch.Generator objects (no .clone()).
+        tracker_states = {
+            n: s.get_state() if isinstance(s, torch.Generator) else s.clone()
+            for n, s in rng_tracker.get_states().items()
+        }
         cpu_rng_state = torch.get_rng_state()
@@ megatron_policy_worker.py L2784-L2787 ยท warmup_first_pass, finally
             torch.cuda.set_rng_state(cuda_rng_state)
-            if tracker_states is not None:
-                rng_tracker.set_states(tracker_states)
+            live = rng_tracker.get_states()  # a new dict holding the same state objects
+            for n, s in live.items():
+                if isinstance(s, torch.Generator):
+                    s.set_state(tracker_states[n])  # in place: graphs keep their generator
+                else:
+                    live[n] = tracker_states[n]
+            rng_tracker.set_states(live)
             self.timer = step_timer
  1. The first hunk skips the warm-up when CUDA graphs are on, so graphs are never captured on fake shapes. It reads the value Megatron actually runs with (TransformerConfig.cuda_graph_impl).
  2. The second saves every state, whatever the tracker kind: a generator's seed and offset, or a tensor copy. This still matters with graphs off, because a run can turn on TE's tracker by hand.
  3. The third writes generator states back into the same objects. get_states() returns a new dict, so set_states is still called for tensor states. This also restores the graph-safe states that the PR currently skips, which an earlier review thread on the same line pointed out.

๐Ÿ”ด review comment C1 โ€” megatron_policy_worker.py:2742   ๐ŸŸก C3 โ€” the missing worker test that would catch it

So what. If you turn on the warm-up in a Megatron run with CUDA graphs, it dies before step 1 with an AttributeError, on every rank. Leave the warm-up off for CUDA-graph runs until C1 lands. The review also asks for a unit test with a fake tracker that stores torch.Generator states: it fails today and would have caught this.

The review comments linked above are part of a pending review, so they open only for its author until the review is published.