Skip to content

Detect fp32 precision flag leaks in TestCase and fix offenders - #185236

Closed
jeffdaily wants to merge 14 commits into
mainfrom
jeffdaily/fp32-precision-audit
Closed

jeffdaily wants to merge 14 commits into
mainfrom
jeffdaily/fp32-precision-audit

Conversation

@jeffdaily

@jeffdaily jeffdaily commented May 26, 2026 •

Copy link
Copy Markdown
Collaborator

Follow-up to #180926. In review there, @albanD asked that we not spread defensive with_ieee_matmul_precision decorators across matmul-using tests, and instead fix the root cause: tests that leave a global fp32 precision flag in a non-default state, plus the base TestCase not catching such leaks.

This makes any test running under torch.testing._internal.common_utils.TestCase start from a known precision baseline, and turns a leak into a loud failure in tearDown rather than a silent tolerance failure in an unrelated sibling test.

The core change is in common_utils.py: a single _fp32_precision_flag_specs() enumerates the six flags (cuda.matmul, cudnn.conv/rnn, mkldnn.matmul/conv/rnn); TestCase.setUp snapshots them and tearDown compares, restores, and raises AssertionError naming the leaked flag. recover_orig_fp32_precision is refactored to reuse the same snapshot/restore. An opt-out env var PYTORCH_DISABLE_FP32_PRECISION_LEAK_CHECK=1 exists as a short-term escape hatch; the goal is zero callers.

With the detector on, the remaining changes fix tests it would now reject. Inductor suites that set process-global precision at import time move the set into setUpModule/tearDownModule with save/restore, so importing the module no longer poisons precision for everything imported after it; distributed suites that set allow_tf32 = False at import time get the same treatment. The test_linalg.py tunableop tests replace a hardcoded finally: allow_tf32 = False with tf32_enabled(), and TestLinalg/TestMatmulCuda setUp/tearDown snapshot the real fp32_precision instead of restoring a hardcoded value. Three single-test leaks (kernel_benchmark, mix_order_reduction, torchinductor) get @recover_orig_fp32_precision.

Finally, with leaks no longer possible, the with_ieee_matmul_precision decorator added in #180926 is redundant: its five call sites (test_old_cholesky, test_rnn_fused, three affine_grid/grid_sample tests) pass at the default precision once nothing leaks TF32 into them, so the decorator and its call sites are removed.

Suggested review order: common_utils.py (detector + helpers) first, then the offender fixes, then the decorator removal.

Test Plan

Verified on ROCm/MI300 (gfx942); CUDA paths validated in CI.

# precision setup/teardown changes in test_linalg
HIP_VISIBLE_DEVICES=7 python test/test_linalg.py \
  TestLinalgCUDA.test_tf32_tunableop_cuda_float32 \
  TestLinalgCUDA.test_tf32_offline_tunableop_cuda_float32

# the five tests that previously needed with_ieee_matmul_precision, now without it
HIP_VISIBLE_DEVICES=7 python test/test_nn.py \
  TestNNDeviceTypeCUDA.test_affine_2d_rotate90_cuda \
  TestNNDeviceTypeCUDA.test_affine_2d_rotateRandom_cuda \
  TestNNDeviceTypeCUDA.test_affine_3d_rotateRandom_cuda \
  TestNNDeviceTypeCUDA.test_rnn_fused_cuda_float32 \
  TestNNDeviceTypeCUDA.test_rnn_fused_cuda_float64
HIP_VISIBLE_DEVICES=7 python test/test_linalg.py TestLinalgCUDA.test_old_cholesky_cuda_float32

All passed. The detector was also confirmed to fire on an intentional leak and to honor the opt-out env var.

BC-breaking?

No. torch.testing._internal is private API, and the removed with_ieee_matmul_precision was only added recently in #180926. The new tearDown assertion can surface pre-existing precision-flag leaks in out-of-tree test suites built on our TestCase; PYTORCH_DISABLE_FP32_PRECISION_LEAK_CHECK=1 disables it if needed.

Authored by Claude.

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

Follow-up to #180926. In review there, @albanD asked that we not spread defensive `with_ieee_matmul_precision` decorators across matmul-using tests, and instead fix the root cause: tests that leave a global fp32 precision flag in a non-default state, plus the base `TestCase` not catching such leaks.

This makes any test running under `torch.testing._internal.common_utils.TestCase` start from a known precision baseline, and turns a leak into a loud failure in `tearDown` rather than a silent tolerance failure in an unrelated sibling test.

The core change is in `common_utils.py`: a single `_fp32_precision_flag_specs()` enumerates the six flags (cuda.matmul, cudnn.conv/rnn, mkldnn.matmul/conv/rnn); `TestCase.setUp` snapshots them and `tearDown` compares, restores, and raises `AssertionError` naming the leaked flag. `recover_orig_fp32_precision` is refactored to reuse the same snapshot/restore. An opt-out env var `PYTORCH_DISABLE_FP32_PRECISION_LEAK_CHECK=1` exists as a short-term escape hatch; the goal is zero callers.

With the detector on, the remaining changes fix tests it would now reject. Inductor suites that set process-global precision at import time move the set into `setUpModule`/`tearDownModule` with save/restore, so importing the module no longer poisons precision for everything imported after it; distributed suites that set `allow_tf32 = False` at import time get the same treatment. The `test_linalg.py` tunableop tests replace a hardcoded `finally: allow_tf32 = False` with `tf32_enabled()`, and `TestLinalg`/`TestMatmulCuda` `setUp`/`tearDown` snapshot the real `fp32_precision` instead of restoring a hardcoded value. Three single-test leaks (kernel_benchmark, mix_order_reduction, torchinductor) get `@recover_orig_fp32_precision`.

Finally, with leaks no longer possible, the `with_ieee_matmul_precision` decorator added in #180926 is redundant: its five call sites (`test_old_cholesky`, `test_rnn_fused`, three affine_grid/grid_sample tests) pass at the default precision once nothing leaks TF32 into them, so the decorator and its call sites are removed.

Suggested review order: `common_utils.py` (detector + helpers) first, then the offender fixes, then the decorator removal.

## Test Plan

Verified on ROCm/MI300 (gfx942); CUDA paths validated in CI.

```
# precision setup/teardown changes in test_linalg
HIP_VISIBLE_DEVICES=7 python test/test_linalg.py \
  TestLinalgCUDA.test_tf32_tunableop_cuda_float32 \
  TestLinalgCUDA.test_tf32_offline_tunableop_cuda_float32

# the five tests that previously needed with_ieee_matmul_precision, now without it
HIP_VISIBLE_DEVICES=7 python test/test_nn.py \
  TestNNDeviceTypeCUDA.test_affine_2d_rotate90_cuda \
  TestNNDeviceTypeCUDA.test_affine_2d_rotateRandom_cuda \
  TestNNDeviceTypeCUDA.test_affine_3d_rotateRandom_cuda \
  TestNNDeviceTypeCUDA.test_rnn_fused_cuda_float32 \
  TestNNDeviceTypeCUDA.test_rnn_fused_cuda_float64
HIP_VISIBLE_DEVICES=7 python test/test_linalg.py TestLinalgCUDA.test_old_cholesky_cuda_float32
```

All passed. The detector was also confirmed to fire on an intentional leak and to honor the opt-out env var.

## BC-breaking?

No. `torch.testing._internal` is private API, and the removed `with_ieee_matmul_precision` was only added recently in #180926. The new `tearDown` assertion can surface pre-existing precision-flag leaks in out-of-tree test suites built on our `TestCase`; `PYTORCH_DISABLE_FP32_PRECISION_LEAK_CHECK=1` disables it if needed.

Authored by Claude.
@pytorch-bot

pytorch-bot Bot commented May 26, 2026 •

Copy link
Copy Markdown

🔗 Helpful Links

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

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

❗ 1 Active SEVs

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

❌ 1 New Failure, 6 Unclassified Failures

As of commit 5dd1a53 with merge base d55bda7 (image):

NEW FAILURE - The following job has failed:

  • trunk / macos-py3-arm64 / test (mps, 1, 1, macos-m2-15) (gh)
    test/test_mps.py::TestBinaryIteratorConformance::test_simple_add_bfloat16_float32_float32_shape0

    AI verdict: AI verdict: probably not related

    The failing test hangs (timeout/KeyboardInterrupt at file_baton.py:50) during cpp_extension.load_inline compilation, not due to any assertion from the fp32 precision changes. The suspect commit only adds a decorator to test_compile_benchmark_util.py and has no causal path to a compilation hang in test_mps.py.

    Full reasoning on HUD →

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

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

The four distributed setUpModule/tearDownModule fixtures saved and restored
the legacy allow_tf32 bool. Because writing allow_tf32 = False maps
fp32_precision to "ieee" rather than the pristine "none" default, the bool
round-trip left fp32_precision at "ieee" instead of its original value.
Snapshot and restore fp32_precision directly, matching the TestLinalg and
TestMatmulCuda fixtures in this PR; the flag is still turned off via the
legacy allow_tf32 = False to preserve the original intent.

