Repository: pytorch
Issue: Distributed training with NCCL hangs on init_process_group when debug is DETAIL
Labels: oncall: distributed,triaged

### 🐛 Describe the bug

When setting `TORCH_CPP_LOG_LEVEL=INFO` and `TORCH_DISTRIBUTED_DEBUG=DETAIL`, torchrun will hang since it tries to initialize a Gloo process group and for some reason that hangs? On machine 1:

```py
import os

import torch
import torch.distributed as dist
import torch.multiprocessing as mp

def worker(rank):
    dist.init_process_group("nccl", rank=0, world_size=2)
    dist.barrier()
    print('synced!')

if __name__ == "__main__":
    os.environ["MASTER_ADDR"] = "<machine 1 IP>"
    os.environ["MASTER_PORT"] = "29501"
    mp.spawn(worker, nprocs=1, args=())
```

and on machine 2:

```py
import os

import torch
import torch.distributed as dist
import torch.multiprocessing as mp

def worker(rank):
    dist.init_process_group("nccl", rank=1, world_size=2)
    dist.barrier()
    print('synced!')

if __name__ == "__main__":
    os.environ["MASTER_ADDR"] = "<machine 1 IP>"
    os.environ["MASTER_PORT"] = "29501"
    mp.spawn(worker, nprocs=1, args=())
```

If I run these without any environment variables, I get `synced!` on both machines. But if I set  `TORCH_CPP_LOG_LEVEL=INFO TORCH_DISTRIBUTED_DEBUG=DETAIL` on any one of the machines, I get a hang:

```
$ TORCH_CPP_LOG_LEVEL=INFO TORCH_DISTRIBUTED_DEBUG=DETAIL python test.py
[I debug.cpp:49] [c10d] The debug level is set to DETAIL.
[I debug.cpp:49] [c10d] The debug level is set to DETAIL.
[I socket.cpp:720] [c10d - debug] The client socket will attempt to connect to an IPv6 address of (192.168.1.13, 29501).
[I socket.cpp:796] [c10d - trace] The client socket is attempting to connect to [::ffff:192.168.1.13]:29501.
[I socket.cpp:884] [c10d] The client socket has connected to [::ffff:192.168.1.13]:29501 on [abcd]:51114.
[I TCPStore.cpp:343] [c10d - debug] TCP client connected to host 192.168.1.13:29501
[I ProcessGroupNCCL.cpp:804] [PG 0 Rank 1] ProcessGroupNCCL initialization options: NCCL version: 2.20.5, size: 2, global rank: 1, TORCH_NCCL_ASYNC_ERROR_HANDLING: 3, TORCH_NCCL_DUMP_ON_TIMEOUT: 1, TORCH_NCCL_WAIT_TIMEOUT_DUMP_MILSEC: 60000, TORCH_NCCL_DESYNC_DEBUG: 1, TORCH_NCCL_ENABLE_TIMING: 1, TORCH_NCCL_BLOCKING_WAIT: 0, TIMEOUT(ms): 600000, USE_HIGH_PRIORITY_STREAM: 0, SPLIT_FROM: 0, SPLIT_COLOR: 0, TORCH_DISTRIBUTED_DEBUG: DETAIL, TORCH_NCCL_USE_TENSOR_REGISTER_ALLOCATOR_HOOK: 0, TORCH_NCCL_ENABLE_MONITORING: 1, TORCH_NCCL_HEARTBEAT_TIMEOUT_SEC: 600, TORCH_NCCL_TRACE_BUFFER_SIZE: 0, TORCH_NCCL_COORD_CHECK_MILSEC: 1000, ID=101734640
```

I'm not too familiar with torch internals, but I looked in `init_process_group` and it looks like when DETAIL level is set, a `ProcessGroupGloo` is created via `_create_process_group_wrapper` here:
https://github.com/pytorch/pytorch/blob/5ceba6a3cbd817922af0363f6ba39a85ab58e309/torch/distributed/distributed_c10d.py#L1813-L1829
and here via `_create_process_group_wrapper`:
https://github.com/pytorch/pytorch/blob/5ceba6a3cbd817922af0363f6ba39a85ab58e309/torch/distributed/distributed_c10d.py#L4263

For some reason this hangs. I didn't dig any deeper into the cpp.

### Versions

```
PyTorch version: 2.3.1+cu121
Is debug build: False
CUDA used to build PyTorch: 12.1
ROCM used to build PyTorch: N/A

OS: Ubuntu 20.04.6 LTS (x86_64)
GCC version: (Ubuntu 9.4.0-1ubuntu1~20.04.2) 9.4.0
Clang version: Could not collect
CMake version: version 3.16.3
Libc version: glibc-2.31

Python version: 3.10.12 | packaged by conda-forge | (main, Jun 23 2023, 22:40:32) [GCC 12.3.0] (64-bit runtime)
Python platform: Linux-5.4.0-177-generic-x86_64-with-glibc2.31
Is CUDA available: True
CUDA runtime version: 12.2.91
CUDA_MODULE_LOADING set to: LAZY
GPU models and configuration: GPU 0: NVIDIA A100 80GB PCIe
Nvidia driver version: 535.54.03
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
Address sizes:                      48 bits physical, 48 bits virtual
CPU(s):                             64
On-line CPU(s) list:                0-63
Thread(s) per core:                 2
Core(s) per socket:                 32
Socket(s):                          1
NUMA node(s):                       1
Vendor ID:                          AuthenticAMD
CPU family:                         25
Model:                              1
Model name:                         AMD EPYC 7543P 32-Core Processor
Stepping:                           1
Frequency boost:                    enabled
CPU MHz:                            1517.799
CPU max MHz:                        2800.0000
CPU min MHz:                        1500.0000
BogoMIPS:                           5589.45
Virtualization:                     AMD-V
L1d cache:                          1 MiB
L1i cache:                          1 MiB
L2 cache:                           16 MiB
L3 cache:                           256 MiB
NUMA node0 CPU(s):                  0-63
Vulnerability Gather data sampling: Not affected
Vulnerability Itlb multihit:        Not affected
Vulnerability L1tf:                 Not affected
Vulnerability Mds:                  Not affected
Vulnerability Meltdown:             Not affected
Vulnerability Mmio stale data:      Not affected
Vulnerability Retbleed:             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 always-on, RSB filling, PBRSB-eIBRS Not affected
Vulnerability Srbds:                Not affected
Vulnerability Tsx async abort:      Not affected
Flags:                              fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush mmx fxsr sse sse2 ht syscall nx mmxext fxsr_opt pdpe1gb rdtscp lm constant_tsc rep_good nopl nonstop_tsc cpuid extd_apicid aperfmperf pni pclmulqdq monitor ssse3 fma cx16 pcid sse4_1 sse4_2 movbe popcnt aes xsave avx f16c rdrand lahf_lm cmp_legacy svm extapic cr8_legacy abm sse4a misalignsse 3dnowprefetch osvw ibs skinit wdt tce topoext perfctr_core perfctr_nb bpext perfctr_llc mwaitx cpb cat_l3 cdp_l3 invpcid_single hw_pstate ssbd mba ibrs ibpb stibp vmmcall fsgsbase bmi1 avx2 smep bmi2 erms invpcid cqm rdt_a rdseed adx smap clflushopt clwb sha_ni xsaveopt xsavec xgetbv1 xsaves cqm_llc cqm_occup_llc cqm_mbm_total cqm_mbm_local clzero irperf xsaveerptr wbnoinvd arat npt lbrv svm_lock nrip_save tsc_scale vmcb_clean flushbyasid decodeassists pausefilter pfthreshold v_vmsave_vmload vgif umip pku ospke vaes vpclmulqdq rdpid overflow_recov succor smca

Versions of relevant libraries:
[pip3] numpy==2.0.0
[pip3] torch==2.3.1
[pip3] torchvision==0.18.1
[pip3] triton==2.3.1
[conda] numpy                     2.0.0                    pypi_0    pypi
[conda] torch                     2.3.1                    pypi_0    pypi
[conda] torchvision               0.18.1                   pypi_0    pypi
[conda] triton                    2.3.1                    pypi_0    pypi
```

cc @mrshenli @pritamdamania87 @zhaojuanmao @satgera @gqchen @aazzolini @osalpekar @jiayisuse @H-Huang @kwen2501 @awgu @fegin @XilunWu @wanchaol @fduwjj @wz337 @tianyu-l @wconstab @chauhang @d4l3k