Skip to content

[dynamo] Keep Inductor deterministic mode on after the first compile - #204320

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

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

Conversation

@eellison

@eellison eellison commented Nov 10, 2026 •

Copy link
Copy Markdown
Contributor

Stack from ghstack (oldest at bottom):

Context

#198572 already changed Dynamo's preserve_global_state to restore the deterministic-algorithms state with torch._C._set_deterministic_algorithms instead of torch.use_deterministic_algorithms, so deterministic mode set through Inductor alone (TORCHINDUCTOR_DETERMINISTIC=1 / config.deterministic = True) is no longer turned off after the first compiled frame. This PR builds on that.

Change

  • preserve_global_state also saves torch._inductor.config.deterministic before compiling a frame and restores it afterwards, so a compile can no longer leave Inductor's deterministic flag changed for later frames (e.g. through a torch.use_deterministic_algorithms call made during compilation).
  • torch.set_deterministic_debug_mode now goes through torch.use_deterministic_algorithms, so it sets Inductor's deterministic flag the same way use_deterministic_algorithms does ([inductor] turn Inductor deterministic mode on with torch.use_deterministic_algorithms #165950). Behavior change: "warn"/"error" (1/2) turn on Inductor's deterministic mode, which skips on-device benchmarking and can be slower, and "default" (0) turns it off, including when it was set with TORCHINDUCTOR_DETERMINISTIC=1.

Test plan

  • test_compile_does_not_leak_deterministic_mode (test/inductor/test_deterministic.py): a change to Inductor's flag during compilation does not persist past the frame.
  • test_deterministic_flag_survives_compile and the Dynamo tests: deterministic mode set through Inductor alone stays on across frames and in the backward compile.
  • test_set_deterministic_debug_mode_sets_inductor_flag: each debug mode sets Inductor's flag to match.
  • test/dynamo/test_misc.py -k "deterministic or global_state".

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

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

[ghstack-poisoned]
@pytorch-bot

pytorch-bot Bot commented Nov 10, 2026 •

Copy link
Copy Markdown

PR Status: Approved 🚀

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

🟡 AUTOMATED REVIEW - Changes requested:

The PR restores `torch._inductor.config.deterministic` in Dynamo's
`preserve_global_state` and routes `torch.set_deterministic_debug_mode` through
`torch.use_deterministic_algorithms`. Recommendation: Request Changes. The only
blocking point is drisspg's unanswered question about the import cost at
`convert_frame.py:355`; every other point is non-blocking.

Findings (9):

[major] torch/_dynamo/convert_frame.py:355
Blocking: drisspg's question here is unanswered: "any affect on import times /
or other affects with importing inductor here?" Nobody has replied in the
thread. The reply is easy: the import adds no cost here. `convert_frame.py:88`
imports `trace_rules`, `trace_rules.py:46` imports
`torch._inductor.test_operators`, and `torch/_inductor/__init__.py:12` imports
`standalone_compile`, which loads `config`. So `torch._inductor.config` is
already in `sys.modules` whenever this code runs, whatever the backend. The `!=`
check at `:392` also avoids dirtying the config hash cache on every frame.
Ideally the reply also covers the new eager-path import in
`set_deterministic_debug_mode`.

[minor] torch/__init__.py:2006
Non-blocking: `set_deterministic_debug_mode`'s docstring doesn't say it now sets
`torch._inductor.config.deterministic`, and the debug-mode round-trip loses
Inductor's setting. `get_deterministic_debug_mode` (`:2018-2030`) reads only the
ATen flags, so under `TORCHINDUCTOR_DETERMINISTIC=1` it returns 0, and `prev =
get_deterministic_debug_mode(); set_deterministic_debug_mode("warn");
set_deterministic_debug_mode(prev)` silently turns off the determinism the env
var enabled. That is the same kind of clobbering this PR fixes in Dynamo. The
description says `"default"` turns the mode off; the docstrings should say so
too, and the round-trip needs a decision. (Optional: the "tuned on" typo at
`:1905` in nearby code.)

[minor] torch/__init__.py:2010
Non-blocking: `set_deterministic_debug_mode` now imports `torch._inductor` in
eager-only programs. `use_deterministic_algorithms` does `import
torch._inductor.config` (`:1953`), which loads the whole lazy `torch._inductor`
package and, through `standalone_compile.py:19`, also `torch._dynamo`. Before
this PR it only called `_C`, so an eager script calling
`torch.set_deterministic_debug_mode("error")` at startup now pays the
Dynamo/Inductor import time. `use_deterministic_algorithms` already pays this,
so it's a consistency trade-off; mention it in the release note and in the reply
to drisspg.