Authored by Claude.
@jeffdaily

Copy link
Copy Markdown
Collaborator Author

For reference, the audit inventory mentioned above was produced by a throwaway AST script (not part of this PR): https://gist.github.com/jeffdaily/c30ed8a1c68703f74ea143e1301f2194

It scans test/ and torch/testing/ for mutations of the six fp32 precision flags and classifies each as safe (save/restore decorator, helper body, or a local save/restore pair) or unsafe (module-level set at import, hardcoded restore, or an unrestored leak). On this branch it reports zero unsafe entries.

@jeffdaily
jeffdaily marked this pull request as ready for review May 26, 2026 16:39
@jeffdaily
jeffdaily requested a review from albanD May 26, 2026 16:39
…ion-audit

# Conflicts:
#	test/inductor/test_mix_order_reduction.py
@jansel
jansel requested a review from zou3519 May 26, 2026 19:18
@jansel

jansel commented May 26, 2026

Copy link
Copy Markdown
Contributor

@claude explain those CI failures, check if they are related, and review the changes in this PR

@claude

claude Bot commented May 26, 2026 •

Copy link
Copy Markdown

Claude finished @jansel's task in 4m 49s —— View job


CI Failure Analysis and PR Review

  • Analyze the 4 new CI failures (ROCm-specific)
  • Check if unclassified failures are related to this PR
  • Review the core changes in common_utils.py
  • Review the offender fixes across test files
  • Review the decorator removal in test_nn.py
  • Provide overall assessment

CI Failure Analysis

All 4 new failures are ROCm-only and share the same root cause.

The failing tests are:

  1. TestNN::test_AdaptiveLogSoftmax_cuda_fp32
  2. DynamicShapesGPUTests::test_conv2d_backward_parametrized_..._dynamic_shapes_cuda
  3. GPUTests::test_alexnet_prefix_cuda
  4. GPUTests::test_conv2d_backward_parametrized_..._nhwc_True_cuda

Root cause: The tf32_off() context manager in torch/testing/_internal/common_cuda.py:264 saves/restores allow_tf32 (a boolean), not fp32_precision (a string). On ROCm/MI300, the default fp32_precision is "none" (from aten/src/ATen/Context.h:553 — TF32 not supported, so Float32Precision::NONE). When tf32_off() runs:

  1. Reads allow_tf32 → False (because "none" means TF32 is not active)
  2. Sets allow_tf32 = False → calls setAllowTF32CuBLAS(false) → sets fp32_precision = "ieee" (per Context.cpp:370)
  3. On exit, restores allow_tf32 = False → again sets fp32_precision = "ieee"

The state changed from "none" → "ieee", and the new leak detector in tearDown catches it. On CUDA hardware with TF32 support, the default is "tf32", and the tf32_off()/restore cycle goes "tf32" → "ieee" → "tf32" cleanly, which is why only ROCm fails.

Fix needed: The tf32_off(), tf32_on(), and tf32_on_and_off() helpers in common_cuda.py should save/restore fp32_precision (the string) rather than allow_tf32 (the boolean), matching the same pattern this PR already applies to TestLinalg.setUp/tearDown and the distributed tests.

Unclassified failures: The test_recompile_on_global_state_change failures across many jobs are likely related — this test in test/dynamo/test_misc.py probably intentionally mutates precision state to test dynamo's recompilation behavior and now triggers the leak detector. The batch_norm and other unclassified failures appear to be pre-existing trunk flakes (they appear on unrelated platforms/configs and involve different code paths).


Code Review

Core Mechanism (common_utils.py) — Well designed

The _fp32_precision_flag_specs() / _snapshot_fp32_precision() / _restore_fp32_precision() pattern is clean:

  • Single source of truth for the 6 flags
  • Snapshot is a tuple (immutable, hashable, comparable)
  • The recover_orig_fp32_precision decorator correctly delegates to these helpers
  • The hasattr guard and env-var escape hatch in tearDown are appropriate for backwards compat

One issue: The leak detector in tearDown (line 3818-3833) first restores the original state and then raises AssertionError. This means the next test starts clean, which is the right choice — but it also means the tearDown method's raise might conflict with other assertion errors from the test itself. This is a minor concern; Python unittest already handles multiple failures gracefully by chaining.

Offender Fixes — Correct approach, one gap

The setUpModule/tearDownModule pattern for inductor and distributed tests is the right fix: it saves fp32_precision (the string) and restores it, rather than using allow_tf32 which loses the "none" state.

However, the PR did not fix the tf32_off() context manager itself, which is the root cause of the 4 ROCm failures. Tests using @with_tf32_off, @tf32_on_and_off, or with tf32_off(): (e.g., test_conv2d_backward_parametrized, test_alexnet_prefix, and all add_test-generated _cuda_fp32 tests in test_nn.py) will still trigger the leak detector on ROCm.

The fix should be in torch/testing/_internal/common_cuda.py:264-271:

@contextlib.contextmanager
def tf32_off():
    old_precision = torch.backends.cuda.matmul.fp32_precision
    try:
        torch.backends.cuda.matmul.allow_tf32 = False
        with torch.backends.cudnn.flags(enabled=None, benchmark=None, deterministic=None, allow_tf32=False):
            yield
    finally:
        torch.backends.cuda.matmul.fp32_precision = old_precision

And similarly for tf32_on() at line 275.

Decorator Removal (test_nn.py) — Correct but premature

Removing with_ieee_matmul_precision and its call sites is logically correct given the leak detector, but only works if the leak detector actually prevents all leaks. Since tf32_off()/tf32_on() still have the round-trip bug, there is currently a window where precision can shift between tests on ROCm. In practice, the tests in question (test_affine_*, test_rnn_fused, test_old_cholesky) will still pass because the leak detector restores state even when it raises — but it's fragile until tf32_off/on are fixed.

test_linalg.py — Good

The switch from allow_tf32 = True hardcoded in tearDown to restoring self._prev_cuda_matmul_fp32 is exactly right. The tf32_enabled() wrapper for tunableop tests is also correct.

test_matmul_cuda.py — Good

Same pattern as test_linalg.py, saves/restores fp32_precision string.


Summary

Aspect Assessment
Core detection mechanism Sound
Offender fixes (setUpModule pattern) Correct
with_ieee_matmul_precision removal Correct (once leaks are all fixed)
CI failures Real bug — tf32_off()/tf32_on() in common_cuda.py need the same fp32_precision save/restore pattern
Unclassified failures Mix of the same tf32_off bug + unrelated trunk flakes

Recommendation: Fix tf32_off() and tf32_on() in torch/testing/_internal/common_cuda.py to save/restore fp32_precision instead of allow_tf32 for the matmul flag. This will resolve all 4 new CI failures and likely the test_recompile_on_global_state_change failures too (if that test uses those helpers). The dynamo test may also need a @recover_orig_fp32_precision decorator if it intentionally mutates precision state.


The TestCase precision-leak detector added in this PR exposed a latent
round-trip bug. tf32_off/tf32_on/tf32_enabled in common_cuda.py, and a few
tests that roll their own restore, saved and restored the legacy allow_tf32
bool. On ROCm the default cuda.matmul fp32_precision is "none", and writing
allow_tf32 back yields "ieee" instead of "none", which the detector correctly
flagged. ("none" and "ieee" are not equivalent: "none" defers to the global
set_float32_matmul_precision, "ieee" forces full FP32.) On CUDA the default
round-trips cleanly, so the failures were ROCm-only.

Fix the three CUDA helpers to snapshot and restore fp32_precision directly,
matching the rest of this PR. Tests that manage the bool themselves are fixed
too: test_cublas_allow_tf32_get_set and test_float32_matmul_precision_get_set
(test_cuda.py) and test_recompile_on_global_state_change (dynamo) get
@recover_orig_fp32_precision; the two CUTLASS sparse tests snapshot
fp32_precision.

Test Plan:

HIP_VISIBLE_DEVICES=7 python test/test_nn.py TestNN.test_AdaptiveLogSoftmax_cuda_fp32
HIP_VISIBLE_DEVICES=7 python test/inductor/test_torchinductor.py GPUTests.test_alexnet_prefix_cuda
HIP_VISIBLE_DEVICES=7 python test/test_cuda.py TestCuda.test_cublas_allow_tf32_get_set TestCuda.test_float32_matmul_precision_get_set
HIP_VISIBLE_DEVICES=7 python test/dynamo/test_misc.py -k test_recompile_on_global_state_change

All pass; tf32_off/tf32_enabled now round-trip fp32_precision none->none.
The CUTLASS sparse tests are skipped on ROCm so were verified by analogy with
the test_cuda fix (same pattern, same mechanism).

Authored by Claude.
@jeffdaily

Copy link
Copy Markdown
Collaborator Author

Fixed in 3361376. The analysis was correct: the leak detector exposed that tf32_off/tf32_on/tf32_enabled in common_cuda.py save and restore the legacy allow_tf32 bool, which on ROCm round-trips "none" to "ieee" (writing allow_tf32 = False yields "ieee", not the "none" default; on CUDA the default round-trips cleanly, so the failures were ROCm-only). Those helpers now snapshot and restore fp32_precision directly.

