Skip to content

[inductor] Online softmax: select exp values with the mask instead of multiplying - #204321

Closed
eellison wants to merge 4 commits into
gh/eellison/1130/basefrom
gh/eellison/1130/head
Closed

eellison wants to merge 4 commits into
gh/eellison/1130/basefrom
gh/eellison/1130/head

Conversation

@eellison

@eellison eellison commented Nov 10, 2026 •

Copy link
Copy Markdown
Contributor

Stack from ghstack (oldest at bottom):

Change

online_softmax_reduce_scalar_combine (used by looped online-softmax reductions, e.g. log_softmax/cross-entropy over a large vocabulary) summed exp(delta) weighted by a 0/1 mask: online_softmax_reduce(rhs, tl.where(mask, 1.0, 0.0), ...), i.e. tl.sum(mask * exp(delta)). It now selects with the mask: tl.sum(tl.where(mask, exp(delta), 0.0)).

The result is bitwise the same: the mask is exactly 0 or 1, acc + 1.0 * e and fma(1.0, e, acc) both equal acc + e, and masked lanes are -inf, so exp there is finite and 0.0 * e == 0. The multiply per element goes away. With FMA contraction off (deterministic mode in the next PR, or triton.enable_fp_fusion=False) that multiply was a separate FMUL feeding each add of the in-thread sum, which made these kernels about 10% slower.

Performance (H100, 2026-11-02 nightly, better-benchmark cross-entropy kernels from HF models, two runs each)

kernel before (us) after (us)
amax_sum_sum_fb4ae0eb915f 1131 942 -17%
amax_sum_sum_52903d400fef 1127 938 -17%
amax_sum_sum_a97be2219d64 1306 1333 +2%
amax_sum_sum_81caaa5dd022 1316 1343 +2%

With the next PR in this stack (deterministic mode, contraction off), amax_sum_sum_a97be2219d64 goes from 1782 us (deterministic mode today) to 1378 us, and amax_sum_sum_fb4ae0eb915f from 2257 us to 1341 us.

Test plan

python test/inductor/test_online_softmax.py (75 tests) passes, with the default config and with TORCHINDUCTOR_ENABLE_FP_FUSION=0. Outputs of the four kernels above are bitwise equal before and after the change.

This change was authored with an AI assistant (Claude Code), with the change and tests reviewed in the session.

cc @voznesenskym @penguinwu @EikanWang @jgong5 @Guobing-Chen @XiaobingSuper @zhuhaozhe @blzheng @wenzhe-nrv @jiayisunx @ipiszy @kadeng @muchulee8 @amjames @chauhang @aakhundov @coconutruben @jataylo

[ghstack-poisoned]
@pytorch-bot

pytorch-bot Bot commented Nov 10, 2026 •

Copy link
Copy Markdown

PR Status: Approved 🚀

Please fix all CI failures and trigger merge by commenting "@pytorchbot merge".

✅ AUTOMATED REVIEW - Ready for human review:

The PR changes online_softmax_reduce_scalar_combine to keep only the unmasked
exp(delta) values with tl.where(rhs_mask, exp(delta), 0.0) instead of
multiplying by a 0/1 mask, which saves one multiply per element; the review
confirmed the result is bitwise identical. Recommendation: Approve. The only
remaining point is a non-blocking duplication issue.

Findings (1):

[minor] torch/_inductor/runtime/triton_helpers.py:504
Duplicated max/delta logic (non-blocking, carried over from the last review). To
drop the multiply, the PR stopped calling `online_softmax_reduce` and copied its
code in. Lines 504-509 repeat `online_softmax_reduce` (448-453) with only the
variable names changed: the max2_strict/max2 choice, the `tl.expand_dims`, and
the `-inf` guard on `delta`. Only the sum line is meant to differ (511 vs 454).
Codegen still emits `online_softmax_reduce` at codegen/triton.py:6859 and :6999
for the persistent and vector paths. If one copy changes later (e.g. the `-inf`
guard), the looped scalar path would silently stop matching those paths.
Suggested fix: add a small `@​ triton.jit` helper that returns `(max, delta)` and
have each caller keep its own sum line, the way `_first_index_of` (:397) is
shared by min/max_with_first_index. Triton inlines jit callees, so the speedup
stays. Optional cleanup: the `strict_signed_zero` branch at 504-505 can't be
reached. Its only caller (triton.py:6584) is gated on
`use_scalar_online_softmax`, which depends on `use_scalar_accumulators`, and
that returns False under `config.strict_signed_zero`. If you keep the copied
code, you could drop the branch.

