Repository: pytorch
Issue: IndexError: map::at with MPI CUDA collectives
Labels: module: multiprocessing,module: cuda,triaged

### 🐛 Describe the bug

Hi! I'm trying to run PyTorch with CUDA-aware MPI as backend and I'm consistently running into the same error with any collective operation. I am pretty confident I have installed MPI correctly since I'm using one of NVIDIA's PyTorch container images which has CUDA-aware MPI pre-installed, and then building PyTorch from there.

I check my CUDA-aware MPI installation (OpenMPI 4.1.5rc2) with `ompi_info --parsable --all | grep mpi_built_with_cuda_support:value`, which returns `true`. The build logs from PyTorch indicate that my MPI installation is correctly recognized, and running `torch.__config__.show()` has the flag `USE_MPI=1`, and `torch.is_mpi_available()` is `True`.

I am attempting to run MPI by launching this script with `mpirun`:
```
import os
import socket
import torch
import torch.distributed as dist
from torch.multiprocessing import Process
import time

def current_time_in_ms():
    return int(round(time.time() * 1000))

def run(rank, size, hostname, gpu, ngpus_per_node):
    print(f"I am {rank} of {size} in {hostname}")
    dim = 64
    input = torch.rand((dim, dim)).to(torch.float16).cuda()
    output = [torch.zeros((dim, dim)).to(torch.float16).cuda() for _ in range(ngpus_per_node)]
    start = current_time_in_ms()
    dist.all_gather(output, input)
    elapsed = current_time_in_ms() - start
    if(rank == 0):
        print("All gather size (bytes):", dim*dim*2, "Time elapsed: ", elapsed)

def init_processes(rank, size, gpu,ngpus_per_node, hostname, fn, backend='mpi'):
    """ Initialize the distributed environment. """
    torch.cuda.set_device(gpu)
    dist.init_process_group(backend, rank=rank, world_size=size)
 
    fn(rank, size, hostname, gpu, ngpus_per_node)
 
if __name__ == "__main__":
    world_size = int(os.environ['OMPI_COMM_WORLD_SIZE'])
    world_rank = int(os.environ['OMPI_COMM_WORLD_RANK'])
    gpu= int(os.environ['OMPI_COMM_WORLD_LOCAL_RANK'])
    ngpus_per_node=torch.cuda.device_count()
    hostname = socket.gethostname()
    init_processes(world_rank, world_size, gpu, ngpus_per_node, hostname, run, backend='cpu:mpi,cuda:mpi')
```

This gives me the following uninformative error:
```
Traceback (most recent call last):
  File "/workspace/test_scripts/benchmark_all_gather.py", line 36, in <module>
    init_processes(world_rank, world_size, gpu, ngpus_per_node, hostname, run, backend='cpu:mpi,cuda:mpi')
  File "/workspace/test_scripts/benchmark_all_gather.py", line 28, in init_processes
    fn(rank, size, hostname, gpu, ngpus_per_node)
  File "/workspace/test_scripts/benchmark_all_gather.py", line 18, in run
    dist.all_reduce(input)
  File "/usr/local/lib/python3.10/dist-packages/torch/distributed/c10d_logger.py", line 47, in wrapper
    return func(*args, **kwargs)
  File "/usr/local/lib/python3.10/dist-packages/torch/distributed/distributed_c10d.py", line 2055, in all_reduce
    work.wait()
IndexError: map::at
```
I have tried running the script above with an `all_reduce` operation as well, with the same error on the `work.wait()` call. I've also set `TORCH_CPP_LOG_LEVEL=INFO` and `TORCH_DISTRIBUTED_DEBUG=DETAIL` but there's nothing else in the error message. I'm also not able to trace the error back to the root cause by following source code.

I'd really appreciate your help with this! Thank you!

### Versions

PyTorch version: 2.1.0a0+32f93b1
Is debug build: False
CUDA used to build PyTorch: 12.2
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.3
Libc version: glibc-2.35

Python version: 3.10.12 (main, Jun 11 2023, 05:26:28) [GCC 11.4.0] (64-bit runtime)
Python platform: Linux-5.4.0-162-generic-x86_64-with-glibc2.35
Is CUDA available: True
CUDA runtime version: 12.2.140
CUDA_MODULE_LOADING set to: LAZY
GPU models and configuration:
GPU 0: NVIDIA H100 80GB HBM3
GPU 1: NVIDIA H100 80GB HBM3
GPU 2: NVIDIA H100 80GB HBM3
GPU 3: NVIDIA H100 80GB HBM3
GPU 4: NVIDIA H100 80GB HBM3
GPU 5: NVIDIA H100 80GB HBM3
GPU 6: NVIDIA H100 80GB HBM3
GPU 7: NVIDIA H100 80GB HBM3