I also swept for tests that manage the bool themselves instead of going through the helpers, since they hit the same issue: test_cublas_allow_tf32_get_set and test_float32_matmul_precision_get_set (test_cuda.py) and test_recompile_on_global_state_change (dynamo) now use @recover_orig_fp32_precision, and the two CUTLASS sparse tests (skipped on ROCm) snapshot fp32_precision.

Verified on MI300: test_AdaptiveLogSoftmax_cuda_fp32, test_alexnet_prefix_cuda, both test_cuda.py API tests, and the dynamo test now pass.

This dynamo test toggles torch.backends.cuda.matmul.allow_tf32 via
create_toggle_fns and resets the saved bool. On platforms where the default
cuda.matmul fp32_precision is "none" (ROCm and CPU builds), resetting the bool
leaves it at "ieee", which the new TestCase precision-leak detector flags. Wrap
the test with @recover_orig_fp32_precision so the ambient precision is restored
exactly, regardless of the bool round-trip; the test's intentional toggling
(which exercises dynamo recompilation on global-state change) is unchanged.

Dr.CI classified this failure as unrelated, but it reproduces locally as a
leak-detector AssertionError and is fixed by this change. The two remaining CI
failures (conv2d_backward on B200, addmm_persistent_tma on H100) contain no
"leak detected" in their logs and are unrelated.

Test Plan:

python test/dynamo/test_graph_region_tracker.py GraphRegionTrackerTests.test_mismatched_global_state

Authored by Claude.
@jeffdaily

Copy link
Copy Markdown
Collaborator Author

@claude Analyze CI failures

@claude

claude Bot commented May 27, 2026 •

Copy link
Copy Markdown

Claude finished @jeffdaily's task in 2m 50s —— View job


CI Failure Analysis

  • Get current CI status
  • Identify failed jobs and download logs
  • Analyze failures and determine if they are related to this PR
  • Provide summary and recommendations

Summary

There are 3 failed workflow runs containing 6 failed jobs (each run has a regular test + OSDC test variant). All failures fall into 2 distinct categories, and neither is caused by this PR.


Failure 1: test_max_autotune_addmm_persistent_tma (H100 - 4 jobs)

Test: TestMaxAutotune::test_max_autotune_addmm_persistent_tma_a_transposed_True_b_transposed_False_dynamic_True_tma_store_True

Error: InductorError: LoweringException: AssertionError: Unregistered range symbol: yindex

Root cause: This is an inductor codegen bug in the persistent TMA (Tensor Memory Accelerator) path for dynamic shapes. The error occurs in torch/_inductor/codegen/triton.py:300 at TritonSymbols.get_block_shape() -- a range symbol yindex is referenced but not registered. The failure happens during template rendering when store_output calls input_node.make_loader()(index_symbols).

Related to this PR? No. The error is deep in the inductor lowering/codegen pipeline and has nothing to do with fp32 precision flags. The test was already decorated with @recover_orig_fp32_precision in this PR's changes to test_max_autotune.py, but the failure is in the compilation logic itself, not in setUp/tearDown or precision handling. This is a pre-existing bug that affects the H100 persistent TMA path with dynamic shapes, and DrCI already marks it as "UNSTABLE" (flaky on trunk).

Affected jobs:

  • Limited CI on H100 run 26485043538: test + test-osdc (same error)
  • Limited CI on H100 run 26485036703: test + test-osdc (same error)

Failure 2: test_conv2d_backward_parametrized (B200 - 2 jobs)

Test: GPUTests::test_conv2d_backward_parametrized_dilation_1_stride_1_padding_1_kernel_1_channels_groups0_nhwc_False_cuda (and dilation_2 variant)

Error: torch.AcceleratorError: CUDA error: an illegal memory access was encountered

Root cause: A previous test in the same process triggered an illegal memory access on the B200 GPU. The error is reported asynchronously during setUp() of the next test when torch.manual_seed() tries to call default_generator.manual_seed(seed), which touches the GPU context. The stack trace shows the CUDA error was raised from currentStreamCaptureIdMayInitCtx -- this is a classic "sticky CUDA error" pattern where the original fault happened in an earlier test and poisons the device for the remainder of the process.

Related to this PR? No. The error is a CUDA illegal memory access from Triton autotune benchmarking (the log shows triton_convolution2d_bwd_weight_* templates producing inf ms timing results just before the crash). This is a B200-specific hardware/driver issue with the Triton convolution backward weight kernels. DrCI already flagged this workflow as "UNSTABLE".

Affected jobs:

  • B200 Smoke Tests run 26485039846: test + test-osdc

Conclusion

Failure Hardware Related to PR? Category
test_max_autotune_addmm_persistent_tma (Unregistered range symbol: yindex) H100 No Pre-existing inductor codegen bug in persistent TMA + dynamic shapes
test_conv2d_backward_parametrized (CUDA illegal memory access) B200 No Pre-existing B200 Triton kernel crash (sticky CUDA error)

Both failures are unrelated to the fp32 precision flag changes in this PR. They are pre-existing issues that happen to be surfaced in these CI runs. The DrCI bot has already classified them as "UNSTABLE" (trunk flakes), which confirms they are known issues.


@jeffdaily

Copy link
Copy Markdown
Collaborator Author

@jansel fixed what claude caught from the CI logs.

@albanD ready for your review, as well.

@jeffdaily

Copy link
Copy Markdown
Collaborator Author

@pytorchbot merge -i

Remaining red is unrelated: the macos-m2-15 mps job fails identically on trunk (test_simple_add_bfloat16_float32 conformance, broken on main), and the rocm-mi300 jobs were queue-cancelled on all three attempts without executing tests; mi300 was green on the previous reland CI and the only changes since are two test-side leak fixes validated on the L4 full-test-set (ci-no-td) run.

youlituao pushed a commit to youlituao/pytorch that referenced this pull request Jul 28, 2026
…ch#185236)

Follow-up to pytorch#180926. In review there, @albanD asked that we not spread defensive `with_ieee_matmul_precision` decorators across matmul-using tests, and instead fix the root cause: tests that leave a global fp32 precision flag in a non-default state, plus the base `TestCase` not catching such leaks.

This makes any test running under `torch.testing._internal.common_utils.TestCase` start from a known precision baseline, and turns a leak into a loud failure in `tearDown` rather than a silent tolerance failure in an unrelated sibling test.

The core change is in `common_utils.py`: a single `_fp32_precision_flag_specs()` enumerates the six flags (cuda.matmul, cudnn.conv/rnn, mkldnn.matmul/conv/rnn); `TestCase.setUp` snapshots them and `tearDown` compares, restores, and raises `AssertionError` naming the leaked flag. `recover_orig_fp32_precision` is refactored to reuse the same snapshot/restore. An opt-out env var `PYTORCH_DISABLE_FP32_PRECISION_LEAK_CHECK=1` exists as a short-term escape hatch; the goal is zero callers.

With the detector on, the remaining changes fix tests it would now reject. Inductor suites that set process-global precision at import time move the set into `setUpModule`/`tearDownModule` with save/restore, so importing the module no longer poisons precision for everything imported after it; distributed suites that set `allow_tf32 = False` at import time get the same treatment. The `test_linalg.py` tunableop tests replace a hardcoded `finally: allow_tf32 = False` with `tf32_enabled()`, and `TestLinalg`/`TestMatmulCuda` `setUp`/`tearDown` snapshot the real `fp32_precision` instead of restoring a hardcoded value. Three single-test leaks (kernel_benchmark, mix_order_reduction, torchinductor) get `@recover_orig_fp32_precision`.

Finally, with leaks no longer possible, the `with_ieee_matmul_precision` decorator added in pytorch#180926 is redundant: its five call sites (`test_old_cholesky`, `test_rnn_fused`, three affine_grid/grid_sample tests) pass at the default precision once nothing leaks TF32 into them, so the decorator and its call sites are removed.

Suggested review order: `common_utils.py` (detector + helpers) first, then the offender fixes, then the decorator removal.

## Test Plan

Verified on ROCm/MI300 (gfx942); CUDA paths validated in CI.

```
# precision setup/teardown changes in test_linalg
HIP_VISIBLE_DEVICES=7 python test/test_linalg.py \
  TestLinalgCUDA.test_tf32_tunableop_cuda_float32 \
  TestLinalgCUDA.test_tf32_offline_tunableop_cuda_float32

# the five tests that previously needed with_ieee_matmul_precision, now without it
HIP_VISIBLE_DEVICES=7 python test/test_nn.py \
  TestNNDeviceTypeCUDA.test_affine_2d_rotate90_cuda \
  TestNNDeviceTypeCUDA.test_affine_2d_rotateRandom_cuda \
  TestNNDeviceTypeCUDA.test_affine_3d_rotateRandom_cuda \
  TestNNDeviceTypeCUDA.test_rnn_fused_cuda_float32 \
  TestNNDeviceTypeCUDA.test_rnn_fused_cuda_float64
HIP_VISIBLE_DEVICES=7 python test/test_linalg.py TestLinalgCUDA.test_old_cholesky_cuda_float32
```

