Repository: pytorch
Issue: DistributedDataParallel _verify_param_shape_across_processes causes reserved memory on GPU
Labels: oncall: distributed

### 🐛 Describe the bug

When running a very straightforward DDP demo (see code below), I see that rank1 also reserves memory on GPU0. This happens inside `DistributedDataParallel.__init__`, specifically in `_verify_param_shape_across_processes`.

Code (also online [here](https://github.com/albertz/playground/blob/master/torch-distributed-demo.py)):
```python
"""
run::
    python -m torch.distributed.run --standalone --nnodes 1 --nproc-per-node=2 torch-distributed-demo.py

https://pytorch.org/docs/stable/notes/ddp.html
"""

import os
import sys
import time
import subprocess as sp
import torch
from torch import nn
from torch import optim
import torch.distributed as dist
from torch.nn.parallel import DistributedDataParallel


def _debug_mem(msg):
    if local_rank == 1:
        print(f"*** {msg} {{")
        print("reserved mem GPU0:", torch.cuda.memory_reserved(0))
        sp.call(
            f"(nvidia-smi; echo '*** {msg} -- {os.getpid()} }}'; ) | grep {os.getpid()}",
            shell=True,
            stdout=sys.stdout,
            stderr=sys.stdout,
        )
        sys.stdout.flush()


dist.init_process_group(backend=None)  # nccl + gloo
local_rank = int(os.environ["LOCAL_RANK"])
local_size = int(os.environ["LOCAL_WORLD_SIZE"])
dev = torch.device(f"cuda:{local_rank}")
print(f"Start running torch distributed training on local rank {local_rank}/{local_size}.")
_debug_mem("start")
# torch.cuda.set_device(dev)  # -- adding this will fix the problem, but should not be needed?


class Model(nn.Module):
    def __init__(self):
        super().__init__()
        self.fc = nn.Linear(10, 10)

    def forward(self, x):
        return self.fc(x)


model = Model()
model.to(dev)
_debug_mem("after model init")

ddp_model = DistributedDataParallel(model, device_ids=[local_rank])
_debug_mem("after DDP wrapping")

# define loss function and optimizer
loss_fn = nn.MSELoss()
optimizer = optim.SGD(ddp_model.parameters(), lr=0.001)
_debug_mem("after optimizer init")

step = 0
while True:
    # forward pass
    outputs = ddp_model(torch.randn(20, 10, device=dev))
    labels = torch.randn(20, 10, device=dev)
    # backward pass
    loss_fn(outputs, labels).backward()
    # update parameters
    optimizer.step()

    print(f"[{local_rank}] step {step}")
    _debug_mem(f"step {step}")

    if step >= 3:
        break
    time.sleep(0.5)
    step += 1
```

Start like this: `python -m torch.distributed.run --standalone --nnodes 1 --nproc-per-node=2 torch-distributed-demo.py`

After running with `NCCL_DEBUG=INFO`, I get the output:
```
master_addr is only used for static rdzv_backend and when rdzv_endpoint is not specified.                                                      
Start running torch distributed training on local rank 1/2.                                                                                    
*** start {                                                                                                                                    
reserved mem GPU0: 0                                                                                                                           
Start running torch distributed training on local rank 0/2.                                                                                    
*** start -- 237143 }                                                                                                                          
*** after model init {                                                                                                                         
reserved mem GPU0: 0                                                                                                                           
|    1   N/A  N/A    237143      C   ...0-torch2.1/bin/python3.10      752MiB |                                                                
*** after model init -- 237143 }                                                                                                               
nd20-01:237142:237142 [0] NCCL INFO Bootstrap : Using bond0:134.61.201.231<0>                                                                  
nd20-01:237142:237142 [0] NCCL INFO NET/Plugin : Plugin load (libnccl-net.so) returned 2 : libnccl-net.so: cannot open shared object file: No su
ch file or directory                                                                                                                           
nd20-01:237142:237142 [0] NCCL INFO NET/Plugin : No plugin found, using internal implementation                                                
nd20-01:237142:237142 [0] NCCL INFO cudaDriverVersion 12000                                                                                    
NCCL version 2.18.1+cuda12.1                                                                                                                   
nd20-01:237142:237283 [0] NCCL INFO NET/IB : Using [0]mlx5_0:1/IB [1]mlx5_bond_0:1/RoCE [RO]; OOB bond0:134.61.201.231<0>                      
nd20-01:237142:237283 [0] NCCL INFO Using network IB                                                                                           
nd20-01:237143:237143 [1] NCCL INFO cudaDriverVersion 12000
nd20-01:237143:237143 [1] NCCL INFO Bootstrap : Using bond0:134.61.201.231<0>                                                                  
nd20-01:237143:237143 [1] NCCL INFO NET/Plugin : Plugin load (libnccl-net.so) returned 2 : libnccl-net.so: cannot open shared object file: No su
ch file or directory                                                                                                                           
nd20-01:237143:237143 [1] NCCL INFO NET/Plugin : No plugin found, using internal implementation                                                
nd20-01:237143:237388 [1] NCCL INFO NET/IB : Using [0]mlx5_0:1/IB [1]mlx5_bond_0:1/RoCE [RO]; OOB bond0:134.61.201.231<0>                      
nd20-01:237143:237388 [1] NCCL INFO Using network IB                                                                                           
nd20-01:237142:237283 [0] NCCL INFO Channel 00/12 :    0   1                                                                                   
nd20-01:237142:237283 [0] NCCL INFO Channel 01/12 :    0   1                                                                                   
nd20-01:237142:237283 [0] NCCL INFO Channel 02/12 :    0   1                                                                                   
nd20-01:237142:237283 [0] NCCL INFO Channel 03/12 :    0   1
nd20-01:237142:237283 [0] NCCL INFO Channel 04/12 :    0   1
nd20-01:237142:237283 [0] NCCL INFO Channel 05/12 :    0   1                                                                                   
nd20-01:237142:237283 [0] NCCL INFO Channel 06/12 :    0   1                                                                                   
nd20-01:237142:237283 [0] NCCL INFO Channel 07/12 :    0   1
nd20-01:237142:237283 [0] NCCL INFO Channel 08/12 :    0   1
nd20-01:237142:237283 [0] NCCL INFO Channel 09/12 :    0   1
nd20-01:237142:237283 [0] NCCL INFO Channel 10/12 :    0   1                                                                                   
nd20-01:237142:237283 [0] NCCL INFO Channel 11/12 :    0   1                                                                                   
nd20-01:237142:237283 [0] NCCL INFO Trees [0] 1/-1/-1->0->-1 [1] 1/-1/-1->0->-1 [2] 1/-1/-1->0->-1 [3] -1/-1/-1->0->1 [4] -1/-1/-1->0->1 [5] -1/
-1/-1->0->1 [6] 1/-1/-1->0->-1 [7] 1/-1/-1->0->-1 [8] 1/-1/-1->0->-1 [9] -1/-1/-1->0->1 [10] -1/-1/-1->0->1 [11] -1/-1/-1->0->1                
nd20-01:237142:237283 [0] NCCL INFO P2P Chunksize set to 524288
nd20-01:237143:237388 [1] NCCL INFO Trees [0] -1/-1/-1->1->0 [1] -1/-1/-1->1->0 [2] -1/-1/-1->1->0 [3] 0/-1/-1->1->-1 [4] 0/-1/-1->1->-1 [5] 0/-
1/-1->1->-1 [6] -1/-1/-1->1->0 [7] -1/-1/-1->1->0 [8] -1/-1/-1->1->0 [9] 0/-1/-1->1->-1 [10] 0/-1/-1->1->-1 [11] 0/-1/-1->1->-1                
nd20-01:237143:237388 [1] NCCL INFO P2P Chunksize set to 524288
nd20-01:237143:237388 [1] NCCL INFO Channel 00/0 : 1[e0000] -> 0[be000] via P2P/IPC                                                            
nd20-01:237142:237283 [0] NCCL INFO Channel 00/0 : 0[be000] -> 1[e0000] via P2P/IPC
nd20-01:237143:237388 [1] NCCL INFO Channel 01/0 : 1[e0000] -> 0[be000] via P2P/IPC
nd20-01:237142:237283 [0] NCCL INFO Channel 01/0 : 0[be000] -> 1[e0000] via P2P/IPC
nd20-01:237143:237388 [1] NCCL INFO Channel 02/0 : 1[e0000] -> 0[be000] via P2P/IPC
nd20-01:237142:237283 [0] NCCL INFO Channel 02/0 : 0[be000] -> 1[e0000] via P2P/IPC
nd20-01:237143:237388 [1] NCCL INFO Channel 03/0 : 1[e0000] -> 0[be000] via P2P/IPC
nd20-01:237142:237283 [0] NCCL INFO Channel 03/0 : 0[be000] -> 1[e0000] via P2P/IPC
nd20-01:237143:237388 [1] NCCL INFO Channel 04/0 : 1[e0000] -> 0[be000] via P2P/IPC
nd20-01:237142:237283 [0] NCCL INFO Channel 04/0 : 0[be000] -> 1[e0000] via P2P/IPC
nd20-01:237143:237388 [1] NCCL INFO Channel 05/0 : 1[e0000] -> 0[be000] via P2P/IPC
nd20-01:237142:237283 [0] NCCL INFO Channel 05/0 : 0[be000] -> 1[e0000] via P2P/IPC
nd20-01:237142:237283 [0] NCCL INFO Channel 06/0 : 0[be000] -> 1[e0000] via P2P/IPC
nd20-01:237143:237388 [1] NCCL INFO Channel 06/0 : 1[e0000] -> 0[be000] via P2P/IPC
nd20-01:237142:237283 [0] NCCL INFO Channel 07/0 : 0[be000] -> 1[e0000] via P2P/IPC
nd20-01:237143:237388 [1] NCCL INFO Channel 07/0 : 1[e0000] -> 0[be000] via P2P/IPC
nd20-01:237142:237283 [0] NCCL INFO Channel 08/0 : 0[be000] -> 1[e0000] via P2P/IPC
nd20-01:237143:237388 [1] NCCL INFO Channel 08/0 : 1[e0000] -> 0[be000] via P2P/IPC
nd20-01:237142:237283 [0] NCCL INFO Channel 09/0 : 0[be000] -> 1[e0000] via P2P/IPC
nd20-01:237143:237388 [1] NCCL INFO Channel 09/0 : 1[e0000] -> 0[be000] via P2P/IPC
nd20-01:237142:237283 [0] NCCL INFO Channel 10/0 : 0[be000] -> 1[e0000] via P2P/IPC
nd20-01:237143:237388 [1] NCCL INFO Channel 10/0 : 1[e0000] -> 0[be000] via P2P/IPC
nd20-01:237143:237388 [1] NCCL INFO Channel 11/0 : 1[e0000] -> 0[be000] via P2P/IPC
nd20-01:237142:237283 [0] NCCL INFO Channel 11/0 : 0[be000] -> 1[e0000] via P2P/IPC
nd20-01:237142:237283 [0] NCCL INFO Connected all rings
nd20-01:237142:237283 [0] NCCL INFO Connected all trees
nd20-01:237142:237283 [0] NCCL INFO threadThresholds 8/8/64 | 16/8/64 | 512 | 512
nd20-01:237142:237283 [0] NCCL INFO 12 coll channels, 0 nvls channels, 16 p2p channels, 16 p2p channels per peer
nd20-01:237143:237388 [1] NCCL INFO Connected all rings 
nd20-01:237143:237388 [1] NCCL INFO Connected all trees 
nd20-01:237143:237388 [1] NCCL INFO threadThresholds 8/8/64 | 16/8/64 | 512 | 512
nd20-01:237143:237388 [1] NCCL INFO 12 coll channels, 0 nvls channels, 16 p2p channels, 16 p2p channels per peer
nd20-01:237143:237388 [1] NCCL INFO comm 0x50bfed10 rank 1 nranks 2 cudaDev 1 busId e0000 commId 0xc704de4fb4f8dbc6 - Init COMPLETE
nd20-01:237142:237283 [0] NCCL INFO comm 0x399758a0 rank 0 nranks 2 cudaDev 0 busId be000 commId 0xc704de4fb4f8dbc6 - Init COMPLETE
*** after DDP wrapping {
reserved mem GPU0: 0
|    0   N/A  N/A    237143      C   ...0-torch2.1/bin/python3.10      818MiB |
|    1   N/A  N/A    237143      C   ...0-torch2.1/bin/python3.10     1114MiB |
*** after DDP wrapping -- 237143 }   
*** after optimizer init {
reserved mem GPU0: 0
|    0   N/A  N/A    237143      C   ...0-torch2.1/bin/python3.10      818MiB |
|    1   N/A  N/A    237143      C   ...0-torch2.1/bin/python3.10     1114MiB |
*** after optimizer init -- 237143 } 
[0] step 0
[1] step 0
*** step 0 {
reserved mem GPU0: 0
[0] step 1
|    0   N/A  N/A    237143      C   ...0-torch2.1/bin/python3.10      966MiB |
|    1   N/A  N/A    237143      C   ...0-torch2.1/bin/python3.10     1298MiB |
*** step 0 -- 237143 }
[1] step 1
*** step 1 {
reserved mem GPU0: 0
[0] step 2
|    0   N/A  N/A    237143      C   ...0-torch2.1/bin/python3.10      966MiB |
|    1   N/A  N/A    237143      C   ...0-torch2.1/bin/python3.10     1298MiB |
*** step 1 -- 237143 }
[1] step 2
*** step 2 {  
reserved mem GPU0: 0
[0] step 3
|    0   N/A  N/A    237143      C   ...0-torch2.1/bin/python3.10     1110MiB |
|    1   N/A  N/A    237143      C   ...0-torch2.1/bin/python3.10     1298MiB |
*** step 2 -- 237143 }
[1] step 3
*** step 3 {
reserved mem GPU0: 0
|    0   N/A  N/A    237143      C   ...0-torch2.1/bin/python3.10     1110MiB |
|    1   N/A  N/A    237143      C   ...0-torch2.1/bin/python3.10     1298MiB |
*** step 3 -- 237143 }
```

You see from the `nvidia-smi` output that the rank1 process uses some memory on GPU0. Interestingly, `torch.cuda.memory_reserved(0)` returns 0 though! It starts to use memory after the `DistributedDataParallel` creation. After step-by-step debugging, I saw that this happens in `_verify_param_shape_across_processes`.

I think this is a bug. It should not use the GPU0 here.

Note I also reported this here: https://github.com/rwth-i6/returnn/issues/1469
And [here](https://discuss.pytorch.org/t/distributed-training-all-procs-reserve-memory-on-gpu-0/192794/).

Note that if I add the `torch.cuda.set_device(dev)` here, then I don't have the problem anymore. But I still think that this is a bug in `_verify_param_shape_across_processes` because that should not use the default CUDA device but instead the model parameter device (which is GPU1 here, as you also see from the output, see "after model init").

### Versions

```
PyTorch version: 2.1.1+cu121
Is debug build: False
CUDA used to build PyTorch: 12.1
ROCM used to build PyTorch: N/A                                                                                                                
                                                                                                                                               
OS: NVIDIA DGX Server (x86_64)                                                                                                                 
GCC version: (GCC) 11.3.0                                                                                                                      
Clang version: Could not collect                                                                                                               
CMake version: Could not collect                                                                                                               
Libc version: glibc-2.28                                                                                                                       

Python version: 3.10.4 (main, Aug  9 2023, 13:18:35) [GCC 11.3.0] (64-bit runtime)                                                             
Python platform: Linux-4.18.0-513.5.1.el8_9.x86_64-x86_64-with-glibc2.28
Is CUDA available: True
CUDA runtime version: Could not collect
CUDA_MODULE_LOADING set to: LAZY
GPU models and configuration:
GPU 0: Tesla V100-SXM3-32GB
GPU 1: Tesla V100-SXM3-32GB

Nvidia driver version: 525.147.05                                                                                                              
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):              96
On-line CPU(s) list: 0-95
Thread(s) per core:  2
Core(s) per socket:  24
Socket(s):           2
NUMA node(s):        2
Vendor ID:           GenuineIntel
CPU family:          6
Model:               85
Model name:          Intel(R) Xeon(R) Platinum 8168 CPU @ 2.70GHz
Stepping:            4
CPU MHz:             3400.000
CPU max MHz:         3700.0000
CPU min MHz:         1200.0000
BogoMIPS:            5400.00
Virtualization:      VT-x
L1d cache:           32K
L1i cache:           32K
L2 cache:            1024K
L3 cache:            33792K
NUMA node0 CPU(s):   0-23,48-71
NUMA node1 CPU(s):   24-47,72-95
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 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 cdp_l3 invpcid_single pti intel_ppin ssbd mba ibrs ibpb stibp tpr_shadow vnmi flexpriority ept vpid ept_ad fsgsbase tsc_adjust bmi1 hle avx2 smep bmi2 erms invpcid rtm cqm mpx rdt_a avx512f avx512dq rdseed adx smap clflushopt clwb intel_pt avx512cd avx512bw avx512vl xsaveopt xsavec xgetbv1 xsaves cqm_llc cqm_occup_llc cqm_mbm_total cqm_mbm_local dtherm ida arat pln pts hwp hwp_act_window hwp_epp hwp_pkg_req pku ospke md_clear flush_l1d arch_capabilities

Versions of relevant libraries:
[pip3] lovely-numpy==0.2.10
[pip3] mypy-extensions==1.0.0
[pip3] numpy==1.26.2
[pip3] torch==2.1.1
[pip3] torchaudio==2.1.1 
[pip3] torchvision==0.16.1
[pip3] triton==2.1.0
[conda] Could not collect
```

cc @mrshenli @pritamdamania87 @zhaojuanmao @satgera @rohan-varma @gqchen @aazzolini @osalpekar @jiayisuse @H-Huang @kwen2501 @awgu @penguinwu @fegin @XilunWu