Nvidia driver version: 535.86.10
cuDNN version: Probably one of the following:
/usr/lib/x86_64-linux-gnu/libcudnn.so.8.9.5
/usr/lib/x86_64-linux-gnu/libcudnn_adv_infer.so.8.9.5
/usr/lib/x86_64-linux-gnu/libcudnn_adv_train.so.8.9.5
/usr/lib/x86_64-linux-gnu/libcudnn_cnn_infer.so.8.9.5
/usr/lib/x86_64-linux-gnu/libcudnn_cnn_train.so.8.9.5
/usr/lib/x86_64-linux-gnu/libcudnn_ops_infer.so.8.9.5
/usr/lib/x86_64-linux-gnu/libcudnn_ops_train.so.8.9.5
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:                      48 bits physical, 57 bits virtual
Byte Order:                         Little Endian
CPU(s):                             176
On-line CPU(s) list:                0-175
Vendor ID:                          GenuineIntel
Model name:                         Intel(R) Xeon(R) Platinum 8468V
CPU family:                         6
Model:                              143
Thread(s) per core:                 2
Core(s) per socket:                 44
Socket(s):                          2
Stepping:                           8
BogoMIPS:                           4800.00
Flags:                              fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush mmx fxsr sse sse2 ss ht syscall nx pdpe1gb rdtscp lm constant_tsc arch_perfmon rep_good nopl xtopology cpuid tsc_known_freq pni pclmulqdq vmx ssse3 fma cx16 pdcm pcid sse4_1 sse4_2 x2apic movbe popcnt tsc_deadline_timer aes xsave avx f16c rdrand hypervisor lahf_lm abm 3dnowprefetch cpuid_fault invpcid_single ssbd ibrs ibpb stibp ibrs_enhanced tpr_shadow vnmi flexpriority ept vpid ept_ad fsgsbase tsc_adjust bmi1 avx2 smep bmi2 erms invpcid avx512f avx512dq rdseed adx smap avx512ifma clflushopt clwb avx512cd sha_ni avx512bw avx512vl xsaveopt xsavec xgetbv1 xsaves avx512_bf16 wbnoinvd arat avx512vbmi umip pku ospke waitpkg avx512_vbmi2 gfni vaes vpclmulqdq avx512_vnni avx512_bitalg avx512_vpopcntdq rdpid cldemote movdiri movdir64b md_clear arch_capabilities
Virtualization:                     VT-x
Hypervisor vendor:                  KVM
Virtualization type:                full
L1d cache:                          5.5 MiB (176 instances)
L1i cache:                          5.5 MiB (176 instances)
L2 cache:                           352 MiB (88 instances)
L3 cache:                           32 MiB (2 instances)
NUMA node(s):                       2
NUMA node0 CPU(s):                  0-87
NUMA node1 CPU(s):                  88-175
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:      Unknown: No mitigations
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; 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.22.2
[pip3] onnx==1.14.0
[pip3] onnxruntime==1.15.1
[pip3] pytorch-quantization==2.1.2
[pip3] pytorch-ranger==0.1.1
[pip3] pytorch-triton==2.1.0+e6216047b8
[pip3] torch==2.1.0a0+32f93b1
[pip3] torch-optimizer==0.3.0
[pip3] torch-tensorrt==0.0.0
[pip3] torchdata==0.7.0a0
[pip3] torchmetrics==1.0.3
[pip3] torchtext==0.16.0a0
[pip3] torchvision==0.16.0a0
[pip3] triton-pre-mlir==2.0.0
[conda] blas                      1.0                         mkl
[conda] cudatoolkit               11.8.0               h6a678d5_0
[conda] magma-cuda121             2.6.1                         1    pytorch
[conda] mkl                       2023.1.0         h213fc3f_46344
[conda] mkl-include               2023.1.0         h06a4308_46344
[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.24.3          py311h08b1b3b_1
[conda] numpy-base                1.24.3          py311hf175353_1

cc @VitalyFedyunin @ptrblck