Repository navigation
Conversation
🔗 Helpful Links🧪 See artifacts and rendered test results at hud.pytorch.org/pr/184046
Note: Links to docs will display an error until the docs builds have been completed. ❗ 1 Active SEVsThere are 1 currently active SEVs. If your PR is affected, please view them below: ✅ No FailuresAs of commit 10c8a69 with merge base 1a1fccc ( This comment was automatically generated by Dr. CI and updates every 15 minutes. |
|
@claude review these changes |
|
Claude finished @jansel's task in 1m 40s —— View job Reviewing PR #184046: Fix scaled softmax nonfinite semantics
SummaryThis PR fixes a correctness bug where the scaled softmax pattern matcher in Inductor transforms ReviewCorrectness: Looks good. The approach is sound — check The key insight — that the numerical instability the pattern was designed to fix only matters for finite values, and for nonfinite values NaN is the correct answer — is well-motivated. Performance consideration: The fix unconditionally computes both paths (
If perf regresses on benchmarks, a possible future optimization would be to elide the guard entirely when static analysis can prove the scale factor won't cause overflow (e.g., small constant scales). But that's out of scope for a correctness fix. Tests: Good coverage. The tests cover mul, div, duplicated-user, and the raw Minor nit (non-blocking): In Overall: LGTM. The fix is minimal, well-scoped, and correctly preserves eager semantics for edge-case inputs without breaking the stability optimization for the common case. |
frgossen
left a comment
There was a problem hiding this comment.
Approving with comment.
|
@pytorchbot merge |
Merge startedYour change will be merged once all checks pass (ETA 0-4 Hours). Learn more about merging in the wiki. Questions? Feedback? Please reach out to the PyTorch DevX Team |
Preserve the original scaled subtraction for nonfinite scaled-softmax inputs so Inductor does not turn eager NaNs into finite softmax results. Fixes pytorch#161150 Generated by my agent Pull Request resolved: pytorch#184046 Approved by: https://github.com/Skylion007, https://github.com/frgossen
Preserve the original scaled subtraction for nonfinite scaled-softmax inputs so Inductor does not turn eager NaNs into finite softmax results. Fixes pytorch#161150 Generated by my agent Pull Request resolved: pytorch#184046 Approved by: https://github.com/Skylion007, https://github.com/frgossen
|
@jansel could you please take a look at the proposed change in the PR’s Files changed? I’m considering skipping the non-finite check for scales in [tiny, 1] when the input and computation dtypes match. Does this seem reasonable? |
<!--
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]>
Stack from ghstack (oldest at bottom):
Preserve the original scaled subtraction for nonfinite scaled-softmax inputs so Inductor does not turn eager NaNs into finite softmax results.
Fixes #161150
Generated by my agent
cc @voznesenskym @penguinwu @EikanWang @jgong5 @Guobing-Chen @XiaobingSuper @zhuhaozhe @blzheng @wenzhe-nrv @jiayisunx @ipiszy @kadeng @muchulee8 @amjames @chauhang @aakhundov @coconutruben @jataylo @mlazos