Repository: pytorch
Issue: Hanging at waitForFutureOrTimeout when actively destroying ProcessGroups
Labels: oncall: distributed,triaged

### 🐛 Describe the bug

Hi, we want to use the existing APIs to actively destroy the ProcessGroups in the main thread without tearing down the health processes. For example, we launch the following script with `NCCL_CUMEM_ENABLE=1 torchrun --nproc_per_node=4 --nnodes=1 test.py` . In the script, we mimic that the rank 2 is hanging and we want to destroy the ProcessGroups at Rank0, 1, 3 so that we can do some reconfiguration later in these processes.
```
import os
import time
import torch
import torch.distributed as dist
import datetime
import time
import torch.distributed as c10d
from concurrent.futures import ThreadPoolExecutor

def run_worker(rank, world_size):
    ndev = torch.cuda.device_count()
    device = torch.device(f'cuda:{rank % ndev}')
    torch.cuda.set_device(device)
    dist.init_process_group('nccl', rank=rank, world_size=world_size,
                            timeout=datetime.timedelta(seconds=1800)
                           )
    print(torch.distributed.get_world_size())
    pg = c10d.distributed_c10d._get_default_group()
    pg1 = torch.distributed.new_group(ranks=[2,3], timeout=datetime.timedelta(seconds=1800), backend="nccl")

    device_id = f"cuda:{rank % torch.cuda.device_count()}"
    tensor0 = torch.ones([1]).cuda(rank) * rank
    tensor = torch.ones([1]).cuda(rank) * rank
    tensor1 = torch.ones([2,3]).cuda(rank) * rank
    # for initialization purpose
    torch.distributed.all_reduce(tensor0, group=pg)
    torch.cuda.synchronize()
    if not isinstance(pg1, int):
        torch.distributed.all_reduce(tensor0, group=pg1)
        torch.cuda.synchronize()
    print(tensor0.item())
    # suppose before the following operations, one rank is down.
    if rank==2:
        time.sleep(1800) # suppose the rank is hanging 
    print("One rank is down, other ranks continue")
    if not isinstance(pg1, int):
        torch.distributed.all_reduce(tensor1, group=pg1)
    torch.distributed.all_reduce(tensor0, group=pg)
    print("Suppose until now we find one rank is down, and we want to destroy ProcessGroups at Rank 0, 1, 3")
    from torch.distributed.distributed_c10d import _world
    pg_lis = list(_world.pg_map.keys())
    print(pg_lis)
    with ThreadPoolExecutor(max_workers=len(pg_lis)) as executor:
        executor.map(lambda x: x._abort(), pg_lis)
    print(f"pg abort {rank}")
    dist.destroy_process_group()
    print(f"finish {rank}")
    
if __name__ == "__main__":
    world_size = int(os.getenv("WORLD_SIZE", 4))
    rank = int(os.getenv("RANK", -1))
    run_worker(rank, world_size)
```
However, we find only Rank0,1 would successfully reach the final print statement `print(f"finish {rank}")` but Rank 3 would would hang at `dist.destroy_process_group()` until the watchdog heartbeat monitor thread is triggered. By GDB, we find the Rank3 would hang at `waitForFutureOrTimeout`:
```
#0  syscall () at ../sysdeps/unix/sysv/linux/x86_64/syscall.S:38
#1  0x000077658bad9706 in std::__atomic_futex_unsigned_base::_M_futex_wait_until_steady(unsigned int*, unsigned int, bool, std::chrono::duration<long, std::ratio<1l, 1l> >, std::chrono::duration<long, std::ratio<1l, 1000000000l> >) ()
   from /home/ubuntu/anaconda3/envs/pytorch/bin/../lib/libstdc++.so.6
#2  0x000077656de81075 in c10d::ProcessGroupNCCL::waitForFutureOrTimeout(std::future<bool>&, std::chrono::duration<long, std::ratio<1l, 1000l> > const&, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > const&, bool) ()
   from /home/ubuntu/pytorch/torch/lib/libtorch_cuda.so
#3  0x000077656de84771 in c10d::ProcessGroupNCCL::shutdown(std::optional<std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > >) () from /home/ubuntu/pytorch/torch/lib/libtorch_cuda.so
#4  0x000077658b384210 in pybind11::cpp_function::initialize<torch::distributed::c10d::(anonymous namespace)::c10d_init(_object*, _object*)::{lambda(c10::intrusive_ptr<c10d::ProcessGroupNCCL, c10::detail::intrusive_target_default_null_type<c10d::ProcessGroupNCCL> > const&)#77}, void, c10::intrusive_ptr<c10d::ProcessGroupNCCL, c10::detail::intrusive_target_default_null_type<c10d::ProcessGroupNCCL> > const&, pybind11::name, pybind11::is_method, pybind11::sibling, pybind11::call_guard<pybind11::gil_scoped_release> >(torch::distributed::c10d::(anonymous namespace)::c10d_init(_object*, _object*)::{lambda(c10::intrusive_ptr<c10d::ProcessGroupNCCL, c10::detail::intrusive_target_default_null_type<c10d::ProcessGroupNCCL> > const&)#77}&&, void (*)(c10::intrusive_ptr<c10d::ProcessGroupNCCL, c10::detail::intrusive_target_default_null_type<c10d::ProcessGroupNCCL> > const&), pybind11::name const&, pybind11::is_method const&, pybind11::sibling const&, pybind11::call_guard<pybind11::gil_scoped_release> const&)::{lambda(pybind11::detail::function_call&)#3}::_FUN(pybind11::detail::function_call&) () from /home/ubuntu/pytorch/torch/lib/libtorch_python.so
#5  0x000077658aa8a6bf in pybind11::cpp_function::dispatcher(_object*, _object*, _object*) () from /home/ubuntu/pytorch/torch/lib/libtorch_python.so
```
I find that this issue is related to the previous unfinished collective operations. When I comment out the ` torch.distributed.all_reduce(tensor0, group=pg)` after Rank 2 sleeps, then Rank 3 can successfully reach to the end as expected.



