Skip to content

Clear ModuleTest/CriterionTest arg cache at every entry point - #196609

Closed
pablo-garay wants to merge 6 commits into
pytorch:mainfrom
ROCm:jeffdaily/test-nn-arg-cache-hermeticity
Closed

pablo-garay wants to merge 6 commits into
pytorch:mainfrom
ROCm:jeffdaily/test-nn-arg-cache-hermeticity

Conversation

@pablo-garay

Copy link
Copy Markdown
Contributor

The generated test_nn variants (cpu, _cuda_fp32, _cuda_tf32, _cuda_double, ...) share one ModuleTest/CriterionTest instance whose _arg_cache lazily draws and caches the input, target and constructor args. setUp reseeds the RNG per variant, but a cache hit skips the input draw, so the module's parameter draw lands at a different RNG position than in a fresh process: which configuration a variant runs depends on which siblings touched the instance earlier in the same process, and it differs from the standalone repro command. This is the mechanism behind the test_nn TF32 transformer tests "failing and then succeeding when run in a new process" on ROCm mi300 CI. Measured on gfx942 the runs are bit-deterministic with three configurations (first toucher = standalone; a test_cuda sibling or in-process rerun first; the cpu sibling first = full unsharded suite order), and CI's two test-level shards with stepcurrent restarts and in-process reruns exercise the first two, which the CI numbers reproduce (TransformerEncoderLayer_gelu 0.2296 abs vs 0.08 in-suite, 0.0157 on the rerun).

First commit: clear the cache at the four public entry points (ModuleTest.call/test_cuda, CriterionTest.call/test_cuda) so the in-suite configuration always equals the standalone one. Standalone configurations are preserved (a fresh process starts from an empty cache), so today's repro commands keep their meaning. Full test_nn before vs after differs by exactly three tests on gfx942 and one on gfx950, each of which already behaves that way standalone; the next two commits handle them.

Second commit ([ROCm]-only): test_Transformer_multilayer_coder_cuda_tf32 (0.129 vs 0.05) and test_AdaptiveLogSoftmax_cuda_tf32 (0.0056 vs 0.005) fail deterministically on gfx942 in the standalone configuration. Single-gemm XF32 calibration is 1.45 x 2^-10 worst case, so hipblasLt meets the TF32 contract; the gaps are a K=4 multilayer composition amplifying that error ~130x, and a single gemm against a tolerance with no TF32 headroom. ROCm-conditional tolerances set to 2x the measurements (0.26, 0.012); derivation, calibration table and caveats in #196605. CUDA tolerances untouched.

Third commit (generic): test_Embedding_discontiguous_cuda flakes standalone on every platform because embedding_dense_backward's fused atomic-accumulate kernel (#172454) is selected for that entry's shape and accumulation order is not reproducible (2.1e-5 spread on gradients of magnitude 56; zero under deterministic algorithms). test_noncontig's parameter-grad compare moves to the same atol=1e-4 its grad-input compare already uses; 25 fresh-process runs go from 7 failures to 0.

Test plan and measurements are in the commit messages. gfx942/gfx90a validation via the ciflow labels below; every generated test_nn variant now runs its standalone configuration in-suite on CUDA too, so the CUDA test_nn shards are the blast-radius check.

This PR was authored with the assistance of an AI agent (Claude). The analysis and test results were verified by hand.

TestBase._arg_cache lazily draws a test's input, target and constructor args and caches them on the ModuleTest/CriterionTest instance. That instance is shared by every generated test_nn variant (the cpu test and the _cuda_fp32/_cuda_tf32/_cuda_double/_cuda_half/... siblings). TestCase.setUp reseeds the RNG before each variant, but on a cache hit the input draw is skipped, so the module constructor's parameter draw happens at a different RNG position than in a fresh process. Which configuration a variant runs therefore depends on which siblings touched the shared instance earlier in the same process, and it silently differs from the standalone repro command the harness prints.

This is the mechanism behind the "failed and then succeeded when run in a new process" pattern on the test_nn TF32 transformer tests on ROCm mi300 CI, which had been read as GPU nondeterminism. Measured on gfx942 with the compares instrumented, every run is bit-deterministic and three configurations exist: (A) the tf32 test is the first to touch the instance, which is what the standalone repro runs; (B) a test_cuda sibling or an in-process rerun of the same test ran first; (C) the cpu sibling ran first, the full unsharded suite order. CI runs test_nn split into two test-level shards with -x/stepcurrent restarts and in-process reruns, so its failing attempts ran (B) (TransformerEncoderLayer_gelu 0.2296 abs vs 0.08 atol; Transformer_multilayer_coder 0.12507 vs 0.05), and its new-process reruns ran (A) (0.0157 pass; 0.12936 fail), matching the gfx942 measurements to the digit. Only (C) passes all five transformer tf32 tests, and CI does not run (C).

Fix: clear the cache at the four public entry points, ModuleTest.__call__/test_cuda and CriterionTest.__call__/test_cuda. The invariant is that the in-suite configuration equals the standalone configuration (A). Clearing at entry preserves every configuration a standalone run produces today (a fresh process starts from an empty cache), so existing repro commands keep meaning what they say; only in-suite runs change, to match them. Alternatives: clearing in TestNN.setUp (every consumer of these entry points, e.g. test_mps and test_xpu, would need the same line) or keying the cache per generated variant (more machinery for the same result). The entry-point clear keeps the invariant inside the class that owns the cache. Direct readers of _get_input() outside these entry points (cpp_api_parity, test_expanded_weights' own TestBase subclass) are unaffected.

Evidence. gfx942 (MI300X, ROCm 10.0): after the fix, the in-suite instrumented values for the transformer tf32 tests reproduce the standalone values bit-for-bit; the four single-layer transformer _tf32 tests pass at their existing tolerances in suite order (worst abs diff 0.0157 / 0.0437 / 0.0257 / 0.0281 vs atol 0.08 / 0.1 / 0.05 / 0.05). Full test_nn.py before vs after (pytest, one process) differs by exactly three tests, all of which already behave this way standalone on the unfixed tree because (A) is the standalone configuration: test_Transformer_multilayer_coder_cuda_tf32 (deterministic 0.129 vs 0.05), test_AdaptiveLogSoftmax_cuda_tf32 (deterministic 0.00559 vs 0.005), and test_Embedding_discontiguous_cuda (flaky at the tolerance edge). The following commits handle those three. gfx950 (MI355X): full test_nn.py before vs after differs only by test_Embedding_discontiguous_cuda (same flake, also standalone).

Test plan (gfx950 and gfx942, editable builds, PYTORCH_TEST_WITH_ROCM=1 as CI sets it):

PYTORCH_TEST_WITH_ROCM=1 python test/test_nn.py -k Transformer
PYTORCH_TEST_WITH_ROCM=1 python test/test_nn.py -k Loss
PYTORCH_TEST_WITH_ROCM=1 python test/test_nn.py

The full-file runs were compared against the same command on the tree without this change. CUDA coverage rides the normal PR CI for test_nn.

Authored with the assistance of an AI agent (Claude); the mechanism, measurements and results were verified by hand.
With the arg-cache fix every test_nn variant runs its standalone configuration in-suite, and on gfx942 (XF32 hardware TF32) two tf32 entries fail deterministically in that configuration. SM90OrLater is True on gfx9, so the effective ROCm atols today are the SM90 branches. Full derivation, calibration table and caveats: pytorch#196605

Transformer_multilayer_coder: 0.1294 abs at max|ref| 6.7 vs 0.05 (mi300 CI: 0.12936). Single-gemm XF32 calibration on the same box is 1.45 x 2^-10 worst case over 100 seeds and five shapes, so hipblasLt meets the TF32 precision contract; the d_model=4 / dim_feedforward=8 two-encoder/two-decoder composition amplifies the systematic operand truncation about 130x for this configuration. 0.26 is 2x the measurement.

AdaptiveLogSoftmax: param-grad 0.0055931 vs 0.005, relative 1.21e-3 = 1.24 x 2^-10, i.e. a single TF32-class gemm error against a tolerance with no TF32 headroom; 0.012 is 2x the measurement, following the 2x pattern the Conv entries in common_nn.py already use (0.01 if TEST_WITH_ROCM else 0.005).

Both configurations are seeded and bit-deterministic, so tolerances chosen against them are stable by construction; a seed sweep shows the multilayer amplification is not bounded across arbitrary seeds, so 0.26 covers the configuration under test rather than the op. gfx950 is unaffected (bf16x3 TF32 emulation, near-fp32 error), gfx90a generates no _tf32 variants, and CUDA tolerances are untouched.

Test plan (gfx942): PYTORCH_TEST_WITH_ROCM=1 python test/test_nn.py -k "Transformer_multilayer_coder or AdaptiveLogSoftmax", suite order, after the arg-cache fix; both tf32 variants pass at the new values and fail at the old ones. gfx950: same command passes before and after.

Authored with the assistance of an AI agent (Claude).
test_noncontig runs the same backward four times (contiguous/non-contiguous input x grad_output) and compares each parameter grad against the first run at the default float32 tolerance (atol 1e-5). Since pytorch#172454 embedding_dense_backward uses a fused atomic-accumulate kernel whenever the segment count is small relative to the GPU; for the Embedding 'discontiguous' entry (4 weights, 3584 indices) the heuristic selects it on every CUDA and ROCm part, and atomic accumulation order is not reproducible. On gfx950, fifty reruns of that backward spread by 2.1e-5 on gradients of magnitude 56 (zero spread under torch.use_deterministic_algorithms(True)), so test_Embedding_discontiguous_cuda fails standalone in 7 of 25 fresh-process runs at 1.07e-5 to 1.53e-5 vs 1e-5 (2 of 6 on gfx942). The full-suite configuration masked this before the arg-cache fix; now every platform runs the standalone data in-suite. The grad-input compare two lines above already uses atol=1e-4, rtol=0 for the same reason; use the same bound for the parameter grads.

Alternative considered: running test_noncontig under deterministic algorithms, rejected because use_deterministic_algorithms raises for modules whose backward has no deterministic implementation and would change what every other entry exercises.

Test plan (gfx950): 25 fresh-process runs of PYTORCH_TEST_WITH_ROCM=1 python test/test_nn.py -k test_Embedding_discontiguous_cuda before (7 failures) and after (0 failures) the change; full test_nn.py unchanged otherwise.

Authored with the assistance of an AI agent (Claude).
@pytorch-bot

pytorch-bot Bot commented Sep 10, 2026 •

Copy link
Copy Markdown

🔗 Helpful Links

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

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 53d0803 with merge base 4c77204 (image):

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.

@pytorch-bot pytorch-bot Bot added the release notes: nn release notes category label Sep 10, 2026
@jithunnair-amd jithunnair-amd added ciflow/trunk Trigger trunk jobs on your pull request ciflow/rocm-mi300 Trigger "default" config CI on ROCm MI300 ciflow/rocm-mi200 Trigger "default" config CI on ROCm MI200 labels Sep 10, 2026
@pytorch-bot

pytorch-bot Bot commented Sep 10, 2026 •

Copy link
Copy Markdown

Workflows were awaiting approval. CI has now been triggered for the ciflow labels on this PR.

The comment at TestBase._arg_cache claimed every public entry point clears the cache and described only the test_cuda ordering. Only ModuleTest and CriterionTest clear it (TestBase subclasses with their own entry points, e.g. test_expanded_weights' ContextManagerTests, do not), and in __call__ the constructor args are drawn before the input, so a stale entry shifts the input draw there and the parameter draw in test_cuda. Reword to state both.

Two corrections to the earlier commit messages on this branch, recorded here since those commits are already pushed: the contiguous/non-contiguous parameter-grad difference measured for test_Embedding_discontiguous_cuda on gfx950 is 3.05e-5 (the 2.1e-5 quoted was the run-to-run spread of the raw backward), so the headroom under the new atol=1e-4 is about 3x; and 76 of the 79 entries that reach test_noncontig run in double on CPU, where that compare's default tolerance was 1e-7, so the shared atol is a much larger loosening there than the float32 framing suggests (measured: no entry changes outcome or becomes vacuous).

Authored with the assistance of an AI agent (Claude).
…dening its tolerance

The previous commit set the ROCm tolerance to 2x the first failing compare, but assertEqual stops at the first failure and the backward loop compares five gradOutput iterations, so later iterations had never been measured; mi300 CI then failed at iteration 3. Measured with the tolerance lifted on gfx942 (all 16 compares), the error is a stable 4e-3 to 2e-2 relative on every compare while the reference magnitude spans 0.1 to 69 across iterations. The 2x-of-worst absolute value (1.1) would make 12 of the 16 compares vacuous, and the harness compares with rtol=0, so no absolute tolerance describes this entry on XF32 hardware. Skip the _tf32 variant on gfx942 only; the _fp32 sibling keeps the correctness coverage and gfx950 (bf16x3 emulation, near-fp32 error) keeps running the tf32 variant. Full envelope: pytorch#196605

test_nn's add_test gains a tf32_decorator entry field applied only to the generated _tf32 variant, so the skip does not touch the cpu, _fp32 or _double siblings and test ids stay the same on every arch. AdaptiveLogSoftmax's 0.012 stands: its full envelope's worst compare (0.00559, a single-gemm 1.24 x 2^-10) is the one it was derived from.

Test plan (gfx950): PYTORCH_TEST_WITH_ROCM=1 python test/test_nn.py -k Transformer_multilayer_coder runs cpu, _cuda_fp32 and _cuda_tf32 (3 ok); with the arch tuple pointed at gfx950 the _tf32 variant reports skipped and the siblings still run. gfx942 via ciflow/rocm-mi300.

Authored with the assistance of an AI agent (Claude).
@jeffdaily

Copy link
Copy Markdown
Collaborator

The only red job is mi350 distributed 1/3, whose test container was killed (exit code 137) before the shard finished; test_nn.py does not run in the distributed config. All eight mi300 default shards, including the one running test_nn, are green on this head: the five transformer _tf32 tests, test_AdaptiveLogSoftmax_cuda_tf32 and test_Embedding_discontiguous_cuda pass with no retry-masked reruns, and the multilayer_coder tf32 variant reports skipped on gfx942 as intended. (Comment drafted with the help of an AI assistant, Claude; verification done by hand.)

@pytorchbot merge -i

@pytorchmergebot

Copy link
Copy Markdown
Collaborator

Merge started

Your change will be merged while ignoring the following 1 checks: trunk / linux-jammy-rocm-py3.10-mi350 / test (distributed, 1, 3, linux.rocm.gpu.gfx950.2)

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

pragupta pushed a commit to ROCm/pytorch that referenced this pull request Sep 22, 2026
…y point (pytorch#196609) (#3654)

Clear ModuleTest/CriterionTest arg cache at every entry point (pytorch#196609)

The generated test_nn variants (cpu, _cuda_fp32, _cuda_tf32,
_cuda_double, ...) share one ModuleTest/CriterionTest instance whose
_arg_cache lazily draws and caches the input, target and constructor
args. setUp reseeds the RNG per variant, but a cache hit skips the input
draw, so the module's parameter draw lands at a different RNG position
than in a fresh process: which configuration a variant runs depends on
which siblings touched the instance earlier in the same process, and it
differs from the standalone repro command. This is the mechanism behind
the test_nn TF32 transformer tests "failing and then succeeding when run
in a new process" on ROCm mi300 CI. Measured on gfx942 the runs are
bit-deterministic with three configurations (first toucher = standalone;
a test_cuda sibling or in-process rerun first; the cpu sibling first =
full unsharded suite order), and CI's two test-level shards with
stepcurrent restarts and in-process reruns exercise the first two, which
the CI numbers reproduce (TransformerEncoderLayer_gelu 0.2296 abs vs
0.08 in-suite, 0.0157 on the rerun).

First commit: clear the cache at the four public entry points
(ModuleTest.__call__/test_cuda, CriterionTest.__call__/test_cuda) so the
in-suite configuration always equals the standalone one. Standalone
configurations are preserved (a fresh process starts from an empty
cache), so today's repro commands keep their meaning. Full test_nn
before vs after differs by exactly three tests on gfx942 and one on
gfx950, each of which already behaves that way standalone; the next two
commits handle them.

Second commit ([ROCm]-only): test_Transformer_multilayer_coder_cuda_tf32
(0.129 vs 0.05) and test_AdaptiveLogSoftmax_cuda_tf32 (0.0056 vs 0.005)
fail deterministically on gfx942 in the standalone configuration.
Single-gemm XF32 calibration is 1.45 x 2^-10 worst case, so hipblasLt
meets the TF32 contract; the gaps are a K=4 multilayer composition
amplifying that error ~130x, and a single gemm against a tolerance with
no TF32 headroom. ROCm-conditional tolerances set to 2x the measurements
(0.26, 0.012); derivation, calibration table and caveats in pytorch#196605.
CUDA tolerances untouched.

Third commit (generic): test_Embedding_discontiguous_cuda flakes
standalone on every platform because embedding_dense_backward's fused
atomic-accumulate kernel (pytorch#172454) is selected for that entry's shape
and accumulation order is not reproducible (2.1e-5 spread on gradients
of magnitude 56; zero under deterministic algorithms). test_noncontig's
parameter-grad compare moves to the same atol=1e-4 its grad-input
compare already uses; 25 fresh-process runs go from 7 failures to 0.

Test plan and measurements are in the commit messages. gfx942/gfx90a
validation via the ciflow labels below; every generated test_nn variant
now runs its standalone configuration in-suite on CUDA too, so the CUDA
test_nn shards are the blast-radius check.

This PR was authored with the assistance of an AI agent (Claude). The
analysis and test results were verified by hand.

Pull Request resolved: pytorch#196609
Approved by: https://github.com/jeffdaily

Co-authored-by: Jeff Daily <[email protected]>
(cherry picked from commit 8b3a092)

Co-authored-by: Jeff Daily <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ciflow/rocm-mi200 Trigger "default" config CI on ROCm MI200 ciflow/rocm-mi300 Trigger "default" config CI on ROCm MI300 ciflow/trunk Trigger trunk jobs on your pull request Merged open source release notes: nn release notes category

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants