Skip to content

fix(loss): normalize the VAPO positive-example NLL by the global token count - #3791

Open
khazic wants to merge 1 commit into
NVIDIA-NeMo:mainfrom
khazic:khazic/fix/vapo-nll-global-normalization
Open

khazic wants to merge 1 commit into
NVIDIA-NeMo:mainfrom
khazic:khazic/fix/vapo-nll-global-normalization

Conversation

@khazic

@khazic khazic commented Aug 24, 2026

Copy link
Copy Markdown

Problem

ClippedPGLossFn implements VAPO's positive-example NLL term (arXiv:2504.05118, Eq. 10). Every other term in the same loss function is normalized by global_valid_toks, a count all-reduced across the DP/CP world before the loss call, so that summing the per-microbatch losses on each rank reproduces the correct global mean. The NLL term instead normalized by correct_mask.sum(), the current microbatch's own count of correct-sample tokens:

nll_loss = torch.tensor(0.0, device=mask.device)
if self.positive_example_nll_weight > 0 and "rewards" in data:
    correct_sample_mask = (data["rewards"] > 0).float()
    correct_mask = mask * correct_sample_mask.unsqueeze(-1)
    correct_valid_toks = correct_mask.sum()
    if correct_valid_toks > 0:
        nll_loss = masked_mean(
            -curr_logprobs, correct_mask,
            global_normalization_factor=correct_valid_toks,
        )

