torch.func.jvp fails when acting on a DistributedDataParallel model
Labels: oncall: distributed, module: forward ad, module: functorch

Evaluating the jvp of a model's forward method with respect to an input variable fails when the model is parallel distributed with DistributedDataParallel. Specifically, the next jvp evaluation after calling backward() fails with the error message:

```
Traceback (most recent call last):
  File "test.py", line 39, in <module>
    out, grad_out = jvp(model, (style,), jvp_tangents)
                    ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/Mamba/envs/ptjvp/lib/python3.11/site-packages/torch/_functorch/eager_transforms.py", line 916, in jvp
    return _jvp_with_argnums(func, primals, tangents, argnums=None, strict=strict, has_aux=has_aux)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/Mamba/envs/ptjvp/lib/python3.11/site-packages/torch/_functorch/vmap.py", line 39, in fn
    return f(*args, **kwargs)
           ^^^^^^^^^^^^^^^^^^
  File "/Mamba/envs/ptjvp/lib/python3.11/site-packages/torch/_functorch/eager_transforms.py", line 965, in _jvp_with_argnums
    result_duals = func(*duals)
                   ^^^^^^^^^^^^
  File "/Mamba/envs/ptjvp/lib/python3.11/site-packages/torch/nn/modules/module.py", line 1502, in _wrapped_call_impl
    return self._call_impl(*args, **kwargs)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/Mamba/envs/ptjvp/lib/python3.11/site-packages/torch/nn/modules/module.py", line 1511, in _call_impl
    return forward_call(*args, **kwargs)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/Mamba/envs/ptjvp/lib/python3.11/site-packages/torch/nn/parallel/distributed.py", line 1531, in forward
    inputs, kwargs = self._pre_forward(*inputs, **kwargs)
                     ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/Mamba/envs/ptjvp/lib/python3.11/site-packages/torch/nn/parallel/distributed.py", line 1419, in _pre_forward
    if torch.is_grad_enabled() and self.reducer._rebuild_buckets():
                                   ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
RuntimeError: Cannot access data pointer of Tensor that doesn't have storage
```

Here is a minimal example:

```python
import os
import torch
import torch.distributed as dist
from torch.nn.parallel import DistributedDataParallel
from torch.func import jvp

class TestNet(torch.nn.Module):

    def __init__(self):
        super().__init__()

        self.weight = torch.nn.Parameter(torch.randn((1,)))

    def forward(self, x) :
        return self.weight * x

if __name__ == '__main__':

    os.environ['MASTER_ADDR'] = '127.0.0.1'
    os.environ['MASTER_PORT'] = '29500'
    dist.init_process_group(backend='nccl', world_size=1, rank=0)
    device = torch.device('cuda', 0)

    model = TestNet().to(device)
    # The code runs without error if this is commented out
    model = DistributedDataParallel(model, device_ids=[device], process_group=dist.new_group())
    criterion = torch.nn.MSELoss().to(device)

    for epoch in range(2) :

        print('epoch {} started'.format(epoch))

        target = torch.randn(1).to(device)
        input = torch.randn([1]).to(device)
        jvp_tangents = (torch.ones_like(input).to(device),)
        out, grad_out = jvp(model, (input,), jvp_tangents)
        loss = criterion(out, target)
        torch.log(loss).backward()

        print('epoch {} finished'.format(epoch))

    print('Success!')
```
If I use DistributedDataParallel with find_unused_parameters=True I get a different error, which occurs the first time jvp is invoked, instead of after the first time torch.log(loss).backward() is called.

```
Traceback (most recent call last):
  File "test.py", line 39, in <module>
    out, grad_out = jvp(model, (style,), jvp_tangents)
                    ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/Mamba/envs/ptjvp/lib/python3.11/site-packages/torch/_functorch/eager_transforms.py", line 916, in jvp
    return _jvp_with_argnums(func, primals, tangents, argnums=None, strict=strict, has_aux=has_aux)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/Mamba/envs/ptjvp/lib/python3.11/site-packages/torch/_functorch/vmap.py", line 39, in fn
    return f(*args, **kwargs)
           ^^^^^^^^^^^^^^^^^^
  File "/Mamba/envs/ptjvp/lib/python3.11/site-packages/torch/_functorch/eager_transforms.py", line 965, in _jvp_with_argnums
    result_duals = func(*duals)
                   ^^^^^^^^^^^^
  File "/Mamba/envs/ptjvp/lib/python3.11/site-packages/torch/nn/modules/module.py", line 1502, in _wrapped_call_impl
    return self._call_impl(*args, **kwargs)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/Mamba/envs/ptjvp/lib/python3.11/site-packages/torch/nn/modules/module.py", line 1511, in _call_impl
    return forward_call(*args, **kwargs)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/Mamba/envs/ptjvp/lib/python3.11/site-packages/torch/nn/parallel/distributed.py", line 1537, in forward
    return self._post_forward(output)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/Mamba/envs/ptjvp/lib/python3.11/site-packages/torch/nn/parallel/distributed.py", line 1511, in _post_forward
    passthrough_tensor_list = _DDPSink.apply(
                              ^^^^^^^^^^^^^^^
  File "/Mamba/envs/ptjvp/lib/python3.11/site-packages/torch/autograd/function.py", line 509, in apply
    raise RuntimeError(
RuntimeError: In order to use an autograd.Function with functorch transforms (vmap, grad, jvp, jacrev, ...), it must override the setup_context staticmethod. For more details, please see https://pytorch.org/docs/master/notes/extending.func.html
```

### Versions

Collecting environment information...
PyTorch version: 2.1.0.dev20230522+cu118
Is debug build: False
CUDA used to build PyTorch: 11.8
ROCM used to build PyTorch: N/A

OS: Rocky Linux release 8.8 (Green Obsidian) (x86_64)
GCC version: (GCC) 8.5.0 20210514 (Red Hat 8.5.0-16)
Clang version: Could not collect
CMake version: version 3.25.0
Libc version: glibc-2.28

Python version: 3.11.3 | packaged by conda-forge | (main, Apr  6 2023, 08:57:19) [GCC 11.3.0] (64-bit runtime)
Python platform: Linux-5.15.90.1.fi-x86_64-with-glibc2.28
Is CUDA available: True
CUDA runtime version: 11.8.89
CUDA_MODULE_LOADING set to: LAZY
GPU models and configuration: 
GPU 0: NVIDIA A100-SXM4-80GB
GPU 1: NVIDIA A100-SXM4-80GB
GPU 2: NVIDIA A100-SXM4-80GB
GPU 3: NVIDIA A100-SXM4-80GB

Nvidia driver version: 530.30.02
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
CPU(s):              64
On-line CPU(s) list: 0-63
Thread(s) per core:  1
Core(s) per socket:  32
Socket(s):           2
NUMA node(s):        2
Vendor ID:           GenuineIntel
CPU family:          6
Model:               106
Model name:          Intel(R) Xeon(R) Platinum 8358 CPU @ 2.60GHz
Stepping:            6
CPU MHz:             2600.000
CPU max MHz:         3400.0000
CPU min MHz:         800.0000
BogoMIPS:            5200.00
Virtualization:      VT-x
L1d cache:           48K
L1i cache:           32K
L2 cache:            1280K
L3 cache:            49152K
NUMA node0 CPU(s):   0-31
NUMA node1 CPU(s):   32-63
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 ds_cpl vmx smx est tm2 ssse3 sdbg fma cx16 xtpr pdcm pcid dca sse4_1 sse4_2 x2apic movbe popcnt tsc_deadline_timer aes xsave avx f16c rdrand lahf_lm abm 3dnowprefetch cpuid_fault epb cat_l3 invpcid_single intel_ppin ssbd mba ibrs ibpb stibp ibrs_enhanced tpr_shadow vnmi flexpriority ept vpid ept_ad fsgsbase tsc_adjust bmi1 avx2 smep bmi2 erms invpcid cqm rdt_a avx512f avx512dq rdseed adx smap avx512ifma clflushopt clwb intel_pt avx512cd sha_ni avx512bw avx512vl xsaveopt xsavec xgetbv1 xsaves cqm_llc cqm_occup_llc cqm_mbm_total cqm_mbm_local split_lock_detect wbnoinvd dtherm ida arat pln pts hwp hwp_act_window hwp_epp hwp_pkg_req avx512vbmi umip pku ospke avx512_vbmi2 gfni vaes vpclmulqdq avx512_vnni avx512_bitalg tme avx512_vpopcntdq rdpid fsrm md_clear pconfig flush_l1d arch_capabilities

Versions of relevant libraries:
[pip3] numpy==1.23.5
[pip3] pytorch-triton==2.1.0+7d1a95b046
[pip3] torch==2.1.0.dev20230522+cu118
[pip3] torchaudio==2.1.0.dev20230522+cu118
[pip3] torchvision==0.16.0.dev20230522+cu118
[pip3] triton==2.0.0
[conda] numpy                     1.23.5                   pypi_0    pypi
[conda] pytorch-triton            2.1.0+7d1a95b046          pypi_0    pypi
[conda] torch                     2.1.0.dev20230522+cu118          pypi_0    pypi
[conda] torchaudio                2.1.0.dev20230522+cu118          pypi_0    pypi
[conda] torchvision               0.16.0.dev20230522+cu118          pypi_0    pypi
[conda] triton                    2.0.0                    pypi_0    pypi

cc @mrshenli @pritamdamania87 @zhaojuanmao @satgera @rohan-varma @gqchen @aazzolini @osalpekar @jiayisuse @H-Huang @kwen2501 @awgu @zou3519 @Chillee @samdow @kshitij12345 @janeyx99