← Back to Pull requests

[algo, worker, fsdp, megatron] fix: normalize bypass-mode token-mean loss by tokens kept after rejection sampling #8176

Open
Alexander230 opened this pull request with 453 lines diff across 11 files
View on GitHub
Alexander230 Alexander230 commented on Oct 09, 2026 20:19 UTC
Author

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 counts batch_num_tokens before any micro-batch runs, and token-mean divides 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 to response_mask before 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

  • The engines set batch_num_tokens = loss_mask.sum(), all-reduced over the data-parallel group, before splitting the mini-batch into micro-batches. ppo_loss copies it into config.global_batch_info.

  • compute_policy_loss_bypass_mode builds the rejection mask from the current log probs and passes it to the policy loss. agg_loss(..., "token-mean") then computes masked_sum(loss, kept mask) / batch_num_tokens * dp_size.
  • Design & Code Changes

  • ppo_loss (verl/workers/utils/losses.py): in bypass mode with rollout_rs, it computes the rejection once and averages every term (policy, entropy, KL) over the kept tokens, as decoupled mode does. Under token-mean it reports the kept-token count as a LOSS_NUM_TOKENS metric, 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 of compute_policy_loss_bypass_mode unchanged.
    - 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): between forward_backward_batch and optimizer_step, it pops that metric and sums it over data-parallel ranks the way batch_num_tokens is summed. It then multiplies the gradients, the loss and its SUM-aggregated metrics by batch_num_tokens / kept tokens.

  • - This happens before clipping, so grad_norm and clipping see the corrected gradient.
    - Losses that report nothing skip this step without any extra communication.
  • scale_gradients per 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's finalize_model_grads uses for per-token loss.
  • Megatron _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 per train_batch. Under dynamic CP the count isn't all-reduced over data parallel, matching batch_num_tokens, because the outputs already cover the whole batch.
  • Scope and behavior:

  • In 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.

  • Behavior change: with rejection sampling, the entropy and KL terms skip rejected tokens in every loss_agg_mode, as in decoupled mode.

  • Other losses in the same backward pass (MoE router auxiliary losses, the distillation loss) are multiplied by the same factor, so their weight relative to the policy loss stays what it was before this PR.

  • Unchanged:

  • - the seq-mean modes, which divide by global_batch_size (the same in both modes), and token-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 runner cpu_unit_tests.yml uses:

    uv run --frozen --all-packages --extra cpu pytest tests/workers/test_bypass_rejection_normalization_on_cpu.py tests/workers/test_fsdp_gradient_accumulation_sync_on_cpu.py
    # 15 passed. With the source changes reverted, the two regression cases fail at half the
    # expected gradient (0.0225 vs 0.045 and 0.09 vs 0.18), and the engine tests lack the new methods.
    uv run --frozen --all-packages --extra cpu pytest -o python_files='*_on_cpu.py' tests/trainer tests/workers tests/utils/test_config_router_replay_on_cpu.py
    # 703 passed, 40 skipped, 1 failed: tests/workers/config/test_model_config_on_cpu.py needs
    # ~/models/Qwen/Qwen2.5-0.5B, which this machine doesn't have; it fails the same way on main.
    uv run --frozen --all-packages --extra cpu pytest tests/trainer/ppo/test_rollout_corr.py tests/trainer/ppo/test_rollout_corr_integration.py
    # 30 passed
    pre-commit run --files <changed files>
    # all 14 hooks passed (ruff, ruff-format, mypy, license, test structure, ...)
    python3 tests/special_sanity/type_coverage_check.py; python3 tests/special_sanity/check_api_docs.py verl
    # both pass
    

    New tests:

  • test_bypass_rejection_divides_by_kept_tokens_of_all_micro_batches (1+7 and 0+8 kept tokens, with entropy and KL): runs ppo_loss through BaseEngine.train_batch over 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 in seq-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_gradients on real FSDP1 and FSDP2 shards equals backpropagating the scaled loss.
  • Also checked during development (not committed):

  • Two data-parallel ranks with unequal retention, including a fully rejected micro-batch, match the single-process token-mean.

  • Each of these mutations makes a test fail: removing the engine rescale, the entropy/KL mask change, the loss rescale, the data-parallel sum, the pipeline broadcast, the dynamic-CP exception, FSDP's scaling, or the token-mean condition.
  • 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 the token-mean denominator match the mask passed to agg_loss.

  • gh pr list --repo verl-project/verl --state open --search "4852 in:body": only this PR.

  • Open PRs found by keyword searches (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-mean normalization.
  • #5993 and #6049 (closed) reference the issue but fix Megatron's context-parallel batch_num_tokens aggregation, 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

    Diff: 453 lines (+407 / -46) across 11 files Reviewer: LingYi-Liang Review duration: 81407m
    All Vouch review confidence checks passed
    Residual risk 0.11 = Change Risk (0.84) × (1 − Review Confidence (0.86)). Review depth and reviewer attention state are adequate.
    Model 1 · Change Risk (XGBoost)
    Score: 0.84 · 453 lines diff across 11 files
    0.84
    Model 2 · Review Depth (DistilBERT)
    Depth Score: 0.87 · 2 substantive comment(s)
    0.87
    Model 3 · Review Timing & Attention
    Session adequacy: 100% · Reviewer familiarity: 35%
    86%
    Bedrock Claude 3 · Risk Narration
    (disconnected)
    Groq
    Groq Risk Narration
    AWS Bedrock is currently disconnected. Generate high-confidence PR triage narration on-demand using Groq.
    Model 1 · Change Risk Attribution
    SHAP Weights
    Diff Size diff_size
    0.366
    Sensitive Paths sensitive_paths
    0.084
    Real PR Conversation Timeline
    4 items
    CLAassistant CLAassistant commented on Oct 09, 2026 20:19 UTC
    Contributor
    LingYi-Liang LingYi-Liang commented on Oct 11, 2026 08:26 UTC
    Reviewer

    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.

    Alexander230 Alexander230 commented on Oct 11, 2026 13:32 UTC
    Author

    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.

    Reviewers
    Assignees
    Alexander230 Alexander230
    Labels
    risk: low confidence: 86.4% reviewed sensitive_module
    Vouch Risk Breakdown
    AI-powered review risk analysis
    Change Risk
    Change Risk · Model 1 (XGBoost)
    Predicted defect probability (0.00–1.00) based on diff churn, modified sensitive files, and author risk history.
    Score: 84.4% (HIGH) · Higher = larger blast radius
    84.4%
    Review Confidence
    Review Confidence · Models 2 & 3
    Scrutiny score (0.00–1.00) combining DistilBERT semantic review depth with reviewer familiarity and session dwell time.
    Score: 86.4% · Lower = rushed or shallow review
    86.4%
    Residual Risk
    Residual Risk · Core Equation
    Residual = Change × (1 − Confidence)
    Unmitigated risk surviving review. ≥ 0.65 triggers an automated re-queue to protect production.
    Score: 11.5% · Safe to merge
    11.5%