Repository: pytorch
Issue: vmap with torch.autograd.grad does not work on output of compiled function
Labels: triaged,module: vmap,oncall: pt2,module: functorch,module: pt2-dispatcher

### 🐛 Describe the bug

The following code is an example provided in the documentation of vmap:
```python
import torch

# Setup
N = 5
f = lambda x: x ** 2
x = torch.randn(N, requires_grad=True)
y = f(x)
I_N = torch.eye(N)

# Sequential approach
jacobian_rows = [torch.autograd.grad(y, x, v, retain_graph=True)[0]
                 for v in I_N.unbind()]
jacobian = torch.stack(jacobian_rows)

# vectorized gradient computation
def get_vjp(v):
    return torch.autograd.grad(y, x, v)

jacobian = torch.vmap(get_vjp)(I_N)
```
It works as expected.

If we instead use a compiled version of `f`, it does not work anymore.

```python
import torch

# Setup
N = 5

@torch.compile
def f(x):
    return x ** 2

x = torch.randn(N, requires_grad=True)
y = f(x)
I_N = torch.eye(N)

# Sequential approach
jacobian_rows = [torch.autograd.grad(y, x, v, retain_graph=True)[0]
                 for v in I_N.unbind()]
jacobian = torch.stack(jacobian_rows)

# vectorized gradient computation
def get_vjp(v):
    return torch.autograd.grad(y, x, v)

jacobian = torch.vmap(get_vjp)(I_N)
```
gives the following error:
```
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/home/valerian/.pyenv/versions/test-venv/lib/python3.12/site-packages/torch/_functorch/apis.py", line 203, in wrapped
    return vmap_impl(
           ^^^^^^^^^^
  File "/home/valerian/.pyenv/versions/test-venv/lib/python3.12/site-packages/torch/_functorch/vmap.py", line 331, in vmap_impl
    return _flat_vmap(
           ^^^^^^^^^^^
  File "/home/valerian/.pyenv/versions/test-venv/lib/python3.12/site-packages/torch/_functorch/vmap.py", line 479, in _flat_vmap
    batched_outputs = func(*batched_inputs, **kwargs)
                      ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "<stdin>", line 2, in get_vjp
  File "/home/valerian/.pyenv/versions/test-venv/lib/python3.12/site-packages/torch/autograd/__init__.py", line 496, in grad
    result = _engine_run_backward(
             ^^^^^^^^^^^^^^^^^^^^^
  File "/home/valerian/.pyenv/versions/test-venv/lib/python3.12/site-packages/torch/autograd/graph.py", line 825, in _engine_run_backward
    return Variable._execution_engine.run_backward(  # Calls into the C++ engine to run the backward pass
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/home/valerian/.pyenv/versions/test-venv/lib/python3.12/site-packages/torch/autograd/function.py", line 307, in apply
    return user_fn(self, *args)
           ^^^^^^^^^^^^^^^^^^^^
  File "/home/valerian/.pyenv/versions/test-venv/lib/python3.12/site-packages/torch/_functorch/_aot_autograd/runtime_wrappers.py", line 2048, in backward
    out = call_compiled_backward()
          ^^^^^^^^^^^^^^^^^^^^^^^^
  File "/home/valerian/.pyenv/versions/test-venv/lib/python3.12/site-packages/torch/_functorch/_aot_autograd/runtime_wrappers.py", line 1980, in call_compiled_backward
    out = call_func_at_runtime_with_args(
          ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/home/valerian/.pyenv/versions/test-venv/lib/python3.12/site-packages/torch/_functorch/_aot_autograd/utils.py", line 124, in call_func_at_runtime_with_args
    out = normalize_as_list(f(args))
                            ^^^^^^^
  File "/home/valerian/.pyenv/versions/test-venv/lib/python3.12/site-packages/torch/_dynamo/eval_frame.py", line 632, in _fn
    return fn(*args, **kwargs)
           ^^^^^^^^^^^^^^^^^^^
  File "/home/valerian/.pyenv/versions/test-venv/lib/python3.12/site-packages/torch/_inductor/codecache.py", line 1478, in __call__
    return self.current_callable(inputs)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/tmp/torchinductor_valerian/rb/crbllcqww3ywex2cpe7oqemxcqzr4ij3i6akxypiwhhen3uac4lf.py", line 60, in call
    cpp_fused_mul_pow_0(tangents_1, primals_1, buf0)
RuntimeError: Cannot access data pointer of Tensor that doesn't have storage
Exception raised from throw_data_ptr_access_error at ../c10/core/TensorImpl.cpp:316 (most recent call first):
frame #0: c10::Error::Error(c10::SourceLocation, std::string) + 0x96 (0x7f0379c0f446 in /home/valerian/.pyenv/versions/test-venv/lib/python3.12/site-packages/torch/lib/libc10.so)
frame #1: c10::detail::torchCheckFail(char const*, char const*, unsigned int, char const*) + 0x68 (0x7f0379bb97ad in /home/valerian/.pyenv/versions/test-venv/lib/python3.12/site-packages/torch/lib/libc10.so)
frame #2: c10::TensorImpl::throw_data_ptr_access_error() const + 0x34 (0x7f0379be7874 in /home/valerian/.pyenv/versions/test-venv/lib/python3.12/site-packages/torch/lib/libc10.so)
frame #3: <unknown function> + 0x8fd078 (0x7f03c41bb078 in /home/valerian/.pyenv/versions/test-venv/lib/python3.12/site-packages/torch/lib/libtorch_python.so)
frame #4: <unknown function> + 0x3bff (0x7f0309d91bff in /tmp/torchinductor_valerian/yh/cyh6svyfmlrinzemycsxqkpt5m5dd25usb5jtjtcy2qihw6hf4m4.so)
<omitting python frames>
frame #15: torch::autograd::PyNode::apply(std::vector<at::Tensor, std::allocator<at::Tensor> >&&) + 0x9e (0x7f03c4161e7e in /home/valerian/.pyenv/versions/test-venv/lib/python3.12/site-packages/torch/lib/libtorch_python.so)
frame #16: <unknown function> + 0x55cafbb (0x7f03b422ffbb in /home/valerian/.pyenv/versions/test-venv/lib/python3.12/site-packages/torch/lib/libtorch_cpu.so)
frame #17: torch::autograd::Engine::evaluate_function(std::shared_ptr<torch::autograd::GraphTask>&, torch::autograd::Node*, torch::autograd::InputBuffer&, std::shared_ptr<torch::autograd::ReadyQueue> const&) + 0x15de (0x7f03b422a0ce in /home/valerian/.pyenv/versions/test-venv/lib/python3.12/site-packages/torch/lib/libtorch_cpu.so)
frame #18: torch::autograd::Engine::thread_main(std::shared_ptr<torch::autograd::GraphTask> const&) + 0x69f (0x7f03b422ad2f in /home/valerian/.pyenv/versions/test-venv/lib/python3.12/site-packages/torch/lib/libtorch_cpu.so)
frame #19: torch::autograd::Engine::execute_with_graph_task(std::shared_ptr<torch::autograd::GraphTask> const&, std::shared_ptr<torch::autograd::Node>, torch::autograd::InputBuffer&&) + 0x3d5 (0x7f03b4225325 in /home/valerian/.pyenv/versions/test-venv/lib/python3.12/site-packages/torch/lib/libtorch_cpu.so)
frame #20: torch::autograd::python::PythonEngine::execute_with_graph_task(std::shared_ptr<torch::autograd::GraphTask> const&, std::shared_ptr<torch::autograd::Node>, torch::autograd::InputBuffer&&) + 0x25 (0x7f03c415d5c5 in /home/valerian/.pyenv/versions/test-venv/lib/python3.12/site-packages/torch/lib/libtorch_python.so)
frame #21: torch::autograd::Engine::execute(std::vector<torch::autograd::Edge, std::allocator<torch::autograd::Edge> > const&, std::vector<at::Tensor, std::allocator<at::Tensor> > const&, bool, bool, bool, std::vector<torch::autograd::Edge, std::allocator<torch::autograd::Edge> > const&) + 0xbac (0x7f03b422855c in /home/valerian/.pyenv/versions/test-venv/lib/python3.12/site-packages/torch/lib/libtorch_cpu.so)
frame #22: torch::autograd::python::PythonEngine::execute(std::vector<torch::autograd::Edge, std::allocator<torch::autograd::Edge> > const&, std::vector<at::Tensor, std::allocator<at::Tensor> > const&, bool, bool, bool, std::vector<torch::autograd::Edge, std::allocator<torch::autograd::Edge> > const&) + 0x56 (0x7f03c415d556 in /home/valerian/.pyenv/versions/test-venv/lib/python3.12/site-packages/torch/lib/libtorch_python.so)
frame #23: THPEngine_run_backward(_object*, _object*, _object*) + 0x300 (0x7f03c415b9a0 in /home/valerian/.pyenv/versions/test-venv/lib/python3.12/site-packages/torch/lib/libtorch_python.so)
frame #36: __libc_start_main + 0xf3 (0x7f03c61be083 in /lib/x86_64-linux-gnu/libc.so.6)
frame #37: _start + 0x2e (0x55681171208e in /home/valerian/.pyenv/versions/test-venv/bin/python)
```