All passed. The detector was also confirmed to fire on an intentional leak and to honor the opt-out env var.

## BC-breaking?

No. `torch.testing._internal` is private API, and the removed `with_ieee_matmul_precision` was only added recently in pytorch#180926. The new `tearDown` assertion can surface pre-existing precision-flag leaks in out-of-tree test suites built on our `TestCase`; `PYTORCH_DISABLE_FP32_PRECISION_LEAK_CHECK=1` disables it if needed.

Authored by Claude.

Pull Request resolved: pytorch#185236
Approved by: https://github.com/albanD
youlituao pushed a commit to youlituao/pytorch that referenced this pull request Jul 28, 2026
pytorch#185236)"

This reverts commit 85ac0b1.

Reverted pytorch#185236 on behalf of https://github.com/pytorch-auto-revert due to Reverted automatically by pytorch's autorevert, to avoid this behaviour add the tag autorevert: disable ([comment](pytorch#185236 (comment)))
youlituao pushed a commit to youlituao/pytorch that referenced this pull request Jul 28, 2026
…ch#185236)

Follow-up to pytorch#180926. In review there, @albanD asked that we not spread defensive `with_ieee_matmul_precision` decorators across matmul-using tests, and instead fix the root cause: tests that leave a global fp32 precision flag in a non-default state, plus the base `TestCase` not catching such leaks.

This makes any test running under `torch.testing._internal.common_utils.TestCase` start from a known precision baseline, and turns a leak into a loud failure in `tearDown` rather than a silent tolerance failure in an unrelated sibling test.

The core change is in `common_utils.py`: a single `_fp32_precision_flag_specs()` enumerates the six flags (cuda.matmul, cudnn.conv/rnn, mkldnn.matmul/conv/rnn); `TestCase.setUp` snapshots them and `tearDown` compares, restores, and raises `AssertionError` naming the leaked flag. `recover_orig_fp32_precision` is refactored to reuse the same snapshot/restore. An opt-out env var `PYTORCH_DISABLE_FP32_PRECISION_LEAK_CHECK=1` exists as a short-term escape hatch; the goal is zero callers.

With the detector on, the remaining changes fix tests it would now reject. Inductor suites that set process-global precision at import time move the set into `setUpModule`/`tearDownModule` with save/restore, so importing the module no longer poisons precision for everything imported after it; distributed suites that set `allow_tf32 = False` at import time get the same treatment. The `test_linalg.py` tunableop tests replace a hardcoded `finally: allow_tf32 = False` with `tf32_enabled()`, and `TestLinalg`/`TestMatmulCuda` `setUp`/`tearDown` snapshot the real `fp32_precision` instead of restoring a hardcoded value. Three single-test leaks (kernel_benchmark, mix_order_reduction, torchinductor) get `@recover_orig_fp32_precision`.

Finally, with leaks no longer possible, the `with_ieee_matmul_precision` decorator added in pytorch#180926 is redundant: its five call sites (`test_old_cholesky`, `test_rnn_fused`, three affine_grid/grid_sample tests) pass at the default precision once nothing leaks TF32 into them, so the decorator and its call sites are removed.

Suggested review order: `common_utils.py` (detector + helpers) first, then the offender fixes, then the decorator removal.

## Test Plan

Verified on ROCm/MI300 (gfx942); CUDA paths validated in CI.

```
# precision setup/teardown changes in test_linalg
HIP_VISIBLE_DEVICES=7 python test/test_linalg.py \
  TestLinalgCUDA.test_tf32_tunableop_cuda_float32 \
  TestLinalgCUDA.test_tf32_offline_tunableop_cuda_float32

# the five tests that previously needed with_ieee_matmul_precision, now without it
HIP_VISIBLE_DEVICES=7 python test/test_nn.py \
  TestNNDeviceTypeCUDA.test_affine_2d_rotate90_cuda \
  TestNNDeviceTypeCUDA.test_affine_2d_rotateRandom_cuda \
  TestNNDeviceTypeCUDA.test_affine_3d_rotateRandom_cuda \
  TestNNDeviceTypeCUDA.test_rnn_fused_cuda_float32 \
  TestNNDeviceTypeCUDA.test_rnn_fused_cuda_float64
HIP_VISIBLE_DEVICES=7 python test/test_linalg.py TestLinalgCUDA.test_old_cholesky_cuda_float32
```

All passed. The detector was also confirmed to fire on an intentional leak and to honor the opt-out env var.

## BC-breaking?

No. `torch.testing._internal` is private API, and the removed `with_ieee_matmul_precision` was only added recently in pytorch#180926. The new `tearDown` assertion can surface pre-existing precision-flag leaks in out-of-tree test suites built on our `TestCase`; `PYTORCH_DISABLE_FP32_PRECISION_LEAK_CHECK=1` disables it if needed.

Authored by Claude.

Pull Request resolved: pytorch#185236
Approved by: https://github.com/albanD
youlituao pushed a commit to youlituao/pytorch that referenced this pull request Jul 28, 2026
pytorch#185236)"

This reverts commit 1344b3c.

Reverted pytorch#185236 on behalf of https://github.com/pytorch-auto-revert due to Reverted automatically by pytorch's autorevert, to avoid this behaviour add the tag autorevert: disable ([comment](pytorch#185236 (comment)))
youlituao pushed a commit to youlituao/pytorch that referenced this pull request Jul 28, 2026
…ch#185236)

Follow-up to pytorch#180926. In review there, @albanD asked that we not spread defensive `with_ieee_matmul_precision` decorators across matmul-using tests, and instead fix the root cause: tests that leave a global fp32 precision flag in a non-default state, plus the base `TestCase` not catching such leaks.

This makes any test running under `torch.testing._internal.common_utils.TestCase` start from a known precision baseline, and turns a leak into a loud failure in `tearDown` rather than a silent tolerance failure in an unrelated sibling test.

The core change is in `common_utils.py`: a single `_fp32_precision_flag_specs()` enumerates the six flags (cuda.matmul, cudnn.conv/rnn, mkldnn.matmul/conv/rnn); `TestCase.setUp` snapshots them and `tearDown` compares, restores, and raises `AssertionError` naming the leaked flag. `recover_orig_fp32_precision` is refactored to reuse the same snapshot/restore. An opt-out env var `PYTORCH_DISABLE_FP32_PRECISION_LEAK_CHECK=1` exists as a short-term escape hatch; the goal is zero callers.

With the detector on, the remaining changes fix tests it would now reject. Inductor suites that set process-global precision at import time move the set into `setUpModule`/`tearDownModule` with save/restore, so importing the module no longer poisons precision for everything imported after it; distributed suites that set `allow_tf32 = False` at import time get the same treatment. The `test_linalg.py` tunableop tests replace a hardcoded `finally: allow_tf32 = False` with `tf32_enabled()`, and `TestLinalg`/`TestMatmulCuda` `setUp`/`tearDown` snapshot the real `fp32_precision` instead of restoring a hardcoded value. Three single-test leaks (kernel_benchmark, mix_order_reduction, torchinductor) get `@recover_orig_fp32_precision`.

Finally, with leaks no longer possible, the `with_ieee_matmul_precision` decorator added in pytorch#180926 is redundant: its five call sites (`test_old_cholesky`, `test_rnn_fused`, three affine_grid/grid_sample tests) pass at the default precision once nothing leaks TF32 into them, so the decorator and its call sites are removed.

Suggested review order: `common_utils.py` (detector + helpers) first, then the offender fixes, then the decorator removal.

## Test Plan

Verified on ROCm/MI300 (gfx942); CUDA paths validated in CI.

```
# precision setup/teardown changes in test_linalg
HIP_VISIBLE_DEVICES=7 python test/test_linalg.py \
  TestLinalgCUDA.test_tf32_tunableop_cuda_float32 \
  TestLinalgCUDA.test_tf32_offline_tunableop_cuda_float32

# the five tests that previously needed with_ieee_matmul_precision, now without it
HIP_VISIBLE_DEVICES=7 python test/test_nn.py \
  TestNNDeviceTypeCUDA.test_affine_2d_rotate90_cuda \
  TestNNDeviceTypeCUDA.test_affine_2d_rotateRandom_cuda \
  TestNNDeviceTypeCUDA.test_affine_3d_rotateRandom_cuda \
  TestNNDeviceTypeCUDA.test_rnn_fused_cuda_float32 \
  TestNNDeviceTypeCUDA.test_rnn_fused_cuda_float64
HIP_VISIBLE_DEVICES=7 python test/test_linalg.py TestLinalgCUDA.test_old_cholesky_cuda_float32
```

All passed. The detector was also confirmed to fire on an intentional leak and to honor the opt-out env var.

## BC-breaking?

No. `torch.testing._internal` is private API, and the removed `with_ieee_matmul_precision` was only added recently in pytorch#180926. The new `tearDown` assertion can surface pre-existing precision-flag leaks in out-of-tree test suites built on our `TestCase`; `PYTORCH_DISABLE_FP32_PRECISION_LEAK_CHECK=1` disables it if needed.

Authored by Claude.

Pull Request resolved: pytorch#185236
Approved by: https://github.com/albanD
youlituao pushed a commit to youlituao/pytorch that referenced this pull request Jul 28, 2026
…ch#185236)

Follow-up to pytorch#180926. In review there, @albanD asked that we not spread defensive `with_ieee_matmul_precision` decorators across matmul-using tests, and instead fix the root cause: tests that leave a global fp32 precision flag in a non-default state, plus the base `TestCase` not catching such leaks.

This makes any test running under `torch.testing._internal.common_utils.TestCase` start from a known precision baseline, and turns a leak into a loud failure in `tearDown` rather than a silent tolerance failure in an unrelated sibling test.

The core change is in `common_utils.py`: a single `_fp32_precision_flag_specs()` enumerates the six flags (cuda.matmul, cudnn.conv/rnn, mkldnn.matmul/conv/rnn); `TestCase.setUp` snapshots them and `tearDown` compares, restores, and raises `AssertionError` naming the leaked flag. `recover_orig_fp32_precision` is refactored to reuse the same snapshot/restore. An opt-out env var `PYTORCH_DISABLE_FP32_PRECISION_LEAK_CHECK=1` exists as a short-term escape hatch; the goal is zero callers.

With the detector on, the remaining changes fix tests it would now reject. Inductor suites that set process-global precision at import time move the set into `setUpModule`/`tearDownModule` with save/restore, so importing the module no longer poisons precision for everything imported after it; distributed suites that set `allow_tf32 = False` at import time get the same treatment. The `test_linalg.py` tunableop tests replace a hardcoded `finally: allow_tf32 = False` with `tf32_enabled()`, and `TestLinalg`/`TestMatmulCuda` `setUp`/`tearDown` snapshot the real `fp32_precision` instead of restoring a hardcoded value. Three single-test leaks (kernel_benchmark, mix_order_reduction, torchinductor) get `@recover_orig_fp32_precision`.

Finally, with leaks no longer possible, the `with_ieee_matmul_precision` decorator added in pytorch#180926 is redundant: its five call sites (`test_old_cholesky`, `test_rnn_fused`, three affine_grid/grid_sample tests) pass at the default precision once nothing leaks TF32 into them, so the decorator and its call sites are removed.

Suggested review order: `common_utils.py` (detector + helpers) first, then the offender fixes, then the decorator removal.

## Test Plan

Verified on ROCm/MI300 (gfx942); CUDA paths validated in CI.

```
# precision setup/teardown changes in test_linalg
HIP_VISIBLE_DEVICES=7 python test/test_linalg.py \
  TestLinalgCUDA.test_tf32_tunableop_cuda_float32 \
  TestLinalgCUDA.test_tf32_offline_tunableop_cuda_float32

# the five tests that previously needed with_ieee_matmul_precision, now without it
HIP_VISIBLE_DEVICES=7 python test/test_nn.py \
  TestNNDeviceTypeCUDA.test_affine_2d_rotate90_cuda \
  TestNNDeviceTypeCUDA.test_affine_2d_rotateRandom_cuda \
  TestNNDeviceTypeCUDA.test_affine_3d_rotateRandom_cuda \
  TestNNDeviceTypeCUDA.test_rnn_fused_cuda_float32 \
  TestNNDeviceTypeCUDA.test_rnn_fused_cuda_float64
HIP_VISIBLE_DEVICES=7 python test/test_linalg.py TestLinalgCUDA.test_old_cholesky_cuda_float32
```

All passed. The detector was also confirmed to fire on an intentional leak and to honor the opt-out env var.

## BC-breaking?

No. `torch.testing._internal` is private API, and the removed `with_ieee_matmul_precision` was only added recently in pytorch#180926. The new `tearDown` assertion can surface pre-existing precision-flag leaks in out-of-tree test suites built on our `TestCase`; `PYTORCH_DISABLE_FP32_PRECISION_LEAK_CHECK=1` disables it if needed.

Authored by Claude.

Pull Request resolved: pytorch#185236
Approved by: https://github.com/albanD
aws-kingrj pushed a commit to amazon-contributing/upstream-to-pytorch that referenced this pull request Jul 29, 2026
…ch#185236)

Follow-up to pytorch#180926. In review there, @albanD asked that we not spread defensive `with_ieee_matmul_precision` decorators across matmul-using tests, and instead fix the root cause: tests that leave a global fp32 precision flag in a non-default state, plus the base `TestCase` not catching such leaks.

This makes any test running under `torch.testing._internal.common_utils.TestCase` start from a known precision baseline, and turns a leak into a loud failure in `tearDown` rather than a silent tolerance failure in an unrelated sibling test.

The core change is in `common_utils.py`: a single `_fp32_precision_flag_specs()` enumerates the six flags (cuda.matmul, cudnn.conv/rnn, mkldnn.matmul/conv/rnn); `TestCase.setUp` snapshots them and `tearDown` compares, restores, and raises `AssertionError` naming the leaked flag. `recover_orig_fp32_precision` is refactored to reuse the same snapshot/restore. An opt-out env var `PYTORCH_DISABLE_FP32_PRECISION_LEAK_CHECK=1` exists as a short-term escape hatch; the goal is zero callers.

With the detector on, the remaining changes fix tests it would now reject. Inductor suites that set process-global precision at import time move the set into `setUpModule`/`tearDownModule` with save/restore, so importing the module no longer poisons precision for everything imported after it; distributed suites that set `allow_tf32 = False` at import time get the same treatment. The `test_linalg.py` tunableop tests replace a hardcoded `finally: allow_tf32 = False` with `tf32_enabled()`, and `TestLinalg`/`TestMatmulCuda` `setUp`/`tearDown` snapshot the real `fp32_precision` instead of restoring a hardcoded value. Three single-test leaks (kernel_benchmark, mix_order_reduction, torchinductor) get `@recover_orig_fp32_precision`.

Finally, with leaks no longer possible, the `with_ieee_matmul_precision` decorator added in pytorch#180926 is redundant: its five call sites (`test_old_cholesky`, `test_rnn_fused`, three affine_grid/grid_sample tests) pass at the default precision once nothing leaks TF32 into them, so the decorator and its call sites are removed.

Suggested review order: `common_utils.py` (detector + helpers) first, then the offender fixes, then the decorator removal.

## Test Plan

Verified on ROCm/MI300 (gfx942); CUDA paths validated in CI.

```
# precision setup/teardown changes in test_linalg
HIP_VISIBLE_DEVICES=7 python test/test_linalg.py \
  TestLinalgCUDA.test_tf32_tunableop_cuda_float32 \
  TestLinalgCUDA.test_tf32_offline_tunableop_cuda_float32

# the five tests that previously needed with_ieee_matmul_precision, now without it
HIP_VISIBLE_DEVICES=7 python test/test_nn.py \
  TestNNDeviceTypeCUDA.test_affine_2d_rotate90_cuda \
  TestNNDeviceTypeCUDA.test_affine_2d_rotateRandom_cuda \
  TestNNDeviceTypeCUDA.test_affine_3d_rotateRandom_cuda \
  TestNNDeviceTypeCUDA.test_rnn_fused_cuda_float32 \
  TestNNDeviceTypeCUDA.test_rnn_fused_cuda_float64
HIP_VISIBLE_DEVICES=7 python test/test_linalg.py TestLinalgCUDA.test_old_cholesky_cuda_float32
```

All passed. The detector was also confirmed to fire on an intentional leak and to honor the opt-out env var.

## BC-breaking?

No. `torch.testing._internal` is private API, and the removed `with_ieee_matmul_precision` was only added recently in pytorch#180926. The new `tearDown` assertion can surface pre-existing precision-flag leaks in out-of-tree test suites built on our `TestCase`; `PYTORCH_DISABLE_FP32_PRECISION_LEAK_CHECK=1` disables it if needed.

Authored by Claude.

Pull Request resolved: pytorch#185236
Approved by: https://github.com/albanD
aws-kingrj pushed a commit to amazon-contributing/upstream-to-pytorch that referenced this pull request Jul 29, 2026
pytorch#185236)"

This reverts commit 85ac0b1.

Reverted pytorch#185236 on behalf of https://github.com/pytorch-auto-revert due to Reverted automatically by pytorch's autorevert, to avoid this behaviour add the tag autorevert: disable ([comment](pytorch#185236 (comment)))
aws-kingrj pushed a commit to amazon-contributing/upstream-to-pytorch that referenced this pull request Jul 29, 2026
…ch#185236)

Follow-up to pytorch#180926. In review there, @albanD asked that we not spread defensive `with_ieee_matmul_precision` decorators across matmul-using tests, and instead fix the root cause: tests that leave a global fp32 precision flag in a non-default state, plus the base `TestCase` not catching such leaks.

This makes any test running under `torch.testing._internal.common_utils.TestCase` start from a known precision baseline, and turns a leak into a loud failure in `tearDown` rather than a silent tolerance failure in an unrelated sibling test.

The core change is in `common_utils.py`: a single `_fp32_precision_flag_specs()` enumerates the six flags (cuda.matmul, cudnn.conv/rnn, mkldnn.matmul/conv/rnn); `TestCase.setUp` snapshots them and `tearDown` compares, restores, and raises `AssertionError` naming the leaked flag. `recover_orig_fp32_precision` is refactored to reuse the same snapshot/restore. An opt-out env var `PYTORCH_DISABLE_FP32_PRECISION_LEAK_CHECK=1` exists as a short-term escape hatch; the goal is zero callers.

With the detector on, the remaining changes fix tests it would now reject. Inductor suites that set process-global precision at import time move the set into `setUpModule`/`tearDownModule` with save/restore, so importing the module no longer poisons precision for everything imported after it; distributed suites that set `allow_tf32 = False` at import time get the same treatment. The `test_linalg.py` tunableop tests replace a hardcoded `finally: allow_tf32 = False` with `tf32_enabled()`, and `TestLinalg`/`TestMatmulCuda` `setUp`/`tearDown` snapshot the real `fp32_precision` instead of restoring a hardcoded value. Three single-test leaks (kernel_benchmark, mix_order_reduction, torchinductor) get `@recover_orig_fp32_precision`.

Finally, with leaks no longer possible, the `with_ieee_matmul_precision` decorator added in pytorch#180926 is redundant: its five call sites (`test_old_cholesky`, `test_rnn_fused`, three affine_grid/grid_sample tests) pass at the default precision once nothing leaks TF32 into them, so the decorator and its call sites are removed.

Suggested review order: `common_utils.py` (detector + helpers) first, then the offender fixes, then the decorator removal.

## Test Plan

Verified on ROCm/MI300 (gfx942); CUDA paths validated in CI.

```
# precision setup/teardown changes in test_linalg
HIP_VISIBLE_DEVICES=7 python test/test_linalg.py \
  TestLinalgCUDA.test_tf32_tunableop_cuda_float32 \
  TestLinalgCUDA.test_tf32_offline_tunableop_cuda_float32

# the five tests that previously needed with_ieee_matmul_precision, now without it
HIP_VISIBLE_DEVICES=7 python test/test_nn.py \
  TestNNDeviceTypeCUDA.test_affine_2d_rotate90_cuda \
  TestNNDeviceTypeCUDA.test_affine_2d_rotateRandom_cuda \
  TestNNDeviceTypeCUDA.test_affine_3d_rotateRandom_cuda \
  TestNNDeviceTypeCUDA.test_rnn_fused_cuda_float32 \
  TestNNDeviceTypeCUDA.test_rnn_fused_cuda_float64
HIP_VISIBLE_DEVICES=7 python test/test_linalg.py TestLinalgCUDA.test_old_cholesky_cuda_float32
```

All passed. The detector was also confirmed to fire on an intentional leak and to honor the opt-out env var.

## BC-breaking?

No. `torch.testing._internal` is private API, and the removed `with_ieee_matmul_precision` was only added recently in pytorch#180926. The new `tearDown` assertion can surface pre-existing precision-flag leaks in out-of-tree test suites built on our `TestCase`; `PYTORCH_DISABLE_FP32_PRECISION_LEAK_CHECK=1` disables it if needed.

Authored by Claude.

Pull Request resolved: pytorch#185236
Approved by: https://github.com/albanD
aws-kingrj pushed a commit to amazon-contributing/upstream-to-pytorch that referenced this pull request Jul 29, 2026
pytorch#185236)"

This reverts commit 1344b3c.

Reverted pytorch#185236 on behalf of https://github.com/pytorch-auto-revert due to Reverted automatically by pytorch's autorevert, to avoid this behaviour add the tag autorevert: disable ([comment](pytorch#185236 (comment)))
aws-kingrj pushed a commit to amazon-contributing/upstream-to-pytorch that referenced this pull request Jul 29, 2026
…ch#185236)

Follow-up to pytorch#180926. In review there, @albanD asked that we not spread defensive `with_ieee_matmul_precision` decorators across matmul-using tests, and instead fix the root cause: tests that leave a global fp32 precision flag in a non-default state, plus the base `TestCase` not catching such leaks.

This makes any test running under `torch.testing._internal.common_utils.TestCase` start from a known precision baseline, and turns a leak into a loud failure in `tearDown` rather than a silent tolerance failure in an unrelated sibling test.

The core change is in `common_utils.py`: a single `_fp32_precision_flag_specs()` enumerates the six flags (cuda.matmul, cudnn.conv/rnn, mkldnn.matmul/conv/rnn); `TestCase.setUp` snapshots them and `tearDown` compares, restores, and raises `AssertionError` naming the leaked flag. `recover_orig_fp32_precision` is refactored to reuse the same snapshot/restore. An opt-out env var `PYTORCH_DISABLE_FP32_PRECISION_LEAK_CHECK=1` exists as a short-term escape hatch; the goal is zero callers.

With the detector on, the remaining changes fix tests it would now reject. Inductor suites that set process-global precision at import time move the set into `setUpModule`/`tearDownModule` with save/restore, so importing the module no longer poisons precision for everything imported after it; distributed suites that set `allow_tf32 = False` at import time get the same treatment. The `test_linalg.py` tunableop tests replace a hardcoded `finally: allow_tf32 = False` with `tf32_enabled()`, and `TestLinalg`/`TestMatmulCuda` `setUp`/`tearDown` snapshot the real `fp32_precision` instead of restoring a hardcoded value. Three single-test leaks (kernel_benchmark, mix_order_reduction, torchinductor) get `@recover_orig_fp32_precision`.

Finally, with leaks no longer possible, the `with_ieee_matmul_precision` decorator added in pytorch#180926 is redundant: its five call sites (`test_old_cholesky`, `test_rnn_fused`, three affine_grid/grid_sample tests) pass at the default precision once nothing leaks TF32 into them, so the decorator and its call sites are removed.

Suggested review order: `common_utils.py` (detector + helpers) first, then the offender fixes, then the decorator removal.

## Test Plan

Verified on ROCm/MI300 (gfx942); CUDA paths validated in CI.

```
# precision setup/teardown changes in test_linalg
HIP_VISIBLE_DEVICES=7 python test/test_linalg.py \
  TestLinalgCUDA.test_tf32_tunableop_cuda_float32 \
  TestLinalgCUDA.test_tf32_offline_tunableop_cuda_float32

# the five tests that previously needed with_ieee_matmul_precision, now without it
HIP_VISIBLE_DEVICES=7 python test/test_nn.py \
  TestNNDeviceTypeCUDA.test_affine_2d_rotate90_cuda \
  TestNNDeviceTypeCUDA.test_affine_2d_rotateRandom_cuda \
  TestNNDeviceTypeCUDA.test_affine_3d_rotateRandom_cuda \
  TestNNDeviceTypeCUDA.test_rnn_fused_cuda_float32 \
  TestNNDeviceTypeCUDA.test_rnn_fused_cuda_float64
HIP_VISIBLE_DEVICES=7 python test/test_linalg.py TestLinalgCUDA.test_old_cholesky_cuda_float32
```

All passed. The detector was also confirmed to fire on an intentional leak and to honor the opt-out env var.

## BC-breaking?

No. `torch.testing._internal` is private API, and the removed `with_ieee_matmul_precision` was only added recently in pytorch#180926. The new `tearDown` assertion can surface pre-existing precision-flag leaks in out-of-tree test suites built on our `TestCase`; `PYTORCH_DISABLE_FP32_PRECISION_LEAK_CHECK=1` disables it if needed.

Authored by Claude.

Pull Request resolved: pytorch#185236
Approved by: https://github.com/albanD
MelindaTan pushed a commit to MelindaTan/pytorch that referenced this pull request Jul 31, 2026
…ch#185236)

Follow-up to pytorch#180926. In review there, @albanD asked that we not spread defensive `with_ieee_matmul_precision` decorators across matmul-using tests, and instead fix the root cause: tests that leave a global fp32 precision flag in a non-default state, plus the base `TestCase` not catching such leaks.

This makes any test running under `torch.testing._internal.common_utils.TestCase` start from a known precision baseline, and turns a leak into a loud failure in `tearDown` rather than a silent tolerance failure in an unrelated sibling test.

The core change is in `common_utils.py`: a single `_fp32_precision_flag_specs()` enumerates the six flags (cuda.matmul, cudnn.conv/rnn, mkldnn.matmul/conv/rnn); `TestCase.setUp` snapshots them and `tearDown` compares, restores, and raises `AssertionError` naming the leaked flag. `recover_orig_fp32_precision` is refactored to reuse the same snapshot/restore. An opt-out env var `PYTORCH_DISABLE_FP32_PRECISION_LEAK_CHECK=1` exists as a short-term escape hatch; the goal is zero callers.