### Versions

The NCCL is from https://github.com/NVIDIA/nccl/tree/v2.22.3-1
```
PyTorch version: 2.4.0a0+gitf6fb80b
Is debug build: False
CUDA used to build PyTorch: 12.2
ROCM used to build PyTorch: N/A

OS: Ubuntu 22.04.4 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, May  6 2024, 19:42:50) [GCC 11.2.0] (64-bit runtime)
Python platform: Linux-6.5.0-1022-aws-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: Tesla T4
GPU 1: Tesla T4
GPU 2: Tesla T4
GPU 3: Tesla T4

Nvidia driver version: 535.161.08
cuDNN version: Probably one of the following:
/usr/lib/x86_64-linux-gnu/libcudnn.so.8.9.7
/usr/lib/x86_64-linux-gnu/libcudnn_adv_infer.so.8.9.7
/usr/lib/x86_64-linux-gnu/libcudnn_adv_train.so.8.9.7
/usr/lib/x86_64-linux-gnu/libcudnn_cnn_infer.so.8.9.7
/usr/lib/x86_64-linux-gnu/libcudnn_cnn_train.so.8.9.7
/usr/lib/x86_64-linux-gnu/libcudnn_ops_infer.so.8.9.7
/usr/lib/x86_64-linux-gnu/libcudnn_ops_train.so.8.9.7
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):                             48
On-line CPU(s) list:                0-47
Vendor ID:                          GenuineIntel
Model name:                         Intel(R) Xeon(R) Platinum 8259CL CPU @ 2.50GHz
CPU family:                         6
Model:                              85
Thread(s) per core:                 2
Core(s) per socket:                 24
Socket(s):                          1
Stepping:                           7
BogoMIPS:                           4999.99
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 nonstop_tsc cpuid aperfmperf tsc_known_freq pni pclmulqdq monitor ssse3 fma cx16 pcid sse4_1 sse4_2 x2apic movbe popcnt tsc_deadline_timer aes xsave avx f16c rdrand hypervisor lahf_lm abm 3dnowprefetch invpcid_single pti fsgsbase tsc_adjust bmi1 avx2 smep bmi2 erms invpcid mpx avx512f avx512dq rdseed adx smap clflushopt clwb avx512cd avx512bw avx512vl xsaveopt xsavec xgetbv1 xsaves ida arat pku ospke avx512_vnni
Hypervisor vendor:                  KVM
Virtualization type:                full
L1d cache:                          768 KiB (24 instances)
L1i cache:                          768 KiB (24 instances)
L2 cache:                           24 MiB (24 instances)
L3 cache:                           35.8 MiB (1 instance)
NUMA node(s):                       1
NUMA node0 CPU(s):                  0-47
Vulnerability Gather data sampling: Unknown: Dependent on hypervisor status
Vulnerability Itlb multihit:        KVM: Mitigation: VMX unsupported
Vulnerability L1tf:                 Mitigation; PTE Inversion
Vulnerability Mds:                  Vulnerable: Clear CPU buffers attempted, no microcode; SMT Host state unknown
Vulnerability Meltdown:             Mitigation; PTI
Vulnerability Mmio stale data:      Vulnerable: Clear CPU buffers attempted, no microcode; SMT Host state unknown
Vulnerability Retbleed:             Vulnerable
Vulnerability Spec rstack overflow: Not affected
Vulnerability Spec store bypass:    Vulnerable
Vulnerability Spectre v1:           Mitigation; usercopy/swapgs barriers and __user pointer sanitization
Vulnerability Spectre v2:           Mitigation; Retpolines; STIBP disabled; RSB filling; PBRSB-eIBRS Not affected; BHI Retpoline
Vulnerability Srbds:                Not affected
Vulnerability Tsx async abort:      Not affected

Versions of relevant libraries:
[pip3] numpy==2.0.1
[pip3] optree==0.12.1
[pip3] pytorch-triton==3.0.0+dedb7bdf33
[pip3] torch==2.4.0a0+gitf6fb80b
[conda] magma-cuda121             2.6.1                         1    pytorch
[conda] magma-cuda124             2.6.1                         1    pytorch
[conda] mkl-include               2024.2.0                 pypi_0    pypi
[conda] mkl-static                2024.2.0                 pypi_0    pypi
[conda] numpy                     2.0.1                    pypi_0    pypi
[conda] optree                    0.12.1                   pypi_0    pypi
[conda] pytorch-triton            3.0.0+dedb7bdf33          pypi_0    pypi
[conda] torch                     2.4.0a0+gitf6fb80b           dev_0    <develop>
```

cc @XilunWu @H-Huang @awgu @kwen2501 @wanchaol @fegin @fduwjj @wz337 @wconstab @d4l3k @c-p-i-o