Repository: pytorch
Issue: DDP backpropagated gradients not the same across all gpus when forward inference not using all declared modules
Labels: oncall: distributed

### 🐛 Describe the bug

Hello,

I don't know whether this is intended behavior,  for training with DDP on multiple GPU, I observe that when I declare two modules  net1 and net2  in my model , but when I do forward inference only use net1,     the backpropagated gradients are not the same for models in different GPUS, as well as the updated weights.

I directly modified the code from https://pytorch.org/tutorials/intermediate/ddp_tutorial.html   ,  instead of `self.net2(self.relu(self.net1(x)))`  I only forward `self.net2(x)`


```python 
import os
import sys
import tempfile
import torch
import torch.distributed as dist
import torch.nn as nn
import torch.optim as optim
import torch.multiprocessing as mp

from torch.nn.parallel import DistributedDataParallel as DDP

def setup(rank, world_size):
    os.environ['MASTER_ADDR'] = 'localhost'
    os.environ['MASTER_PORT'] = '12355'

    # initialize the process group
    dist.init_process_group("nccl", rank=rank, world_size=world_size)


def cleanup():
    dist.destroy_process_group()


class ToyModel(nn.Module):
    def __init__(self):
        super(ToyModel, self).__init__()
        self.net1 = nn.Linear(10, 10)
        self.relu = nn.ReLU()
        self.net2 = nn.Linear(10, 5)

    def forward(self, x):
        return self.net2(x) #self.net2(self.relu(self.net1(x)))


def demo_basic(rank, world_size):
    print(f"Running basic DDP example on rank {rank}.")
    setup(rank, world_size)

    # create model and move it to GPU with id rank
    model = ToyModel().to(rank)
    ddp_model = DDP(model, device_ids=[rank])

    loss_fn = nn.MSELoss()
    optimizer = optim.SGD(ddp_model.module.parameters(), lr=0.001)

    for name, p in ddp_model.named_parameters():
        if 'net2' in name:
            print('Device {}, name: {} , init weight sum: {}'.format(rank, name, p.
                                                                  sum()))
    dist.barrier()

    optimizer.zero_grad()
    outputs = ddp_model(torch.randn(20, 10))
    labels = torch.randn(20, 5).to(rank) + 3.56
    l = loss_fn(outputs, labels)
    l.backward()
    print('rank {}, Loss backpropagated {}'.format(rank, l))
    dist.barrier()

    for name, p in ddp_model.named_parameters():
        if p.grad is not None:
            print('Device {}, name: {} , grads sum: {}'.format(rank, name, p.grad.abs().sum()))
    dist.barrier()

    optimizer.step()
    for name, p in ddp_model.named_parameters():
        if 'net2' in name:
            print('Device {}, name: {} , weights after updates: {}'.format(rank, name, p.
                                                           sum()))
    cleanup()


def run_demo(demo_fn, world_size):
    mp.spawn(demo_fn,
             args=(world_size,),
             nprocs=world_size,
             join=True)


if __name__ == '__main__':
    run_demo(demo_basic, 2)
```

We can see the grads and updated weights are different for model on 2 gpus 

```
Running basic DDP example on rank 1.
Running basic DDP example on rank 0.

Device 1, name: module.net2.weight , init weight sum: 1.7563303709030151
Device 1, name: module.net2.bias , init weight sum: 0.21714895963668823
Device 0, name: module.net2.weight , init weight sum: 1.7563303709030151
Device 0, name: module.net2.bias , init weight sum: 0.21714895963668823


rank 0, Loss backpropagated 14.259430885314941
rank 1, Loss backpropagated 14.629181861877441

Device 0, name: module.net2.weight , grads sum: 18.091848373413086
Device 0, name: module.net2.bias , grads sum: 7.1830339431762695
Device 1, name: module.net2.weight , grads sum: 17.01994514465332
Device 1, name: module.net2.bias , grads sum: 7.35475492477417

Device 0, name: module.net2.weight , weights after updates: 1.7523858547210693
Device 0, name: module.net2.bias , weights after updates: 0.22433198988437653
Device 1, name: module.net2.weight , weights after updates: 1.7569527626037598
Device 1, name: module.net2.bias , weights after updates: 0.22450372576713562
```

However, if I inference with `self.net2(self.relu(self.net1(x)))`, backpropagated grads and model updated weights are hte same 
```
Running basic DDP example on rank 0.
Running basic DDP example on rank 1.
Device 0, name: module.net2.weight , init weight sum: -2.716691017150879
Device 0, name: module.net2.bias , init weight sum: 0.3666578531265259
Device 1, name: module.net2.weight , init weight sum: -2.716691017150879
Device 1, name: module.net2.bias , init weight sum: 0.3666578531265259


rank 0, Loss backpropagated 15.042831420898438
rank 1, Loss backpropagated 14.309487342834473

Device 0, name: module.net1.weight , grads sum: 6.896458148956299
Device 0, name: module.net1.bias , grads sum: 2.9502363204956055
Device 0, name: module.net2.weight , grads sum: 15.993313789367676
Device 0, name: module.net2.bias , grads sum: 7.368213653564453
Device 1, name: module.net1.weight , grads sum: 6.896458148956299
Device 1, name: module.net1.bias , grads sum: 2.9502363204956055
Device 1, name: module.net2.weight , grads sum: 15.993313789367676
Device 1, name: module.net2.bias , grads sum: 7.368213653564453

Device 0, name: module.net2.weight , weights after updates: -2.700697422027588
Device 0, name: module.net2.bias , weights after updates: 0.3740260601043701
Device 1, name: module.net2.weight , weights after updates: -2.700697422027588
Device 1, name: module.net2.bias , weights after updates: 0.3740260601043701

```

We are trying to improve training speed with multip-gpu training and we observe that after a while weights at different gpu are not the same,  we think this issue may be the cause of the problem. 
This case occurs when say I have a RL system with 2 sets of actions parametrized by net1 and net2, sometimes I need to use net1 and other times I need to use net2 . 



Please let me know if you need additional information.


Thank you


 



### Versions

Collecting environment information...
PyTorch version: 2.1.0
Is debug build: False
CUDA used to build PyTorch: 11.8
ROCM used to build PyTorch: N/A

OS: Ubuntu 22.04.2 LTS (x86_64)
GCC version: (Ubuntu 11.3.0-1ubuntu1~22.04) 11.3.0
Clang version: 14.0.0-1ubuntu1
CMake version: version 3.22.1
Libc version: glibc-2.35

Python version: 3.11.5 (main, Sep 11 2023, 13:54:46) [GCC 11.2.0] (64-bit runtime)
Python platform: Linux-5.15.0-67-generic-x86_64-with-glibc2.35
Is CUDA available: True
CUDA runtime version: 11.8.89
CUDA_MODULE_LOADING set to: LAZY
GPU models and configuration: 
GPU 0: Quadro RTX 6000
GPU 1: Quadro RTX 6000
GPU 2: Quadro RTX 6000
GPU 3: Quadro RTX 6000
GPU 4: Quadro RTX 6000
GPU 5: Quadro RTX 6000

Nvidia driver version: 525.85.05
cuDNN version: Probably one of the following:
/usr/lib/x86_64-linux-gnu/libcudnn.so.7.6.5
/usr/lib/x86_64-linux-gnu/libcudnn.so.8.8.0
/usr/lib/x86_64-linux-gnu/libcudnn_adv_infer.so.8.8.0
/usr/lib/x86_64-linux-gnu/libcudnn_adv_train.so.8.8.0
/usr/lib/x86_64-linux-gnu/libcudnn_cnn_infer.so.8.8.0
/usr/lib/x86_64-linux-gnu/libcudnn_cnn_train.so.8.8.0
/usr/lib/x86_64-linux-gnu/libcudnn_ops_infer.so.8.8.0
/usr/lib/x86_64-linux-gnu/libcudnn_ops_train.so.8.8.0
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):                          96
On-line CPU(s) list:             0-95
Vendor ID:                       GenuineIntel
Model name:                      Intel(R) Xeon(R) Gold 5220R CPU @ 2.20GHz
CPU family:                      6
Model:                           85
Thread(s) per core:              2
Core(s) per socket:              24
Socket(s):                       2
Stepping:                        7
CPU max MHz:                     4000.0000
CPU min MHz:                     1000.0000
BogoMIPS:                        4400.00
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 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 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 pku ospke avx512_vnni md_clear flush_l1d arch_capabilities
Virtualization:                  VT-x
L1d cache:                       1.5 MiB (48 instances)
L1i cache:                       1.5 MiB (48 instances)
L2 cache:                        48 MiB (48 instances)
L3 cache:                        71.5 MiB (2 instances)
NUMA node(s):                    2
NUMA node0 CPU(s):               0-23,48-71
NUMA node1 CPU(s):               24-47,72-95
Vulnerability Itlb multihit:     KVM: Mitigation: VMX disabled
Vulnerability L1tf:              Not affected
Vulnerability Mds:               Not affected
Vulnerability Meltdown:          Not affected
Vulnerability Mmio stale data:   Mitigation; Clear CPU buffers; SMT vulnerable
Vulnerability Retbleed:          Mitigation; Enhanced IBRS
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; Enhanced IBRS, IBPB conditional, RSB filling, PBRSB-eIBRS SW sequence
Vulnerability Srbds:             Not affected
Vulnerability Tsx async abort:   Mitigation; TSX disabled

Versions of relevant libraries:
[pip3] numpy==1.26.0
[pip3] torch==2.1.0
[pip3] torchaudio==2.1.0
[pip3] torchvision==0.16.0
[pip3] triton==2.1.0
[conda] blas                      1.0                         mkl  
[conda] ffmpeg                    4.3                  hf484d3e_0    pytorch
[conda] libjpeg-turbo             2.0.0                h9bf148f_0    pytorch
[conda] mkl                       2023.1.0         h213fc3f_46343  
[conda] mkl-service               2.4.0           py311h5eee18b_1  
[conda] mkl_fft                   1.3.8           py311h5eee18b_0  
[conda] mkl_random                1.2.4           py311hdb19cb5_0  
[conda] numpy                     1.26.0          py311h08b1b3b_0  
[conda] numpy-base                1.26.0          py311hf175353_0  
[conda] pytorch                   2.1.0           py3.11_cuda11.8_cudnn8.7.0_0    pytorch
[conda] pytorch-cuda              11.8                 h7e8668a_5    pytorch
[conda] pytorch-mutex             1.0                        cuda    pytorch
[conda] torchaudio                2.1.0               py311_cu118    pytorch
[conda] torchtriton               2.1.0                     py311    pytorch
[conda] torchvision               0.16.0              py311_cu118    pytorch


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