With the detector on, the remaining changes fix tests it would now reject. Inductor suites that set process-global precision at import time move the set into `setUpModule`/`tearDownModule` with save/restore, so importing the module no longer poisons precision for everything imported after it; distributed suites that set `allow_tf32 = False` at import time get the same treatment. The `test_linalg.py` tunableop tests replace a hardcoded `finally: allow_tf32 = False` with `tf32_enabled()`, and `TestLinalg`/`TestMatmulCuda` `setUp`/`tearDown` snapshot the real `fp32_precision` instead of restoring a hardcoded value. Three single-test leaks (kernel_benchmark, mix_order_reduction, torchinductor) get `@recover_orig_fp32_precision`.

Finally, with leaks no longer possible, the `with_ieee_matmul_precision` decorator added in pytorch#180926 is redundant: its five call sites (`test_old_cholesky`, `test_rnn_fused`, three affine_grid/grid_sample tests) pass at the default precision once nothing leaks TF32 into them, so the decorator and its call sites are removed.

Suggested review order: `common_utils.py` (detector + helpers) first, then the offender fixes, then the decorator removal.

## Test Plan

Verified on ROCm/MI300 (gfx942); CUDA paths validated in CI.

```
# precision setup/teardown changes in test_linalg
HIP_VISIBLE_DEVICES=7 python test/test_linalg.py \
  TestLinalgCUDA.test_tf32_tunableop_cuda_float32 \
  TestLinalgCUDA.test_tf32_offline_tunableop_cuda_float32

# the five tests that previously needed with_ieee_matmul_precision, now without it
HIP_VISIBLE_DEVICES=7 python test/test_nn.py \
  TestNNDeviceTypeCUDA.test_affine_2d_rotate90_cuda \
  TestNNDeviceTypeCUDA.test_affine_2d_rotateRandom_cuda \
  TestNNDeviceTypeCUDA.test_affine_3d_rotateRandom_cuda \
  TestNNDeviceTypeCUDA.test_rnn_fused_cuda_float32 \
  TestNNDeviceTypeCUDA.test_rnn_fused_cuda_float64
HIP_VISIBLE_DEVICES=7 python test/test_linalg.py TestLinalgCUDA.test_old_cholesky_cuda_float32
```

All passed. The detector was also confirmed to fire on an intentional leak and to honor the opt-out env var.

## BC-breaking?

No. `torch.testing._internal` is private API, and the removed `with_ieee_matmul_precision` was only added recently in pytorch#180926. The new `tearDown` assertion can surface pre-existing precision-flag leaks in out-of-tree test suites built on our `TestCase`; `PYTORCH_DISABLE_FP32_PRECISION_LEAK_CHECK=1` disables it if needed.

Authored by Claude.

Pull Request resolved: pytorch#185236
Approved by: https://github.com/albanD
MelindaTan pushed a commit to MelindaTan/pytorch that referenced this pull request Jul 31, 2026
pytorch#185236)"

This reverts commit 1344b3c.

Reverted pytorch#185236 on behalf of https://github.com/pytorch-auto-revert due to Reverted automatically by pytorch's autorevert, to avoid this behaviour add the tag autorevert: disable ([comment](pytorch#185236 (comment)))
MelindaTan pushed a commit to MelindaTan/pytorch that referenced this pull request Jul 31, 2026
…ch#185236)

Follow-up to pytorch#180926. In review there, @albanD asked that we not spread defensive `with_ieee_matmul_precision` decorators across matmul-using tests, and instead fix the root cause: tests that leave a global fp32 precision flag in a non-default state, plus the base `TestCase` not catching such leaks.

This makes any test running under `torch.testing._internal.common_utils.TestCase` start from a known precision baseline, and turns a leak into a loud failure in `tearDown` rather than a silent tolerance failure in an unrelated sibling test.

The core change is in `common_utils.py`: a single `_fp32_precision_flag_specs()` enumerates the six flags (cuda.matmul, cudnn.conv/rnn, mkldnn.matmul/conv/rnn); `TestCase.setUp` snapshots them and `tearDown` compares, restores, and raises `AssertionError` naming the leaked flag. `recover_orig_fp32_precision` is refactored to reuse the same snapshot/restore. An opt-out env var `PYTORCH_DISABLE_FP32_PRECISION_LEAK_CHECK=1` exists as a short-term escape hatch; the goal is zero callers.

With the detector on, the remaining changes fix tests it would now reject. Inductor suites that set process-global precision at import time move the set into `setUpModule`/`tearDownModule` with save/restore, so importing the module no longer poisons precision for everything imported after it; distributed suites that set `allow_tf32 = False` at import time get the same treatment. The `test_linalg.py` tunableop tests replace a hardcoded `finally: allow_tf32 = False` with `tf32_enabled()`, and `TestLinalg`/`TestMatmulCuda` `setUp`/`tearDown` snapshot the real `fp32_precision` instead of restoring a hardcoded value. Three single-test leaks (kernel_benchmark, mix_order_reduction, torchinductor) get `@recover_orig_fp32_precision`.

Finally, with leaks no longer possible, the `with_ieee_matmul_precision` decorator added in pytorch#180926 is redundant: its five call sites (`test_old_cholesky`, `test_rnn_fused`, three affine_grid/grid_sample tests) pass at the default precision once nothing leaks TF32 into them, so the decorator and its call sites are removed.

Suggested review order: `common_utils.py` (detector + helpers) first, then the offender fixes, then the decorator removal.

## Test Plan

Verified on ROCm/MI300 (gfx942); CUDA paths validated in CI.

```
# precision setup/teardown changes in test_linalg
HIP_VISIBLE_DEVICES=7 python test/test_linalg.py \
  TestLinalgCUDA.test_tf32_tunableop_cuda_float32 \
  TestLinalgCUDA.test_tf32_offline_tunableop_cuda_float32

# the five tests that previously needed with_ieee_matmul_precision, now without it
HIP_VISIBLE_DEVICES=7 python test/test_nn.py \
  TestNNDeviceTypeCUDA.test_affine_2d_rotate90_cuda \
  TestNNDeviceTypeCUDA.test_affine_2d_rotateRandom_cuda \
  TestNNDeviceTypeCUDA.test_affine_3d_rotateRandom_cuda \
  TestNNDeviceTypeCUDA.test_rnn_fused_cuda_float32 \
  TestNNDeviceTypeCUDA.test_rnn_fused_cuda_float64
HIP_VISIBLE_DEVICES=7 python test/test_linalg.py TestLinalgCUDA.test_old_cholesky_cuda_float32
```

All passed. The detector was also confirmed to fire on an intentional leak and to honor the opt-out env var.

## BC-breaking?

No. `torch.testing._internal` is private API, and the removed `with_ieee_matmul_precision` was only added recently in pytorch#180926. The new `tearDown` assertion can surface pre-existing precision-flag leaks in out-of-tree test suites built on our `TestCase`; `PYTORCH_DISABLE_FP32_PRECISION_LEAK_CHECK=1` disables it if needed.

Authored by Claude.

Pull Request resolved: pytorch#185236
Approved by: https://github.com/albanD
torchxpubot pushed a commit to intel/torch-xpu-ops that referenced this pull request Aug 14, 2026
Fixes issues reported in:
#4438

Test cases fixed:
```
dynamo.test_misc_xpu.MiscTests,test_recompile_on_global_state_change
dynamo.test_regional_inductor_xpu.RegionalInductorInvokeSubgraphTests,test_max_autotune_no_cudagraphs_serialize_False
dynamo.test_regional_inductor_xpu.RegionalInductorInvokeSubgraphTests,test_invalid_inductor_config
```
`test_misc_xpu` changed upstream in
pytorch/pytorch#185236
`test_regional_inductor_xpu` changed upstream in
pytorch/pytorch#190068
pytorchmergebot pushed a commit that referenced this pull request Aug 19, 2026
Reading torch.get_float32_matmul_precision() or torch.backends.cuda.matmul.allow_tf32 raises a mixed-API TORCH_CHECK error whenever fp32 precision was last written through the new per-backend torch.backends.cuda.matmul.fp32_precision API, because the new-style setter intentionally does not update the legacy global enum. Several framework-internal hot paths still read through the legacy getters, so a single new-style write poisons inductor compilation (cache keys in codecache and select_algorithm), dynamo region tracking, TunableOp type naming, and ROCm CK instance gating. This blocks migrating tests and user code to the new API, as suggested by review on #185236.

This PR converts those framework-internal readers to the resolved per-backend getters (torch._C._get_fp32_precision_getter in Python, Context::float32Precision in C++), which never throw and are the same source of truth the aten matmul paths already consult. The two inductor cache keys now key on the (cuda, mkldnn) matmul precision pair via a shared fp32_matmul_precision_key() helper; the pair carries exactly the information of the legacy string ("highest" -> ieee/ieee, "high" -> tf32/tf32, "medium" -> tf32/bf16). torch/utils/benchmark/utils/compile.py previously called the legacy getter at import time; the snapshot is now taken lazily and only when the util actually changes the precision. The legacy API surface itself (the bindings behind get_float32_matmul_precision and allow_tf32) keeps its consistency check by design, and legacy writers are untouched since the legacy setters keep both representations in sync.

