Repository: pytorch
Issue: `torch.distributed` hangs when using `torch.distributed.barrier` before any other communication primitives.
Labels: oncall: distributed,triaged

### 🐛 Describe the bug

When running distributed program on multi-node and multi-device environment using the following scripts. (In my case, 2 nodes with 4 gpus each)

run_ddp.sh
```bash
#node 0

#!/bin/bash
 
# export CUDA_VISIBLE_DEVICES=0,1
export N=2
export MASTER_ADDR=10.100.144.18
export MASTER_PORT=12355
 
python -m torch.distributed.launch \
    --nnodes=$N \
    --node_rank=0 \
    --nproc_per_node=2 \
    --master_addr=$MASTER_ADDR \
    --master_port=$MASTER_PORT \
    test_ddp.py

#node 1

#!/bin/bash
 
# export CUDA_VISIBLE_DEVICES=0,1
export N=2
export MASTER_ADDR=10.100.144.18
export MASTER_PORT=12355
 
python -m torch.distributed.launch \
    --nnodes=$N \
    --node_rank=1 \
    --nproc_per_node=2 \
    --master_addr=$MASTER_ADDR \
    --master_port=$MASTER_PORT \
    test_ddp.py
```

test_ddp.py
```python
import torch
import os
 
def init_distributed():
    local_rank = int(os.environ["LOCAL_RANK"])
    global_rank = int(os.environ["RANK"])
    world_size = int(os.environ["WORLD_SIZE"])
     
    print("local_rank:" + str(local_rank))
     
    torch.distributed.init_process_group("nccl", rank=global_rank, world_size=world_size)
    torch.cuda.set_device(local_rank)
     
    torch.distributed.barrier()
     
    torch.distributed.all_reduce(torch.rand(1).cuda())
     
    print("Done initializing distributed")
 
if __name__ == "__main__":
    init_distributed()
```
I ran the scripts above on two nodes with 4 gpus each and I DO NOT set the `CUDA_VISIBLE_DEVICES`, and the program hangs until the timeout reached.

I've found this relates to the `torch.distributed.barrier` call. There are several phenomenon I've noticed:
1. The program runs well when I move the `torch.distributed.barrier` just after `torch.distributed.all_reduce`
2. When I set the environment variable `CUDA_VISIBLE_DEVICES=0,1` on the rank 1 node, I got the program running well too.

And then I looked into the source code of `torch.distributed.barrier` , I've found that `barrier` will calculate the device idx and use it for all_reduce: https://github.com/pytorch/pytorch/blob/7b6e354ecd0fbbbf2999cef19dc1947cdc9ee4a4/torch/csrc/distributed/c10d/ProcessGroupNCCL.cpp#L3743

And my problem is exactly caused by this behavior. When I'm NOT set `CUDA_VISIBLE_DEVICES`, this will calculate device idx `2` and `3` on node 1, which then cause the later `torch.distributed.all_reduce` hanging.

So I'm wondering if I use the `torch.distributed.barrier` in the wrong way(I didn't find any instructions about such case on the doc website), or there is a bug in this function?

Besides there is indeed a INFO message for unknown device. But it seems not obvious for users to debug. https://github.com/pytorch/pytorch/blob/4efb980e0794eaaab551861cede82ef7032697d4/torch/csrc/distributed/c10d/ProcessGroupNCCL.cpp#L3749

### Versions

Collecting environment information...                                                                                                                                                         
PyTorch version: 2.4.0.dev20240421+cu121                                                                                                                                                      
Is debug build: False                                                                                                                                                                         
CUDA used to build PyTorch: 12.1                                                                                                                                                              
ROCM used to build PyTorch: N/A                                                                                                                                                               
                                                                                                                                                                                              
OS: Ubuntu 22.04.3 LTS (x86_64)                                                                                                                                                               
GCC version: (Ubuntu 11.4.0-1ubuntu1~22.04) 11.4.0                                                                                                                                            
Clang version: Could not collect                                                                                                                                                              
CMake version: version 3.26.4                                                                                                                                                                 
Libc version: glibc-2.35                                                                                                                                                                      
                                                                                                                                                                                              
Python version: 3.10.14 (main, Mar 21 2024, 16:24:04) [GCC 11.2.0] (64-bit runtime)                                                                                                           
Python platform: Linux-5.11.0-27-generic-x86_64-with-glibc2.35                                                                                                                                
Is CUDA available: True                                                                                                                                                                       
CUDA runtime version: 12.1.105                                                                                                                                                                
CUDA_MODULE_LOADING set to: LAZY                                                                                                                                                              
GPU models and configuration:                                                                                                                                                                 
GPU 0: Tesla V100-SXM2-16GB                                                                                                                                                                   
GPU 1: Tesla V100-SXM2-16GB                                                                                                                                                                   
GPU 2: Tesla V100-SXM2-16GB                                                                                                                                                                   
GPU 3: Tesla V100-SXM2-16GB                                                                                                                                                                   
                                                                                                                                                                                              
Nvidia driver version: 535.104.05                                                                                                                                                             
cuDNN version: Probably one of the following:                                                                                                                                                 
/usr/lib/x86_64-linux-gnu/libcudnn.so.8.9.0                                                                                                                                                   
/usr/lib/x86_64-linux-gnu/libcudnn_adv_infer.so.8.9.0                                                                                                                                         
/usr/lib/x86_64-linux-gnu/libcudnn_adv_train.so.8.9.0                                                                                                                                         
/usr/lib/x86_64-linux-gnu/libcudnn_cnn_infer.so.8.9.0                                                                                                                                         
/usr/lib/x86_64-linux-gnu/libcudnn_cnn_train.so.8.9.0                                                                                                                                         
/usr/lib/x86_64-linux-gnu/libcudnn_ops_infer.so.8.9.0                                                                                                                                         
/usr/lib/x86_64-linux-gnu/libcudnn_ops_train.so.8.9.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):                          64
On-line CPU(s) list:             0-63
Vendor ID:                       GenuineIntel
Model name:                      Intel(R) Xeon(R) Gold 6130 CPU @ 2.10GHz
CPU family:                      6
Model:                           85
Thread(s) per core:              2
Core(s) per socket:              16
Socket(s):                       2
Stepping:                        4
CPU max MHz:                     3700.0000
CPU min MHz:                     1000.0000
BogoMIPS:                        4200.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 x
2apic 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 pku ospke md_clear flush_l1d arch_capabilities
Virtualization:                  VT-x
L1d cache:                       1 MiB (32 instances)
L1i cache:                       1 MiB (32 instances)
L2 cache:                        32 MiB (32 instances)
L3 cache:                        44 MiB (2 instances)
NUMA node(s):                    2
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,48,50,52,54,56,58,60,62
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,49,51,53,55,57,59,61,63
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 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; Full generic retpoline, IBPB conditional, IBRS_FW, STIBP conditional, RSB filling
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-triton==3.0.0+989adb9a29
[pip3] torch==2.4.0.dev20240421+cu121
[pip3] torchaudio==2.2.2
[pip3] torchelastic==0.2.2
[pip3] torchvision==0.17.2
[pip3] triton==2.2.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_46344
[conda] mkl-service               2.4.0           py310h5eee18b_1  
[conda] mkl_fft                   1.3.8           py310h5eee18b_0  
[conda] mkl_random                1.2.4           py310hdb19cb5_0  
[conda] numpy                     1.26.4          py310h5f9d8c6_0  
[conda] numpy-base                1.26.4          py310hb5e798b_0  
[conda] optree                    0.11.0                   pypi_0    pypi
[conda] pytorch-cuda              12.1                 ha16c6d3_5    pytorch
[conda] pytorch-mutex             1.0                        cuda    pytorch
[conda] pytorch-triton            3.0.0+989adb9a29          pypi_0    pypi
[conda] torch                     2.4.0.dev20240421+cu121          pypi_0    pypi
[conda] torchaudio                2.2.2               py310_cu121    pytorch
[conda] torchelastic              0.2.2                    pypi_0    pypi
[conda] torchtriton               2.2.0                     py310    pytorch
[conda] torchvision               0.17.2              py310_cu121    pytorch

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