Reviewed commit: 9ccea8e

Review run

🐛 Report a bad review

🔗 Helpful Links

🧪 See artifacts and rendered test results at hud.pytorch.org/pr/204321

Note: Links to docs will display an error until the docs builds have been completed.

❌ 3 Cancelled Jobs, 1 Unclassified Failure

As of commit 9ccea8e with merge base 304eed3 (image):

🟢 GREEN LIGHT - PR approved to be merged without human review:

  • Triviality
    • Behavior-neutral tweak: online_softmax_reduce_scalar_combine inlines online_softmax_reduce and swaps mask * exp(delta) for tl.where(mask, exp(delta), 0.0)
    • Inlined max/delta lines match online_softmax_reduce in triton_helpers.py exactly; same tl.sum over the same shape and dim
  • Numerics
    • Masked lanes are -inf, so their exp is 0, or 1 when the row max is -inf; 0 * e is +0.0 either way, and 1.0 * e is exact even under FMA
    • A NaN or +inf row max comes from an unmasked lane, which already makes the sum NaN in both forms
    • Accumulators use acc_type (codegen/triton.py scalar_online_softmax branch), so the sum dtype is unchanged
  • Evidence
    • TestScalarAccumulators in test/inductor/test_online_softmax.py checks for the helper's marker with non-power-of-2 masked sizes (8193, 50265); description reports passing and bitwise-equal kernels

reason: clean
Reviewed commit: 9ccea8e

Inference job

🐛 Report a wrong verdict

UNCLASSIFIED FAILURE - DrCI could not classify the following job because the workflow did not run on the merge base. The failure may be pre-existing on trunk or introduced by this PR:

CANCELLED JOBS - The following jobs were cancelled. Please retry:

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

@pytorchbot pytorchbot added the in progress PR is being worked on by the author, until the automated review accepts it label Nov 10, 2026
@pytorchgreenlight pytorchgreenlight Bot added the GL/human GreenLight marked as needing human review label Nov 10, 2026
github-actions[bot]

This comment was marked as outdated.

[ghstack-poisoned]
github-actions[bot]

This comment was marked as outdated.

[ghstack-poisoned]
@pytorchgreenlight pytorchgreenlight Bot added GL/approved Approved by GreenLight and removed GL/human GreenLight marked as needing human review labels Nov 12, 2026

@github-actions github-actions 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.

Automated review of 18dbec9: nothing blocking; ready for human review.

The PR changes online_softmax_reduce_scalar_combine to select exp(delta) with tl.where(rhs_mask, ..., 0.0) instead of multiplying by a 0/1 mask, dropping one multiply per element, and the review confirms it is bitwise-equivalent. Recommendation: Approve; the only remaining point, about duplicated max/delta code, is labeled non-blocking.

⚪ 1 non-blocking finding

if strict_signed_zero:

Duplicated max/delta logic (non-blocking, carried over from the last review, no reply yet). Lines 475-480 copy the max/delta code of online_softmax_reduce (lines 419-424) with only the variable names changed: the max2_strict/max2 choice, the tl.expand_dims call, and the -inf guard on delta. online_softmax_reduce is still used through online_softmax_reduce_final_reduction (triton.py:6883) by the persistent, looped-vector and cooperative paths. If one copy changes later (e.g. the -inf guard), the looped scalar path would silently disagree with those paths. Fix: add a small @ triton.jit helper that returns (max, delta) and have each caller keep its own sum line, as max_with_first_index and online_softmax_combine_with_sum already do. Triton inlines jit callees, so the speedup is kept. Also, the strict_signed_zero branch at lines 475-476 can't be reached from codegen, because use_scalar_accumulators (triton.py:5851) turns the scalar path off under config.strict_signed_zero. If the copy stays, that branch could be dropped instead of being duplicated.