I think this is closely related to a similar issue that has already been fixed: https://github.com/pytorch/pytorch/issues/100320

### Versions

/home/valerian/.pyenv/versions/test-venv/lib/python3.12/site-packages/torch/_subclasses/functional_tensor.py:295: UserWarning: Failed to initialize NumPy: No module named 'numpy' (Triggered internally at ../torch/csrc/utils/tensor_numpy.cpp:84.)
  cpu = _conversion_method_template(device=torch.device("cpu"))
Collecting environment information...
PyTorch version: 2.5.0+cu124
Is debug build: False
CUDA used to build PyTorch: 12.4
ROCM used to build PyTorch: N/A

OS: Ubuntu 20.04.6 LTS (x86_64)
GCC version: (Ubuntu 7.5.0-6ubuntu2) 7.5.0
Clang version: Could not collect
CMake version: version 3.26.3
Libc version: glibc-2.31

Python version: 3.12.4 (main, Oct 20 2024, 16:13:26) [GCC 7.5.0] (64-bit runtime)
Python platform: Linux-5.15.0-122-generic-x86_64-with-glibc2.31
Is CUDA available: True
CUDA runtime version: Could not collect
CUDA_MODULE_LOADING set to: LAZY
GPU models and configuration: GPU 0: NVIDIA GeForce GTX 1080
Nvidia driver version: 535.183.01
cuDNN version: Could not collect
HIP runtime version: N/A
MIOpen runtime version: N/A
Is XNNPACK available: True

CPU:
Architecture:                         x86_64
CPU op-mode(s):                       32-bit, 64-bit
Byte Order:                           Little Endian
Address sizes:                        39 bits physical, 48 bits virtual
CPU(s):                               12
On-line CPU(s) list:                  0-11
Thread(s) per core:                   2
Core(s) per socket:                   6
Socket(s):                            1
NUMA node(s):                         1
Vendor ID:                            GenuineIntel
CPU family:                           6
Model:                                158
Model name:                           Intel(R) Core(TM) i7-8750H CPU @ 2.20GHz
Stepping:                             10
CPU MHz:                              2200.000
CPU max MHz:                          4100,0000
CPU min MHz:                          800,0000
BogoMIPS:                             4399.99
Virtualization:                       VT-x
L1d cache:                            192 KiB
L1i cache:                            192 KiB
L2 cache:                             1,5 MiB
L3 cache:                             9 MiB
NUMA node0 CPU(s):                    0-11
Vulnerability Gather data sampling:   Mitigation; Microcode
Vulnerability Itlb multihit:          KVM: Mitigation: VMX disabled
Vulnerability L1tf:                   Mitigation; PTE Inversion; VMX conditional cache flushes, SMT vulnerable
Vulnerability Mds:                    Mitigation; Clear CPU buffers; SMT vulnerable
Vulnerability Meltdown:               Mitigation; PTI
Vulnerability Mmio stale data:        Mitigation; Clear CPU buffers; SMT vulnerable
Vulnerability Reg file data sampling: Not affected
Vulnerability Retbleed:               Mitigation; IBRS
Vulnerability Spec rstack overflow:   Not affected
Vulnerability Spec store bypass:      Mitigation; Speculative Store Bypass disabled via prctl and seccomp
Vulnerability Spectre v1:             Mitigation; usercopy/swapgs barriers and __user pointer sanitization
Vulnerability Spectre v2:             Mitigation; IBRS; IBPB conditional; STIBP conditional; RSB filling; PBRSB-eIBRS Not affected; BHI Not affected
Vulnerability Srbds:                  Mitigation; Microcode
Vulnerability Tsx async abort:        Not affected
Flags:                                fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush dts acpi mmx fxsr sse sse2 ss ht tm pbe syscall nx pdpe1gb rdtscp lm constant_tsc art arch_perfmon pebs bts rep_good nopl xtopology nonstop_tsc cpuid aperfmperf pni pclmulqdq dtes64 monitor ds_cpl vmx est tm2 ssse3 sdbg fma cx16 xtpr pdcm pcid sse4_1 sse4_2 x2apic movbe popcnt tsc_deadline_timer aes xsave avx f16c rdrand lahf_lm abm 3dnowprefetch cpuid_fault epb invpcid_single pti ssbd ibrs ibpb stibp tpr_shadow vnmi flexpriority ept vpid ept_ad fsgsbase tsc_adjust bmi1 avx2 smep bmi2 erms invpcid mpx rdseed adx smap clflushopt intel_pt xsaveopt xsavec xgetbv1 xsaves dtherm ida arat pln pts hwp hwp_notify hwp_act_window hwp_epp md_clear flush_l1d arch_capabilities

Versions of relevant libraries:
[pip3] nvidia-cublas-cu12==12.4.5.8
[pip3] nvidia-cuda-cupti-cu12==12.4.127
[pip3] nvidia-cuda-nvrtc-cu12==12.4.127
[pip3] nvidia-cuda-runtime-cu12==12.4.127
[pip3] nvidia-cudnn-cu12==9.1.0.70
[pip3] nvidia-cufft-cu12==11.2.1.3
[pip3] nvidia-curand-cu12==10.3.5.147
[pip3] nvidia-cusolver-cu12==11.6.1.9
[pip3] nvidia-cusparse-cu12==12.3.1.170
[pip3] nvidia-nccl-cu12==2.21.5
[pip3] nvidia-nvjitlink-cu12==12.4.127
[pip3] nvidia-nvtx-cu12==12.4.127
[pip3] torch==2.5.0
[pip3] triton==3.1.0
[conda] Could not collect

cc @zou3519 @ezyang @chauhang @penguinwu @Chillee @samdow @kshitij12345 @bdhirsh @yf225