An alternative was to relax the TORCH_CHECK in Context::allowTF32CuBLAS() and Context::float32MatmulPrecision(), but that check is the only guard alerting users to genuinely inconsistent mixed usage, so migrating the internal readers is strictly safer.

Test Plan:

Verified the failure mode and the fix on a ROCm host (gfx90a). Before this change, importing the benchmark util or reading the legacy getters after a new-style write raises; after it, all converted readers work under both APIs:

```
python -c "
import torch
torch.backends.cuda.matmul.fp32_precision = 'tf32'
print(torch._C._get_fp32_precision_getter('cuda', 'matmul'))"
```

Exercised the modified benchmark util end to end (enable sets high, disable restores highest, idempotent, and no throw under mixed state). Verified getter equivalences under the legacy setter: highest -> ieee/ieee, high -> tf32/tf32, medium -> tf32/bf16 for (cuda, mkldnn).

```
python -m py_compile torch/_inductor/utils.py torch/_inductor/codecache.py torch/_inductor/select_algorithm.py torch/_inductor/codegen/rocm/ck_template.py torch/_dynamo/graph_region_tracker.py torch/utils/benchmark/utils/compile.py
uv run --script tools/linter/adapters/flake8_linter.py -- <changed py files>
uv run --script tools/linter/adapters/ruff_linter.py --config=pyproject.toml --show-disable -- <changed py files>
g++ -fsyntax-only -std=c++17 (snippet using Context::float32Precision with Float32Backend::CUDA / Float32Op::MATMUL)
```

Authored with Claude Code (Claude).
@github-actions
github-actions Bot deleted the jeffdaily/fp32-precision-audit branch August 21, 2026 02:14
jeffdaily added a commit that referenced this pull request Sep 9, 2026
Reading torch.get_float32_matmul_precision() or torch.backends.cuda.matmul.allow_tf32 raises a mixed-API TORCH_CHECK error whenever fp32 precision was last written through the new per-backend torch.backends.cuda.matmul.fp32_precision API, because the new-style setter intentionally does not update the legacy global enum. Several framework-internal hot paths still read through the legacy getters, so a single new-style write poisons inductor compilation (cache keys in codecache and select_algorithm), ROCm CK instance gating, and the benchmark compile util. This blocks migrating tests and user code to the new API, as suggested by review on #185236.

This PR converts those framework-internal readers to the resolved per-backend getter (torch._C._get_fp32_precision_getter), which never throws and is the same source of truth the aten matmul paths already consult. The two inductor cache keys now key on the (cuda, mkldnn) matmul precision pair via a shared fp32_matmul_precision_key() helper; the pair carries exactly the information of the legacy string ("highest" -> ieee/ieee, "high" -> tf32/tf32, "medium" -> tf32/bf16). torch/utils/benchmark/utils/compile.py previously called the legacy getter at import time; the snapshot is now taken lazily and only when the util actually changes the precision. The legacy API surface itself (the bindings behind get_float32_matmul_precision and allow_tf32) keeps its consistency check by design, and legacy writers are untouched since the legacy setters keep both representations in sync.

The TunableOp TypeName and dynamo graph_region_tracker readers this PR originally also migrated were converted upstream in the meantime by #195301, so they dropped out of the diff when rebasing onto viable/strict.

An alternative was to relax the TORCH_CHECK in Context::allowTF32CuBLAS() and Context::float32MatmulPrecision(), but that check is the only guard alerting users to genuinely inconsistent mixed usage, so migrating the internal readers is strictly safer.

Test Plan:

Verified the failure mode and the fix on a ROCm host (gfx90a). Before this change, importing the benchmark util or reading the legacy getters after a new-style write raises; after it, all converted readers work under both APIs:

```
python -c "
import torch
torch.backends.cuda.matmul.fp32_precision = 'tf32'
print(torch._C._get_fp32_precision_getter('cuda', 'matmul'))"
```

Exercised the modified benchmark util end to end (enable sets high, disable restores highest, idempotent, and no throw under mixed state). Verified getter equivalences under the legacy setter: highest -> ieee/ieee, high -> tf32/tf32, medium -> tf32/bf16 for (cuda, mkldnn).

```
python -m py_compile torch/_inductor/utils.py torch/_inductor/codecache.py torch/_inductor/select_algorithm.py torch/_inductor/codegen/rocm/ck_template.py torch/utils/benchmark/utils/compile.py
lintrunner --skip PYREFLY <changed py files>
```

Authored with Claude Code (Claude).
minmingzhu pushed a commit to minmingzhu/torch-xpu-ops that referenced this pull request Sep 15, 2026
Fixes issues reported in:
intel#4438

Test cases fixed:
```
dynamo.test_misc_xpu.MiscTests,test_recompile_on_global_state_change
dynamo.test_regional_inductor_xpu.RegionalInductorInvokeSubgraphTests,test_max_autotune_no_cudagraphs_serialize_False
dynamo.test_regional_inductor_xpu.RegionalInductorInvokeSubgraphTests,test_invalid_inductor_config
```
`test_misc_xpu` changed upstream in
pytorch/pytorch#185236
`test_regional_inductor_xpu` changed upstream in
pytorch/pytorch#190068
pytorchmergebot pushed a commit that referenced this pull request Sep 18, 2026
)

Reading `torch.get_float32_matmul_precision()` or `torch.backends.cuda.matmul.allow_tf32` raises a mixed-API TORCH_CHECK error whenever fp32 precision was last written through the new per-backend `torch.backends.cuda.matmul.fp32_precision` API, because the new-style setter intentionally does not update the legacy global enum. Several framework-internal hot paths still read through the legacy getters, so a single new-style write poisons inductor compilation (cache keys in codecache and select_algorithm), ROCm CK instance gating, flex attention precision selection, and the benchmark compile util. This blocks migrating tests and user code to the new API, as suggested in review on #185236.

This PR converts those framework-internal readers to the resolved per-backend getter (`torch._C._get_fp32_precision_getter`), which never throws and is the same source of truth the aten matmul paths already consult. The converted readers are the two inductor cache keys (now keyed on the (cuda, mkldnn) matmul precision pair via a shared `fp32_matmul_precision_key()` helper; the pair carries exactly the information of the legacy string: "highest" -> ieee/ieee, "high" -> tf32/tf32, "medium" -> tf32/bf16), ROCm CK instance gating, flex attention's `set_float32_precision()` (its legacy fallback for the unset "none" state still threw on new-style writes to other backends; a resolved "none" means unset at every level of the per-backend hierarchy, which is exactly the legacy default "highest", so the fallback collapses to "ieee"), and `torch/utils/benchmark/utils/compile.py`, which previously called the legacy getter at import time and now snapshots lazily. The legacy API surface itself keeps its consistency check by design, and legacy writers are untouched since the legacy setters keep both representations in sync. A regression test (`test_fp32_precision_new_api_internal_readers` in test_cuda.py) exercises the converted readers under the mixed state that makes the legacy getters raise.

The TunableOp TypeName and dynamo `get_global_state_key()` readers this PR originally also migrated were converted upstream in the meantime by #195301, so they dropped out of the diff when rebasing.

#196860 landed a narrower workaround at the two autotune cache-key sites this PR migrates: it reads the new-style per-backend value and only falls back to the legacy getter when that value is not `bfx9`. That dodges the throw for `bfx9` specifically, but the legacy getter still throws for every other precision written through the new API. `fp32_matmul_precision_key()` supersedes it, because it never consults the legacy getter at all and so covers `bfx9` along with the rest; merging main therefore drops that workaround. `test_precompile_cache_key_handles_bfx9` is updated for the pair-format key and tightened to assert the legacy getter is never called for any precision.

Compatibility note: the autotune/precompile cache-key component changes format (e.g. "high" becomes "cuda:tf32,mkldnn:tf32"), which invalidates existing on-disk autotune caches once on upgrade; this causes a one-time re-benchmark and has no correctness impact.

An alternative was to relax the TORCH_CHECK in `Context::allowTF32CuBLAS()` / `Context::float32MatmulPrecision()`, but that check is the only guard alerting users to genuinely inconsistent mixed usage, so migrating the internal readers is strictly safer.

A follow-up will migrate the module-level precision setup in the test suite to the per-backend API (the follow-up promised in the #185236 review thread).

Authored with an AI assistant (Claude Code).

Pull Request resolved: #189955
Approved by: https://github.com/drisspg
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ci-no-td Do not run TD on this PR ciflow/b200 ciflow/h100 ciflow/inductor ciflow/rocm-mi300 Trigger "default" config CI on ROCm MI300 ciflow/trunk Trigger trunk jobs on your pull request Merged module: dynamo module: inductor open source release notes: distributed (c10d) release notes category Reverted triaged This issue has been looked at a team member, and triaged and prioritized into an appropriate module

Projects

None yet

Development

Successfully merging this pull request may close these issues.

6 participants