Repository: pytorch
Issue: distributed training: lots of "Exception ignored" at the end of each epoch
Labels: oncall: distributed

### 🐛 Describe the bug

Using PyTorch 1.12.1. Trying distributed training for the first time, using the LambdaLabs AI cloud service. It seems to work well, except at the end of many (but not all) epochs, I get 56 of these complaints (batch size of 32):

```
Exception ignored in: <Finalize object, dead>
Traceback (most recent call last):
  File "/usr/lib/python3.8/multiprocessing/util.py", line 224, in __call__
    res = self._callback(*self._args, **self._kwargs)
  File "/usr/lib/python3.8/multiprocessing/synchronize.py", line 87, in _cleanup
    sem_unlink(name)
FileNotFoundError: [Errno 2] No such file or directory
```

I've tried all sorts of things to get rid of that. E.g. I tried with and without "drop_last", I've even tweaked the Dataset so that nothing needs to be dropped. I've also switched to only 1 server with only 1 GPU, but still using DDP. The same issue still occurs. Not sure what else to try.

Maybe I can ignore these complaints? But they scare me, maybe it's a sign of something going wrong?

Here's the rough skeleton of my code:

```
import [...]

def train(rank, num_gpus):
    # init various stuff
    torch.cuda.set_device(rank)
    torch.distributed.init_process_group(backend='nccl', rank=rank, world_size=num_gpus, init_method='env://')
    model = Model(rank)
    scaler = amp.GradScaler()
    if rank == 0:
        writer = SummaryWriter('train')

    # init dataset, distributed sampler and dataloader
    dataset = SomeDataset()
    sampler = torch.utils.data.distributed.DistributedSampler(dataset)
    train_data = DataLoader(dataset, batch_size=batch_size, num_workers=16, pin_memory=True, drop_last=True, shuffle=False, sampler=sampler)

    # epoch train loop
    torch.distributed.barrier()
    step = 0
    for epoch in range(epochs):

        # inform sampler about epoch
        torch.distributed.barrier()  # removing this doesn't help
        sampler.set_epoch(epoch)     # the complaints occur right before barrier+set_epoch is called
        torch.distributed.barrier()  # removing this doesn't help

        # dataset iterations
        for i, data in enumerate(train_data):
            # just to be safe
            self.train()

            # update learning rate
            learning_rate = calculateLearningRate(step)
            for param_group in self.optimG.param_groups:
                param_group['lr'] = learning_rate

            # move data to the GPU
            data_gpu = data.cuda(rank, non_blocking=True)

            # actual training
            self.optimG.zero_grad()
            with torch.autocast(device_type='cuda', dtype=torch.float16):
              image = model(data_gpu)
              loss = (image - gt).abs().mean()
            scaler.scale(loss).backward()
            scaler.step(self.optimG)
            scaler.update()

            # every 1000 iterations, do some logging and testing
            if step % 1000 == 0:
               torch.distributed.barrier()  # just to be safe, maybe not needed
               if rank == 0:
                   torch.save(model.state_dict(),'dict.pth')
                   writer.add_scalar('train/l1', info['loss_l1'], step)
                   writer.flush()
                   self.eval()
                   image = model(testData_gpu)
                   saveImage(image)

            if rank == 0:
              step += 1

if __name__ == "__main__":    
    os.environ['MASTER_ADDR'] = 'localhost'
    os.environ['MASTER_PORT'] = '12355'
    torch.backends.cudnn.benchmark = True
    num_gpus = torch.cuda.device_count()
    torch.multiprocessing.spawn(train, args=(num_gpus, ), nprocs=num_gpus, join=True)
```

To me, this looks like a bug in PyTorch, or am I missing something in my code?

### Versions

PyTorch version: 1.12.1
Is debug build: False
CUDA used to build PyTorch: 11.6
ROCM used to build PyTorch: N/A

OS: Ubuntu 20.04.5 LTS (x86_64)
GCC version: (Ubuntu 9.4.0-1ubuntu1~20.04.1) 9.4.0
Clang version: Could not collect
CMake version: version 3.16.3
Libc version: glibc-2.31

Python version: 3.8.10 (default, Jun 22 2022, 20:18:18)  [GCC 9.4.0] (64-bit runtime)
Python platform: Linux-5.15.0-52-generic-x86_64-with-glibc2.29
Is CUDA available: True
CUDA runtime version: 11.6.124
CUDA_MODULE_LOADING set to: 
GPU models and configuration: GPU 0: NVIDIA A100-SXM4-40GB
Nvidia driver version: 515.65.01
cuDNN version: Could not collect
HIP runtime version: N/A
MIOpen runtime version: N/A
Is XNNPACK available: False

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):                          30
On-line CPU(s) list:             0-29
Thread(s) per core:              1
Core(s) per socket:              1
Socket(s):                       30
NUMA node(s):                    1
Vendor ID:                       AuthenticAMD
CPU family:                      25
Model:                           1
Model name:                      AMD EPYC 7J13 64-Core Processor
Stepping:                        1
CPU MHz:                         2449.998
BogoMIPS:                        4899.99
Virtualization:                  AMD-V
Hypervisor vendor:               KVM
Virtualization type:             full
L1d cache:                       1.9 MiB
L1i cache:                       1.9 MiB
L2 cache:                        15 MiB
L3 cache:                        480 MiB
NUMA node0 CPU(s):               0-29
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 disabled, 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 syscall nx mmxext fxsr_opt pdpe1gb rdtscp lm rep_good nopl cpuid extd_apicid tsc_known_freq pni pclmulqdq ssse3 fma cx16 pcid sse4_1 sse4_2 x2apic movbe popcnt tsc_deadline_timer aes xsave avx f16c rdrand hypervisor lahf_lm cmp_legacy svm cr8_legacy abm sse4a misalignsse 3dnowprefetch osvw perfctr_core invpcid_single ssbd ibrs ibpb stibp vmmcall fsgsbase tsc_adjust bmi1 avx2 smep bmi2 erms invpcid rdseed adx smap clflushopt clwb sha_ni xsaveopt xsavec xgetbv1 xsaves clzero xsaveerptr wbnoinvd arat npt nrip_save umip pku ospke vaes vpclmulqdq rdpid fsrm arch_capabilities

Versions of relevant libraries:
[pip3] numpy==1.23.4
[pip3] torch==1.12.1
[pip3] torchvision==0.13.1
[conda] Could not collect

cc @mrshenli @pritamdamania87 @zhaojuanmao @satgera @rohan-varma @gqchen @aazzolini @osalpekar @jiayisuse @H-Huang @kwen2501 @awgu