Repository navigation
[rl] One scoring step and one metrics step for every RL loss; add DPPOLoss - #5474
Closed
felipemello1 wants to merge 1 commit into
Closed
felipemello1 wants to merge 1 commit into
felipemello1 wants to merge 1 commit into
Conversation
…OLoss score_tokens runs DAPO's first steps (temperature, logprobs, non-finite mask, ratio) and policy_metrics logs the metrics every loss logs. DAPOLoss and GRPOLoss keep the same ops in the same order (bitwise equal to main). DPPOLoss is built on the two functions. Dr. GRPO is a TODO.
This was referenced Nov 3, 2026
felipemello1
added a commit
that referenced
this pull request
Nov 7, 2026
<!--
Reviewers need to be convinced, not just informed. Delete sections you
don't need.
Agents: follow .claude/skills/pr-description/SKILL.md. Never fill in the
Summary.
-->
## Summary (human-written)
<!-- Write this yourself, not with an AI tool. 2-5 sentences: the
problem, why
this approach, and what you checked yourself. -->
## Agent details
**TLDR:** `DAPOLoss` divided the logits by the sampling temperature in
eager, outside the compiled `loss` region. `compute_logprobs` now takes
`temperature` and divides inside the region, so the divide rides along
in the loss kernels. Qwen3-4B output stage, 10240 tokens, at the
recipe's TP=2: 28.1 -> 22.2 ms per microbatch (-21%, fastest of 15
iterations, slowest rank), same peak memory. About 0.7% of the trainer's
forward/backward.
```text
main: lm_head -> pred / temperature (eager: one fp32 pass over [T, V] forward, one backward) -> loss region
this PR: lm_head -> loss region (divides while it reads pred)
```
```python
# before (DAPOLoss)
logits = pred / temperature.unsqueeze(-1)
trainer_logprobs, token_entropy = compute_logprobs(logits, labels, ...)
# after
trainer_logprobs, token_entropy = compute_logprobs(pred, labels, ..., temperature=temperature)
```
**Problem**
1. RL losses score tokens at the sampling temperature: `DAPOLoss` (and
`GRPOLoss`, which inherits it) divides the fp32 `[T, V]` logits by a
per-token `temperature[T]`.
2. The divide ran in eager, right before `compute_logprobs`, which is
the compiled `loss` region.
3. So every loss chunk paid two extra fp32 passes over `[T, V]`: the
divide and its backward.
4. Cost at TP=1, 8 chunks of [1280, 151936]: 520 + 621 us per chunk, 9.1
ms of the 39.4 ms output stage (23%).
**Solution**
1. `compute_logprobs(..., temperature=None)` divides first when given a
temperature, inside the region. `DAPOLoss` passes `temperature=`.
2. The divisor is the expanded view
`temperature.unsqueeze(-1).expand_as(logits)`. With a `[T, 1]` divisor,
Inductor's scaled-softmax rewrite fires, and its isfinite guard
(`pytorch/pytorch#184046`) writes two fp32 `[T, V]` buffers. A TODO at
the divide tracks it.
3. Unchanged: batch-invariant mode can't enable the `loss` region, so it
runs the same eager divide as main, bitwise. The generator's
batch-invariant patch calls `compute_logprobs` without a temperature, as
before.
**Results**
```text
Numerics, batch-invariant mode: bitwise identical to main (logprobs, entropy, logits grad).
Numerics, default mode (loss region compiled): not bitwise. The divide now runs inside the compiled kernel, with
Triton's division. Error vs fp64 stays at the same level: logprobs equal, entropy and grad within 1.4x of main.
One [1280, 151936] fp32 chunk, T = 0.8, GB300, rel L2 vs fp64:
logprobs entropy logits grad
main 3.5e-8 7.0e-7 1.4e-7
this PR 3.5e-8 9.4e-7 1.7e-7
Qwen3-4B output stage: final norm + fp32 LM head + DAPO loss, ChunkedLossWrapper with 8 chunks, fwd+bwd, GB300, ms.
Trainer only: the generator never runs this loss.
layout tokens main this PR delta
TP=2, vocab-parallel loss (the recipe's) 10240 28.1 22.2 -21% (fastest of 15 iterations, slowest rank)
no CUDA graphs, loss region compiled 32.3 22.7 -30% (one run's median; main ran first, its arm was noisier)
TP=1, CUDA-graph replay 10240 39.4 30.7 -22%
16384 60.1 47.2 -22%
32768 113.3 88.1 -22%
65536 224.4 172.6 -23%
Peak memory: equal in every row. Ideal for the TP=1 stage (bytes at 7.1 TB/s, GEMM FLOPs at 1.9 PFLOP/s): 18.1 ms.
One TP=1 chunk, fwd+bwd of compute_logprobs with entropy, us
main: eager divide, then the region 1760
divide in the region, [T, 1] divisor (Inductor's rewrite fires) 1529
same, with the region's pattern matcher off 1446 (also loses the rewrite that keeps the loss backward from zero-filling a [T, V] buffer)
divide in the region, expanded divisor + IEEE division (div_rn) 1023
divide in the region, expanded divisor (this PR) 806
```
End to end: a 50-step Qwen3-4B DAPO run on this main (2 GB300, trainer
TP=2) spent 0.87 s per 10240-token microbatch in forward/backward. The
TP=2 row saves 5.9 ms per microbatch (fastest to fastest), so ~0.7% of
the trainer. TP=1's removed divide kernels cost 9.2 ms; half the vocab
per rank predicts ~4.6 ms at TP=2, and 5.9 ms was measured. Smaller
models with the same vocab gain more.
You may ask:
- Why not multiply by `1 / temperature`? It rounds differently from a
divide, so batch-invariant bits would change vs main.
- Why not turn the pattern matcher off, or use IEEE division? Both are
slower (table). Default mode isn't bitwise anyway.
NOTE:
- The TODO cites the PyTorch PR that added the guard. An issue for the
tensor-divisor case is drafted, not filed yet.
- Overlap: the open draft `#5474` moves the same eager divide into
`losses/common.py`. Whichever lands second must pass `temperature=` to
`compute_logprobs`, or the eager pass comes back with no failing test.
- The TP=2 row runs each rank's vocab shard of the LM head and the
vocab-parallel loss on 2 GB300. The all-reduce of the hidden-state grad
is not modeled (the same in both arms).
- Not run: a full RL run.
Follow up: fuse the fp32 -> bf16 split of the logits grad
(`fp32_to_bf16_split`, 342 us per chunk) into the loss backward. It
needs one compiled graph across `HiMidLoLinear`'s backward, whose
`mm(out_dtype=)` and in-place `addmm(out=weight.grad)` Inductor can't
lower today.
**Test plan**
- `pytest tests/unit_tests/cpu/components/test_loss.py -k
policy_stats_parity`: the new temperature case (TP4 and DP2 x TP2,
strict SPMD type checks) fails on main (`unexpected keyword argument
'temperature'`).
- `pytest tests/rl/unit_tests/cpu/test_losses.py`:
`test_dapo_loss_matches_vllm_tempered_logprobs_bitwise` now runs through
`compute_logprobs(temperature=)` and checks bitwise logprobs vs dividing
first (catches a reciprocal multiply).
- `pytest tests/unit_tests/cpu/components/test_loss.py
tests/rl/unit_tests/cpu/test_losses.py
tests/rl/unit_tests/cpu/test_batch_invariance.py`: all pass but
`test_lora_head_only_matches_cross_entropy`, which fails on main too (a
flex CPU lowering error in this torch nightly).
- `pytest tests/rl/unit_tests/cpu`: same as main (379 pass; the same 9
failures and 8 collection errors, all from vLLM failing to import in
this environment).
---------
Co-authored-by: Felipe Mello <[email protected]>
felipemello1
added a commit
that referenced
this pull request
Nov 9, 2026
<!--
Reviewers need to be convinced, not just informed. Delete sections you
don't need.
Agents: follow .claude/skills/pr-description/SKILL.md. Never fill in the
Summary.
-->
## Summary (human-written)
<!-- Write this yourself, not with an AI tool. 2-5 sentences: the
problem, why
this approach, and what you checked yourself. -->
## Agent details
**TLDR:** One decorator puts all of `DAPOLoss.__call__` in the `loss`
region. Before, only `compute_logprobs` was compiled, and the clip,
surrogate and 7 metrics after it ran as ~80 small eager kernels per
chunk. Qwen3-4B output stage, 10240 tokens, at the recipe's TP=2 without
CUDA graphs: 22.2 -> 17.1 ms per microbatch (-23%).
```text
main: compute_logprobs (compiled) -> mask, ratio, clip, surrogate, normalize, 7 metrics (eager, + backward)
this PR: DAPOLoss.__call__ (one compiled graph; compute_logprobs is inlined)
kernels per output stage (8 chunks, fwd+bwd): 822 -> 158
```
**Problem**
1. Only `compute_logprobs` is in the `loss` region.
2. The rest of `DAPOLoss.__call__` is `[T]` work: one tiny kernel per
op, forward and backward, in each of the 8 chunks.
3. Cost: ~6 ms of the 23 ms TP=2 output stage.
**Solution**
1. `@local_compile("loss", batch_invariant=False)` on
`DAPOLoss.__call__`. `GRPOLoss` inherits it.
2. `loss` now turns on 5 functions: `cross_entropy_loss`,
`cross_entropy_and_logsumexp`, `mse_loss`, `compute_logprobs` and
`DAPOLoss.__call__`. DAPO's graph inlines `compute_logprobs`, so the
DAPO loss compiles one graph, not two.
3. Unchanged: batch-invariant mode can't enable the `loss` region, so it
runs main's eager code.
**Results**
```text
Numerics: not bitwise vs eager (Inductor fuses the [T] sums in another order). 8 DAPO/GRPO clip settings in one
process, the trainer's inputs (1-D int64 token count, NaN generator logprobs), GB300: all match eager; loss and
7 metrics max abs diff 9.5e-7, logits grad rel L2 <= 2.9e-7.
Qwen3-4B output stage: final norm + fp32 LM head + DAPO loss, 8 chunks, fwd+bwd, GB300, ms.
Same inputs as the trainer: DAPO-Math's packed loss mask (86% loss tokens), 1-D int64 count, NaN logprobs.
base (#5921) free function for the tail this PR
TP=2, no CUDA graphs (the recipe's)
fastest of 15 iterations, slowest rank 22.2 17.5 17.1 -23%
median 23.1 17.6 17.2 -26%
TP=1, CUDA graphs (GPU time only) 30.7 29.6 29.5 -3.9%
kernels / compiled graphs 822 / 2 166 / 3 158 / 2
Peak memory: equal. All arms in one exclusive lock; base ran first and last, and the table shows the last run
(the first was noisy: median 34.0, fastest 23.4).
```
End to end: the trainer spends 0.87 s of forward/backward per
10240-token microbatch (Qwen3-4B DAPO, 2 GB300, TP=2). GPU time saved:
1.2 ms (0.14%). Without CUDA graphs: 5-6 ms (0.6-0.7%), mostly CPU
launch time, which the trainer hides if its CPU runs ahead of the GPU.
You may ask:
- Why not a free function for the code after `compute_logprobs`?
Measured (table): it ties at TP=1 and is 0.4 ms slower at TP=2. It also
moves ~60 lines.
- Several clip settings in one process? New clip pairs add graphs until
the clip floats turn dynamic, and `GRPOLoss` adds one: 4 graphs for 8
instances, all correct on today's torch. A run builds one loss: 1 graph.
NOTE:
- Overlap: the open draft `#5474` rewrites `DAPOLoss.__call__` and adds
`DPPOLoss`. The decorator moves with `__call__`, and each loss with its
own `__call__` needs one decorator line.
- Not run: a full RL run.
**Test plan**
- No new test. CI's RL Integration Tests already run the compiled `loss`
region on GPU: `rl_grpo_fsdp2_gen_tp2_compile` trains GRPO with Qwen3's
default regions, which include `loss`.
- Numerics vs eager: the GPU probe in Results.
- `pytest tests/rl/unit_tests/cpu/test_losses.py`: 2 passed.
---------
Co-authored-by: Felipe Mello <[email protected]>
Contributor
|
Closing in favor of #6376, coordinated with @felipemello1: DPPOLoss is there as a PolicyGradientLoss subclass alongside DAPO/GRPO, CISPO and IcePop, with Felipe as co-author. |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
TLDR: The RL losses now share one function that scores the sampled tokens and one that logs the metrics every loss logs, so a loss file holds only its own per-token loss.
DAPOLossandGRPOLossrun the same ops in the same order (bitwise unchanged vs main), andDPPOLossis the second loss built on the two functions.Problem
DAPOLoss.__call__does everything inline: temperature, trainer logprobs, the non-finite mask, the ratio, the PPO clip and 7 metrics (trainer/losses/dapo.py:73-167)._normalizeand_MAX_LOG_RATIO.TrainingMicrobatch.loss_kwargs).is_policy_age_0, and DPPO, IPO and score centering would fail withTypeErroronce those PRs land.Solution
losses/common.pyaddsscore_tokens(logits, labels, **loss_inputs). It runs DAPO's first steps unchanged: divide by the temperature, trainer logprobs and entropy, drop tokens with a non-finite generator logprob, ratio. It returns them as aScoredTokens.policy_metrics(tokens, own_sums, ...)adds the 5 metrics every loss logs and divides every sum byglobal_loss_token_counts.**loss_inputsand passes them toscore_tokens. A new input is one keyword argument with a default there, and no loss signature changes. An unknown key still raises.DAPOLosskeeps its config, ops and op order.GRPOLossis untouched, apart from a TODO for Dr. GRPO.DPPOLoss(https://arxiv.org/abs/2602.04879) drops a token oncesign(A) * (p - p_gen) > 0.2, and trains the others with-A * detach(min(p / p_gen, 5)) * log p. It is the standalone DPPO PR's loss, already reviewed twice there, rebuilt on the two functions: 120 lines instead of 157.Results
You may ask:
**loss_inputsinstead of named arguments on each loss? Named arguments on every loss are what let one loss's new input crash the others.score_tokenskeeps the named, typed list, in one place.__call__and a per-loss hook? Each loss's__call__shows its whole computation in ~25 lines; a hook would hide half of it in the base class.NOTE:
DPPOLoss'sloss/meanis the REINFORCE surrogate-A * w * log p, so it can't be compared withDAPOLoss's on the same dashboard. No recipe usesDPPOLossyet.Test plan
DAPOLoss/GRPOLossvs this PR's on the same saved inputs. CPU and CUDA, T=64 and T=4096 x V=151936, fp32 and bf16 logits, NaN and ±inf generator logprobs, clips (0.2, 0.28) and GRPO's 0.2.torch.equalon the loss, the logits grad and every metric: 16/16 equal.tests/assets/losses/rl_grpo_cuda.txt) unchanged, since GRPO is bitwise unchanged.test_policy_loss_matches_vllm_tempered_logprobs_bitwise[dapo|dppo],test_policy_loss_through_chunked_loss_wrapper_matches_unchunked[dapo|dppo], and the 5 DPPO rule tests from the standalone DPPO PR.