[minor] torch/_dynamo/convert_frame.py:392
Non-blocking: forward and backward can lower in different modes when
`set_deterministic_debug_mode` is called inside a compiled function. It is in
`torch_non_c_binding_in_graph_functions` (`trace_rules.py:3010`) and
`variables/torch.py` has no handler, so `get_fake_value` actually runs it while
tracing (`_dynamo/utils.py:4642`), flipping Inductor's flag before the forward
is lowered. `preserve_global_state` (here, `:392-393`) then puts the old value
back, so a lazily compiled backward is lowered in the old mode. The ATen half
already existed before the PR; the Inductor half is new.

[minor] test/dynamo/test_misc.py:14165
Non-blocking: `test_inductor_deterministic_in_backward_compile` doesn't test the
lazy backward in the dynamic-shapes variant. `DynamicShapesMiscTests` sets
`assume_static_by_default=False`; with a symint saved for backward, AOTAutograd
compiles the backward eagerly (`graph_compile.py:2453-2464`), so the test passes
without reaching the lazy path its comment describes. Pass `dynamic=False`, and
assert `len(seen) == 1` before `.backward()`.

(4 more not shown, see the review run)

Reviewed commit: 9b705e7

Review run

🐛 Report a bad review

🔗 Helpful Links

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

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

✅ You can merge normally! (1 Unrelated Failure)

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

⚪ GREEN LIGHT - OUTDATED (earlier commit) - Green Light review did not complete:

reason: failed
Reviewed commit: fe77d6c (NOT the current head 9b705e7)

Inference job

FLAKY - The following job failed but was likely due to flakiness present on trunk:

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

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

This comment was marked as outdated.

[ghstack-poisoned]
github-actions[bot]

This comment was marked as outdated.

[ghstack-poisoned]

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

The PR stops Dynamo's preserve_global_state from overwriting torch._inductor.config.deterministic after each compiled frame, and makes set_deterministic_debug_mode go through use_deterministic_algorithms. Recommendation: Approve. The earlier blocking finding (the graph-node target) is fixed, and every remaining point is non-blocking.

⚪ 7 non-blocking findings

use_deterministic_algorithms(False)

Non-blocking, still open from the last review: set_deterministic_debug_mode now changes Inductor's deterministic mode, but neither docstring says so. The set_deterministic_debug_mode docstring doesn't mention it, and the use_deterministic_algorithms docstring (typo "tuned on") only covers turning the mode on. Round-trip problem: get_deterministic_debug_mode() reads only the ATen flags, so under TORCHINDUCTOR_DETERMINISTIC=1 it returns 0. Then prev = get_deterministic_debug_mode(); set_deterministic_debug_mode("warn"); set_deterministic_debug_mode(prev) quietly turns off the Inductor determinism the env var enabled. That is the same kind of clobbering this PR fixes in Dynamo. Suggested fix: document the Inductor side effect in both docstrings, and decide whether the round-trip should keep Inductor's own setting.


use_deterministic_algorithms(False)

New point, low severity: set_deterministic_debug_mode is an in-graph function with no Dynamo handler (trace_rules.py:3008). When it is called inside a compiled function, get_fake_value runs it for real while Dynamo traces (_dynamo/utils.py:4589). That flips Inductor's flag before AOT starts, so the whole forward lowers in the new mode. preserve_global_state then restores the flag, so the lazy backward compiles in the old mode. The ATen half of this already existed at the merge base; the Inductor half is new.


if inductor_config.deterministic != prior_inductor_deterministic:

Non-blocking backward-compat point: torch.use_deterministic_algorithms(True) called inside a compiled function no longer turns on Inductor's deterministic mode at all. The graph node sets only the ATen flag (variables/torch.py:1606-1612). At the merge base, the next frame compile's restore (use_deterministic_algorithms(prior=True)) synced Inductor's flag to True, a delayed, accidental but real sync. Here, lines 390-391 put Inductor's own prior value back, so that sync is gone, and the test covering it (test_deterministic_algorithms_sets_inductor_flag) went away with the revert. The PR description is out of date: it says use_deterministic_algorithms(True) keeps turning on Inductor's mode "as before" (true only for eager calls), says "leave Inductor's flag alone" though these lines restore it, omits the set_deterministic_debug_mode change, and its "6 tests" test plan is stale. There is no release notes:/topic: label. The release note should cover the per-frame slowdown for TORCHINDUCTOR_DETERMINISTIC=1 jobs, the debug-mode side effect, and the in-graph limitation.


