Skip to content

[inductor] Add triton.enable_fp_fusion flag to turn off FMA contraction (#202218) - #202218

Closed
dmdok wants to merge 1 commit into
pytorch:mainfrom
dmdok:export-D127104145
Closed

dmdok wants to merge 1 commit into
pytorch:mainfrom
dmdok:export-D127104145

Conversation

@dmdok

@dmdok dmdok commented Oct 27, 2026 •

Copy link
Copy Markdown
Contributor

Summary:

Problem

The same Inductor kernel can produce different bits depending on which config autotuning picks. With triton.autotune_pointwise=True (the default), a 1D pointwise kernel gets two candidate configs, XBLOCK=256 and XBLOCK=128; CachingAutotuner times both at the first launch and keeps the faster one. Timing is noisy, so different processes can keep different configs. Deterministic mode (TORCHINDUCTOR_DETERMINISTIC=1) does not prevent this: it pins reduction configs, but pointwise kernels still pick their config by timing.

The config changes the result because Triton contracts multiply-adds into FMAs (one rounding instead of two), and which products it fuses depends on the block size. For x / B * 0.01 + buf * 0.99 with a dynamic B, the two configs compile to (on H100):

  • XBLOCK=128: fma(x/B, 0.01, buf*0.99)
  • XBLOCK=256: fma(buf, 0.99, (x/B)*0.01)

They round differently, and 4042 of 16384 outputs differ in the last bits.

How this was found

We need bit-exact, reproducible training runs, so we train with deterministic mode on. Two identical runs of a 64-GPU training job still diverged within the first steps.

  • The first tensor that differed between the runs was a buffer updated by one Inductor pointwise kernel, the x / B * 0.01 + buf * 0.99 update above with a dynamic batch size B. All of the kernel's inputs were bit-identical.
  • On 8 A100s, each GPU's autotuner kept XBLOCK=256 or XBLOCK=128 depending on timing, differently from run to run, and the outputs split into two groups that matched the XBLOCK each GPU kept.
  • With triton.autotune_pointwise=False, all 8 GPUs matched bit for bit.

Turning autotuning off works around it, but only removes timing as the source of variation: results still depend on the config, so a different tensor size or tuning path can still change the bits. Turning FMA contraction off removes the dependence on the config itself.

Fix

Add config.triton.enable_fp_fusion (env TORCHINDUCTOR_ENABLE_FP_FUSION), on by default. When it is off, triton_meta_common compiles Inductor's generated Triton kernels with Triton's enable_fp_fusion=False, so every multiply and add rounds separately and the result no longer depends on the block size or num_warps, whichever path picks them: autotuning by timing, coordinate descent, or the default heuristic for a given tensor size. emulate_precision_casts sets the same compile option and still turns FMA off as before.

Why a separate flag:

  • Deterministic mode itself is unchanged, for backward compatibility. torch.use_deterministic_algorithms(True) also turns it on, so tying FMA to it would shift numerics and slow kernels for every job that calls it.
  • emulate_precision_casts already turns FMA off, but it also keeps bf16/fp16 intermediates rounded like eager, uses CUDA's libdevice instead of Triton's, and blocks some cast-removal rewrites. Bitwise reproducibility across configs only needs FMA off.

Alternatives considered

  • Pin each pointwise kernel's config in deterministic mode (an earlier version of this change). That removes timing as a source of variation, but results still depend on the config: the default XBLOCK depends on the tensor size, and every tuning path needs its own guard.
  • Turn FMA off whenever deterministic mode is on. That changes numerics and speed for every torch.use_deterministic_algorithms caller.
  • Turn FMA off by default. That changes numerics and speed for all users; with this flag it becomes a default change if measurements support it.

Scope

Behavior changes only when the flag is off. Like emulate_precision_casts, the flag applies through triton_meta_common to Inductor's generated pointwise, reduction, foreach and combo kernels; template kernels (select_algorithm) keep their current option. The speed cost of turning FMA off is not measured here.

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

Test Plan:
New tests in test/inductor/test_deterministic.py:

  • test_fp_fusion (flag on and off, deterministic mode on and off): the generated Triton code has 'enable_fp_fusion': False only when the flag is off. Deterministic mode alone keeps FMA contraction.
  • test_pointwise_config_numerics (flag off, deterministic mode on): compiles the kernel above twice, with CachingAutotuner.bench patched so timing picks XBLOCK=128 the first time and XBLOCK=256 the second. It checks that two different XBLOCKs were picked and that the outputs are bitwise equal.
python test/inductor/test_deterministic.py

Ran from Meta's internal build of this file on a remote A100 (the command above is the OSS equivalent):

  • With the change: 15 tests passed, 26 skipped (test_run2run_determinism, skipped in that build, and test_max_autotune, which needs a larger GPU).
  • With triton_meta_common ignoring the flag: test_pointwise_config_numerics fails (4042 of 16384 outputs differ) and both flag-off cases of test_fp_fusion fail.

The two FMA forms above come from the PTX of the two kernels on H100: the XBLOCK=128 kernel has one FMA per thread, fusing the 0.01 product; the XBLOCK=256 kernel has two, both fusing the 0.99 product.

Reviewed By: eellison, jansel

Differential Revision: D127104145

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

@pytorch-bot

pytorch-bot Bot commented Oct 27, 2026 •

Copy link
Copy Markdown

PR Status: Approved 🚀

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

✅ AUTOMATED REVIEW - OUTDATED (earlier commit) - Ready for human review:

In deterministic mode, `pointwise()` now uses the heuristic's
`get_default_config` instead of timing several configs; the PR also pins foreach
`num_warps`, turns off pointwise coordinate-descent tuning, and fixes a test
that leaked deterministic state. Recommendation: Approve  none of the three
remaining issues is a correctness bug in the default configuration, and the
tests cover the new behaviour well.

Findings (3):

[minor] torch/_inductor/runtime/triton_heuristics.py:2406
Coordinate-descent gate: with the new POINTWISE check, deterministic mode now
turns off coordinate-descent tuning for every heuristic type that gets this far
(POINTWISE, REDUCTION, PERSISTENT_REDUCTION and SPLIT_SCAN are all excluded;
TEMPLATE, USER_AUTOTUNE and FIXED already return False on line 2389). Two
type-specific branches hide this, and the comment on line 2395 still says the
rule is about reductions. Replace them with one `if self.deterministic_mode:
return False`, and keep the reduction-type check only for
`"strict_reduction_rblock"`. A heuristic type added later would then be pinned
in deterministic mode by default, rather than tuned without anyone noticing.

[minor] torch/_inductor/runtime/triton_heuristics.py:4792
Unused hint configs: `hinted_configs = autotune_hints_to_configs(...)` (line
4776) still runs before the new `if deterministic:` branch, and its result is
thrown away in deterministic mode. Move the call into the `else:` branch next to
`get_configs`, the only code that reads it.

[minor] torch/_inductor/runtime/triton_heuristics.py:4791
Combo per-subkernel path has no guard:
`_handle_combo_kernel_per_subkernel_blocks` (line 4752) returns before the new
deterministic branch, and the description says this path is not covered. Each
subkernel's `pointwise()`/`reduction()` probe now yields a single config, but
the combo can still time configs in deterministic mode with no error or log:
`combo_warp_stage_candidates` collects every distinct `(num_warps, num_stages)`
pair across subkernels plus the max pair, and the `stitched_launch_candidates`
path returns one config per launch candidate. Either keep only the `(max warps,
max stages)` base config when `inductor_meta.get("deterministic")` is set, or at
least emit a `log.warning` that this path is not deterministic. The setting
(`combo_kernel_per_subkernel_blocks`) is off by default, which limits impact.
Low confidence on exactly how much gets timed: `_combo_sequential_autotune` was
not traced end to end.

Reviewed commit: 9e40e56 (NOT the current head b39d110)

Review run

🔗 Helpful Links

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

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

❌ 1 New Failure

As of commit b39d110 with merge base 33a7c40 (image):

NEW FAILURE - The following job has failed:

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

@meta-codesync

meta-codesync Bot commented Oct 27, 2026

Copy link
Copy Markdown

@dmdok has exported this pull request. If you are a Meta employee, you can view the originating Diff in D127104145.

@pytorchbot pytorchbot added the in progress PR is being worked on by the author, until the automated review accepts it label Oct 27, 2026
github-actions[bot]

This comment was marked as outdated.

@meta-codesync meta-codesync Bot changed the title [inductor] Fix deterministic mode picking pointwise configs by timing [inductor] Fix deterministic mode picking pointwise configs by timing (#202218) Oct 27, 2026
@dmdok
dmdok force-pushed the export-D127104145 branch from 5b8fbd3 to 89289c9 Compare October 27, 2026 16:29
dmdok added a commit to dmdok/pytorch that referenced this pull request Oct 27, 2026
…pytorch#202218)

Summary:

Deterministic mode (`TORCHINDUCTOR_DETERMINISTIC=1`, also turned on by `batch_invariant` and `torch.use_deterministic_algorithms`) skips on-device benchmarking that can change numerics. Reductions already get a single config there, but pointwise kernels still pick their config by timing. With `triton.autotune_pointwise=True` (the default), a 1D pointwise kernel gets two candidate configs, XBLOCK=256 and XBLOCK=128; `CachingAutotuner` times both at the first launch and keeps the faster one. Timing is noisy, so different processes can keep different configs.

The config changes the result. For `x / B * 0.01 + buf * 0.99` with a dynamic `B`, the two configs compile to PTX that fuses a different product into the FMA: on H100, XBLOCK=128 computes `fma(x/B, 0.01, buf*0.99)` and XBLOCK=256 computes `fma(buf, 0.99, (x/B)*0.01)`. They round differently, and 4042 of 16384 outputs differ in the last bits. This was found while debugging run-to-run divergence of an 8-GPU training job: the ranks that kept XBLOCK=256 disagreed with the rest, and with `triton.autotune_pointwise=False` all ranks matched bit for bit.

Fix: in deterministic mode, `PointwiseHeuristic.get_configs` returns only its default config, the one it already uses when pointwise autotuning is off (`_default_config`, now shared by those branches). The ROCm and XPU heuristics inherit `get_configs`, so every device and 1D/2D/3D kernel is covered, including the XPU 3D path, which ignores the autotune flags. When TMA restrictions apply, `_maybe_filter_configs_for_tma_restrictions` turns that config into one TMA-compatible config or two identical ones, so timing still cannot change the result. Coordinate-descent tuning, which also tunes XBLOCK by timing, is turned off for pointwise kernels in deterministic mode, as it already is for reductions. The `may_ban_benchmarking` message no longer lists pointwise config autotuning as safe.

The new test exposed a test-isolation bug: `test_cumsum_deterministic` turned on `torch.use_deterministic_algorithms`, which also sets `inductor_config.deterministic`, and never turned it off, so `test_pointwise_coordesc_tuning` ran in deterministic mode. It now restores the previous setting.

Alternatives considered:
- Pass `autotune_pointwise`, `max_autotune` and `max_autotune_pointwise` as off to the heuristic. This relies on every heuristic checking those flags, and the XPU 3D path does not.
- Keep the first generated config. This relies on the list order, which nothing guarantees.
- Disable FMA contraction (`enable_fp_fusion=False`) in deterministic mode. This makes all configs bit-equivalent, but slows every kernel and changes numerics compared with normal compiles.

Only deterministic mode changes: its pointwise kernels now always use the heuristic's default config, the one used when pointwise autotuning is off. Not covered: combo kernels with per-subkernel blocks (they run their own block-size tuning) and foreach kernels under max-autotune (they time `num_warps`).

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

Test Plan:
New and changed tests in `test/inductor/test_deterministic.py`:
- `test_pointwise_autotuning` (deterministic on and off) compiles the kernel above twice, with `CachingAutotuner.bench` patched so the first compile prefers XBLOCK=128 and the second XBLOCK=256, and with coordinate descent on. Deterministic: nothing is timed, coordinate descent does not run, and the two outputs are bitwise equal. Off: configs are timed and coordinate descent runs.
- `test_pointwise_heuristic_single_config` (CUDA, ROCm and XPU heuristics, 1D/2D/3D): with max-autotune on, the heuristic offers several configs; in deterministic mode it returns exactly the default config. It records configs instead of building them, so it needs no ROCm or XPU hardware.

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

Ran on one H100 from Meta's internal build of these files (the commands above are the OSS equivalent):
- `test_deterministic.py`: 46 tests OK, 24 skipped (`test_run2run_determinism`, skipped in that build). `test_coordinate_descent_tuner.py`: 27 tests OK.
- Without the `pointwise.py` change: `test_pointwise_autotuning_deterministic_True` and all 9 `test_pointwise_heuristic_single_config` cases fail (2 to 10 configs instead of 1).
- Without the coordinate-descent change: `test_pointwise_autotuning_deterministic_True` fails, because coordinate descent times configs.
- Without the cumsum fix: `test_pointwise_coordesc_tuning` fails.

Numerics repro with deterministic mode off, run on H100 as a temporary test with this body:

```python
def fn(x, buf):
    return x / x.shape[0] * 0.01 + buf * 0.99

x, buf = torch.randn(16384, device="cuda"), torch.randn(16384, device="cuda")
outs = []
for prefer_small in (True, False):  # timing picks XBLOCK=128, then XBLOCK=256
    def bench(self, launcher, *args, **kwargs):
        xblock = launcher.config.kwargs["XBLOCK"]
        return xblock if prefer_small else 1 / xblock
    torch._dynamo.reset()
    with fresh_cache(), unittest.mock.patch.object(CachingAutotuner, "bench", bench):
        outs.append(torch.compile(fn, dynamic=True)(x, buf))
print((outs[0].view(torch.int32) != outs[1].view(torch.int32)).sum())
```

Result: 4042 of 16384 outputs differ. The PTX of the XBLOCK=128 kernel has one FMA per thread, fusing the `0.01` product; the XBLOCK=256 kernel has two, both fusing the `0.99` product.

Differential Revision: D127104145
github-actions[bot]

This comment was marked as outdated.

@dmdok
dmdok force-pushed the export-D127104145 branch from 89289c9 to d5c0aca Compare October 27, 2026 18:46
dmdok added a commit to dmdok/pytorch that referenced this pull request Oct 27, 2026
…pytorch#202218)

Summary:

Deterministic mode (`TORCHINDUCTOR_DETERMINISTIC=1`, also turned on by `batch_invariant` and `torch.use_deterministic_algorithms`) skips on-device benchmarking that can change numerics. Reductions already get a single config there, but pointwise kernels still pick their config by timing. With `triton.autotune_pointwise=True` (the default), a 1D pointwise kernel gets two candidate configs, XBLOCK=256 and XBLOCK=128; `CachingAutotuner` times both at the first launch and keeps the faster one. Timing is noisy, so different processes can keep different configs.

The config changes the result. For `x / B * 0.01 + buf * 0.99` with a dynamic `B`, the two configs compile to PTX that fuses a different product into the FMA: on H100, XBLOCK=128 computes `fma(x/B, 0.01, buf*0.99)` and XBLOCK=256 computes `fma(buf, 0.99, (x/B)*0.01)`. They round differently, and 4042 of 16384 outputs differ in the last bits. This was found while debugging run-to-run divergence of an 8-GPU training job: the ranks that kept XBLOCK=256 disagreed with the rest, and with `triton.autotune_pointwise=False` all ranks matched bit for bit.

Fix: in deterministic mode, `pointwise()` in `triton_heuristics.py` asks the device's heuristic for its default config (`get_default_config`) instead of its config list, the same place reductions enforce determinism. The default is the config `PointwiseHeuristic` already uses when pointwise autotuning is off; the CUDA, ROCm and XPU heuristics all inherit it, which also covers the XPU 3D path that ignores the autotune flags. `get_default_config` is part of the `CodegenConfigHeuristics` contract and raises `NotImplementedError` by default, so a registered heuristic that does not define it fails loudly in deterministic mode instead of timing configs. When TMA restrictions apply, `_maybe_filter_configs_for_tma_restrictions` can add a copy of the default config; a `unique_configs` pass drops it. Coordinate-descent tuning, which also tunes XBLOCK by timing, is turned off for pointwise kernels in deterministic mode, as it already is for reductions. The `may_ban_benchmarking` message no longer lists pointwise config autotuning as safe.

The new test exposed a test-isolation bug: `test_cumsum_deterministic` turned on `torch.use_deterministic_algorithms`, which also sets `inductor_config.deterministic`, and never turned it off, so `test_pointwise_coordesc_tuning` ran in deterministic mode. It now restores the previous setting.

Alternatives considered:
- Pass `autotune_pointwise`, `max_autotune` and `max_autotune_pointwise` as off to the heuristic. This relies on every heuristic checking those flags, and the XPU 3D path does not.
- Return the default config from inside `PointwiseHeuristic.get_configs`. A registered heuristic that does not inherit that method would skip the guard without any error.
- Keep the first generated config. This relies on the list order, which nothing guarantees.
- Disable FMA contraction (`enable_fp_fusion=False`) in deterministic mode. This makes all configs bit-equivalent, but slows every kernel and changes numerics compared with normal compiles.

Only deterministic mode changes: its pointwise kernels now always use the heuristic's default config, the one used when pointwise autotuning is off. Not covered: combo kernels with per-subkernel blocks (they run their own block-size tuning) and foreach kernels under max-autotune (they time `num_warps`).

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

Test Plan:
New and changed tests in `test/inductor/test_deterministic.py`:
- `test_pointwise_autotuning` (deterministic on and off) compiles the kernel above twice, with `CachingAutotuner.bench` patched so the first compile prefers XBLOCK=128 and the second XBLOCK=256, and with coordinate descent on. Deterministic: nothing is timed, coordinate descent does not run, and the two outputs are bitwise equal. Off: configs are timed and coordinate descent runs.
- `test_pointwise_deterministic_uses_default_config` calls `pointwise()` with a heuristic that subclasses `CodegenConfigHeuristics` directly and returns two configs. Deterministic mode returns only its default config; with TMA restrictions the duplicate copy is dropped; a heuristic without `get_default_config` raises `NotImplementedError`.
- `test_pointwise_heuristic_default_config` (CUDA, ROCm and XPU heuristics, 1D/2D/3D): the default config is the one used when autotuning is off (XBLOCK=`bs`, 32x32, 16x16x16). It records configs instead of building them, so it needs no ROCm or XPU hardware.

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

Ran on one H100 from Meta's internal build of these files (the commands above are the OSS equivalent):
- `test_deterministic.py`: 47 tests OK, 24 skipped (`test_run2run_determinism`, skipped in that build). `test_coordinate_descent_tuner.py`: 27 tests OK.
- Without the deterministic branch in `pointwise()`: `test_pointwise_autotuning_deterministic_True` and `test_pointwise_deterministic_uses_default_config` fail.
- Without the `unique_configs` pass: the TMA check fails (2 configs instead of 1).
- Without the coordinate-descent change: `test_pointwise_autotuning_deterministic_True` fails, because coordinate descent times configs.
- Without the cumsum fix: `test_pointwise_coordesc_tuning` fails.

Numerics repro with deterministic mode off, run on H100 as a temporary test with this body:

```python
def fn(x, buf):
    return x / x.shape[0] * 0.01 + buf * 0.99

x, buf = torch.randn(16384, device="cuda"), torch.randn(16384, device="cuda")
outs = []
for prefer_small in (True, False):  # timing picks XBLOCK=128, then XBLOCK=256
    def bench(self, launcher, *args, **kwargs):
        xblock = launcher.config.kwargs["XBLOCK"]
        return xblock if prefer_small else 1 / xblock
    torch._dynamo.reset()
    with fresh_cache(), unittest.mock.patch.object(CachingAutotuner, "bench", bench):
        outs.append(torch.compile(fn, dynamic=True)(x, buf))
print((outs[0].view(torch.int32) != outs[1].view(torch.int32)).sum())
```

Result: 4042 of 16384 outputs differ. The PTX of the XBLOCK=128 kernel has one FMA per thread, fusing the `0.01` product; the XBLOCK=256 kernel has two, both fusing the `0.99` product.

Differential Revision: D127104145
github-actions[bot]

This comment was marked as outdated.

@dmdok
dmdok force-pushed the export-D127104145 branch from d5c0aca to 9e40e56 Compare October 27, 2026 19:35
dmdok added a commit to dmdok/pytorch that referenced this pull request Oct 27, 2026
…pytorch#202218)

Summary:
Pull Request resolved: pytorch#202218

Deterministic mode (`TORCHINDUCTOR_DETERMINISTIC=1`, also turned on by `batch_invariant` and `torch.use_deterministic_algorithms`) skips on-device benchmarking that can change numerics. Reductions already get a single config there, but pointwise kernels still pick their config by timing. With `triton.autotune_pointwise=True` (the default), a 1D pointwise kernel gets two candidate configs, XBLOCK=256 and XBLOCK=128; `CachingAutotuner` times both at the first launch and keeps the faster one. Timing is noisy, so different processes can keep different configs.

The config changes the result. For `x / B * 0.01 + buf * 0.99` with a dynamic `B`, the two configs compile to PTX that fuses a different product into the FMA: on H100, XBLOCK=128 computes `fma(x/B, 0.01, buf*0.99)` and XBLOCK=256 computes `fma(buf, 0.99, (x/B)*0.01)`. They round differently, and 4042 of 16384 outputs differ in the last bits. This was found while debugging run-to-run divergence of an 8-GPU training job: the ranks that kept XBLOCK=256 disagreed with the rest, and with `triton.autotune_pointwise=False` all ranks matched bit for bit.

Fix: in deterministic mode, `pointwise()` in `triton_heuristics.py` asks the device's heuristic for its default config (`get_default_config`) instead of its config list, the same place reductions enforce determinism. The default is the config `PointwiseHeuristic` already uses when pointwise autotuning is off; the CUDA, ROCm and XPU heuristics all inherit it, which also covers the XPU 3D path that ignores the autotune flags. `get_default_config` is part of the `CodegenConfigHeuristics` contract and raises `NotImplementedError` by default, so a registered heuristic that does not define it fails loudly in deterministic mode instead of timing configs. When TMA restrictions apply, `_maybe_filter_configs_for_tma_restrictions` can add a copy of the default config; a `unique_configs` pass drops it. Coordinate-descent tuning, which also tunes XBLOCK by timing, is turned off for pointwise kernels in deterministic mode, as it already is for reductions. Foreach kernels, which time `num_warps` under max-autotune, keep their single `num_warps=8` config in deterministic mode. The `may_ban_benchmarking` message no longer lists pointwise config autotuning as an example of safe benchmarking.

The new test exposed a test-isolation bug: `test_cumsum_deterministic` turned on `torch.use_deterministic_algorithms`, which also sets `inductor_config.deterministic`, and never turned it off, so `test_pointwise_coordesc_tuning` ran in deterministic mode. It now restores both settings with `DeterministicGuard` and `inductor_config.patch`.

Alternatives considered:
- Pass `autotune_pointwise`, `max_autotune` and `max_autotune_pointwise` as off to the heuristic. This relies on every heuristic checking those flags, and the XPU 3D path does not.
- Return the default config from inside `PointwiseHeuristic.get_configs`. A registered heuristic that does not inherit that method would skip the guard without any error.
- Keep the first generated config. This relies on the list order, which nothing guarantees.
- Disable FMA contraction (`enable_fp_fusion=False`) in deterministic mode. This makes all configs bit-equivalent, but slows every kernel and changes numerics compared with normal compiles.

Only deterministic mode changes: its pointwise kernels now always use the heuristic's default config, the one used when pointwise autotuning is off. Not covered: combo kernels with per-subkernel blocks (`combo_kernel_per_subkernel_blocks`, off by default), which run their own block-size tuning.

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

Test Plan:
New and changed tests in `test/inductor/test_deterministic.py`:
- `test_pointwise_autotuning` (deterministic on and off) compiles the kernel above twice, with `CachingAutotuner.bench` patched so the first compile prefers XBLOCK=128 and the second XBLOCK=256, and with coordinate descent on. Deterministic: nothing is timed, coordinate descent does not run, and the two outputs are bitwise equal. Off: configs are timed and coordinate descent runs.
- `test_foreach_autotuning` (deterministic on and off) compiles `torch._foreach_add` under max-autotune and counts timed foreach configs: none in deterministic mode, some otherwise.
- `test_pointwise_deterministic_uses_default_config` calls `pointwise()` with a heuristic that subclasses `CodegenConfigHeuristics` directly and returns two configs. Deterministic mode returns only its default config; with TMA restrictions the duplicate copy is dropped; a heuristic without `get_default_config` raises `NotImplementedError`.
- `test_pointwise_heuristic_default_config` (CUDA, ROCm and XPU heuristics, 1D/2D/3D): the default config is the one used when autotuning is off (XBLOCK=`bs`, 32x32, 16x16x16). It records configs instead of building them, so it needs no ROCm or XPU hardware.

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

Ran on one H100 from Meta's internal build of these files (the commands above are the OSS equivalent):
- `test_deterministic.py`: 49 tests OK, 24 skipped (`test_run2run_determinism`, skipped in that build). `test_coordinate_descent_tuner.py`: 27 tests OK.
- Without the deterministic branch in `pointwise()`: `test_pointwise_autotuning_deterministic_True` and `test_pointwise_deterministic_uses_default_config` fail.
- Without the `unique_configs` pass: the TMA check fails (2 configs instead of 1).
- Without the foreach change: `test_foreach_autotuning_deterministic_True` fails.
- Without the coordinate-descent change: `test_pointwise_autotuning_deterministic_True` fails, because coordinate descent times configs.
- Without the cumsum fix: `test_pointwise_coordesc_tuning` fails.

Numerics repro with deterministic mode off, run on H100 as a temporary test with this body:

```python
def fn(x, buf):
    return x / x.shape[0] * 0.01 + buf * 0.99

x, buf = torch.randn(16384, device="cuda"), torch.randn(16384, device="cuda")
outs = []
for prefer_small in (True, False):  # timing picks XBLOCK=128, then XBLOCK=256
    def bench(self, launcher, *args, **kwargs):
        xblock = launcher.config.kwargs["XBLOCK"]
        return xblock if prefer_small else 1 / xblock
    torch._dynamo.reset()
    with fresh_cache(), unittest.mock.patch.object(CachingAutotuner, "bench", bench):
        outs.append(torch.compile(fn, dynamic=True)(x, buf))
print((outs[0].view(torch.int32) != outs[1].view(torch.int32)).sum())
```

Result: 4042 of 16384 outputs differ. The PTX of the XBLOCK=128 kernel has one FMA per thread, fusing the `0.01` product; the XBLOCK=256 kernel has two, both fusing the `0.99` product.

Differential Revision: D127104145

@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 9e40e56: nothing blocking; ready for human review.

In deterministic mode, pointwise() now uses the heuristic's get_default_config instead of timing several configs; the PR also pins foreach num_warps, turns off pointwise coordinate-descent tuning, and fixes a test that leaked deterministic state. Recommendation: Approve none of the three remaining issues is a correctness bug in the default configuration, and the tests cover the new behaviour well.

⚪ 3 non-blocking findings

if self.deterministic_mode and self.heuristic_type == HeuristicType.POINTWISE:

Coordinate-descent gate: with the new POINTWISE check, deterministic mode now turns off coordinate-descent tuning for every heuristic type that gets this far (POINTWISE, REDUCTION, PERSISTENT_REDUCTION and SPLIT_SCAN are all excluded; TEMPLATE, USER_AUTOTUNE and FIXED already return False on line 2389). Two type-specific branches hide this, and the comment on line 2395 still says the rule is about reductions. Replace them with one if self.deterministic_mode: return False, and keep the reduction-type check only for "strict_reduction_rblock". A heuristic type added later would then be pinned in deterministic mode by default, rather than tuned without anyone noticing.


Unused hint configs: hinted_configs = autotune_hints_to_configs(...) (line 4776) still runs before the new if deterministic: branch, and its result is thrown away in deterministic mode. Move the call into the else: branch next to get_configs, the only code that reads it.


deterministic = inductor_meta.get("deterministic")

Combo per-subkernel path has no guard: _handle_combo_kernel_per_subkernel_blocks (line 4752) returns before the new deterministic branch, and the description says this path is not covered. Each subkernel's pointwise()/reduction() probe now yields a single config, but the combo can still time configs in deterministic mode with no error or log: combo_warp_stage_candidates collects every distinct (num_warps, num_stages) pair across subkernels plus the max pair, and the stitched_launch_candidates path returns one config per launch candidate. Either keep only the (max warps, max stages) base config when inductor_meta.get("deterministic") is set, or at least emit a log.warning that this path is not deterministic. The setting (combo_kernel_per_subkernel_blocks) is off by default, which limits impact. Low confidence on exactly how much gets timed: _combo_sequential_autotune was not traced end to end.

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

@github-actions
github-actions Bot dismissed stale reviews from themself October 27, 2026 19:41

Withdrawn: the automated review of 9e40e56 found nothing blocking.

@pytorch-bot pytorch-bot Bot added ready for review Automated review passed, ready for a final review by a maintainer. and removed in progress PR is being worked on by the author, until the automated review accepts it labels Oct 27, 2026
@dmdok
dmdok force-pushed the export-D127104145 branch from 9e40e56 to 6a81cf5 Compare October 28, 2026 05:44
dmdok added a commit to dmdok/pytorch that referenced this pull request Oct 28, 2026
…pytorch#202218)

Summary:

Deterministic mode (`TORCHINDUCTOR_DETERMINISTIC=1`, also turned on by `batch_invariant` and `torch.use_deterministic_algorithms`) skips on-device benchmarking that can change numerics. Reductions already get a single config there, but pointwise kernels still pick their config by timing. With `triton.autotune_pointwise=True` (the default), a 1D pointwise kernel gets two candidate configs, XBLOCK=256 and XBLOCK=128; `CachingAutotuner` times both at the first launch and keeps the faster one. Timing is noisy, so different processes can keep different configs.

The config changes the result. For `x / B * 0.01 + buf * 0.99` with a dynamic `B`, the two configs compile to PTX that fuses a different product into the FMA: on H100, XBLOCK=128 computes `fma(x/B, 0.01, buf*0.99)` and XBLOCK=256 computes `fma(buf, 0.99, (x/B)*0.01)`. They round differently, and 4042 of 16384 outputs differ in the last bits. This was found while debugging run-to-run divergence of an 8-GPU training job: the ranks that kept XBLOCK=256 disagreed with the rest, and with `triton.autotune_pointwise=False` all ranks matched bit for bit.

Fix: in deterministic mode, `pointwise()` in `triton_heuristics.py` asks the device's heuristic for its default config (`get_default_config`) instead of its config list, the same place reductions enforce determinism. The default is the config `PointwiseHeuristic` already uses when pointwise autotuning is off; the CUDA, ROCm and XPU heuristics all inherit it, which also covers the XPU 3D path that ignores the autotune flags. `get_default_config` is part of the `CodegenConfigHeuristics` contract and raises `NotImplementedError` by default, so a registered heuristic that does not define it fails loudly in deterministic mode instead of timing configs. When TMA restrictions apply, `_maybe_filter_configs_for_tma_restrictions` can add a copy of the default config; a `unique_configs` pass drops it. Coordinate-descent tuning, which also tunes XBLOCK by timing, is turned off for pointwise kernels in deterministic mode, as it already is for reductions. Foreach kernels, which time `num_warps` under max-autotune, keep their single `num_warps=8` config in deterministic mode. The `may_ban_benchmarking` message no longer lists pointwise config autotuning as an example of safe benchmarking.

The new test exposed a test-isolation bug: `test_cumsum_deterministic` turned on `torch.use_deterministic_algorithms`, which also sets `inductor_config.deterministic`, and never turned it off, so `test_pointwise_coordesc_tuning` ran in deterministic mode. It now restores both settings with `DeterministicGuard` and `inductor_config.patch`.

Alternatives considered:
- Pass `autotune_pointwise`, `max_autotune` and `max_autotune_pointwise` as off to the heuristic. This relies on every heuristic checking those flags, and the XPU 3D path does not.
- Return the default config from inside `PointwiseHeuristic.get_configs`. A registered heuristic that does not inherit that method would skip the guard without any error.
- Keep the first generated config. This relies on the list order, which nothing guarantees.
- Disable FMA contraction (`enable_fp_fusion=False`) in deterministic mode. This makes all configs bit-equivalent, but slows every kernel and changes numerics compared with normal compiles.

Only deterministic mode changes: its pointwise kernels now always use the heuristic's default config, the one used when pointwise autotuning is off. Not covered: combo kernels with per-subkernel blocks (`combo_kernel_per_subkernel_blocks`, off by default), which run their own block-size tuning.

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

Test Plan:
New and changed tests in `test/inductor/test_deterministic.py`:
- `test_pointwise_autotuning` (deterministic on and off) compiles the kernel above twice, with `CachingAutotuner.bench` patched so the first compile prefers XBLOCK=128 and the second XBLOCK=256, and with coordinate descent on. Deterministic: nothing is timed, coordinate descent does not run, and the two outputs are bitwise equal. Off: configs are timed and coordinate descent runs.
- `test_foreach_autotuning` (deterministic on and off) compiles `torch._foreach_add` under max-autotune and counts timed foreach configs: none in deterministic mode, some otherwise.
- `test_pointwise_deterministic_uses_default_config` calls `pointwise()` with a heuristic that subclasses `CodegenConfigHeuristics` directly and returns two configs. Deterministic mode returns only its default config; with TMA restrictions the duplicate copy is dropped; a heuristic without `get_default_config` raises `NotImplementedError`.
- `test_pointwise_heuristic_default_config` (CUDA, ROCm and XPU heuristics, 1D/2D/3D): `get_default_config` returns XBLOCK=`bs`, 32x32 or 16x16x16; with `autotune_pointwise=False`, `get_configs` returns exactly that config (the XPU 3D path still returns all its configs); more than 3 dimensions raises. It records configs instead of building them, so it needs no ROCm or XPU hardware.

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

Ran on one H100 from Meta's internal build of these files (the commands above are the OSS equivalent):
- `test_deterministic.py`: 49 tests OK, 24 skipped (`test_run2run_determinism`, skipped in that build). `test_coordinate_descent_tuner.py`: 27 tests OK.
- Without the deterministic branch in `pointwise()`: `test_pointwise_autotuning_deterministic_True` and `test_pointwise_deterministic_uses_default_config` fail.
- Without the `unique_configs` pass: the TMA check fails (2 configs instead of 1).
- With the ROCm 2D autotune-off branch changed to return a different config: its `test_pointwise_heuristic_default_config` case fails.
- Without the foreach change: `test_foreach_autotuning_deterministic_True` fails.
- Without the coordinate-descent change: `test_pointwise_autotuning_deterministic_True` fails, because coordinate descent times configs.
- Without the cumsum fix: `test_pointwise_coordesc_tuning` fails.

Numerics repro with deterministic mode off, run on H100 as a temporary test with this body:

```python
def fn(x, buf):
    return x / x.shape[0] * 0.01 + buf * 0.99

x, buf = torch.randn(16384, device="cuda"), torch.randn(16384, device="cuda")
outs = []
for prefer_small in (True, False):  # timing picks XBLOCK=128, then XBLOCK=256
    def bench(self, launcher, *args, **kwargs):
        xblock = launcher.config.kwargs["XBLOCK"]
        return xblock if prefer_small else 1 / xblock
    torch._dynamo.reset()
    with fresh_cache(), unittest.mock.patch.object(CachingAutotuner, "bench", bench):
        outs.append(torch.compile(fn, dynamic=True)(x, buf))
print((outs[0].view(torch.int32) != outs[1].view(torch.int32)).sum())
```

Result: 4042 of 16384 outputs differ. The PTX of the XBLOCK=128 kernel has one FMA per thread, fusing the `0.01` product; the XBLOCK=256 kernel has two, both fusing the `0.99` product.

Differential Revision: D127104145
dmdok added a commit to dmdok/pytorch that referenced this pull request Oct 28, 2026
…pytorch#202218)

Summary:

**Problem**

Deterministic mode (`TORCHINDUCTOR_DETERMINISTIC=1`, also turned on by `batch_invariant` and `torch.use_deterministic_algorithms`) skips on-device benchmarking that can change numerics. Reductions already get a single config there, but pointwise kernels still pick their config by timing. With `triton.autotune_pointwise=True` (the default), a 1D pointwise kernel gets two candidate configs, XBLOCK=256 and XBLOCK=128; `CachingAutotuner` times both at the first launch and keeps the faster one. Timing is noisy, so different processes can keep different configs.

The config changes the result. For `x / B * 0.01 + buf * 0.99` with a dynamic `B`, the two configs compile to PTX that fuses a different product into the FMA (on H100):
- XBLOCK=128: `fma(x/B, 0.01, buf*0.99)`
- XBLOCK=256: `fma(buf, 0.99, (x/B)*0.01)`

They round differently, and 4042 of 16384 outputs differ in the last bits.

**How this was found**

We need bit-exact, reproducible training runs, so we train with deterministic mode on. Two identical runs of a 64-GPU training job still diverged within the first steps.
- The first tensor that differed between the runs was a buffer updated by one Inductor pointwise kernel, the `x / B * 0.01 + buf * 0.99` update above with a dynamic batch size `B`. All of the kernel's inputs were bit-identical.
- On 8 A100s, each GPU's autotuner kept XBLOCK=256 or XBLOCK=128 depending on timing, differently from run to run, and the outputs split into two groups that matched the XBLOCK each GPU kept.
- With `triton.autotune_pointwise=False`, all 8 GPUs matched bit for bit.

Turning pointwise autotuning off globally works around it, but deterministic mode exists to avoid benchmarking that changes numerics, so it should cover this itself, without users having to know which autotuning settings change numerics.

**Fix**

In deterministic mode, `pointwise()` in `triton_heuristics.py` asks the device's heuristic for its default config (`get_default_config`) instead of its config list, the same place reductions enforce determinism. The default is the config `PointwiseHeuristic` already uses when pointwise autotuning is off; the CUDA, ROCm and XPU heuristics all inherit it, which also covers the XPU 3D path that ignores the autotune flags. `get_default_config` is part of the `CodegenConfigHeuristics` contract and raises `NotImplementedError` by default, so a registered heuristic that does not define it fails loudly in deterministic mode instead of timing configs. When TMA restrictions apply, `_maybe_filter_configs_for_tma_restrictions` can add a copy of the default config; a `unique_configs` pass drops it.

The other paths that pick a config by timing are closed the same way. Coordinate-descent tuning, which also tunes XBLOCK by timing, is turned off for pointwise kernels in deterministic mode, as it already is for reductions. Foreach kernels, which time `num_warps` under max-autotune, keep their single `num_warps=8` config. The `may_ban_benchmarking` message no longer lists pointwise config autotuning as an example of safe benchmarking.

The new test exposed a test-isolation bug: `test_cumsum_deterministic` turned on `torch.use_deterministic_algorithms`, which also sets `inductor_config.deterministic`, and never turned it off, so `test_pointwise_coordesc_tuning` ran in deterministic mode. It now restores both settings with `DeterministicGuard` and `inductor_config.patch`.

**Alternatives considered**
- Pass `autotune_pointwise`, `max_autotune` and `max_autotune_pointwise` as off to the heuristic. This relies on every heuristic checking those flags, and the XPU 3D path does not.
- Return the default config from inside `PointwiseHeuristic.get_configs`. A registered heuristic that does not inherit that method would skip the guard without any error.
- Keep the first generated config. This relies on the list order, which nothing guarantees.
- Disable FMA contraction (`enable_fp_fusion=False`) in deterministic mode. This makes all configs bit-equivalent, but slows every kernel and changes numerics compared with normal compiles.

**Scope**

Only deterministic mode changes: its pointwise kernels now always use the heuristic's default config, the one used when pointwise autotuning is off. Not covered: combo kernels with per-subkernel blocks (`combo_kernel_per_subkernel_blocks`, off by default), which run their own block-size tuning.

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

Test Plan:
New and changed tests in `test/inductor/test_deterministic.py`:
- `test_pointwise_autotuning` (deterministic on and off) compiles the kernel above twice, with `CachingAutotuner.bench` patched so the first compile prefers XBLOCK=128 and the second XBLOCK=256, and with coordinate descent on. Deterministic: nothing is timed, coordinate descent does not run, and the two outputs are bitwise equal. Off: configs are timed and coordinate descent runs.
- `test_foreach_autotuning` (deterministic on and off) compiles `torch._foreach_add` under max-autotune and counts timed foreach configs: none in deterministic mode, some otherwise.
- `test_pointwise_deterministic_uses_default_config` calls `pointwise()` with a heuristic that subclasses `CodegenConfigHeuristics` directly and returns two configs. Deterministic mode returns only its default config; with TMA restrictions the duplicate copy is dropped; a heuristic without `get_default_config` raises `NotImplementedError`.
- `test_pointwise_heuristic_default_config` (CUDA, ROCm and XPU heuristics, 1D/2D/3D): `get_default_config` returns XBLOCK=`bs`, 32x32 or 16x16x16; with `autotune_pointwise=False`, `get_configs` returns exactly that config (the XPU 3D path still returns all its configs); more than 3 dimensions raises. It records configs instead of building them, so it needs no ROCm or XPU hardware.

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

Ran on one H100 from Meta's internal build of these files (the commands above are the OSS equivalent):
- `test_deterministic.py`: 49 tests OK, 24 skipped (`test_run2run_determinism`, skipped in that build). `test_coordinate_descent_tuner.py`: 27 tests OK.
- Without the deterministic branch in `pointwise()`: `test_pointwise_autotuning_deterministic_True` and `test_pointwise_deterministic_uses_default_config` fail.
- Without the `unique_configs` pass: the TMA check fails (2 configs instead of 1).
- With the ROCm 2D autotune-off branch changed to return a different config: its `test_pointwise_heuristic_default_config` case fails.
- Without the foreach change: `test_foreach_autotuning_deterministic_True` fails.
- Without the coordinate-descent change: `test_pointwise_autotuning_deterministic_True` fails, because coordinate descent times configs.
- Without the cumsum fix: `test_pointwise_coordesc_tuning` fails.

Numerics repro with deterministic mode off, run on H100 as a temporary test with this body:

```python
def fn(x, buf):
    return x / x.shape[0] * 0.01 + buf * 0.99

x, buf = torch.randn(16384, device="cuda"), torch.randn(16384, device="cuda")
outs = []
for prefer_small in (True, False):  # timing picks XBLOCK=128, then XBLOCK=256
    def bench(self, launcher, *args, **kwargs):
        xblock = launcher.config.kwargs["XBLOCK"]
        return xblock if prefer_small else 1 / xblock
    torch._dynamo.reset()
    with fresh_cache(), unittest.mock.patch.object(CachingAutotuner, "bench", bench):
        outs.append(torch.compile(fn, dynamic=True)(x, buf))
print((outs[0].view(torch.int32) != outs[1].view(torch.int32)).sum())
```

Result: 4042 of 16384 outputs differ. The PTX of the XBLOCK=128 kernel has one FMA per thread, fusing the `0.01` product; the XBLOCK=256 kernel has two, both fusing the `0.99` product.

Differential Revision: D127104145
@dmdok
dmdok force-pushed the export-D127104145 branch from 6a81cf5 to ff3f3a8 Compare October 28, 2026 05:54
@meta-codesync meta-codesync Bot changed the title [inductor] Fix deterministic mode picking pointwise configs by timing (#202218) [inductor] Add triton.enable_fp_fusion flag to turn off FMA contraction (#202218) Nov 1, 2026
@dmdok
dmdok force-pushed the export-D127104145 branch from ff3f3a8 to b9a591c Compare November 1, 2026 06:21
dmdok added a commit to dmdok/pytorch that referenced this pull request Nov 1, 2026
…on (pytorch#202218)

Summary:

**Problem**

The same Inductor kernel can produce different bits depending on which config autotuning picks. With `triton.autotune_pointwise=True` (the default), a 1D pointwise kernel gets two candidate configs, XBLOCK=256 and XBLOCK=128; `CachingAutotuner` times both at the first launch and keeps the faster one. Timing is noisy, so different processes can keep different configs. Deterministic mode (`TORCHINDUCTOR_DETERMINISTIC=1`) does not prevent this: it pins reduction configs, but pointwise kernels still pick their config by timing.

The config changes the result because Triton contracts multiply-adds into FMAs (one rounding instead of two), and which products it fuses depends on the block size. For `x / B * 0.01 + buf * 0.99` with a dynamic `B`, the two configs compile to (on H100):
- XBLOCK=128: `fma(x/B, 0.01, buf*0.99)`
- XBLOCK=256: `fma(buf, 0.99, (x/B)*0.01)`

They round differently, and 4042 of 16384 outputs differ in the last bits.

**How this was found**

We need bit-exact, reproducible training runs, so we train with deterministic mode on. Two identical runs of a 64-GPU training job still diverged within the first steps.
- The first tensor that differed between the runs was a buffer updated by one Inductor pointwise kernel, the `x / B * 0.01 + buf * 0.99` update above with a dynamic batch size `B`. All of the kernel's inputs were bit-identical.
- On 8 A100s, each GPU's autotuner kept XBLOCK=256 or XBLOCK=128 depending on timing, differently from run to run, and the outputs split into two groups that matched the XBLOCK each GPU kept.
- With `triton.autotune_pointwise=False`, all 8 GPUs matched bit for bit.

Turning autotuning off works around it, but only removes timing as the source of variation: results still depend on the config, so a different tensor size or tuning path can still change the bits. Turning FMA contraction off removes the dependence on the config itself.

**Fix**

Add `config.triton.enable_fp_fusion` (env `TORCHINDUCTOR_ENABLE_FP_FUSION`), on by default. When it is off, `triton_meta_common` compiles Inductor's generated Triton kernels with Triton's `enable_fp_fusion=False`, so every multiply and add rounds separately and the result no longer depends on the block size or `num_warps`, whichever path picks them: autotuning by timing, coordinate descent, or the default heuristic for a given tensor size. `emulate_precision_casts` sets the same compile option and still turns FMA off as before.

Why a separate flag:
- Deterministic mode itself is unchanged, for backward compatibility. `torch.use_deterministic_algorithms(True)` also turns it on, so tying FMA to it would shift numerics and slow kernels for every job that calls it.
- `emulate_precision_casts` already turns FMA off, but it also keeps bf16/fp16 intermediates rounded like eager, uses CUDA's libdevice instead of Triton's, and blocks some cast-removal rewrites. Bitwise reproducibility across configs only needs FMA off.

**Alternatives considered**
- Pin each pointwise kernel's config in deterministic mode (an earlier version of this change). That removes timing as a source of variation, but results still depend on the config: the default XBLOCK depends on the tensor size, and every tuning path needs its own guard.
- Turn FMA off whenever deterministic mode is on. That changes numerics and speed for every `torch.use_deterministic_algorithms` caller.
- Turn FMA off by default. That changes numerics and speed for all users; with this flag it becomes a default change if measurements support it.

**Scope**

Behavior changes only when the flag is off. Like `emulate_precision_casts`, the flag applies through `triton_meta_common` to Inductor's generated pointwise, reduction, foreach and combo kernels; template kernels (`select_algorithm`) keep their current option. The speed cost of turning FMA off is not measured here.

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

Test Plan:
New tests in `test/inductor/test_deterministic.py`:
- `test_fp_fusion` (flag on and off, deterministic mode on and off): the generated Triton code has `'enable_fp_fusion': False` only when the flag is off. Deterministic mode alone keeps FMA contraction.
- `test_pointwise_config_numerics` (flag off, deterministic mode on): compiles the kernel above twice, with `CachingAutotuner.bench` patched so timing picks XBLOCK=128 the first time and XBLOCK=256 the second. It checks that two different XBLOCKs were picked and that the outputs are bitwise equal.

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

Ran from Meta's internal build of this file on a remote A100 (the command above is the OSS equivalent):
- With the change: 15 tests passed, 26 skipped (`test_run2run_determinism`, skipped in that build, and `test_max_autotune`, which needs a larger GPU).
- With `triton_meta_common` ignoring the flag: `test_pointwise_config_numerics` fails (4042 of 16384 outputs differ) and both flag-off cases of `test_fp_fusion` fail.

The two FMA forms above come from the PTX of the two kernels on H100: the XBLOCK=128 kernel has one FMA per thread, fusing the `0.01` product; the XBLOCK=256 kernel has two, both fusing the `0.99` product.

Differential Revision: D127104145
@pytorch-bot pytorch-bot Bot added the ciflow/trunk Trigger trunk jobs on your pull request label Nov 1, 2026
…on (pytorch#202218)

Summary:

**Problem**

The same Inductor kernel can produce different bits depending on which config autotuning picks. With `triton.autotune_pointwise=True` (the default), a 1D pointwise kernel gets two candidate configs, XBLOCK=256 and XBLOCK=128; `CachingAutotuner` times both at the first launch and keeps the faster one. Timing is noisy, so different processes can keep different configs. Deterministic mode (`TORCHINDUCTOR_DETERMINISTIC=1`) does not prevent this: it pins reduction configs, but pointwise kernels still pick their config by timing.

The config changes the result because Triton contracts multiply-adds into FMAs (one rounding instead of two), and which products it fuses depends on the block size. For `x / B * 0.01 + buf * 0.99` with a dynamic `B`, the two configs compile to (on H100):
- XBLOCK=128: `fma(x/B, 0.01, buf*0.99)`
- XBLOCK=256: `fma(buf, 0.99, (x/B)*0.01)`

They round differently, and 4042 of 16384 outputs differ in the last bits.

**How this was found**

We need bit-exact, reproducible training runs, so we train with deterministic mode on. Two identical runs of a 64-GPU training job still diverged within the first steps.
- The first tensor that differed between the runs was a buffer updated by one Inductor pointwise kernel, the `x / B * 0.01 + buf * 0.99` update above with a dynamic batch size `B`. All of the kernel's inputs were bit-identical.
- On 8 A100s, each GPU's autotuner kept XBLOCK=256 or XBLOCK=128 depending on timing, differently from run to run, and the outputs split into two groups that matched the XBLOCK each GPU kept.
- With `triton.autotune_pointwise=False`, all 8 GPUs matched bit for bit.

Turning autotuning off works around it, but only removes timing as the source of variation: results still depend on the config, so a different tensor size or tuning path can still change the bits. Turning FMA contraction off removes the dependence on the config itself.

**Fix**

Add `config.triton.enable_fp_fusion` (env `TORCHINDUCTOR_ENABLE_FP_FUSION`), on by default. When it is off, `triton_meta_common` compiles Inductor's generated Triton kernels with Triton's `enable_fp_fusion=False`, so every multiply and add rounds separately and the result no longer depends on the block size or `num_warps`, whichever path picks them: autotuning by timing, coordinate descent, or the default heuristic for a given tensor size. `emulate_precision_casts` sets the same compile option and still turns FMA off as before.

Why a separate flag:
- Deterministic mode itself is unchanged, for backward compatibility. `torch.use_deterministic_algorithms(True)` also turns it on, so tying FMA to it would shift numerics and slow kernels for every job that calls it.
- `emulate_precision_casts` already turns FMA off, but it also keeps bf16/fp16 intermediates rounded like eager, uses CUDA's libdevice instead of Triton's, and blocks some cast-removal rewrites. Bitwise reproducibility across configs only needs FMA off.

**Alternatives considered**
- Pin each pointwise kernel's config in deterministic mode (an earlier version of this change). That removes timing as a source of variation, but results still depend on the config: the default XBLOCK depends on the tensor size, and every tuning path needs its own guard.
- Turn FMA off whenever deterministic mode is on. That changes numerics and speed for every `torch.use_deterministic_algorithms` caller.
- Turn FMA off by default. That changes numerics and speed for all users; with this flag it becomes a default change if measurements support it.

**Scope**

Behavior changes only when the flag is off. Like `emulate_precision_casts`, the flag applies through `triton_meta_common` to Inductor's generated pointwise, reduction, foreach and combo kernels; template kernels (`select_algorithm`) keep their current option. The speed cost of turning FMA off is not measured here.

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

Test Plan:
New tests in `test/inductor/test_deterministic.py`:
- `test_fp_fusion` (flag on and off, deterministic mode on and off): the generated Triton code has `'enable_fp_fusion': False` only when the flag is off. Deterministic mode alone keeps FMA contraction.
- `test_pointwise_config_numerics` (flag off, deterministic mode on): compiles the kernel above twice, with `CachingAutotuner.bench` patched so timing picks XBLOCK=128 the first time and XBLOCK=256 the second. It checks that two different XBLOCKs were picked and that the outputs are bitwise equal.

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

Ran from Meta's internal build of this file on a remote A100 (the command above is the OSS equivalent):
- With the change: 15 tests passed, 26 skipped (`test_run2run_determinism`, skipped in that build, and `test_max_autotune`, which needs a larger GPU).
- With `triton_meta_common` ignoring the flag: `test_pointwise_config_numerics` fails (4042 of 16384 outputs differ) and both flag-off cases of `test_fp_fusion` fail.

The two FMA forms above come from the PTX of the two kernels on H100: the XBLOCK=128 kernel has one FMA per thread, fusing the `0.01` product; the XBLOCK=256 kernel has two, both fusing the `0.99` product.

Reviewed By: eellison, jansel

Differential Revision: D127104145
@dmdok
dmdok force-pushed the export-D127104145 branch from b9a591c to b39d110 Compare November 1, 2026 20:22
@meta-codesync

meta-codesync Bot commented Nov 1, 2026

Copy link
Copy Markdown

@pytorchbot merge

(Initiating merge automatically since Phabricator Diff has merged)

@pytorchmergebot

Copy link
Copy Markdown
Collaborator

Adding the topic: not user facing label automatically: this co-dev PR is being merged after its internal diff landed, without a release-notes label. If this change is user facing, please replace the label with the appropriate release notes: ... one.

@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

@pytorchmergebot

Copy link
Copy Markdown
Collaborator

Merge failed

Reason: 1 jobs have failed, first few of them are: trunk / macos-py3-arm64 / test (default, 3, 3, macos-m1-stable)

Details for Dev Infra team

Raised by workflow job

@huydhn

huydhn commented Nov 2, 2026

Copy link
Copy Markdown
Contributor

@pytorchbot merge -i

@pytorchmergebot

Copy link
Copy Markdown
Collaborator

Merge started

Your change will be merged while ignoring the following 1 checks: trunk / macos-py3-arm64 / test (default, 3, 3, macos-m1-stable)

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

dominikjastrzebskix pushed a commit to dominikjastrzebskix/pytorch that referenced this pull request Nov 5, 2026
…on (pytorch#202218) (pytorch#202218)

Summary:

**Problem**

The same Inductor kernel can produce different bits depending on which config autotuning picks. With `triton.autotune_pointwise=True` (the default), a 1D pointwise kernel gets two candidate configs, XBLOCK=256 and XBLOCK=128; `CachingAutotuner` times both at the first launch and keeps the faster one. Timing is noisy, so different processes can keep different configs. Deterministic mode (`TORCHINDUCTOR_DETERMINISTIC=1`) does not prevent this: it pins reduction configs, but pointwise kernels still pick their config by timing.

The config changes the result because Triton contracts multiply-adds into FMAs (one rounding instead of two), and which products it fuses depends on the block size. For `x / B * 0.01 + buf * 0.99` with a dynamic `B`, the two configs compile to (on H100):
- XBLOCK=128: `fma(x/B, 0.01, buf*0.99)`
- XBLOCK=256: `fma(buf, 0.99, (x/B)*0.01)`

They round differently, and 4042 of 16384 outputs differ in the last bits.

**How this was found**

We need bit-exact, reproducible training runs, so we train with deterministic mode on. Two identical runs of a 64-GPU training job still diverged within the first steps.
- The first tensor that differed between the runs was a buffer updated by one Inductor pointwise kernel, the `x / B * 0.01 + buf * 0.99` update above with a dynamic batch size `B`. All of the kernel's inputs were bit-identical.
- On 8 A100s, each GPU's autotuner kept XBLOCK=256 or XBLOCK=128 depending on timing, differently from run to run, and the outputs split into two groups that matched the XBLOCK each GPU kept.
- With `triton.autotune_pointwise=False`, all 8 GPUs matched bit for bit.

Turning autotuning off works around it, but only removes timing as the source of variation: results still depend on the config, so a different tensor size or tuning path can still change the bits. Turning FMA contraction off removes the dependence on the config itself.

**Fix**

Add `config.triton.enable_fp_fusion` (env `TORCHINDUCTOR_ENABLE_FP_FUSION`), on by default. When it is off, `triton_meta_common` compiles Inductor's generated Triton kernels with Triton's `enable_fp_fusion=False`, so every multiply and add rounds separately and the result no longer depends on the block size or `num_warps`, whichever path picks them: autotuning by timing, coordinate descent, or the default heuristic for a given tensor size. `emulate_precision_casts` sets the same compile option and still turns FMA off as before.

Why a separate flag:
- Deterministic mode itself is unchanged, for backward compatibility. `torch.use_deterministic_algorithms(True)` also turns it on, so tying FMA to it would shift numerics and slow kernels for every job that calls it.
- `emulate_precision_casts` already turns FMA off, but it also keeps bf16/fp16 intermediates rounded like eager, uses CUDA's libdevice instead of Triton's, and blocks some cast-removal rewrites. Bitwise reproducibility across configs only needs FMA off.

**Alternatives considered**
- Pin each pointwise kernel's config in deterministic mode (an earlier version of this change). That removes timing as a source of variation, but results still depend on the config: the default XBLOCK depends on the tensor size, and every tuning path needs its own guard.
- Turn FMA off whenever deterministic mode is on. That changes numerics and speed for every `torch.use_deterministic_algorithms` caller.
- Turn FMA off by default. That changes numerics and speed for all users; with this flag it becomes a default change if measurements support it.

**Scope**

Behavior changes only when the flag is off. Like `emulate_precision_casts`, the flag applies through `triton_meta_common` to Inductor's generated pointwise, reduction, foreach and combo kernels; template kernels (`select_algorithm`) keep their current option. The speed cost of turning FMA off is not measured here.

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

Test Plan:
New tests in `test/inductor/test_deterministic.py`:
- `test_fp_fusion` (flag on and off, deterministic mode on and off): the generated Triton code has `'enable_fp_fusion': False` only when the flag is off. Deterministic mode alone keeps FMA contraction.
- `test_pointwise_config_numerics` (flag off, deterministic mode on): compiles the kernel above twice, with `CachingAutotuner.bench` patched so timing picks XBLOCK=128 the first time and XBLOCK=256 the second. It checks that two different XBLOCKs were picked and that the outputs are bitwise equal.

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

Ran from Meta's internal build of this file on a remote A100 (the command above is the OSS equivalent):
- With the change: 15 tests passed, 26 skipped (`test_run2run_determinism`, skipped in that build, and `test_max_autotune`, which needs a larger GPU).
- With `triton_meta_common` ignoring the flag: `test_pointwise_config_numerics` fails (4042 of 16384 outputs differ) and both flag-off cases of `test_fp_fusion` fail.

The two FMA forms above come from the PTX of the two kernels on H100: the XBLOCK=128 kernel has one FMA per thread, fusing the `0.01` product; the XBLOCK=256 kernel has two, both fusing the `0.99` product.

Reviewed By: eellison, jansel

Differential Revision: D127104145

Pull Request resolved: pytorch#202218
Approved by: https://github.com/jansel
dominikjastrzebskix pushed a commit to dominikjastrzebskix/pytorch that referenced this pull request Nov 9, 2026
…on (pytorch#202218) (pytorch#202218)

Summary:

**Problem**

The same Inductor kernel can produce different bits depending on which config autotuning picks. With `triton.autotune_pointwise=True` (the default), a 1D pointwise kernel gets two candidate configs, XBLOCK=256 and XBLOCK=128; `CachingAutotuner` times both at the first launch and keeps the faster one. Timing is noisy, so different processes can keep different configs. Deterministic mode (`TORCHINDUCTOR_DETERMINISTIC=1`) does not prevent this: it pins reduction configs, but pointwise kernels still pick their config by timing.

The config changes the result because Triton contracts multiply-adds into FMAs (one rounding instead of two), and which products it fuses depends on the block size. For `x / B * 0.01 + buf * 0.99` with a dynamic `B`, the two configs compile to (on H100):
- XBLOCK=128: `fma(x/B, 0.01, buf*0.99)`
- XBLOCK=256: `fma(buf, 0.99, (x/B)*0.01)`

They round differently, and 4042 of 16384 outputs differ in the last bits.

**How this was found**

We need bit-exact, reproducible training runs, so we train with deterministic mode on. Two identical runs of a 64-GPU training job still diverged within the first steps.
- The first tensor that differed between the runs was a buffer updated by one Inductor pointwise kernel, the `x / B * 0.01 + buf * 0.99` update above with a dynamic batch size `B`. All of the kernel's inputs were bit-identical.
- On 8 A100s, each GPU's autotuner kept XBLOCK=256 or XBLOCK=128 depending on timing, differently from run to run, and the outputs split into two groups that matched the XBLOCK each GPU kept.
- With `triton.autotune_pointwise=False`, all 8 GPUs matched bit for bit.

Turning autotuning off works around it, but only removes timing as the source of variation: results still depend on the config, so a different tensor size or tuning path can still change the bits. Turning FMA contraction off removes the dependence on the config itself.

**Fix**

Add `config.triton.enable_fp_fusion` (env `TORCHINDUCTOR_ENABLE_FP_FUSION`), on by default. When it is off, `triton_meta_common` compiles Inductor's generated Triton kernels with Triton's `enable_fp_fusion=False`, so every multiply and add rounds separately and the result no longer depends on the block size or `num_warps`, whichever path picks them: autotuning by timing, coordinate descent, or the default heuristic for a given tensor size. `emulate_precision_casts` sets the same compile option and still turns FMA off as before.

Why a separate flag:
- Deterministic mode itself is unchanged, for backward compatibility. `torch.use_deterministic_algorithms(True)` also turns it on, so tying FMA to it would shift numerics and slow kernels for every job that calls it.
- `emulate_precision_casts` already turns FMA off, but it also keeps bf16/fp16 intermediates rounded like eager, uses CUDA's libdevice instead of Triton's, and blocks some cast-removal rewrites. Bitwise reproducibility across configs only needs FMA off.

**Alternatives considered**
- Pin each pointwise kernel's config in deterministic mode (an earlier version of this change). That removes timing as a source of variation, but results still depend on the config: the default XBLOCK depends on the tensor size, and every tuning path needs its own guard.
- Turn FMA off whenever deterministic mode is on. That changes numerics and speed for every `torch.use_deterministic_algorithms` caller.
- Turn FMA off by default. That changes numerics and speed for all users; with this flag it becomes a default change if measurements support it.

**Scope**

Behavior changes only when the flag is off. Like `emulate_precision_casts`, the flag applies through `triton_meta_common` to Inductor's generated pointwise, reduction, foreach and combo kernels; template kernels (`select_algorithm`) keep their current option. The speed cost of turning FMA off is not measured here.

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

Test Plan:
New tests in `test/inductor/test_deterministic.py`:
- `test_fp_fusion` (flag on and off, deterministic mode on and off): the generated Triton code has `'enable_fp_fusion': False` only when the flag is off. Deterministic mode alone keeps FMA contraction.
- `test_pointwise_config_numerics` (flag off, deterministic mode on): compiles the kernel above twice, with `CachingAutotuner.bench` patched so timing picks XBLOCK=128 the first time and XBLOCK=256 the second. It checks that two different XBLOCKs were picked and that the outputs are bitwise equal.

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

Ran from Meta's internal build of this file on a remote A100 (the command above is the OSS equivalent):
- With the change: 15 tests passed, 26 skipped (`test_run2run_determinism`, skipped in that build, and `test_max_autotune`, which needs a larger GPU).
- With `triton_meta_common` ignoring the flag: `test_pointwise_config_numerics` fails (4042 of 16384 outputs differ) and both flag-off cases of `test_fp_fusion` fail.

The two FMA forms above come from the PTX of the two kernels on H100: the XBLOCK=128 kernel has one FMA per thread, fusing the `0.01` product; the XBLOCK=256 kernel has two, both fusing the `0.99` product.

Reviewed By: eellison, jansel

Differential Revision: D127104145

Pull Request resolved: pytorch#202218
Approved by: https://github.com/jansel
eellison added a commit that referenced this pull request Nov 12, 2026
…explicit FMAs

**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. It was kept separate because `torch.use_deterministic_algorithms(True)` also turns deterministic mode on, and turning FMA off slows some kernels.

**Change**

- Deterministic mode (and `batch_invariant`) now compiles Inductor's generated Triton kernels with `enable_fp_fusion=False` (`triton_fp_fusion_enabled()` in `utils.py`, used by `triton_meta_common`).
- To keep most of the speed, Inductor contracts multiply-adds itself, choosing them from the graph instead of the config:
  - New LoopBody pass `form_explicit_fmas` (`optimize_loop_body.py`): rewrites a float32/float64 `add`/`sub` whose operand is a `mul` in the same loop body into `ops.fma` (`tl.fma`): `a*b + c -> fma(a, b, c)`, `a*b - c -> fma(a, b, -c)`, `c - a*b -> fma(-a, b, c)`. Dtypes come from running `DtypePropagationOpsHandler` over the body (its `masked` rule is fixed in the previous PR, so e.g. an int64 pointwise cat is not mistaken for a float). `x - y` where codegen's CSE would give `x` and `y` one variable is left alone, so it stays exactly 0 as `TritonOverrides.sub` makes it today. Tracing does not deduplicate, so this compares what the nodes compute: the same op on equal operands, with each traced copy of a `masked` body (e.g. from `pad` or `cat`) compared by its graph, and each copy of an indirect index (e.g. from a gather) by the value it comes from. Forms that default mode does not keep at 0 either (checked in the PTX: `x*y - y*x`, `x*y + -(x*y)`, `(a*b + c*d) - (c*d + a*b)`, which Triton contracts there) can get an FMA. It runs once in `ComputedBuffer.get_default_sizes_body` for buffers on a Triton backend; later bodies are copies and keep the rewrite.
  - `ValueRangeAnalysis` gets an `fma` rule (`add(mul(a, b), c)`), so float index math that became an `fma` keeps its bounds.
  - `triton_helpers` use `tl.fma` for their multiply-adds: `welford_reduce`, `welford_combine`, `online_softmax_combine(_with_sum)`, and `rand_eager_kernel` (whose eager CUDA counterpart uses an FMA). This applies in every mode. With contraction on, Triton could already contract these, and they time the same as before on the affected kernels. The last bit can still change in default mode where Triton contracted differently: e.g. in `online_softmax_combine_with_sum` (`a*b + c*d`), the explicit FMA fuses the first product, and Triton might have fused the second. Under `emulate_precision_casts` (contraction off) they now use an FMA, closer to the eager CUDA kernels, which nvcc compiles with contraction on.
  - The LoopBody pass runs whenever Triton's contraction is off (deterministic mode, `batch_invariant`, or `triton.enable_fp_fusion=False`), except under `emulate_precision_casts`. So `triton.enable_fp_fusion=False` / `TORCHINDUCTOR_ENABLE_FP_FUSION=0` now gives config-independent explicit FMAs rather than no FMAs.
- Templates (matmul, flex attention) keep Triton's contraction: they build their own `triton_meta`, and deterministic mode already picks their config without benchmarking. With `triton.enable_fp_fusion=False` alone, templates still autotune with contraction on, so their bits can still depend on the chosen config. fp32 `tl.dot(..., input_precision="ieee")` keeps its FMAs either way (Triton emits them explicitly). Epilogues fused into a template come from ComputedBuffers, so they get the explicit FMAs too, and Triton may contract the rest.

**Not covered** (contraction is off there, so results stay config-independent, just without an FMA):
- a multiply and add in different fused nodes, or inside `masked` subblocks;
- reduction accumulators (`acc + x*y` in a looped `sum`) and `tl.sum(x*y)` trees;
- the template's own code, e.g. flex attention's `score_mod` (Triton's contraction stays on there).

**Performance**

better-benchmark (1724 kernels from torchbench/HF/timm, default shape each), H100, 2026-11-02 nightly, clocks locked, deterministic mode on for every compile (`torch.use_deterministic_algorithms(True, warn_only=True)` in each worker). Geomean of kernel time:

| | geomean | median |
|---|---|---|
| this PR vs. the online-softmax PR below it | -0.07% | -0.01% |
| same, with `form_explicit_fmas` disabled (contraction off, no explicit FMAs) | +0.25% | +0.11% |
| whole stack vs. today's deterministic mode | -0.29% | -0.04% |

Two sweeps of the same code differ by about 0.14% geomean (and about 40 kernels each way by more than 5%), so these are close to the noise. Turning contraction off costs about 0.25%, and the explicit FMAs recover it; no single kernel got reproducibly faster from them. Outside deterministic mode the stack is neutral (+0.03% geomean).

Slower in every rerun (at least three runs each):

| kernel | before (us) | after (us) | |
|---|---|---|---|
| `amax_sum_c372431bff28` (softmax) | 28.0 | 38.4 | +37% |
| `amax_sum_13a9aaa2eadb` (softmax) | 28.0 | 36.8 | +31% |
| `var_mean_d0ae6f6e894f` (LayerNorm) | 33.3 | 37.0 | +11% |
| `sum_sum_sum_00a35e7a9bcb` | 68.2 | 74.5 | +9% |
| `amax_sum_cb8fc73675a3` | 275.4 | 292.1 | +6% |

These are small, latency-bound kernels, and the extra time is not the lost FMAs: the instruction counts barely change (softmax: the same 448 instructions, with 8 FFMAs replaced by FADDs; `var_mean`: 840 vs. 848), but ptxas schedules the global loads differently. For the softmax kernels, the trigger is LLVM's contraction being off; ptxas's `--fmad=false` makes no difference. For `var_mean_d0ae6f6e894f` and `sum_sum_sum_00a35e7a9bcb`, the trigger is the explicit `tl.fma` from the new pass: with the pass disabled and contraction off, `var_mean` times 33.5 us (34.2 us in a separate run), the same as today.

**Test plan**

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

- `test_fp_fusion`: `enable_fp_fusion` is off in the kernel's `triton_meta` in deterministic mode as well as with the flag off, and exactly then the kernel has `tl.fma`.
- `test_explicit_fma` (fp32, bf16): `p + z`, `p - z`, `z - p` each become one `tl.fma`; an integer multiply-add is left alone; results match.
- `test_pointwise_config_numerics` now runs both with deterministic mode alone and with the flag alone: forcing XBLOCK=128 vs 256 by timing gives bitwise-equal outputs.
- `test_form_explicit_fmas`: the LoopBody rewrite on a constant-only body (all three forms, integer skip, op counts). `test_form_explicit_fmas_skips`: `p - p` (same node, two identical nodes, and identical `masked` subblocks) and an integer coming out of `masked` with a float fill are left alone.
- `test_explicit_fma_skips`: in deterministic mode, `p - p.detach()`, also for products of a `pad`, a pointwise `cat` and a gather, is exactly 0, and an int64 pointwise cat multiply-add compiles and matches, without any `tl.fma`.
- `test_triton_helpers.py`: the expected `online_softmax_combine` sum is now computed with the same `tl.fma`, so it stays bitwise equal with `enable_fp_fusion=False`.
- Checked that the tests fail when the pass is disabled and when deterministic mode keeps Triton's contraction.
- `test_explicit_fma_welford`: a looped `var_mean` (multi-output welford reduction) compiles and matches.
- Ran on an H100 against the 2026-11-02 cu130 nightly (main at 42ab44e) with this stack applied:
  - `test_deterministic.py` passes, including two `test_run2run_determinism` cases (BertForMaskedLM inference fp32, DistillGPT2 training bf16). So do `test_optimize_loop_body.py`, `test_triton_helpers.py`, `test_op_dtype_prop.py`, and `test_max_autotune.py -k prologue`.
  - `test_online_softmax.py` passes with the default config and with `TORCHINDUCTOR_ENABLE_FP_FUSION=0`.
  - `test_torchinductor.py` GPU tests for cat, pad, masked, embedding, index, gather, welford, var_mean and softmax (478) pass with and without `TORCHINDUCTOR_ENABLE_FP_FUSION=0`, except two tests that also fail on the unpatched nightly (they use a config option the nightly does not have).
  - On an earlier revision of this PR, all of `test_torchinductor.py -k GPUTests` (1476 tests) passed with `TORCHINDUCTOR_ENABLE_FP_FUSION=0`, which runs the new pass and helpers everywhere.

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

ghstack-source-id: cd50b99
Pull-Request: #204322
eellison added a commit that referenced this pull request Nov 12, 2026
**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. It was kept separate because `torch.use_deterministic_algorithms(True)` also turns deterministic mode on, and turning FMA off slows some kernels.

**Change**

- Deterministic mode (and `batch_invariant`) now compiles Inductor's generated Triton kernels with `enable_fp_fusion=False` (`triton_fp_fusion_enabled()` in `utils.py`, used by `triton_meta_common`). Explicit FMAs (`tl.fma`, libdevice) are kept.
- `triton_helpers` use `tl.fma` for their multiply-adds: `welford_reduce`, `welford_combine`, `online_softmax_combine(_with_sum)`, and `rand_eager_kernel` (whose eager CUDA counterpart uses an FMA). These are fixed expressions, the same for every config, so they keep their FMAs in deterministic mode; the eager CUDA kernels, which nvcc compiles with contraction on, have FMAs there too.
  - This applies in every mode. With contraction on, Triton could already contract these, and they time the same as before. The last bit can still change in default mode where Triton contracted differently: e.g. in `online_softmax_combine_with_sum` (`a*b + c*d`), the explicit FMA fuses the first product, and Triton might have fused the second. Under `emulate_precision_casts` (contraction off) they now use an FMA.
- Templates (matmul, flex attention) keep Triton's contraction: they build their own `triton_meta`, and deterministic mode already picks their config without benchmarking. With `triton.enable_fp_fusion=False` alone, templates still autotune with contraction on, so their bits can still depend on the chosen config. fp32 `tl.dot(..., input_precision="ieee")` keeps its FMAs either way (Triton emits them explicitly).

Multiply-adds in Inductor's generated code are not contracted in deterministic mode. Emitting explicit FMAs for them from the LoopBody (choosing them from the graph, not the config) recovered the cost below on average, but added a pass, value numbering for `x - x`, and a dtype-propagation fix, and made two kernels slower by changing how ptxas schedules their loads, so it is left out.

**Performance**

better-benchmark (1725 kernels from torchbench/HF/timm, default shape each), H100, 2026-11-02 nightly, clocks locked, deterministic mode on for every compile (`torch.use_deterministic_algorithms(True, warn_only=True)` in each worker). Geomean of kernel time:

| | geomean | median |
|---|---|---|
| this PR vs. the online-softmax PR below it | +0.25% (+0.38% with coordinate descent) | +0.11% |
| whole stack vs. today's deterministic mode | +0.03% | +0.10% |

Two sweeps of the same code differ by about 0.14% geomean (and about 40 kernels each way by more than 5%). Outside deterministic mode the stack is neutral (+0.03% geomean).

Slower or faster with contraction off in two separate sweeps (the first three also in at least three reruns):

| kernel | before (us) | after (us) | |
|---|---|---|---|
| `amax_sum_c372431bff28` (softmax) | 28.0 | 37.7 | +35% |
| `amax_sum_13a9aaa2eadb` (softmax) | 28.0 | 36.9 | +32% |
| `amax_sum_cb8fc73675a3` | 275.4 | 291.5 | +6% |
| `sum_sum_b50ad423ed16` | 661.8 | 714.5 | +8% |
| `amax_amax_any_99a4f19df20a` | 405.2 | 376.1 | -7% |
| `sum_sum_sum_28aca384bafa` | 252.9 | 238.2 | -6% |
| `sum_sum_3eee452cee40` | 1208.4 | 1143.7 | -5% |

The two softmax kernels are small and latency-bound, and the extra time is not the lost FMAs: the kernel has the same 448 instructions, with 8 FFMAs replaced by FADDs, but ptxas schedules the global loads differently. The trigger is LLVM's contraction being off; ptxas's `--fmad=false` makes no difference.

**Test plan**

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

- `test_fp_fusion`: `enable_fp_fusion` is off in the kernel's `triton_meta` in deterministic mode as well as with the flag off.
- `test_pointwise_config_numerics` now runs both with deterministic mode alone and with the flag alone: forcing XBLOCK=128 vs 256 by timing gives bitwise-equal outputs (they differ with contraction on).
- `test_triton_helpers.py`: the expected `online_softmax_combine` sum is now computed with the same `tl.fma`, so it stays bitwise equal with `enable_fp_fusion=False`.
- Ran on an H100 against the 2026-11-02 cu130 nightly (main at 42ab44e) with this stack applied: `test_deterministic.py` (including two `test_run2run_determinism` cases), `test_triton_helpers.py`, and `test_online_softmax.py` with the default config and with `TORCHINDUCTOR_ENABLE_FP_FUSION=0` pass.

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

ghstack-source-id: 83507a0
Pull-Request: #204322
eellison added a commit that referenced this pull request Nov 12, 2026
**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. It was kept separate because `torch.use_deterministic_algorithms(True)` also turns deterministic mode on, and turning FMA off slows some kernels.

**Change**

- Deterministic mode (and `batch_invariant`) now compiles Inductor's generated Triton kernels with `enable_fp_fusion=False` (`triton_fp_fusion_enabled()` in `utils.py`, used by `triton_meta_common`). Explicit FMAs (`tl.fma`, libdevice) are kept.
- `triton_helpers` use `tl.fma` for their multiply-adds: `welford_reduce`, `welford_combine`, `online_softmax_combine(_with_sum)`, and `rand_eager_kernel` (whose eager CUDA counterpart uses an FMA). These are fixed expressions, the same for every config, so they keep their FMAs in deterministic mode; the eager CUDA kernels, which nvcc compiles with contraction on, have FMAs there too.
  - This applies in every mode. With contraction on, Triton could already contract these, and they time the same as before. The last bit can still change in default mode where Triton contracted differently: e.g. in `online_softmax_combine_with_sum` (`a*b + c*d`), the explicit FMA fuses the first product, and Triton might have fused the second. Under `emulate_precision_casts` (contraction off) they now use an FMA.
- Templates (matmul, flex attention) keep Triton's contraction: they build their own `triton_meta`, and deterministic mode already picks their config without benchmarking. With `triton.enable_fp_fusion=False` alone, templates still autotune with contraction on, so their bits can still depend on the chosen config. fp32 `tl.dot(..., input_precision="ieee")` keeps its FMAs either way (Triton emits them explicitly).

Multiply-adds in Inductor's generated code are not contracted in deterministic mode. Emitting explicit FMAs for them from the LoopBody (choosing them from the graph, not the config) recovered the cost below on average, but added a pass, value numbering for `x - x`, and a dtype-propagation fix, and made two kernels slower by changing how ptxas schedules their loads, so it is left out.

**Performance**

better-benchmark (1725 kernels from torchbench/HF/timm, default shape each), H100, 2026-11-02 nightly, clocks locked, deterministic mode on for every compile (`torch.use_deterministic_algorithms(True, warn_only=True)` in each worker). Geomean of kernel time:

| | geomean | median |
|---|---|---|
| this PR vs. the online-softmax PR below it | +0.25% (+0.38% with coordinate descent) | +0.11% |
| whole stack vs. today's deterministic mode | +0.03% | +0.10% |

Two sweeps of the same code differ by about 0.14% geomean (and about 40 kernels each way by more than 5%). Outside deterministic mode the stack is neutral (+0.03% geomean).

Slower or faster with contraction off in two separate sweeps (the first three also in at least three reruns):

| kernel | before (us) | after (us) | |
|---|---|---|---|
| `amax_sum_c372431bff28` (softmax) | 28.0 | 37.7 | +35% |
| `amax_sum_13a9aaa2eadb` (softmax) | 28.0 | 36.9 | +32% |
| `amax_sum_cb8fc73675a3` | 275.4 | 291.5 | +6% |
| `sum_sum_b50ad423ed16` | 661.8 | 714.5 | +8% |
| `amax_amax_any_99a4f19df20a` | 405.2 | 376.1 | -7% |
| `sum_sum_sum_28aca384bafa` | 252.9 | 238.2 | -6% |
| `sum_sum_3eee452cee40` | 1208.4 | 1143.7 | -5% |

The two softmax kernels are small and latency-bound, and the extra time is not the lost FMAs: the kernel has the same 448 instructions, with 8 FFMAs replaced by FADDs, but ptxas schedules the global loads differently. The trigger is LLVM's contraction being off; ptxas's `--fmad=false` makes no difference.

**Test plan**

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

- `test_fp_fusion`: `enable_fp_fusion` is off in the kernel's `triton_meta` in deterministic mode as well as with the flag off.
- `test_pointwise_config_numerics` now runs both with deterministic mode alone and with the flag alone: forcing XBLOCK=128 vs 256 by timing gives bitwise-equal outputs (they differ with contraction on).
- `test_triton_helpers.py`: the expected `online_softmax_combine` sum is now computed with the same `tl.fma`, so it stays bitwise equal with `enable_fp_fusion=False`.
- Ran on an H100 against the 2026-11-02 cu130 nightly (main at 42ab44e) with this stack applied: `test_deterministic.py` (including two `test_run2run_determinism` cases), `test_triton_helpers.py`, and `test_online_softmax.py` with the default config and with `TORCHINDUCTOR_ENABLE_FP_FUSION=0` pass.

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

ghstack-source-id: 83507a0
Pull-Request: #204322
eellison added a commit that referenced this pull request Nov 12, 2026
**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. It was kept separate because `torch.use_deterministic_algorithms(True)` also turns deterministic mode on, and turning FMA off slows some kernels.

**Change**

- Deterministic mode (and `batch_invariant`) now compiles Inductor's generated Triton kernels with `enable_fp_fusion=False` (`triton_fp_fusion_enabled()` in `utils.py`, used by `triton_meta_common`). Explicit FMAs (`tl.fma`, libdevice) are kept.
- `triton_helpers` use `tl.fma` for their multiply-adds: `welford_reduce`, `welford_combine`, `online_softmax_combine(_with_sum)`, and `rand_eager_kernel` (whose eager CUDA counterpart uses an FMA). These are fixed expressions, the same for every config, so they keep their FMAs in deterministic mode; the eager CUDA kernels, which nvcc compiles with contraction on, have FMAs there too.
  - This applies in every mode. With contraction on, Triton could already contract these, and they time the same as before. The last bit can still change in default mode where Triton contracted differently: e.g. in `online_softmax_combine_with_sum` (`a*b + c*d`), the explicit FMA fuses the first product, and Triton might have fused the second. Under `emulate_precision_casts` (contraction off) they now use an FMA.
- Templates (matmul, flex attention) keep Triton's contraction: they build their own `triton_meta`, and deterministic mode already picks their config without benchmarking. With `triton.enable_fp_fusion=False` alone, templates still autotune with contraction on, so their bits can still depend on the chosen config. fp32 `tl.dot(..., input_precision="ieee")` keeps its FMAs either way (Triton emits them explicitly).

Multiply-adds in Inductor's generated code are not contracted in deterministic mode. Emitting explicit FMAs for them from the LoopBody (choosing them from the graph, not the config) recovered the cost below on average, but added a pass, value numbering for `x - x`, and a dtype-propagation fix, and made two kernels slower by changing how ptxas schedules their loads, so it is left out.

**Performance**

better-benchmark (1725 kernels from torchbench/HF/timm, default shape each), H100, 2026-11-02 nightly, clocks locked, deterministic mode on for every compile (`torch.use_deterministic_algorithms(True, warn_only=True)` in each worker). Geomean of kernel time:

| | geomean | median |
|---|---|---|
| this PR vs. the online-softmax PR below it | +0.25% (+0.38% with coordinate descent) | +0.11% |
| whole stack vs. today's deterministic mode | +0.03% | +0.10% |

Two sweeps of the same code differ by about 0.14% geomean (and about 40 kernels each way by more than 5%). Outside deterministic mode the stack is neutral (+0.03% geomean).

Slower or faster with contraction off in two separate sweeps (the first three also in at least three reruns):

| kernel | before (us) | after (us) | |
|---|---|---|---|
| `amax_sum_c372431bff28` (softmax) | 28.0 | 37.7 | +35% |
| `amax_sum_13a9aaa2eadb` (softmax) | 28.0 | 36.9 | +32% |
| `amax_sum_cb8fc73675a3` | 275.4 | 291.5 | +6% |
| `sum_sum_b50ad423ed16` | 661.8 | 714.5 | +8% |
| `amax_amax_any_99a4f19df20a` | 405.2 | 376.1 | -7% |
| `sum_sum_sum_28aca384bafa` | 252.9 | 238.2 | -6% |
| `sum_sum_3eee452cee40` | 1208.4 | 1143.7 | -5% |

The two softmax kernels are small and latency-bound, and the extra time is not the lost FMAs: the kernel has the same 448 instructions, with 8 FFMAs replaced by FADDs, but ptxas schedules the global loads differently. The trigger is LLVM's contraction being off; ptxas's `--fmad=false` makes no difference.

**Test plan**

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

- `test_fp_fusion`: `enable_fp_fusion` is off in the kernel's `triton_meta` in deterministic mode as well as with the flag off.
- `test_pointwise_config_numerics` now runs both with deterministic mode alone and with the flag alone: forcing XBLOCK=128 vs 256 by timing gives bitwise-equal outputs (they differ with contraction on).
- `test_triton_helpers.py`: the expected `online_softmax_combine` sum is now computed with the same `tl.fma`, so it stays bitwise equal with `enable_fp_fusion=False`.
- Ran on an H100 against the 2026-11-02 cu130 nightly (main at 42ab44e) with this stack applied: `test_deterministic.py` (including two `test_run2run_determinism` cases), `test_triton_helpers.py`, and `test_online_softmax.py` with the default config and with `TORCHINDUCTOR_ENABLE_FP_FUSION=0` pass.

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

ghstack-source-id: 987034c
Pull-Request: #204322
eellison added a commit that referenced this pull request Nov 13, 2026
**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. It was kept separate because `torch.use_deterministic_algorithms(True)` also turns deterministic mode on, and turning FMA off slows some kernels.

**Change**

- Deterministic mode (and `batch_invariant`) now compiles Inductor's generated Triton kernels with `enable_fp_fusion=False` (`triton_fp_fusion_enabled()` in `utils.py`, used by `triton_meta_common`). Explicit FMAs (`tl.fma`, libdevice) are kept.
- `triton_helpers` use `tl.fma` for their multiply-adds: `welford_reduce`, `welford_combine`, `online_softmax_combine(_with_sum)`, and `rand_eager_kernel` (whose eager CUDA counterpart uses an FMA). These are fixed expressions, the same for every config, so they keep their FMAs in deterministic mode; the eager CUDA kernels, which nvcc compiles with contraction on, have FMAs there too.
  - This applies in every mode. With contraction on, Triton could already contract these, and they time the same as before. The last bit can still change in default mode where Triton contracted differently: e.g. in `online_softmax_combine_with_sum` (`a*b + c*d`), the explicit FMA fuses the first product, and Triton might have fused the second. Under `emulate_precision_casts` (contraction off) they now use an FMA.
- Templates (matmul, flex attention) keep Triton's contraction: they build their own `triton_meta`, and deterministic mode already picks their config without benchmarking. With `triton.enable_fp_fusion=False` alone, templates still autotune with contraction on, so their bits can still depend on the chosen config. fp32 `tl.dot(..., input_precision="ieee")` keeps its FMAs either way (Triton emits them explicitly).

Multiply-adds in Inductor's generated code are not contracted in deterministic mode. Emitting explicit FMAs for them from the LoopBody (choosing them from the graph, not the config) recovered the cost below on average, but added a pass, value numbering for `x - x`, and a dtype-propagation fix, and made two kernels slower by changing how ptxas schedules their loads, so it is left out.

**Performance**

better-benchmark (1725 kernels from torchbench/HF/timm, default shape each), H100, 2026-11-02 nightly, clocks locked, deterministic mode on for every compile (`torch.use_deterministic_algorithms(True, warn_only=True)` in each worker). Geomean of kernel time:

| | geomean | median |
|---|---|---|
| this PR vs. the online-softmax PR below it | +0.25% (+0.38% with coordinate descent) | +0.11% |
| whole stack vs. today's deterministic mode | +0.03% | +0.10% |

Two sweeps of the same code differ by about 0.14% geomean (and about 40 kernels each way by more than 5%). Outside deterministic mode the stack is neutral (+0.03% geomean).

Slower or faster with contraction off in two separate sweeps (the first three also in at least three reruns):

| kernel | before (us) | after (us) | |
|---|---|---|---|
| `amax_sum_c372431bff28` (softmax) | 28.0 | 37.7 | +35% |
| `amax_sum_13a9aaa2eadb` (softmax) | 28.0 | 36.9 | +32% |
| `amax_sum_cb8fc73675a3` | 275.4 | 291.5 | +6% |
| `sum_sum_b50ad423ed16` | 661.8 | 714.5 | +8% |
| `amax_amax_any_99a4f19df20a` | 405.2 | 376.1 | -7% |
| `sum_sum_sum_28aca384bafa` | 252.9 | 238.2 | -6% |
| `sum_sum_3eee452cee40` | 1208.4 | 1143.7 | -5% |

The two softmax kernels are small and latency-bound, and the extra time is not the lost FMAs: the kernel has the same 448 instructions, with 8 FFMAs replaced by FADDs, but ptxas schedules the global loads differently. The trigger is LLVM's contraction being off; ptxas's `--fmad=false` makes no difference.

**Test plan**

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

- `test_fp_fusion`: `enable_fp_fusion` is off in the kernel's `triton_meta` in deterministic mode as well as with the flag off.
- `test_pointwise_config_numerics` now runs both with deterministic mode alone and with the flag alone: forcing XBLOCK=128 vs 256 by timing gives bitwise-equal outputs (they differ with contraction on).
- `test_triton_helpers.py`: the expected `online_softmax_combine` sum is now computed with the same `tl.fma`, so it stays bitwise equal with `enable_fp_fusion=False`.
- Ran on an H100 against the 2026-11-02 cu130 nightly (main at 42ab44e) with this stack applied: `test_deterministic.py` (including two `test_run2run_determinism` cases), `test_triton_helpers.py`, and `test_online_softmax.py` with the default config and with `TORCHINDUCTOR_ENABLE_FP_FUSION=0` pass.

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

ghstack-source-id: 987034c
Pull-Request: #204322
pytorchmergebot pushed a commit that referenced this pull request Nov 24, 2026
**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. It was kept separate because `torch.use_deterministic_algorithms(True)` also turns deterministic mode on, and turning FMA off slows some kernels.

**Change**

- Deterministic mode (and `batch_invariant`) now compiles Inductor's generated Triton kernels with `enable_fp_fusion=False` (`triton_fp_fusion_enabled()` in `utils.py`, used by `triton_meta_common`). Explicit FMAs (`tl.fma`, libdevice) are kept.
- `triton_helpers` use `tl.fma` for their multiply-adds: `welford_reduce`, `welford_combine`, `online_softmax_combine(_with_sum)`, and `rand_eager_kernel` (whose eager CUDA counterpart uses an FMA). These are fixed expressions, the same for every config, so they keep their FMAs in deterministic mode; the eager CUDA kernels, which nvcc compiles with contraction on, have FMAs there too.
  - This applies in every mode. With contraction on, Triton could already contract these, and they time the same as before. The last bit can still change in default mode where Triton contracted differently: e.g. in `online_softmax_combine_with_sum` (`a*b + c*d`), the explicit FMA fuses the first product, and Triton might have fused the second. Under `emulate_precision_casts` (contraction off) they now use an FMA.
- Templates (matmul, flex attention) keep Triton's contraction: they build their own `triton_meta`, and deterministic mode already picks their config without benchmarking. With `triton.enable_fp_fusion=False` alone, templates still autotune with contraction on, so their bits can still depend on the chosen config. fp32 `tl.dot(..., input_precision="ieee")` keeps its FMAs either way (Triton emits them explicitly).

Multiply-adds in Inductor's generated code are not contracted in deterministic mode. Emitting explicit FMAs for them from the LoopBody (choosing them from the graph, not the config) recovered the cost below on average, but added a pass, value numbering for `x - x`, and a dtype-propagation fix, and made two kernels slower by changing how ptxas schedules their loads, so it is left out.

**Performance**

better-benchmark (1725 kernels from torchbench/HF/timm, default shape each), H100, 2026-11-02 nightly, clocks locked, deterministic mode on for every compile (`torch.use_deterministic_algorithms(True, warn_only=True)` in each worker). Geomean of kernel time:

| | geomean | median |
|---|---|---|
| this PR vs. the online-softmax PR below it | +0.25% (+0.38% with coordinate descent) | +0.11% |
| whole stack vs. today's deterministic mode | +0.03% | +0.10% |

Two sweeps of the same code differ by about 0.14% geomean (and about 40 kernels each way by more than 5%). Outside deterministic mode the stack is neutral (+0.03% geomean).

Slower or faster with contraction off in two separate sweeps (the first three also in at least three reruns):

| kernel | before (us) | after (us) | |
|---|---|---|---|
| `amax_sum_c372431bff28` (softmax) | 28.0 | 37.7 | +35% |
| `amax_sum_13a9aaa2eadb` (softmax) | 28.0 | 36.9 | +32% |
| `amax_sum_cb8fc73675a3` | 275.4 | 291.5 | +6% |
| `sum_sum_b50ad423ed16` | 661.8 | 714.5 | +8% |
| `amax_amax_any_99a4f19df20a` | 405.2 | 376.1 | -7% |
| `sum_sum_sum_28aca384bafa` | 252.9 | 238.2 | -6% |
| `sum_sum_3eee452cee40` | 1208.4 | 1143.7 | -5% |

The two softmax kernels are small and latency-bound, and the extra time is not the lost FMAs: the kernel has the same 448 instructions, with 8 FFMAs replaced by FADDs, but ptxas schedules the global loads differently. The trigger is LLVM's contraction being off; ptxas's `--fmad=false` makes no difference.

**Test plan**

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

- `test_fp_fusion`: `enable_fp_fusion` is off in the kernel's `triton_meta` in deterministic mode as well as with the flag off.
- `test_pointwise_config_numerics` now runs both with deterministic mode alone and with the flag alone: forcing XBLOCK=128 vs 256 by timing gives bitwise-equal outputs (they differ with contraction on).
- `test_triton_helpers.py`: the expected `online_softmax_combine` sum is now computed with the same `tl.fma`, so it stays bitwise equal with `enable_fp_fusion=False`.
- Ran on an H100 against the 2026-11-02 cu130 nightly (main at 42ab44e) with this stack applied: `test_deterministic.py` (including two `test_run2run_determinism` cases), `test_triton_helpers.py`, and `test_online_softmax.py` with the default config and with `TORCHINDUCTOR_ENABLE_FP_FUSION=0` pass.

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

ghstack-source-id: 38441b8
Pull-Request: #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

ciflow/inductor ciflow/torchtitan Run TorchTitan integration tests ciflow/trunk Trigger trunk jobs on your pull request Merged meta-exported module: inductor ready for review Automated review passed, ready for a final review by a maintainer. topic: not user facing topic category

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants