Repository: pytorch
Issue: dist.destroy_process_group did not destroy the process group well
Labels: oncall: distributed,triaged

### 🐛 Describe the bug

The function destroy_progress_group(group) is not working. As below code shows, after executing this function, the memory consumption did not decrease. By executing "del group", the memory consumption decrease normally.

In addition, before executing "del group", I could still use this group to do communication.

Please check what is wrong.

```python
import torch
import os
import torch.distributed as dist
import torch.multiprocessing as mp
import pynvml
from itertools import combinations


def print0(msg):
    if dist.get_rank() ==0:
        print(msg)

def run(rank: int, size: int):
    """ This function can test all-reduce on all possible process groups.
    This function consists of two steps:
        step1: creates all possible NCCL process groups.
        step2: do dist.allreduce on all process groups.

    :param rank:
    :param size:
    :return:
    """

    handle = pynvml.nvmlDeviceGetHandleByIndex(0)
    # Step 1: creates all possible process groups.
    comb=[0,1]
    print0(f"on rank {rank}: {comb}")
    group = dist.new_group(comb)
    print0(f"on rank {rank}: successfully create group for {comb}, group is {group}")


    # Step2: test all-reduce on all process groups
    tensor = torch.rand((1024, 1024)).to(0)
    dist.barrier()
    meminfo = pynvml.nvmlDeviceGetMemoryInfo(handle)
    temp = meminfo.used
    print0(f"Before group [0,1] all_reduce:  NVIDIA-SMI: {meminfo.used/1024/1024}")

    dist.all_reduce(tensor, group=group, async_op=False)
    dist.barrier()
    meminfo = pynvml.nvmlDeviceGetMemoryInfo(handle)
    print0(f"{dist.get_rank()}, NVIDIA-SMI: after running [0,1]: {meminfo.used / 1024 / 1024}, add: {(meminfo.used - temp)/1024/1024}")

    dist.destroy_process_group(group)
    dist.barrier()
    meminfo = pynvml.nvmlDeviceGetMemoryInfo(handle)
    print0(f"{dist.get_rank()}, NVIDIA-SMI: after dist.detroy_process_group [0,1]: {meminfo.used / 1024 / 1024}")
    del group

    meminfo = pynvml.nvmlDeviceGetMemoryInfo(handle)
    print0(f"{dist.get_rank()}, NVIDIA-SMI: after delete group [0,1]: {meminfo.used / 1024 / 1024}")


def init_process(rank, size, fn, backend='nccl'):
    pynvml.nvmlInit()
    handle = pynvml.nvmlDeviceGetHandleByIndex(rank)
    meminfo = pynvml.nvmlDeviceGetMemoryInfo(handle)
    os.environ["CUDA_VISIBLE_DEVICES"] = str(rank)
    os.environ['MASTER_ADDR'] = '127.0.0.1'
    os.environ['MASTER_PORT'] = '29500'
    dist.init_process_group(backend, rank=rank, world_size=size)
    fn(rank, size)


if __name__ == '__main__':
    world_size = 4
    processes = []
    mp.set_start_method("spawn")
    for rank in range(world_size):
        p = mp.Process(target=init_process, args=(rank, world_size, run))
        p.start()
        processes.append(p)
    for p in processes:
        p.join()

```

Here is the output log.

```
0, NVIDIA-SMI: after running [0,1]: 2285.0, add: 548.0
0, NVIDIA-SMI: after dist.detroy_process_group [0,1]: 2285.0
0, NVIDIA-SMI: after delete group: 1741.0

```

### Versions

Collecting environment information...
PyTorch version: 2.1.0.dev20230809+cu118
Is debug build: False
CUDA used to build PyTorch: 11.8
ROCM used to build PyTorch: N/A

OS: CentOS Linux 7 (Core) (x86_64)
GCC version: (GCC) 7.3.1 20180303 (Red Hat 7.3.1-5)
Clang version: Could not collect
CMake version: Could not collect
Libc version: glibc-2.17

Python version: 3.9.17 (main, Jul  5 2023, 20:41:20)  [GCC 11.2.0] (64-bit runtime)
Python platform: Linux-4.18.0-147.mt20200626.413.el8_1.x86_64-x86_64-with-glibc2.17
Is CUDA available: True
CUDA runtime version: 11.7.99
CUDA_MODULE_LOADING set to: LAZY
GPU models and configuration:
GPU 0: NVIDIA A100-SXM4-40GB
GPU 1: NVIDIA A100-SXM4-40GB
GPU 2: NVIDIA A100-SXM4-40GB
GPU 3: NVIDIA A100-SXM4-40GB

Nvidia driver version: 470.103.01
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
CPU(s):                192
On-line CPU(s) list:   0-47
Off-line CPU(s) list:  48-191
Thread(s) per core:    0
Core(s) per socket:    48
Socket(s):             2
NUMA node(s):          2
Vendor ID:             AuthenticAMD
CPU family:            23
Model:                 49
Model name:            AMD EPYC 7642 48-Core Processor
Stepping:              0
CPU MHz:               3292.764
CPU max MHz:           2300.0000
CPU min MHz:           1500.0000
BogoMIPS:              4591.24
Virtualization:        AMD-V
L1d cache:             32K
L1i cache:             32K
L2 cache:              512K
L3 cache:              16384K
NUMA node0 CPU(s):     0-47,96-143
NUMA node1 CPU(s):     48-95,144-191
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 xtopology nonstop_tsc cpuid extd_apicid aperfmperf pni pclmulqdq monitor ssse3 fma cx16 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 hw_pstate sme ssbd mba sev ibrs ibpb stibp vmmcall fsgsbase bmi1 avx2 smep bmi2 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 avic v_vmsave_vmload vgif umip rdpid overflow_recov succor smca

Versions of relevant libraries:
[pip3] numpy==1.24.1
[pip3] pytorch-triton==2.1.0+e6216047b8
[pip3] torch==2.1.0.dev20230809+cu118
[pip3] torchaudio==2.1.0.dev20230809+cu118
[pip3] torchvision==0.16.0.dev20230809+cu118
[conda] numpy                     1.24.1                   pypi_0    pypi
[conda] pytorch-triton            2.1.0+e6216047b8          pypi_0    pypi
[conda] torch                     2.1.0.dev20230809+cu118          pypi_0    pypi
[conda] torchaudio                2.1.0.dev20230809+cu118          pypi_0    pypi
[conda] torchvision               0.16.0.dev20230809+cu118          pypi_0    pypi

cc @mrshenli @pritamdamania87 @zhaojuanmao @satgera @rohan-varma @gqchen @aazzolini @osalpekar @jiayisuse @H-Huang @kwen2501 @awgu @penguinwu