def test_compile_does_not_leak_deterministic_mode(self):

Non-blocking, still open: test_compile_does_not_leak_deterministic_mode uses only CPU tensors, but the file calls run_tests() only under HAS_GPU_AND_TRITON. It is the only test of the new restore branch (convert_frame.py:390-391), so CPU-only CI never runs it. It also passes at the merge base. Move it, or add a copy, next to the new tests in test/dynamo/test_misc.py.


def test_inductor_deterministic_in_backward_compile(self):

Non-blocking: MiscTests also runs as the dynamic-shapes variant with assume_static_by_default=False (test_dynamic_shapes.py:41-50,74). There the saved x has shape [s0], so the backward saves a symint, and AOTAutograd compiles the backward eagerly inside the frame compile (graph_compile.py:2454-2457). In that variant test_inductor_deterministic_in_backward_compile doesn't exercise the lazy path, and its "compiled lazily" comment is wrong. Suggested fix: pass dynamic=False, and assert len(seen) == 1 between the forward and .backward(), so the test fails loudly instead of passing without testing anything if the backward stops being lazy.


def _restore_deterministic_state(self):

Non-blocking: _restore_deterministic_state saves and assigns torch._inductor.config.deterministic by hand, while test_deterministic.py:44-45 in the same PR does the same job with config.patch(deterministic=False) plus DeterministicGuard(False). Suggested replacement: self.enterContext(torch._inductor.config.patch(deterministic=False)) then self.enterContext(DeterministicGuard(False)). Python >=3.11 is required, so enterContext is available, and cleanups run in reverse order, so the patch restores Inductor's flag last. This also removes the explicit torch.use_deterministic_algorithms(False) lines in each test. Naming: the helper registers a cleanup and restores nothing when called, so the name is misleading. Alternative: have DeterministicGuard (common_utils.py:2797-2820) save and restore Inductor's flag itself, removing both this helper and the ordering trick in test_deterministic.py.


torch._dynamo.reset()

Non-blocking, still open: this torch._dynamo.reset() is redundant, because run_and_get_code already resets Dynamo (torch/_inductor/utils.py:3706).

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

@github-actions
github-actions Bot dismissed stale reviews from themself November 12, 2026 22:56

Withdrawn: the automated review of fe77d6c found nothing blocking.

prior_inference_mode = torch.is_inference_mode_enabled()
prior_deterministic = torch.are_deterministic_algorithms_enabled()
prior_warn_only = torch.is_deterministic_algorithms_warn_only_enabled()
import torch._inductor.config as inductor_config

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.

any affect on import times / or other affects with importing inductor here?

@drisspg drisspg left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

approving to get in better state but I wants to thinks bout this some more

@pytorchgreenlight pytorchgreenlight Bot added GL/superseded GreenLight review is superseded by changes and removed GL/human GreenLight marked as needing human review labels Nov 13, 2026
[ghstack-poisoned]
@pytorchmergebot

Copy link
Copy Markdown
Collaborator

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

@pytorchmergebot

Copy link
Copy Markdown
Collaborator

Starting merge as part of PR stack under #204322

1 similar comment
@pytorchmergebot

Copy link
Copy Markdown
Collaborator

Starting merge as part of PR stack under #204322

pytorchmergebot pushed a commit that referenced this pull request Nov 25, 2026
… multiplying (#204321)

**Change**

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

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

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

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

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

**Test plan**

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

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

Pull Request resolved: #204321
Approved by: https://github.com/pytorchgreenlight
ghstack dependencies: #204320
pytorchmergebot pushed a commit that referenced this pull request Nov 25, 2026
…explicit FMAs (#204322)

**Problem**

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

**Change**

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

**Numerics outside deterministic mode**

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

**Performance**

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

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

**Test plan**

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

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

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

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

Labels

GL/superseded GreenLight review is superseded by changes in progress PR is being worked on by the author, until the automated review accepts it Merged module: dynamo module: inductor release notes: inductor

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants