Repository navigation
Closed
Labels
actionablemodule: fsdponcall: distributedAdd this issue/PR to distributed oncall triage queuetriagedThis issue has been looked at a team member, and triaged and prioritized into an appropriate module
Description
🐛 Describe the bug
Nesting torch.no_grad context and torch.autocast context when using FSDP2 with fp32 param_dtype, a critical incompatibility arises.
Minimal Reproducible Code:
import torch
import torch.distributed as dist
from torch import nn
from torch.distributed.fsdp import fully_shard, MixedPrecisionPolicy
dist.init_process_group(backend="nccl")
torch.cuda.set_device(dist.get_rank())
m = nn.Linear(2, 2)
# setting both the following flags to True will cause the error
fail_condition1 = True
fail_condition2 = True
if fail_condition1:
param_dtype = torch.float32
else:
param_dtype = torch.bfloat16
m = fully_shard(m, mp_policy=MixedPrecisionPolicy(param_dtype=param_dtype))
m.requires_grad_(True)
inp = torch.randn(8, 2)
with torch.autocast("cuda", dtype=torch.bfloat16, enabled=True):
if fail_condition2:
with torch.no_grad():
m(inp)
m(inp).mean().backward()Error log
[rank0]: Traceback (most recent call last):
[rank0]: File "/tmp/bug.py", line 30, in <module>
[rank0]: m(inp).mean().backward()
[rank0]: File "/usr/local/lib64/python3.12/site-packages/torch/_tensor.py", line 626, in backward
[rank0]: torch.autograd.backward(
[rank0]: File "/usr/local/lib64/python3.12/site-packages/torch/autograd/__init__.py", line 347, in backward
[rank0]: _engine_run_backward(
[rank0]: File "/usr/local/lib64/python3.12/site-packages/torch/autograd/graph.py", line 823, in _engine_run_backward
[rank0]: return Variable._execution_engine.run_backward( # Calls into the C++ engine to run the backward pass
[rank0]: ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
[rank0]: RuntimeError: element 0 of tensors does not require grad and does not have a grad_fn
Please note that the error arises only when both conditions are met:
- Performing a forward pass first, which should be in the nested torch.no_grad-torch.autocast context
- FSDP's MixedPrecisionPolicy specifies param_dtype=torch.float32
Versions
PyTorch version: 2.6.0+cu124
Is debug build: False
CUDA used to build PyTorch: 12.4
ROCM used to build PyTorch: N/A
cc @H-Huang @awgu @wanchaol @fegin @fduwjj @wz337 @wconstab @d4l3k @zhaojuanmao @mrshenli @rohan-varma @chauhang @mori360
Reacted by Wei Feng
Metadata
Metadata
Assignees
Labels
actionablemodule: fsdponcall: distributedAdd this issue/PR to distributed oncall triage queuetriagedThis issue has been looked at a team member, and triaged and prioritized into an appropriate module
Activity
weifengpy commentedon Jul 14, 2025
thanks for the valuable feedback. will take a look. is there a real application to motivate the usage of torch.autocast + mixed prexision + 1st forward in no_grad? your question/repro is valid but understanding the real application could be helfpul
for example, why mixed prexision is not enough and we have to use autocast as well? why 1st forward in no_grad?
KimbingNg commentedon Jul 15, 2025
@weifengpy Thank you for your response. I encountered this issue when using pipeline parallelism with fsdp and autocast.
autocast: Some operators and parameters in my model need to be kept in full precision to avoid numerical instability and some other operators should be automatically applied in lower precision for speed optimization. FSDP MixedPrecisionPolicy only simply convert parameters and inputs to a given dtype and does not support such automatic precision control. That's why we need autocast.
1st no_grad: In Pipeline Parallelism, the first forward call is wrapped in
no_grad()for shape inference (this line). If we callpipelineschedule.step()inautocastcontext, similar issue will arise.stmcgovern commentedon Oct 9, 2025
Hi @weifengpy , I believe it to be an autocast caching issue that FSDP2's use case exposes. This PR resolves the runtime error.
158232 Fix autocast cache incorrectly retaining no_grad state (pytorc…
158232 Fix autocast cache incorrectly retaining no_grad state (pytorc…
158232 Fix autocast cache incorrectly retaining no_grad state (pytorc…
Fix autocast cache gradient tracking (issue pytorch#158232)
Fix autocast cache gradient tracking (issue pytorch#158232)
158232 Fix autocast cache incorrectly retaining no_grad state (#165068)
158232 Fix autocast cache incorrectly retaining no_grad state (pytorc…
[test] Refactor test_autocast.py: make behavior/cache tests device-ag…
fix(bf16): clamp Cohere2 mask + audio targets (XLA NaN hardening)