Why the logprob backward can write its grad into the logits, and when that is safe

NVIDIA-NeMo/RL #4776, commit 4a8997dba · all links pinned to head 96ec8a36

Before
The chunked logprob backward made a second tensor the full size of the logits to hold the grad. The PR estimates about 12 GiB for a 98k-token shard with an fp32 LM head.
This PR
A new opt-in flag, reuse_logits_storage, writes the grad into the logits' own memory, one chunk at a time. Only the fused packed loss turns it on.
Status
Correct on today's code: nothing else reads those logits after backward. The review agrees with moving this commit to its own PR and lists three asks for it (last section, proposed, not in the PR).

Three pages on this PR, one question each. This one: how the memory change works.

The policy loss needs the log-probability of each chosen token. ChunkedDistributedLogprob computes it in chunks of tokens to save memory, and saves the logits for backward. In backward, each chunk's grad is one_hot(target) − softmax(logits), scaled by the incoming grad. Before, every chunk was copied into a new zeros_like(logits). Now, when the flag is on, it is copied back into the logits. Each chunk is read before it is written, so the math does not change.

One buffer instead of two

Tiny example: [1, 6, 4] = [sequences, tokens, vocab on this GPU], fp32 logits, chunk size 2, so 3 chunks. The picture is backward, halfway through chunk 1.

Before: grad in a new tensor (48 floats) This PR: grad written into the logits (24 floats) logits [1, 6, 4] grad = zeros_like(logits) token rows 0–1: chunk 0 · 2–3: chunk 1 · 4–5: chunk 2 2 × [1, 6, 4] alive at once logits [1, 6, 4] (same memory holds the grad) chunk 0: grad chunk 1: read, then overwritten chunk 2: still logits 1 × [1, 6, 4]: saves one logits-sized tensor being read (softmax) grad written zeros, not used yet logits, not touched yet model_utils.py:321-346

The change itself, at the pinned head:

@@ model_utils.py L307-L319 · ChunkedDistributedLogprob.backward
-        grad_input: torch.Tensor = torch.zeros_like(vocab_parallel_logits)
+        # Opt-in: write the grad into the fp32 logits' storage instead of a second
+        # [B, S, V/TP] tensor. Only safe when this op is the logits' sole consumer;
+        # each chunk is read before it is overwritten, and leaf tensors are left intact.
+        reuse_logits_storage = (
+            ctx.reuse_logits_storage
+            and vocab_parallel_logits.dtype == torch.float32
+            and not vocab_parallel_logits.is_leaf
+        )
+        grad_input: torch.Tensor = (
+            vocab_parallel_logits
+            if reuse_logits_storage
+            else torch.zeros_like(vocab_parallel_logits)
+        )
@@ loss_input.py L538-L539 · prepare_packed_loss_input
+        # Sole consumer of the packed logits, so the grad may overwrite them.
+        reuse_logits_storage=True,

Only fp32 logits qualify, because the grad is fp32. With bf16 logits the old path runs. No shipped config sets fp32_lm_head: true, so no recipe or nightly test reaches this code today.

Why it is safe today, and what would break it

After backward, the logits tensor holds the grad. Anything that reads it as logits later gets wrong numbers. If that reader saved the logits for its own backward, PyTorch raises "modified by an inplace operation". If it kept them some other way (a ctx attribute, .data), it reads the grad silently. The review checked every reader on the one path that turns the flag on:

Reader of the packed logitsAffected?
This logprob opReads each chunk before overwriting it.
Second logprob call for the unfiltered KL termNo. It runs only with top-k/top-p, which turns chunking off, so the reuse never runs. But the "sole consumer" comment is wrong.
Packed draft loss (speculative decoding head)No. It copies the logits with torch.roll during forward.
MTP loss, context-parallel gatherNo. They use hidden states and logprobs, not these logits.

A CPU check gave the same weight and input grads with the flag on and off, including the pre-packed view path and temperature scaling.

Asks for the split-out PR — proposed, not in the PR

Where these land: RL only. loss_input.py, test_sequence_packing_fusion.py, and the PR description. Nothing below is implemented.

@@ loss_input.py L538-L539 · prepare_packed_loss_input (proposed)
-        # Sole consumer of the packed logits, so the grad may overwrite them.
-        reuse_logits_storage=True,
+        # The grad may overwrite these logits only on the chunked path. The
+        # unfiltered KL call below reads them again, but only with chunking off.
+        reuse_logits_storage=use_chunking,
  1. Pass use_chunking instead of True (above). Same behavior today, and the safety condition is now in the code.
  2. Add chunk_size (None, 3) to test_sequence_packing_fusion_vs_baseline. Today it passes no chunk size, so no test runs the reuse with real tensor- and context-parallel all-reduces.
  3. Add measured peak GPU memory with the flag on and off, plus a few steps of loss and grad norm. The 12 GiB is the size of one tensor, not a measurement.

↪ C1 · review comment — model_utils.py:1110

So what. This saves one logits-sized fp32 tensor per step on the fused packed path, and it is correct for today's readers. It is also the only commit in the PR that touches the shared training loss. On its own PR it can be measured, tested at TP and CP above 1, and reverted alone if needed.