Skip to content

158232 Fix autocast cache incorrectly retaining no_grad state - #165068

Closed
stmcgovern wants to merge 1 commit into
pytorch:mainfrom
stmcgovern:158232-fsdp2-nograd-autocast
Closed

stmcgovern wants to merge 1 commit into
pytorch:mainfrom
stmcgovern:158232-fsdp2-nograd-autocast

Conversation

@stmcgovern

@stmcgovern stmcgovern commented Oct 9, 2025 •

Copy link
Copy Markdown
Collaborator

Fixes #158232
The autocast caching heuristic in aten/src/ATen/autocast_mode.cpp:139 did not account for gradient mode state when deciding whether to cache. FSDP2 is not directly related.

This PR adds GradMode::is_enabled() check to caching condition. Caching is now disabled in no_grad() contexts to prevent storing tensors with incorrect gradient state. Ensures correctness at the cost of using cache.
This PR proposes separate caches for gradient-enabled and gradient-disabled modes.
This PR uses a single cache and always creates cached tensors with grad enabled. Skips caching in inference_mode (not no_grad). Cached tensors work in both no_grad and grad contexts.
Adds tests.

cc @mcarilli @ptrblck @leslie-fang-intel @jgong5

@pytorch-bot

pytorch-bot Bot commented Oct 9, 2025 •

Copy link
Copy Markdown

🔗 Helpful Links

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

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

✅ You can merge normally! (4 Unrelated Failures)

As of commit 5ecda48 with merge base 75d1815 (image):

FLAKY - The following jobs failed but were likely due to flakiness present on trunk:

BROKEN TRUNK - The following jobs failed but were present on the merge base:

👉 Rebase onto the `viable/strict` branch to avoid these failures

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

Comment thread aten/src/ATen/autocast_mode.cpp Outdated
arg.is_leaf() && !arg.is_view() && cache_enabled &&
!at::caching::is_cached_tensor(arg));
!at::caching::is_cached_tensor(arg) &&
at::GradMode::is_enabled()); // Only cache when gradients are enabled

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.

@janeyx99 : this unblocks fsdp2 training but regress inference perf. any opinions?

@stmcgovern great finding! any chance to not affecting inference? this can be a big perf change

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

@weifengpy Thanks! Yes, I was just trying to highlight the root cause. One idea is to maintain separate caches for gradient-enabled and gradient-disabled modes.

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.

got you - just being able to identify the root cause is a big step

@stmcgovern

Copy link
Copy Markdown
Collaborator Author

I've pushed a dual cache solution for consideration @weifengpy @janeyx99

@janeyx99
janeyx99 requested a review from ngimel October 10, 2025 18:06
@janeyx99

Copy link
Copy Markdown
Contributor

@ngimel Flagging this autocast bug + also for the perf implication

@ngimel

ngimel commented Oct 10, 2025

Copy link
Copy Markdown
Collaborator

Please fix the PR description to reflect the actual PR change. If people complain about extra memory use we'd need to expose control over which mode gets cached, but for now I think it's ok to land as is

@stmcgovern

Copy link
Copy Markdown
Collaborator Author

@pytorchbot label "topic: not user facing"

@pytorch-bot pytorch-bot Bot added the topic: not user facing topic category label Oct 10, 2025
@soulitzer soulitzer added the triaged This issue has been looked at a team member, and triaged and prioritized into an appropriate module label Oct 13, 2025
@stmcgovern

Copy link
Copy Markdown
Collaborator Author

I've added the skip for dynamo decorators for 3 of 4 added tests (failed in previous CI run) and resolved the merge conflict. @ngimel @janeyx99 @weifengpy

@stmcgovern

Copy link
Copy Markdown
Collaborator Author

Hi, any update on this issue?

ngimel
ngimel previously approved these changes Oct 16, 2025
@ngimel

ngimel commented Oct 16, 2025

Copy link
Copy Markdown
Collaborator

@janeyx99 are you ok with landing this?

@janeyx99 janeyx99 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.

The change looks good to me, but I don't feel great that we're just skipping dynamo tests. Do you know why those 3 tests run into KeyErrors?

At the very least, let's track the fact that dynamo doesn't work with the new autocast cache system in an issue and link to that issue in the test skips.

@ngimel

ngimel commented Oct 16, 2025

Copy link
Copy Markdown
Collaborator

Dynamo/inductor already turn off autocast caching

janeyx99
janeyx99 previously approved these changes Oct 16, 2025

@janeyx99 janeyx99 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.

Oh. Then sounds good to me lol

@janeyx99

Copy link
Copy Markdown
Contributor

@pytorchbot merge

@pytorch-bot pytorch-bot Bot added the ciflow/trunk Trigger trunk jobs on your pull request label Oct 16, 2025
@pytorchmergebot

Copy link
Copy Markdown
Collaborator

Merge started

Your change will be merged once all checks pass (ETA 0-4 Hours).

Learn more about merging in the wiki.

Questions? Feedback? Please reach out to the PyTorch DevX Team

Advanced Debugging
Check the merge workflow status
here

@jeffdaily

Copy link
Copy Markdown
Collaborator

@pytorchbot revert -c nosignal -m "This broke ROCm CI. test/test_transformers.py::TestTransformersCUDA::test_transformerencoder_fastpath_use_torchscript_False_enable_nested_tensor_True_use_autocast_True_d_model_256_cuda GH job link HUD commit link"

@pytorchmergebot

Copy link
Copy Markdown
Collaborator

@pytorchbot successfully started a revert job. Check the current status here.
Questions? Feedback? Please reach out to the PyTorch DevX Team

zhudada0120 pushed a commit to zhudada0120/pytorch that referenced this pull request Oct 22, 2025
…h#165068)

Fixes pytorch#158232
The autocast caching heuristic in `aten/src/ATen/autocast_mode.cpp:139` did not account for gradient mode state when deciding whether to cache. FSDP2 is not directly related.

~~This PR adds `GradMode::is_enabled()` check to caching condition. Caching is now disabled in `no_grad()` contexts to prevent storing tensors with incorrect gradient state. Ensures correctness at the cost of using cache.~~
This PR proposes separate caches for gradient-enabled and gradient-disabled modes.
Adds tests.

Pull Request resolved: pytorch#165068
Approved by: https://github.com/ngimel, https://github.com/janeyx99
@stmcgovern
stmcgovern force-pushed the 158232-fsdp2-nograd-autocast branch from 3a8fb13 to 1bb6cfd Compare December 5, 2025 00:36
@pytorch-bot pytorch-bot Bot removed ciflow/trunk Trigger trunk jobs on your pull request ciflow/rocm ciflow/rocm-mi300 Trigger "default" config CI on ROCm MI300 labels Dec 5, 2025
@stmcgovern

Copy link
Copy Markdown
Collaborator Author

@pytorchbot revert -c nosignal -m "This broke ROCm CI. test/test_transformers.py::TestTransformersCUDA::test_transformerencoder_fastpath_use_torchscript_False_enable_nested_tensor_True_use_autocast_True_d_model_256_cuda GH job link HUD commit link"

When I got the opportunity to reproduce this failure on MI300X, investigation showed that the values used in the two caches (one for no_grad and one for grad_enabled) accumulated slightly different values. Different requires_grad states led to different kernel dispatch paths and tiny numerical differences accumulate through transformer layers. This also occurred on CUDA but stayed under the tolerance.

The new commit uses a single cache but always creates the tensor in grad_enabled mode to ensure that it works for grad and no_grad.

The autocast cache was not handling tensors created in no_grad() context.
When a weight was first cast in no_grad mode, the cached result had no
grad_fn. Subsequent uses in grad-enabled mode would reuse this tensor,
breaking gradient computation.

Fix:
1. Skip caching in inference_mode (enable_grad can't override it)
2. Always create cached tensors with grad enabled via AutoGradMode RAII

The cached tensor now has grad_fn and works in both contexts:
- no_grad: grad_fn ignored (correct)
- grad enabled: grad_fn used (correct)

Fixes pytorch#158232
@stmcgovern
stmcgovern force-pushed the 158232-fsdp2-nograd-autocast branch from 1bb6cfd to 5ecda48 Compare December 9, 2025 18:46
@stmcgovern

Copy link
Copy Markdown
Collaborator Author

@janeyx99 @ngimel Would you please take a look at the current version of this fix. Thanks!

@stmcgovern

Copy link
Copy Markdown
Collaborator Author

@pytorchbot merge

@pytorch-bot pytorch-bot Bot added the ciflow/trunk Trigger trunk jobs on your pull request label Dec 10, 2025
@pytorchmergebot

Copy link
Copy Markdown
Collaborator

Merge started

Your change will be merged once all checks pass (ETA 0-4 Hours).

Learn more about merging in the wiki.

Questions? Feedback? Please reach out to the PyTorch DevX Team

Advanced Debugging
Check the merge workflow status
here

@pytorchmergebot

Copy link
Copy Markdown
Collaborator

The merge job was canceled or timed out. This most often happen if two merge requests were issued for the same PR, or if merge job was waiting for more than 6 hours for tests to finish. In later case, please do not hesitate to reissue the merge command
For more information see pytorch-bot wiki.

@stmcgovern

Copy link
Copy Markdown
Collaborator Author

@pytorchbot merge

@pytorchmergebot

Copy link
Copy Markdown
Collaborator

Merge started

Your change will be merged once all checks pass (ETA 0-4 Hours).

Learn more about merging in the wiki.

Questions? Feedback? Please reach out to the PyTorch DevX Team

Advanced Debugging
Check the merge workflow status
here

daisyden pushed a commit to daisyden/pytorch that referenced this pull request Dec 11, 2025
…h#165068)

Fixes pytorch#158232
The autocast caching heuristic in `aten/src/ATen/autocast_mode.cpp:139` did not account for gradient mode state when deciding whether to cache. FSDP2 is not directly related.

~~This PR adds `GradMode::is_enabled()` check to caching condition. Caching is now disabled in `no_grad()` contexts to prevent storing tensors with incorrect gradient state. Ensures correctness at the cost of using cache.~~
~~This PR proposes separate caches for gradient-enabled and gradient-disabled modes.~~
This PR uses a single cache and always creates cached tensors with grad enabled. Skips caching in inference_mode (not no_grad). Cached tensors work in both no_grad and grad contexts.
Adds tests.

Pull Request resolved: pytorch#165068
Approved by: https://github.com/ngimel
bhimrazy added a commit to bhimrazy/pytorch-lightning that referenced this pull request Apr 20, 2026
- Bump `onnx-ir < 0.3.0` to support PyTorch 2.11 schemas
- Update AMP test to expect `grad_fn` since PyTorch 2.11 fixed the autocast cache bug (pytorch/pytorch#165068)
tchaton pushed a commit to Lightning-AI/pytorch-lightning that referenced this pull request Jul 14, 2026
* ci: add pytorch 2.11 to cpu tests

* test: fix precision and onnx tests for PyTorch 2.11

- Bump `onnx-ir < 0.3.0` to support PyTorch 2.11 schemas
- Update AMP test to expect `grad_fn` since PyTorch 2.11 fixed the autocast cache bug (pytorch/pytorch#165068)

* fix: update gloo device condition for PyTorch 2.11 compatibility

* fix: update xfail condition for gloo device in PyTorch 2.11

* update
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/trunk Trigger trunk jobs on your pull request Merged module: amp (automated mixed precision) autocast open source Reverted topic: not user facing topic category 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.

Incompatibility between torch.no_grad, torch.autocast, and FSDP2

8 participants