Skip to content

[rl] Divide by the sampling temperature inside the loss region - #5921

Merged
felipemello1 merged 6 commits into
pytorch:mainfrom
felipemello1:rl-temperature-in-loss-region
Nov 7, 2026
Merged

felipemello1 merged 6 commits into
pytorch:mainfrom
felipemello1:rl-temperature-in-loss-region

Conversation

@felipemello1

Copy link
Copy Markdown
Contributor

Summary (human-written)

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.

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)
# 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

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).

Felipe Mello added 3 commits November 6, 2026 18:23
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.
@felipemello1

Copy link
Copy Markdown
Contributor Author

Reply from claude: @claude review

@pytorch-bot pytorch-bot Bot added the ciflow/rl label Nov 7, 2026
@meta-cla meta-cla Bot added the CLA Signed This label is managed by the Meta Open Source bot. label Nov 7, 2026
@claude

claude Bot commented Nov 7, 2026 •

Copy link
Copy Markdown
Contributor

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 torchtitan/components/loss.py.

@claude claude Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

  1. PR description -- the "Summary (human-written)" section is empty. The author needs to fill it in before merge.
  2. 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; use linspace (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. temperature is 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 the vocab_parallel_group branch, so before the spmd.redistribute all-gather. Elementwise division by a broadcast tensor and by an expand_as view give the same values in eager. dtype promotion is unchanged: bf16 or fp32 pred divided by fp32 temperature gives fp32, and the later .float() does nothing.
  • SPMD: temperature has the same type as labels (I@TP, S(0)@DP), and dividing S(-1) by it locally stays S(-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 keep temperature= on the compute_logprobs call.

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.

Comment on lines +528 to +529
# 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).

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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).

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment on lines +875 to +877
global_temperature = torch.full(
(T,), temperature_value, device=self.device_type
)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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:

Suggested change
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.)

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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).

@felipemello1
felipemello1 marked this pull request as ready for review November 7, 2026 04:42
@pytorch-bot pytorch-bot Bot added the ciflow/fake-pg Run 1-GPU Fake PG integration tests label Nov 7, 2026
@github-actions
github-actions Bot requested a review from pzhan9 November 7, 2026 04:43
@felipemello1

Copy link
Copy Markdown
Contributor Author

Reply from claude: @claude review

@claude

claude Bot commented Nov 7, 2026 •

Copy link
Copy Markdown
Contributor

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 torchtitan/components/loss.py.

@claude claude Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 with label_placements and 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)

  1. PR description -- the "Summary (human-written)" section is still the empty template. The author fills it in; agents don't.
  2. 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= is rl/trainer/losses/dapo.py:101. rl/generator/vllm/batch_invariance.py:56 still calls without it, which is correct because vLLM applies temperature itself. The test callers in tests/rl/unit_tests/{cpu,gpu} and tests/unit_tests/cpu/components/test_loss.py keep working because the argument defaults to None.
  • dtype: bf16 or fp32 pred divided by fp32 temperature gives fp32, the same as main. vLLM's logits.to(float32).div_(temperature) gives the same values. test_dapo_loss_matches_vllm_tempered_logprobs_bitwise (unchanged file) now runs through the new path via DAPOLoss.
  • SPMD: temperature has the same type as labels (I@TP, S(0)@DP). Dividing an S(-1) shard by it locally stays S(-1).
  • Overlap: #5474 rewrites the same DAPO call site. Whichever PR lands second must keep temperature= on the compute_logprobs call.

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,

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm not sure: should this be renamed to preds? asking because naming is no longer 100% consistent

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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, ...), Megatron vocab_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).

@felipemello1
felipemello1 merged commit 201e79f into pytorch:main Nov 7, 2026
@felipemello1
felipemello1 deleted the rl-temperature-in-loss-region branch November 7, 2026 05:55
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]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ciflow/fake-pg Run 1-GPU Fake PG integration tests ciflow/rl CLA Signed This label is managed by the Meta Open Source bot.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants