Skip to content

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

Closed

Description

@KimbingNg

🐛 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

Activity

  1. added
    oncall: distributed
    triaged
    on Jul 14, 2025
  2. weifengpy commented on Jul 14, 2025

    @weifengpy
    Contributor

    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?

  3. KimbingNg commented on Jul 15, 2025

    @KimbingNg
    ContributorAuthor

    @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 call pipelineschedule.step() in autocast context, similar issue will arise.

  4. stmcgovern commented on Oct 9, 2025

    @stmcgovern
    Collaborator

    Hi @weifengpy , I believe it to be an autocast caching issue that FSDP2's use case exposes. This PR resolves the runtime error.

  5. added a commit that references this issue on Oct 16, 2025
    5daef30
  6. added a commit that references this issue on Oct 21, 2025
    10ae1a6
  7. added a commit that references this issue on Oct 22, 2025
    e933063
  8. added a commit that references this issue on Dec 10, 2025
    b80d355
  9. added a commit that references this issue on Dec 11, 2025
    0d2098d
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    actionablemodule: fsdponcall: distributedtriaged

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions