Repository: pytorch
Issue: Error using torch.func transforms with DDP (broadcast_buffers=True)
Labels: oncall: distributed,triaged,module: ddp,module: functorch

### 🐛 Describe the bug

Running torch.func transforms (tested vmap and jacfwd) on a DDP module with buffer broadcasting causes an exception.

```python
import torch                                                                                                                                                                                                       
import torch.distributed                                                                                                                                                                                           
from torch import nn                                                                                                                                                                                               
                                                                                                                                                                                            
class TestModule(nn.Module):                                                                                                                                                                                       
    def __init__(self):                                                                                                                                                                                            
        super().__init__()                                                                                                                                                                                         
        self.register_buffer("buf", torch.randn(100, ))                                                                                                                                                            
        self.model = nn.Sequential(                                                                                                                                                                                
            nn.Linear(1, 100),                                                                                                                                                                                     
            nn.ReLU(),                                                                                                                                                                                             
            nn.Linear(100, 10)                                                                                                                                                                                     
        )                                                                                                                                                                                                          
                                                                                                                                                                                                                   
    def forward(self, x):                                                                                                                                                                                          
        return self.model(x)                                                                                                                                                                                       
                                                                                                                                                                                                                   
def run():                                                                                                                                                                                                         
    torch.distributed.init_process_group(backend="nccl", init_method='env://')                                                                                                                                     
    torch.cuda.set_device(0)                                                                                                                                                                                       
    model = TestModule().cuda()                                                                                                                                                                                    
    model_ddp = nn.parallel.DistributedDataParallel(model, device_ids=[0], broadcast_buffers=True)                                                                                                                 
    data = torch.randn((1, )).cuda()                                                                                                                                                                               
    
    dfdx = torch.func.jacfwd(model_ddp, argnums=0)(data)                                                                                                                                                           
    print(dfdx.shape)                                                                                                                                                                                              
                                                                                                                                                                                                                   
if __name__ == "__main__":                                                                                                                                                                                         
    run()
```

```bash
>>> torchrun --standalone --nproc_per_node=1 --master_port=25678 test_bug.py

[rank0]: Traceback (most recent call last):                                                                                                                                                               [21/1997]
[rank0]:   File "/home/giodiro/diffusion/test_bug.py", line 34, in <module>
[rank0]:     run()
[rank0]:   File "/home/giodiro/diffusion/test_bug.py", line 30, in run
[rank0]:     dfdx = torch.func.jacfwd(model_ddp, argnums=0)(data)
[rank0]:   File "/scratch/clear/giodiro/miniforge3/envs/torch/lib/python3.10/site-packages/torch/_functorch/eager_transforms.py", line 1163, in wrapper_fn
[rank0]:     results = vmap(push_jvp, randomness=randomness)(basis)
[rank0]:   File "/scratch/clear/giodiro/miniforge3/envs/torch/lib/python3.10/site-packages/torch/_functorch/apis.py", line 188, in wrapped
[rank0]:     return vmap_impl(func, in_dims, out_dims, randomness, chunk_size, *args, **kwargs)
[rank0]:   File "/scratch/clear/giodiro/miniforge3/envs/torch/lib/python3.10/site-packages/torch/_functorch/vmap.py", line 281, in vmap_impl
[rank0]:     return _flat_vmap(
[rank0]:   File "/scratch/clear/giodiro/miniforge3/envs/torch/lib/python3.10/site-packages/torch/_functorch/vmap.py", line 47, in fn
[rank0]:     return f(*args, **kwargs)
[rank0]:   File "/scratch/clear/giodiro/miniforge3/envs/torch/lib/python3.10/site-packages/torch/_functorch/vmap.py", line 403, in _flat_vmap
[rank0]:     batched_outputs = func(*batched_inputs, **kwargs)
[rank0]:   File "/scratch/clear/giodiro/miniforge3/envs/torch/lib/python3.10/site-packages/torch/_functorch/eager_transforms.py", line 1154, in push_jvp
[rank0]:     output = _jvp_with_argnums(func, args, basis, argnums=argnums, has_aux=has_aux)
[rank0]:   File "/scratch/clear/giodiro/miniforge3/envs/torch/lib/python3.10/site-packages/torch/_functorch/vmap.py", line 47, in fn
[rank0]:     return f(*args, **kwargs)
[rank0]:   File "/scratch/clear/giodiro/miniforge3/envs/torch/lib/python3.10/site-packages/torch/_functorch/eager_transforms.py", line 1000, in _jvp_with_argnums
[rank0]:     result_duals = func(*duals)
[rank0]:   File "/scratch/clear/giodiro/miniforge3/envs/torch/lib/python3.10/site-packages/torch/nn/modules/module.py", line 1532, in _wrapped_call_impl
[rank0]:     return self._call_impl(*args, **kwargs)
[rank0]:   File "/scratch/clear/giodiro/miniforge3/envs/torch/lib/python3.10/site-packages/torch/nn/modules/module.py", line 1541, in _call_impl
[rank0]:     return forward_call(*args, **kwargs)
[rank0]:   File "/scratch/clear/giodiro/miniforge3/envs/torch/lib/python3.10/site-packages/torch/nn/parallel/distributed.py", line 1589, in forward
[rank0]:     inputs, kwargs = self._pre_forward(*inputs, **kwargs)
[rank0]:   File "/scratch/clear/giodiro/miniforge3/envs/torch/lib/python3.10/site-packages/torch/nn/parallel/distributed.py", line 1487, in _pre_forward
[rank0]:     self._sync_buffers()
[rank0]:   File "/scratch/clear/giodiro/miniforge3/envs/torch/lib/python3.10/site-packages/torch/nn/parallel/distributed.py", line 2129, in _sync_buffers
[rank0]:     self._sync_module_buffers(authoritative_rank)
[rank0]:   File "/scratch/clear/giodiro/miniforge3/envs/torch/lib/python3.10/site-packages/torch/nn/parallel/distributed.py", line 2133, in _sync_module_buffers
[rank0]:     self._default_broadcast_coalesced(authoritative_rank=authoritative_rank)
[rank0]:   File "/scratch/clear/giodiro/miniforge3/envs/torch/lib/python3.10/site-packages/torch/nn/parallel/distributed.py", line 2155, in _default_broadcast_coalesced
[rank0]:     self._distributed_broadcast_coalesced(bufs, bucket_size, authoritative_rank)
[rank0]:   File "/scratch/clear/giodiro/miniforge3/envs/torch/lib/python3.10/site-packages/torch/nn/parallel/distributed.py", line 2070, in _distributed_broadcast_coalesced
[rank0]:     dist._broadcast_coalesced(
[rank0]: RuntimeError: During a grad (vjp, jvp, grad, etc) transform, the function provided attempted to call in-place operation (aten::copy_) that would mutate a captured Tensor. This is not supported; please r
ewrite the function being transformed to explicitly accept the mutated Tensor(s) as inputs.
```

Possibly connected to [this functorch issue](https://github.com/pytorch/functorch/issues/1112).

No error occurs if the module does not have buffers of if DDP is initialized with `broadcast_buffers=False`.

### Versions

PyTorch version: 2.3.0
Is debug build: False
CUDA used to build PyTorch: 12.1
ROCM used to build PyTorch: N/A

OS: Ubuntu 22.04.2 LTS (x86_64)
GCC version: (Ubuntu 11.4.0-1ubuntu1~22.04) 11.4.0
Clang version: Could not collect
CMake version: Could not collect
Libc version: glibc-2.35

Python version: 3.10.14 | packaged by conda-forge | (main, Mar 20 2024, 12:45:18) [GCC 12.3.0] (64-bit runtime)
Python platform: Linux-5.15.0-91-generic-x86_64-with-glibc2.35
Is CUDA available: True
CUDA runtime version: Could not collect
CUDA_MODULE_LOADING set to: LAZY
GPU models and configuration: 
GPU 0: NVIDIA RTX A5000
GPU 1: NVIDIA RTX A5000

Nvidia driver version: 545.23.08
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
Address sizes:                      46 bits physical, 48 bits virtual
Byte Order:                         Little Endian
CPU(s):                             16
On-line CPU(s) list:                0-15
Vendor ID:                          GenuineIntel
Model name:                         Intel(R) Xeon(R) CPU E5-2623 v4 @ 2.60GHz
CPU family:                         6
Model:                              79
Thread(s) per core:                 2
Core(s) per socket:                 4
Socket(s):                          2
Stepping:                           1
CPU max MHz:                        3200.0000
CPU min MHz:                        1200.0000
BogoMIPS:                           5200.46
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 arch_perfmon 
pebs bts rep_good nopl xtopology nonstop_tsc cpuid aperfmperf pni pclmulqdq dtes64 monitor 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 x
save avx f16c rdrand lahf_lm abm 3dnowprefetch cpuid_fault epb cat_l3 cdp_l3 invpcid_single pti ssbd ibrs ibpb stibp tpr_shadow vnmi flexpriority ept vpid ept_ad fsgsbase tsc_adjust bmi1 hle avx2 smep bmi2 erms 
invpcid rtm cqm rdt_a rdseed adx smap intel_pt xsaveopt cqm_llc cqm_occup_llc cqm_mbm_total cqm_mbm_local dtherm ida arat pln pts md_clear flush_l1d
Virtualization:                     VT-x
L1d cache:                          256 KiB (8 instances)
L1i cache:                          256 KiB (8 instances)
L2 cache:                           2 MiB (8 instances)
L3 cache:                           20 MiB (2 instances)
NUMA node(s):                       2
NUMA node0 CPU(s):                  0,2,4,6,8,10,12,14
NUMA node1 CPU(s):                  1,3,5,7,9,11,13,15
Vulnerability Gather data sampling: Not affected
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 Retbleed:             Not affected
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; Retpolines, IBPB conditional, IBRS_FW, STIBP conditional, RSB filling, PBRSB-eIBRS Not affected
Vulnerability Srbds:                Not affected
Vulnerability Tsx async abort:      Mitigation; Clear CPU buffers; SMT vulnerable

Versions of relevant libraries:
[pip3] numpy==1.26.4
[pip3] optree==0.11.0
[pip3] pytorch-lightning==2.2.2
[pip3] torch==2.3.0
[pip3] torchaudio==2.3.0
[pip3] torchdiffeq==0.2.4
[pip3] torchmetrics==1.4.0.post0
[pip3] torchvision==0.18.0
[pip3] triton==2.3.0
[conda] blas                      2.116                       mkl    conda-forge
[conda] blas-devel                3.9.0            16_linux64_mkl    conda-forge
[conda] ffmpeg                    4.3                  hf484d3e_0    pytorch
[conda] libblas                   3.9.0            16_linux64_mkl    conda-forge
[conda] libcblas                  3.9.0            16_linux64_mkl    conda-forge
[conda] libjpeg-turbo             2.0.0                h9bf148f_0    pytorch
[conda] liblapack                 3.9.0            16_linux64_mkl    conda-forge
[conda] liblapacke                3.9.0            16_linux64_mkl    conda-forge
[conda] mkl                       2022.1.0           h84fe81f_915    conda-forge
[conda] mkl-devel                 2022.1.0           ha770c72_916    conda-forge
[conda] mkl-include               2022.1.0           h84fe81f_915    conda-forge
[conda] numpy                     1.26.4          py310hb13e2d6_0    conda-forge
[conda] optree                    0.11.0                   pypi_0    pypi
[conda] pytorch                   2.3.0           py3.10_cuda12.1_cudnn8.9.2_0    pytorch
[conda] pytorch-cuda              12.1                 ha16c6d3_5    pytorch
[conda] pytorch-lightning         2.2.2              pyhd8ed1ab_0    conda-forge
[conda] pytorch-mutex             1.0                        cuda    pytorch
[conda] torchaudio                2.3.0               py310_cu121    pytorch
[conda] torchdiffeq               0.2.4                    pypi_0    pypi
[conda] torchmetrics              1.4.0.post0        pyhd8ed1ab_0    conda-forge
[conda] torchtriton               2.3.0                     py310    pytorch
[conda] torchvision               0.18.0              py310_cu121    pytorch


cc @XilunWu @H-Huang @awgu @kwen2501 @wanchaol @fegin @fduwjj @wz337 @wconstab @d4l3k @c-p-i-o @zou3519 @Chillee @samdow @kshitij12345 @janeyx99