This review is AI-generated and advisory. Each new automated review replaces the previous one. Report a bad review

@eellison eellison added the topic: not user facing topic category label Nov 24, 2026
[ghstack-poisoned]
@pytorchmergebot

Copy link
Copy Markdown
Collaborator

Rebased gh/eellison/1131/orig onto refs/remotes/origin/viable/strict because #204322 was rebased, please pull locally before adding more changes (for example, via ghstack checkout https://github.com/pytorch/pytorch/pull/204321)

@pytorchmergebot

Copy link
Copy Markdown
Collaborator

Starting merge as part of PR stack under #204322

1 similar comment
@pytorchmergebot

Copy link
Copy Markdown
Collaborator

Starting merge as part of PR stack under #204322

pytorchmergebot pushed a commit that referenced this pull request Nov 25, 2026
…explicit FMAs (#204322)

**Problem**

#202218 added `triton.enable_fp_fusion`: with it off, Inductor's Triton kernels round every multiply and add separately, so results no longer depend on the block size or `num_warps` that autotuning, coordinate descent or the default heuristic picks. Deterministic mode itself still left contraction on, so a deterministic-mode run could still produce different bits depending on which pointwise config timing picked.

**Change**

- Deterministic mode (and `batch_invariant`) now compiles Inductor's generated Triton kernels with `enable_fp_fusion=False`, via a new `triton_fp_fusion_enabled()` helper in `utils.py` used by `triton_meta_common`.
- The multiply-adds in `triton_helpers` are written as explicit `tl.fma`, so they keep a single rounding regardless of the contraction setting: `welford_reduce`, `welford_combine`, `online_softmax_combine(_with_sum)`, and `rand_eager_kernel` (bit-neutral there, since `inv = 2**-32` makes the product exact).
- Templates (matmul, flex attention) build their own `triton_meta` and keep Triton's contraction. In deterministic mode their config is already chosen without benchmarking. Under `batch_invariant` alone, templates and their fused epilogues are not covered by this PR.

**Numerics outside deterministic mode**

The `tl.fma` calls in `triton_helpers` are unconditional. In modes where contraction was already off before this PR (`triton.enable_fp_fusion=False`, `emulate_precision_casts`, and `numerics="strict"` / `strict_pointwise`, which imply it), welford (`var_mean`, `layer_norm`) and online-softmax results can change in the last bit. With contraction on (the default), Triton was already free to form these FMAs.

**Performance**

Turning contraction off costs speed in deterministic mode only; default mode is unchanged. On better-benchmark (1724 kernels, H100, Nov 2 nightly), `triton.enable_fp_fusion=False` measured +0.25% geomean. The slowdowns are concentrated in a few latency-bound reductions where a product feeding an add is no longer fused, e.g. two softmax kernels (~+30%), a `var_mean` (~+12%) and a `sum` (~+10%). These per-kernel numbers were measured on an earlier revision of this PR; the kernels were attributed to contraction being off, not to the helper changes. The online-softmax change below this PR (#204321) recovers the cross-entropy kernels (`amax_sum_sum_a97be2219d64`: 1782 us in deterministic mode today -> 1378 us).

Note: without the Dynamo fix at the bottom of this stack (#204320), `config.deterministic` set alone is turned off after the first compiled frame.

**Test plan**

```
python test/inductor/test_deterministic.py
python test/inductor/test_triton_helpers.py
```

- `test_fp_fusion`: deterministic mode turns off `enable_fp_fusion`; the flag alone still works as before.
- `test_pointwise_config_numerics` runs with deterministic mode alone and with `triton.enable_fp_fusion=False` alone: forcing XBLOCK=128 vs 256 by timing gives bitwise-equal outputs.
- `test_kernel_online_softmax_combine`: reference updated to the explicit-FMA form.

This change was authored with an AI assistant (Claude Code), with the change and tests reviewed in the session.

Pull Request resolved: #204322
Approved by: https://github.com/mlazos
ghstack dependencies: #204320, #204321
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

GL/approved Approved by GreenLight in progress PR is being worked on by the author, until the automated review accepts it Merged module: inductor topic: not user facing topic category

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants