Skip to content

Fix scaled softmax nonfinite semantics - #184046

Closed
jansel wants to merge 1 commit into
gh/jansel/716/basefrom
gh/jansel/716/head
Closed

jansel wants to merge 1 commit into
gh/jansel/716/basefrom
gh/jansel/716/head

Conversation

@jansel

@jansel jansel commented May 16, 2026 •

Copy link
Copy Markdown
Contributor

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

[ghstack-poisoned]
@pytorch-bot

pytorch-bot Bot commented May 16, 2026 •

Copy link
Copy Markdown

🔗 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 SEVs

There are 1 currently active SEVs. If your PR is affected, please view them below:

✅ No Failures

As of commit 10c8a69 with merge base 1a1fccc (image):
💚 Looks good so far! There are no failures yet. 💚

This comment was automatically generated by Dr. CI and updates every 15 minutes.

@jansel

jansel commented May 16, 2026

Copy link
Copy Markdown
Contributor Author

@claude review these changes

@claude

claude Bot commented May 16, 2026 •

Copy link
Copy Markdown

Claude finished @jansel's task in 1m 40s —— View job


Reviewing PR #184046: Fix scaled softmax nonfinite semantics

  • Gather context and read the diff
  • Review torch/_inductor/fx_passes/joint_graph.py changes
  • Review test/inductor/test_pattern_matcher.py changes
  • Post review feedback

Summary

This PR fixes a correctness bug where the scaled softmax pattern matcher in Inductor transforms scale(x) - amax(scale(x)) into scale(x - amax(x)). While mathematically equivalent for finite values, when scale(x) overflows to infinity, the original produces inf - inf = NaN but the optimized form produces finite results (since subtraction happens before scaling). The fix adds a runtime torch.where that falls back to the original expression when nonfinite values are detected.

Review

Correctness: Looks good. The approach is sound — check torch.all(torch.isfinite(scaled)) along the reduction dim, use the stable form when everything is finite, and fall back to the original scaled - amax(scaled) otherwise. The keepdim=True on finite_scaled correctly broadcasts for the torch.where regardless of the pattern's actual keepdim value.

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 (original and stable) plus isfinite + all + where. In the common case (all finite), the original path and the checks are pure overhead. For a hot softmax path this could be measurable. A few thoughts:

  1. Could Inductor DCE the original computation when torch.where selects stable? No — the condition is data-dependent, so both branches are always computed. This is the expected tradeoff for a correctness fix.
  2. An alternative design that avoids the extra amax would be to check finiteness of scaled and conditionally bypass the optimization entirely (i.e., at the graph level use torch.where(finite, stable, scaled - amax(scaled))). But that's exactly what this does, so there's no shortcut.

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 scaled - amax(scaled) sub-pattern. They verify both that the pattern matcher fires (assertGreaterEqual on the counter) and that the output matches eager semantics (NaN where expected).

Minor nit (non-blocking): In test_scaled_softmax_nonfinite_matches_eager, the check helper asserts torch.isnan(expected[-1]).all() and torch.isnan(actual[-1]).all() — this works because the test inputs are crafted so the entire softmax output is NaN. If you later add test cases where only part of the output is NaN, this assertion would need adjustment. Not a problem today.

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.


@jansel
jansel marked this pull request as ready for review May 17, 2026 04:10
@jansel
jansel requested a review from frgossen May 17, 2026 04:10

@frgossen frgossen 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.

Approving with comment.

@jansel

jansel commented May 21, 2026

Copy link
Copy Markdown
Contributor Author

@pytorchbot merge

@pytorch-bot pytorch-bot Bot added the ciflow/trunk Trigger trunk jobs on your pull request label May 21, 2026
@pytorchmergebot

Copy link
Copy Markdown
Collaborator

Merge started

Your 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

Advanced Debugging
Check the merge workflow status
here

@github-actions
github-actions Bot deleted the gh/jansel/716/head branch June 21, 2026 02:28
gplutop7 pushed a commit to gplutop7/pytorch that referenced this pull request Jul 15, 2026
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
aws-kingrj pushed a commit to amazon-contributing/upstream-to-pytorch that referenced this pull request Jul 29, 2026
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
@msnliu

msnliu commented Oct 15, 2026

Copy link
Copy Markdown
Contributor

@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?

felipemello1 added a commit to pytorch/torchtitan 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]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ciflow/inductor ciflow/torchtitan Run TorchTitan integration tests ciflow/trunk Trigger trunk jobs on your pull request Merged module: inductor release notes: inductor

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants