Repository navigation
[rl] Divide by the sampling temperature inside the loss region - #5921
Conversation
DAPOLoss divided the fp32 logits by the per-token temperature in eager, outside the compiled loss region: two extra fp32 passes over [T, V] (forward and backward). compute_logprobs now takes temperature and divides first, so the divide fuses into the loss kernels. The divisor is expanded to [T, V] so Inductor's scaled-softmax rewrite does not fire; its isfinite guard made the loss 1.9x slower. Eager divides the same values, so batch-invariant runs stay bitwise.
… duplicate test - The "divide, never multiply by the reciprocal" rule moves next to the divide in compute_logprobs; DAPOLoss keeps only "score tokens under the distribution vLLM sampled from". - expand_as gets its numbers and a TODO naming Inductor's isfinite guard. - One-line temperature doc in compute_logprobs. - Drop test_compute_logprobs_temperature_matches_dividing_first: test_losses.py's DAPO-vs-divide-first bitwise test already covers it. The TP parity case stays.
…ned TODO - Docstring: "logprobs and entropy use softmax(logits / temperature)". - The divide rule says what must match: logprobs bitwise equal to vLLM's, which divides. - The timing names which number belongs to which divisor. - The TODO states its condition on its own, so it reads before an issue exists.
|
Reply from claude: @claude review |
|
Claude finished @felipemello1's task in 1m 30s —— View job Approve, with three small items to fix before merging -- see review. A maintainer still needs to review, since this touches |
There was a problem hiding this comment.
Verdict: Approve -- please address the items below before merging. The divide moves into the compiled loss region at the right layer. Batch-invariant mode keeps the same op order as before (divide the local vocab shard, then all-gather), and the only numerics change is the documented, small non-bitwise difference in default mode. This touches core torchtitan/components/loss.py, so a maintainer still needs to review.
What this PR does. DAPOLoss (and GRPOLoss, which inherits it) used to divide the fp32 [T, V] logits by the per-token temperature in eager code, just before calling compute_logprobs. compute_logprobs now takes temperature= and does that divide as its first step, inside the @local_compile("loss", batch_invariant=False) region. The divisor is expanded to the full logits shape, which stops Inductor from applying a slower div-softmax rewrite.
Example.
# main: eager pass over [T, V] fwd + bwd, then the compiled region
logits = pred / temperature.unsqueeze(-1)
lp, ent = compute_logprobs(logits, labels, vocab_parallel_group=tp, ...)
# this PR: one call; the divide fuses into the region's kernels
lp, ent = compute_logprobs(pred, labels, vocab_parallel_group=tp, ..., temperature=temperature)
# Batch-invariant mode (region not compiled): same eager divide on the local shard,
# then the same S(-1) -> I all-gather, so the result is bitwise equal to main.
# Default mode: Triton division inside the kernel, not bitwise; error vs fp64 is about the same (PR table).Must fix
- PR description -- the "Summary (human-written)" section is empty. The author needs to fill it in before merge.
torchtitan/components/loss.py:528-- the TODO links the PyTorch PR, not an upstream issue (see inline comment).
Should consider
tests/unit_tests/cpu/components/test_loss.py:875-- a single temperature for every token can't catch per-token broadcasting or shard-alignment bugs; uselinspace(see inline comment).
Details
- Necessity: the cost is measured both at the kernel level and end to end (about 0.7% of trainer fwd/bwd for Qwen3-4B at TP=2, more for smaller models with the same vocab). There is no new knob.
temperatureis an optional argument whose only caller is the RL loss; the generator's batch-invariant patch (rl/generator/vllm/batch_invariance.py:56) still calls without it, which is correct because vLLM applies temperature itself. - Batch-invariant bitwise claim: on main,
pred / temperature[:, None]ran on the local vocab shard before the call. Now the same divide runs on the local shard before thevocab_parallel_groupbranch, so before thespmd.redistributeall-gather. Elementwise division by a broadcast tensor and by anexpand_asview give the same values in eager. dtype promotion is unchanged: bf16 or fp32preddivided by fp32temperaturegives fp32, and the later.float()does nothing. - SPMD:
temperaturehas the same type aslabels(I@TP,S(0)@DP), and dividingS(-1)by it locally staysS(-1). The extended parity test checks this in strict mode on TP4 and DP2 x TP2. - Golden numerics: no RL golden-loss files exist under
tests/rl, so the default-mode numerics change has nothing to regenerate. - Overlap: #5474 (open) rewrites the same call site in
rl/trainer/losses/. As the description says, whichever PR lands second must keeptemperature=on thecompute_logprobscall.
Not verified: the GPU timings and fp64 error table (no GPU here). The CPU parity test runs eagerly and never compiles the region, so the expand_as perf path is only covered by the author's benchmark.
| # TODO: drop expand_as once Inductor's div-softmax rewrite stops writing its isfinite | ||
| # buffers for a broadcast tensor divisor (guard added in pytorch/pytorch#184046). |
There was a problem hiding this comment.
This TODO points at the PyTorch PR that added the isfinite guard, not at an issue that tracks the regression for broadcast tensor divisors. The repo rule asks for an upstream issue link, so that whoever cleans this up later can tell when expand_as is safe to remove. Once the drafted issue is filed, link it here, e.g. (pytorch/pytorch#NNNNN; guard added in #184046).
There was a problem hiding this comment.
Reply from claude: Agreed. Felipe owns this item: the PyTorch issue for the broadcast-tensor-divisor case is drafted and waits for him to file it. After that, this TODO links the issue and keeps #184046 as the PR that added the guard. The TODO already states its removal condition on its own, so it reads correctly until then.
| global_temperature = torch.full( | ||
| (T,), temperature_value, device=self.device_type | ||
| ) |
There was a problem hiding this comment.
Every token gets the same temperature (0.7), so the new case can't catch a per-token mistake. If the divide used the wrong axis, or the DP2 x TP2 run got a temperature shard that didn't line up with its token shard, every row would still be divided by 0.7 and the test would pass. Using a different temperature per token costs nothing and closes that gap:
| global_temperature = torch.full( | |
| (T,), temperature_value, device=self.device_type | |
| ) | |
| global_temperature = torch.linspace( | |
| 0.5, 1.5, T, device=self.device_type | |
| ) |
(temperature_value then only acts as an on/off switch, so it could become a bool.)
There was a problem hiding this comment.
Reply from claude: Done in 60726b9. The temperature case now uses a per-token torch.linspace(0.5, 1.5, T), so a wrong axis or a temperature shard that doesn't line up with its token shard fails the TP4 and DP2 x TP2 subtests. The 4th case field is now a bool (use_temperature).
|
Reply from claude: @claude review |
|
Claude finished @felipemello1's task in 49s —— View job Approve, but two small items from the last review are still open: the empty human-written summary and the TODO's upstream issue link. The new commit adds no new problems, and the per-token temperature test is resolved. See review. A maintainer still needs to review, since this touches |
There was a problem hiding this comment.
Verdict: Approve -- please address the items below before merging. This re-review covers the new commit 60726b9. It adds no new problems and fixes the test-coverage gap. Two small must-fix items from the last review are still open. This touches core torchtitan/components/loss.py, so a maintainer still needs to review.
What this PR does. compute_logprobs now takes an optional temperature[T] and divides the logits by it as its first step, inside the compiled loss region. DAPOLoss (and GRPOLoss, which inherits it) passes temperature= instead of dividing in eager first. The divisor is temperature.unsqueeze(-1).expand_as(logits), so Inductor skips a slower div-softmax rewrite.
Example.
# main
logits = pred / temperature.unsqueeze(-1) # eager fp32 [T, V] pass, fwd + bwd
lp, ent = compute_logprobs(logits, labels, ...)
# this PR
lp, ent = compute_logprobs(pred, labels, ..., temperature=temperature)
# Batch-invariant mode: same eager divide on the local vocab shard, before the
# S(-1) -> I all-gather, so bitwise equal to main. Default mode: the divide fuses
# into the region's kernels; not bitwise, error vs fp64 about the same (PR table).Since the last review
- Resolved: the parity test now uses a per-token
torch.linspace(0.5, 1.5, T)temperature, sharded withlabel_placementsand checked under strict SPMD types. A wrong broadcast axis, or a temperature shard that doesn't line up with its token shard, now fails on both TP4 and DP2 x TP2.
Must fix (still open)
- PR description -- the "Summary (human-written)" section is still the empty template. The author fills it in; agents don't.
torchtitan/components/loss.py:528-529-- the TODO still cites the PyTorch PR that added the guard (#184046), not an upstream issue. The author replied that the issue is drafted but not filed yet. Once it's filed, link it here, e.g.(pytorch/pytorch#NNNNN; guard added in #184046). One-line edit, no re-review needed.
Details
- Callsites: the only production caller that passes
temperature=isrl/trainer/losses/dapo.py:101.rl/generator/vllm/batch_invariance.py:56still calls without it, which is correct because vLLM applies temperature itself. The test callers intests/rl/unit_tests/{cpu,gpu}andtests/unit_tests/cpu/components/test_loss.pykeep working because the argument defaults toNone. - dtype: bf16 or fp32
preddivided by fp32temperaturegives fp32, the same as main. vLLM'slogits.to(float32).div_(temperature)gives the same values.test_dapo_loss_matches_vllm_tempered_logprobs_bitwise(unchanged file) now runs through the new path viaDAPOLoss. - SPMD:
temperaturehas the same type aslabels(I@TP,S(0)@DP). Dividing anS(-1)shard by it locally staysS(-1). - Overlap: #5474 rewrites the same DAPO call site. Whichever PR lands second must keep
temperature=on thecompute_logprobscall.
Not verified: the GPU timings and the fp64 error table. The CPU tests don't compile the region, so the expand_as perf path is covered only by the author's benchmark.
|
|
||
| @local_compile("loss", batch_invariant=False) | ||
| def compute_logprobs( | ||
| logits: torch.Tensor, |
There was a problem hiding this comment.
I'm not sure: should this be renamed to preds? asking because naming is no longer 100% consistent
There was a problem hiding this comment.
Reply from claude: Kept logits, and the RL path now uses it end to end (1680ca7). ChunkedLossWrapper already calls the loss with logits, DAPOLoss.__call__ now takes logits (was pred), and compute_logprobs keeps logits. This also makes the class docstring's "logits is the current-policy output passed to compute_logprobs" true again.
Every library we checked names this tensor logits:
- verl
logprobs_from_logits(logits, labels) - prime-rl
selective_log_softmax(logits, index) - slime
calculate_log_probs_and_entropy(logits, tokens, ...) - AReaL
gather_logprobs(logits, labels, temperature) - SkyRL
logprobs_from_logits(logits, labels) - torchtune
logits_to_logprobs(logits, sequences, temperature) - NeMo-RL
from_parallel_logits_to_logprobs(vocab_parallel_logits, ...), Megatronvocab_parallel_cross_entropy(vocab_parallel_logits, ...) - vLLM
Sampler.compute_logprobs(logits)
pred stays on the generic Loss.__call__ interface, which also serves losses whose input isn't logits (MSE).
<!--
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]>
Summary (human-written)
Agent details
TLDR:
DAPOLossdivided the logits by the sampling temperature in eager, outside the compiledlossregion.compute_logprobsnow takestemperatureand 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.Problem
DAPOLoss(andGRPOLoss, which inherits it) divides the fp32[T, V]logits by a per-tokentemperature[T].compute_logprobs, which is the compiledlossregion.[T, V]: the divide and its backward.Solution
compute_logprobs(..., temperature=None)divides first when given a temperature, inside the region.DAPOLosspassestemperature=.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.lossregion, so it runs the same eager divide as main, bitwise. The generator's batch-invariant patch callscompute_logprobswithout a temperature, as before.Results
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:
1 / temperature? It rounds differently from a divide, so batch-invariant bits would change vs main.NOTE:
#5474moves the same eager divide intolosses/common.py. Whichever lands second must passtemperature=tocompute_logprobs, or the eager pass comes back with no failing test.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 acrossHiMidLoLinear's backward, whosemm(out_dtype=)and in-placeaddmm(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_bitwisenow runs throughcompute_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 buttest_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).