Trainers call the loss function once per microbatch and sum the results (dtensor_policy_worker.py also multiplies by dp_size * cp_size to undo FSDP's gradient averaging). A term normalized by a local count contributes a full local mean on every microbatch instead of its share of one global mean, so:

  • the term's effective weight scales with the number of microbatches the global batch is split into, a value that has nothing to do with the objective (train_micro_batch_size is a hardware knob);
  • it further scales with dp_size * cp_size, since that factor is applied uniformly to the whole loss including this now-inflated term.

Changing train_micro_batch_size, dp_size, or cp_size therefore silently changes what mu in L = L_PPO + mu * L_NLL(correct) actually means, with no error or warning.

Fix

Normalize by global_valid_toks, the same denominator actor_loss and kl use. mu is now defined relative to all valid tokens in the batch rather than to correct-sample tokens alone; that is a constant rescaling of the weight (correct-token count / total valid-token count, roughly the training accuracy), not a change to what the term computes, and it is now invariant to how the batch is split into microbatches or across DP/CP.

positive_nll_loss moves from MetricNormalizer.NONE to TOKENS in metric_normalizations, since it is now normalized the same way as the loss term it reports, and the metric-normalization table in docs/guides/grpo.md and the config comment in ClippedPGLossConfig are updated to match.

Evidence

tests/unit/algorithms/test_loss_functions.py::test_clipped_pg_positive_nll_is_microbatch_invariant builds one batch of 4 samples (3 correct, 1 incorrect) and compares the loss and the input gradient computed in a single call against the same computation split into two microbatches of 2, summed. This is exactly the microbatch pattern dtensor_policy_worker.py and megatron_policy_worker.py use.

On the current main, with positive_example_nll_weight disabled the two computations agree, and with it enabled they diverge:

tests/unit/algorithms/test_loss_functions.py::test_clipped_pg_positive_nll_is_microbatch_invariant[0.0] PASSED
tests/unit/algorithms/test_loss_functions.py::test_clipped_pg_positive_nll_is_microbatch_invariant[0.5] FAILED

>       assert (first_loss + second_loss).item() == pytest.approx(single_loss.item(), abs=1e-6)
E       assert 0.2159305214881897 == -0.0661458671092987 ± 1.0e-06
E
E         comparison failed
E         Obtained: 0.2159305214881897
E         Expected: -0.0661458671092987 ± 1.0e-06

1 failed, 1 passed

mu=0.0 passing on unpatched main and mu=0.5 failing isolates the bug to the VAPO term specifically: everything else in the loss is already microbatch-invariant.

With the fix applied, both parametrizations pass:

tests/unit/algorithms/test_loss_functions.py::test_clipped_pg_positive_nll_is_microbatch_invariant[0.0] PASSED
tests/unit/algorithms/test_loss_functions.py::test_clipped_pg_positive_nll_is_microbatch_invariant[0.5] PASSED

2 passed

The full test_loss_functions.py suite (79 tests, covering GRPO/PPO clipping, GSPO, CISPO, dual-clip, TIS variants, DPO, distillation, and the metric-normalization advertisement) passes on the fix branch, so the change does not regress any other loss path:

79 passed, 4 warnings

Scope

This only touches the VAPO NLL term's normalization and its metric classification. The rest of ClippedPGLossFn, the PPO/GRPO/GSPO/CISPO ratio computation, KL penalty, and truncated importance sampling, is unchanged.

@khazic
khazic requested review from a team as code owners August 24, 2026 05:18
@copy-pr-bot

copy-pr-bot Bot commented Aug 24, 2026

Copy link
Copy Markdown

This pull request requires additional validation before any workflows can run on NVIDIA's runners.

Pull request vetters can view their responsibilities here.

Contributors can view more details about this message here.

@github-actions github-actions Bot added the Documentation Improvements or additions to documentation label Aug 24, 2026
@khazic

khazic commented Aug 26, 2026

Copy link
Copy Markdown
Author

Measured this in a training run rather than only in the unit test. The inflation factor comes out at exactly the number of microbatches, which is the quantity the bug predicts.

Measurement

GRPO, Qwen3-0.6B, gsm8k, positive_example_nll_weight: 0.1, train_global_batch_size: 32, 3 steps. The term itself is inert on current main (see #3792), so these runs all carry #3792 in order to make the term observable at all.

build positive_nll_loss at step 1 train/loss
#3792 only, local normalization 1.077010 0.130577
#3792 plus this PR, global normalization 0.033657 0.026242
reference: term disabled 0.000000 0.022877

1.077010 / 0.033657 = 32.000.

That is train_global_batch_size, which is the number of microbatches the global batch is split into for this configuration. It is exactly what the bug predicts: normalizing by the microbatch's own correct_valid_toks makes every microbatch contribute a full local mean, and the trainer sums the per-microbatch losses, so the term arrives at M times its intended weight where M is the microbatch count.

The loss figures corroborate it independently: 0.130577 - 0.022877 = 0.1077, which is positive_example_nll_weight * 1.077010. The term reaches the objective at the inflated value, not just the reported metric.

What this means for the configured weight

The practical consequence is that positive_example_nll_weight does not mean what it says. Setting 0.1 applies an effective weight of 0.1 * M, and M is a function of train_global_batch_size and train_micro_batch_size, neither of which is a property of the objective. Changing a memory-side knob silently rescales a loss term. After this PR the term is normalized by global_valid_toks like every other term in the same function, so the configured weight is the effective weight.

Merge ordering

This PR and #3792 should land together, or this one first. On current main the NLL term never executes, so this bug is latent. #3792 activates the term, and without this fix it comes back at 32x its configured weight. A wrong contribution to the gradient is harder to detect than no contribution, so activating the term without this fix would be a regression relative to today's silent no-op.

One limitation, stated explicitly

I could not demonstrate the microbatch dependence end to end. The natural experiment is to hold train_global_batch_size fixed and vary train_micro_batch_size, but in this stack train_micro_batch_size does not drive the microbatch split: with sequence packing enabled it feeds a token budget (train_mb_tokens), and with packing disabled the measured term was unchanged (1.079612 at train_micro_batch_size: 1 versus 1.073267 at 2). So the 32x figure above is measured by comparing local against global normalization directly, not by varying the microbatch count.

The unit test in this PR covers the invariance claim precisely, by comparing a single call against the same computation split into two microbatches and summed, which is the pattern the trainers use.

…n count

ClippedPGLossFn normalized the positive-example NLL term by correct_mask.sum(),
the microbatch's own count of correct-sample tokens, while every other term in
the same loss is normalized by global_valid_toks. Trainers call the loss once
per microbatch, sum the results and rescale by the DP/CP world size, so a local
denominator makes each microbatch contribute a full mean instead of its share of
one. The effective weight of the term became mu times the number of microbatches
times dp_size times cp_size, so changing train_micro_batch_size or the world size
silently changed the objective.

Normalize by global_valid_toks instead, which makes the term invariant to the
microbatch split and to the world size. mu is now defined relative to all valid
tokens rather than to correct-sample tokens alone, which is a constant rescaling
of the weight; the docs and the config comment say so. positive_nll_loss also
moves from MetricNormalizer.NONE to TOKENS, since it is now normalized the same
way as the loss term it reports.

Signed-off-by: khazic <[email protected]>
@khazic
khazic force-pushed the khazic/fix/vapo-nll-global-normalization branch from d4ff4e7 to b6bc930 Compare September 24, 2026 15:16
@terrykong terrykong removed the Documentation Improvements or additions to documentation label Nov 28, 2026

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

community-request waiting-on-maintainers Waiting on maintainers to respond

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants