Repository: pytorch
Issue: OOM error for collection communication primitive provided by torch.distributed
Labels: oncall: distributed

### 🐛 Describe the bug

While using torch.distributed's nccl backend for GPU communication, I found a strange bug: When the Memory usage Of the video card exceeds a certain threshold (usually less than half of the memory usage), calling the collection communication primitive of torch.distributed will cause an **Out Of Memory error**. Even if the length of the communicated tensor data is **1**, the primitive of point-to-point communication can run normally under the same memory usage.

Here is a piece of code that can **replicate the bug** on my device
```python
class Compute2(mp.Process):
    def __init__(self, rank, size, data_size):
        super().__init__()
        self.rank = rank
        self.size = size
        self.device = f'cuda:{self.rank}'
        self.data_size = data_size
        

    def init_porcess(self, backend='nccl'):
        os.environ['MASTER_ADDR'] = '127.0.0.1'
        os.environ['MASTER_PORT'] = '29510'
        dist.init_process_group(backend, rank=self.rank, world_size=self.size)
        logging.info('rank {} init process done'.format(self.rank))
    
    def run(self):
        os.environ['CUDA_LAUNCH_BLOCKING'] = '1'
        self.init_porcess()

        # move data to device: size = data_size * 4 / 1024 / 1024 / 1024 GB
        self.data = torch.rand(self.data_size, dtype=torch.float32, device=self.device)
        
        # nccl communication
        tensor = torch.ones(1, dtype=torch.float32, device=self.device)
        group = dist.new_group([i for i in range(self.size)])

        # collective communication
        # dist.all_reduce(tensor, group=group)
        # logging.info('rank {} collective communication done'.format(self.rank))

        # point to point communication between device 0 and device 1
        if self.rank == 0:
            dist.send(tensor, dst=1, group=group)
        elif self.rank == 1:
            dist.recv(tensor, src=0, group=group)
        logging.info('rank {} p2p communication done'.format(self.rank))

if __name__ == "__main__":
    mp.set_start_method('spawn', force=True)

    data_size = 100000000 * 13  
    size = 4
    processes = []
    for i in range(size):
        p = Compute2(i, size, data_size)
        processes.append(p)
        p.start()
    
    for p in processes:
        p.join()
```
As shown in the code above，Video memory usage is：13 * 100000000 * 4  / 1024 ** 3 ≈ 4.8 GB. There are four Nvidia RTX 3080Ti with 12 GB device Memory.

OOM error occurs in collection communication when executing code, but not in point-to-point communication. The following error message is displayed：
Traceback (most recent call last):
  File "/root/miniconda3/lib/python3.8/multiprocessing/process.py", line 315, in _bootstrap
    self.run()
  File "/root/Project/TCRGraph/val/timetest.py", line 275, in run
    dist.all_reduce(tensor, group=group)
  File "/root/miniconda3/lib/python3.8/site-packages/torch/distributed/distributed_c10d.py", line 1316, in all_reduce
    work = group.allreduce([tensor], opts)
RuntimeError: CUDA error: out of memory
Process Compute2-2:
Traceback (most recent call last):
  File "/root/miniconda3/lib/python3.8/multiprocessing/process.py", line 315, in _bootstrap
    self.run()
  File "/root/Project/TCRGraph/val/timetest.py", line 275, in run
    dist.all_reduce(tensor, group=group)
  File "/root/miniconda3/lib/python3.8/site-packages/torch/distributed/distributed_c10d.py", line 1316, in all_reduce
    work = group.allreduce([tensor], opts)
RuntimeError: CUDA error: out of memory
Process Compute2-4:
Traceback (most recent call last):
  File "/root/miniconda3/lib/python3.8/multiprocessing/process.py", line 315, in _bootstrap
    self.run()
  File "/root/Project/TCRGraph/val/timetest.py", line 275, in run
    dist.all_reduce(tensor, group=group)
  File "/root/miniconda3/lib/python3.8/site-packages/torch/distributed/distributed_c10d.py", line 1316, in all_reduce
    work = group.allreduce([tensor], opts)
RuntimeError: CUDA error: out of memory




### Versions

Collecting environment information...
PyTorch version: 1.11.0+cu113
Is debug build: False
CUDA used to build PyTorch: 11.3
ROCM used to build PyTorch: N/A

OS: Ubuntu 20.04.4 LTS (x86_64)
GCC version: (Ubuntu 9.4.0-1ubuntu1~20.04.2) 9.4.0
Clang version: 10.0.0-4ubuntu1 
CMake version: version 3.16.3
Libc version: glibc-2.31

Python version: 3.8.10 (default, Jun  4 2021, 15:09:15)  [GCC 7.5.0] (64-bit runtime)
Python platform: Linux-5.4.0-162-generic-x86_64-with-glibc2.17
Is CUDA available: True
CUDA runtime version: 11.3.109
CUDA_MODULE_LOADING set to: 
GPU models and configuration: 
GPU 0: NVIDIA GeForce RTX 3080 Ti
GPU 1: NVIDIA GeForce RTX 3080 Ti
GPU 2: NVIDIA GeForce RTX 3080 Ti
GPU 3: NVIDIA GeForce RTX 3080 Ti

Nvidia driver version: 535.104.05
cuDNN version: Probably one of the following:
/usr/lib/x86_64-linux-gnu/libcudnn.so.8.2.0
/usr/lib/x86_64-linux-gnu/libcudnn_adv_infer.so.8.2.0
/usr/lib/x86_64-linux-gnu/libcudnn_adv_train.so.8.2.0
/usr/lib/x86_64-linux-gnu/libcudnn_cnn_infer.so.8.2.0
/usr/lib/x86_64-linux-gnu/libcudnn_cnn_train.so.8.2.0
/usr/lib/x86_64-linux-gnu/libcudnn_ops_infer.so.8.2.0
/usr/lib/x86_64-linux-gnu/libcudnn_ops_train.so.8.2.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
Byte Order:                         Little Endian
Address sizes:                      46 bits physical, 48 bits virtual
CPU(s):                             48
On-line CPU(s) list:                0-47
Thread(s) per core:                 2
Core(s) per socket:                 12
Socket(s):                          2
NUMA node(s):                       2
Vendor ID:                          GenuineIntel
CPU family:                         6
Model:                              85
Model name:                         Intel(R) Xeon(R) Silver 4214R CPU @ 2.40GHz
Stepping:                           7
CPU MHz:                            1000.062
BogoMIPS:                           4800.00
Virtualization:                     VT-x
L1d cache:                          768 KiB
L1i cache:                          768 KiB
L2 cache:                           24 MiB
L3 cache:                           33 MiB
NUMA node0 CPU(s):                  0,2,4,6,8,10,12,14,16,18,20,22,24,26,28,30,32,34,36,38,40,42,44,46
NUMA node1 CPU(s):                  1,3,5,7,9,11,13,15,17,19,21,23,25,27,29,31,33,35,37,39,41,43,45,47
Vulnerability Gather data sampling: Mitigation; Microcode
Vulnerability Itlb multihit:        KVM: Mitigation: Split huge pages
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
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

Versions of relevant libraries:
[pip3] numpy==1.22.4
[pip3] pytorch-memlab==0.3.0
[pip3] torch==1.11.0+cu113
[pip3] torch-cluster==1.6.0
[pip3] torch-scatter==2.0.9
[pip3] torchvision==0.12.0+cu113
[conda] numpy                     1.22.4                   pypi_0    pypi
[conda] pytorch-memlab            0.3.0                    pypi_0    pypi
[conda] torch                     1.11.0+cu113             pypi_0    pypi
[conda] torch-cluster             1.6.0                    pypi_0    pypi
[conda] torch-scatter             2.0.9                    pypi_0    pypi
[conda] torchvision               0.12.0+cu113             pypi_0    pypi

cc @mrshenli @pritamdamania87 @zhaojuanmao @satgera @rohan-varma @gqchen @aazzolini @osalpekar @jiayisuse @H-Huang @kwen2501 @awgu @penguinwu @fegin @XilunWu @wanchaol @fduwjj @wz337 @tianyu-l @wconstab @yf225