Why filtering inside the loss needs a gradient correction afterwards

Companion illustration for NVIDIA-NeMo/RL #4171. All permalinks pin the PR head ae5a6d9.

Two pages on this PR, one question each โ€” this one: three ways to normalize the same gradient, and why the PR picks the one it does.

Before
Setting grpo.seq_logprob_error_threshold forced an extra forward pass over the whole batch, purely to get the logprobs the filter needed.
This PR
Adds loss_fn.seq_logprob_error_in_loss. The filter runs inside the training forward, and the worker corrects the gradient once the loop is done.
Status
New feature, off by default. Non-streaming Megatron GRPO only โ€” SingleController is rejected outright.

GRPO can throw away a sequence when the logprobs from the generator and from the trainer disagree too much. Each microbatch's loss divides by the global number of surviving response tokens โ€” global meaning across every microbatch and every data-parallel rank โ€” so that once the gradients accumulate and get summed, the total comes out as (sum of contributions) / (global count).

The whole PR turns on one thing: when is that global count knowable? If you filter before training, you know it before the first microbatch runs โ€” divide by it and you are done. If you filter inside the loss, you cannot know it while microbatch 1 is running, because you have not yet seen what microbatches 2โ€ฆN will reject. So you divide by the count you do have, and fix the gradient afterwards. That fix-up is the only reason the correction step exists.

Below: the flow today, the flow this PR adds, and the third shape raised in review. All three land on the identical gradient. Same batch throughout โ€” three sequences of 7, 9 and 4 response tokens, split across two microbatches, where the 4-token one fails the threshold.

1 ยท Today: filter first, then train

# --- driver, nemo_rl/algorithms/grpo.py --- prev_logprobs = policy.get_logprobs(train_data) # EXTRA FORWARD PASS over the whole batch compute_and_apply_seq_logprob_error_masking(train_data, ...) err = mean(exp|generation_logprobs - prev_logprobs|) # per sequence train_data["sample_mask"][err > 2.0] = 0 # seq C (4 tok) rejected -> weight 0 policy.train(train_data, loss_fn) | | # --- worker, nemo_rl/models/megatron/data.py --- | process_global_batch: | local = sum(token_mask * sample_mask) # C already contributes 0 | G = all_reduce(local) = 16 # 7 + 9. ALREADY the survivor count | | mb1: loss = (A's token losses).sum() / 16 | mb2: loss = (B's token losses).sum() / 16 | backward, DP all-reduce | +-- gradient = S / 16 -> optimizer.step() # clip sees S/16

Nothing to correct: G was the right denominator from the start, because the rejects were already zeroed out of sample_mask before process_global_batch counted them.

That extra forward pass was pure overhead

This mode requires force_on_policy_ratio: true, and under that flag the loss does not even load prev_logprobs (loss_functions.py:514-516) and then overwrites it with curr_logprobs.detach() (:528-529). So that pass produced a tensor the loss throws away โ€” its only consumer was the filter.

2 ยท This PR: divide by the unfiltered count, then correct

# --- driver --- prev_logprobs = policy.get_logprobs(train_data) # SKIPPED โ€” this is the saving # sample_mask untouched here; nothing is filtered yet policy.train(train_data, loss_fn) | | process_global_batch: | G = all_reduce(sum(token_mask * sample_mask)) = 20 # 7+9+4, NOT filtered | | mb1: curr_logprobs = forward(...) # the pass we were doing anyway | err = mean(exp|generation_logprobs - curr_logprobs.detach()|) | sample_mask *= (err <= 2.0) # seq C -> 0 | emit seq_logprob_error_valid_tokens = 7 | loss = (A's token losses).sum() / 20 # C contributes exactly 0 | mb2: ... emit 9 ... | loss = (B's token losses).sum() / 20 | | backward, DP all-reduce -> gradient = S / 20 # too small by 20/16 | | # --- _normalize_in_loss_seq_filter, after the loop --- | K = all_reduce(7 + 9) over DP, broadcast over PP # = 16, knowable only NOW | scale_gradients(20 / 16 = 1.25) | +-- gradient = S / 16 -> optimizer.step() # same as path 1
The difference between 1 and 2: when the denominator becomes knowable today filter -> count -> microbatch 1 -> microbatch 2 -> step G = 16 known here already the survivor count this PR count -> microbatch 1 (filters) -> microbatch 2 (filters) -> correct -> step G = 20 known here K = 16 known only here after every microbatch has run

