[algo, worker, fsdp, megatron] fix: normalize bypass-mode token-mean loss by tokens kept after rejection sampling #8176
 <br/>All committers have signed the CLA.
One regression worth adding for the documented approximation: in a scalar fixture with [1, 7] retained tokens, full/split losses match but gradients are +0.05/-0.4. I reproduced this through ppo_loss on CPU; a tiny classifier also gets different SGD updates. Equal-retention and entropy/KL controls pass.
Thank you, I reproduced it: with micro-batches keeping 1 and 7 of their 8 tokens, the exact token-mean gradient is +0.05, main gives +0.025 and the first version of this PR gave -0.4. That version also did nothing for micro-batches whose tokens are all rejected.
I've replaced it with an engine-level fix. ppo_loss now reports how many tokens it kept, and BaseEngine.train_batch divides by the kept total once every micro-batch has run, before gradient clipping (Megatron also broadcasts the count across pipeline stages). Entropy and KL now skip rejected tokens too, as in decoupled mode. The token-mean is then exact however the mini-batch is split.
A small change can't fix this. The kept-token count only exists after the last micro-batch's forward pass, but each micro-batch runs its backward pass right after its forward. Normalizing each micro-batch on its own either keeps main's scale error or reweights the micro-batches (the sign flip above). The only other exact option is an extra forward pass before the update, which is what decoupled mode does and what bypass mode exists to avoid.
So this needs a maintainer decision. The fix changes BaseEngine.train_batch and adds a scale_gradients to each engine. If an engine change isn't worth it for this bug, I'll close the PR; the alternative is documenting that bypass mode divides by the token count before rejection.
LingYi-Liang
Alexander230
What does this PR do?
Fixes #4852.
In bypass mode, rejection sampling (
rollout_rs) drops tokens inside the loss, using each micro-batch's current log probs. The engine countsbatch_num_tokensbefore any micro-batch runs, andtoken-meandivides the kept tokens' loss by that pre-rejection count, which shrinks the loss by the fraction of tokens kept. Decoupled mode applies the rejection mask toresponse_maskbefore the update, so its count matches.The kept-token count of the whole mini-batch is only known after the last micro-batch's forward pass, but each micro-batch runs its backward pass right after its own forward. This PR therefore normalizes in the engine, after gradient accumulation and before gradient clipping.
Revision. The first version of this PR rescaled each micro-batch by its own share of kept tokens. As pointed out in review, that can turn the gradient around when micro-batches keep different shares (with 1 and 7 kept tokens: exact +0.05, that version −0.4,
main+0.025). It also does nothing for micro-batches whose tokens are all rejected. This version replaces that approach.Root cause
batch_num_tokens = loss_mask.sum(), all-reduced over the data-parallel group, before splitting the mini-batch into micro-batches.ppo_losscopies it intoconfig.global_batch_info.compute_policy_loss_bypass_modebuilds the rejection mask from the current log probs and passes it to the policy loss.agg_loss(..., "token-mean")then computesmasked_sum(loss, kept mask) / batch_num_tokens * dp_size.Design & Code Changes
ppo_loss(verl/workers/utils/losses.py): in bypass mode withrollout_rs, it computes the rejection once and averages every term (policy, entropy, KL) over the kept tokens, as decoupled mode does. Undertoken-meanit reports the kept-token count as aLOSS_NUM_TOKENSmetric, summed over micro-batches.- The rejection is computed by the new
compute_bypass_mode_rollout_correction(core_algos.py), which is the code moved out ofcompute_policy_loss_bypass_modeunchanged.- The bypass loss takes the result as an optional
rollout_correction; without it, it behaves as before.BaseEngine.train_batch(verl/workers/engine/base.py): betweenforward_backward_batchandoptimizer_step, it pops that metric and sums it over data-parallel ranks the waybatch_num_tokensis summed. It then multiplies the gradients, the loss and itsSUM-aggregated metrics bybatch_num_tokens / kept tokens.- This happens before clipping, so
grad_normand clipping see the corrected gradient.- Losses that report nothing skip this step without any extra communication.
scale_gradientsper engine:- FSDP/FSDP2 (and VeOmni, which inherits it), TorchTitan and Automodel multiply
param.grad.- Megatron calls the DDP wrapper's
scale_gradients(Megatron-FSDP implements it too), the same call Megatron'sfinalize_model_gradsuses for per-token loss._reduce_loss_num_tokens: only the last pipeline stage runs the loss, so the count is broadcast to the other stages. With PP > 1, that is one 2-element broadcast pertrain_batch. Under dynamic CP the count isn't all-reduced over data parallel, matchingbatch_num_tokens, because the outputs already cover the whole batch.Scope and behavior:
token-mean, every PPO term of the bypass-mode loss is now the token-mean over the kept tokens of the whole mini-batch, however the mini-batch is split into micro-batches and ranks.loss_agg_mode, as in decoupled mode.- the seq-mean modes, which divide by
global_batch_size(the same in both modes), andtoken-sum;- IS-only bypass mode (no
rollout_rs), which doesn't change the mask.Test
Run on CPU, in the environment from
uv sync --frozen --all-packages --extra cpu, with the runnercpu_unit_tests.ymluses:New tests:
test_bypass_rejection_divides_by_kept_tokens_of_all_micro_batches(1+7 and 0+8 kept tokens, with entropy and KL): runsppo_lossthroughBaseEngine.train_batchover two micro-batches. It compares the gradient and the logged loss with the token-mean over all kept tokens.test_bypass_rejection_keeps_the_seq_mean_normalization: no rescale inseq-mean-token-mean.test_megatron_loss_num_tokens_reach_every_pipeline_stage(2 gloo processes, Megatron's parallel state patched): the count reaches a non-last pipeline stage, is summed over data-parallel ranks, and isn't summed under dynamic CP.test_scale_gradients_matches_scaled_loss_on_shards(2 gloo processes):FSDPEngine.scale_gradientson real FSDP1 and FSDP2 shards equals backpropagating the scaled loss.Also checked during development (not committed):
token-meancondition.Not run: GPU training. The Megatron, VeOmni, TorchTitan and Automodel engines are covered only by the CPU tests above and by reading their code.
Duplicate check
gh issue view 4852 --repo verl-project/verl --comments: one comment (automated triage). It confirms the problem and suggests making thetoken-meandenominator match the mask passed toagg_loss.gh pr list --repo verl-project/verl --state open --search "4852 in:body": only this PR.bypass mode token-mean,rejection batch_num_tokens,scale_gradients,kept tokens rejection,compute_policy_loss_bypass_mode):- #8025 (log-prob mismatch metrics), #7519 (MXFP8 training), #7772 (off-policy sequence metrics), #4930 (bypass-mode config timing) and #7945 (Liger cross entropy).
- #6800 adds a rejection mode in
rollout_corr_helper.py, which this change would also normalize.- None of them changes the
token-meannormalization.batch_num_tokensaggregation, not the bypass-mode mask.AI assistance
This PR was prepared with AI assistance: Claude Code (Claude Opus 5.5) wrote the fix, the tests and this description.
🤖 Generated with Claude Code