3 ยท The alternative raised in review: do not normalize at all, divide once

The review question on this PR was why the loss divides by 20 at all, when it is going to be corrected away. The alternative: have the loss divide by nothing, let the raw sum accumulate, and divide by the survivor count once at the end. That is not hypothetical โ€” it is how the split-API path in this same file already works, and it passes a literal placeholder of 1.0 into the loss to do it.

# --- the split-API path, megatron_policy_worker.py:1837-1840 --- # "Placeholder N=1: loss returns un-normalized sums. backward deposits raw # d(sum)/dtheta into param.main_grad via the DDP hooks. The 1/N rescale # happens once at finish." placeholder_n = torch.tensor(1.0) # passed as BOTH global_valid_seqs # and global_valid_toks | mb1: loss = (A's token losses).sum() / 1 # raw sum, not normalized | mb2: loss = (B's token losses).sum() / 1 | | backward, DP all-reduce -> gradient = S # 20x bigger than path 2's | | # --- _finish_train_step_body --- | K = all_reduce(local_valid_toks) = 16 | scale_gradients(1 / 16) | # one multiply, whole buffer โ€” | # main, MoE and MTP params alike | +-- gradient = S / 16 -> optimizer.step() # same as paths 1 and 2

So paths 2 and 3 are the same single multiply on the finished gradient. The survivor count is not knowable any earlier in either one. The only thing that differs is which constant the loss divides by on the way in โ€” 20 or 1 โ€” and that choice has knock-on effects:

2 ยท divide by G = 203 ยท divide by 1
End-of-step multiply ร— 20/16 ร— 1/16
Final gradient S / 16 S / 16 โ€” identical
Loss metrics Already on the denominator everything else expects. rescale_loss_metrics only touches the keys the loss advertises. Every metric comes back un-normalized and has to be undone downstream โ€” which is exactly what the metric_normalizations machinery exists for on that path.
MoE aux-loss hook The hook is hardcoded to 1/global_valid_toks (:1186), which is the same value as C โ€” so main and aux come out of the backward on one denominator, and the single end multiply takes both to 1/K. The hook still says 1/global_valid_toks, but the main loss is now on 1/1. They leave the backward already off by G, and the end multiply scales both and keeps the gap. That line has to change too.
Numerics No difference. G is at most 2^18 here (512 sequences ร— 512 tokens), against bf16's 2^-126 โ€ฆ 2^128 โ€” roughly 100 spare binades at either end, so neither form comes near overflow or underflow. FP8 and NVFP4 pick their scale factors from each tensor's own amax, so a constant factor is absorbed exactly and relative error is unchanged. And bf16's mantissa is 8 bits at every exponent, so precision does not vary with scale.

The aux-loss row is the one that bites, because those hooks sit at a different place in the code from the loss's own divide and name the same quantity by hand. MoE is a live case โ€” this feature does not reject it, and a shipped MoE recipe already sets seq_logprob_error_threshold. MTP is not: the validator refuses it outright (grpo.py:485-491), along with draft models, positive-example NLL and distillation.

What you get, and what you give up. You save one forward pass over the whole batch per step โ€” measured at 17.8% lower mean step time on a 1.5B model over 450 steps. You pay in two ways. Rejected sequences still cost a full forward and backward, because the filter only learns they are bad partway through. And the decision now comes from the training forward rather than a separate inference forward, so FP8 scale history and packing can change which sequences pass; the PR says plainly that bitwise agreement with the old path is not expected.