Repository: pytorch
Issue: [W CudaIPCTypes.cpp:95] Producer process tried to deallocate over 1000 memory blocks referred by consumer processes. Deallocation might be significantly slowed down. We assume it will never going to be the case, but if it is, please file but to https://github.com/pytorch/pytorch
Labels: module: multiprocessing,module: cuda,triaged

### 🐛 Describe the bug

I get the following output:
```python
[W CudaIPCTypes.cpp:95] Producer process tried to deallocate over 1000 memory blocks referred by consumer processes. Deallocation might be significantly slowed down. We assume it will never going to be the case, but if it is, please file but to https://github.com/pytorch/pytorch
```

Before I enabled multiprocessing, nothing like this happened.
If I change num_workers to 0, I can solve this problem.

```
class NormModule(torch.nn.Module):
    def __init__(self, gru_hidden_size, num_gru_layers, out_dim, dropout=0.5):
        super().__init__()

        self.gru = torch.nn.GRU(input_size=1, hidden_size=gru_hidden_size//2, num_layers=num_gru_layers, batch_first=True, bidirectional=True)
        self.dropout = torch.nn.Dropout(dropout)
        # self.fc1 = torch.nn.Linear(in_features=gru_hidden_size, out_features=fc_hidden_size)
        self.relu = torch.nn.ReLU()
        # self.fc2 = torch.nn.Linear(in_features=fc_hidden_size, out_features=out_dim)
        self.fc = torch.nn.Linear(in_features=gru_hidden_size, out_features=out_dim)

        self.init_weights()

    def init_weights(self):
        for name, param in self.named_parameters():
            if 'weight' in name:
                if 'gru' in name:
                    torch.nn.init.orthogonal_(param)
                elif 'fc' in name:
                    torch.nn.init.xavier_normal_(param)
            elif 'bias' in name:
                torch.nn.init.constant_(param, 0.0)

    def forward(self, texts, lengths):
        batch_size = len(texts)
        max_length = len(texts[0])

        texts = texts.reshape((batch_size, max_length, 1)) # -> batch_size, max_length, input_size

        out = torch.nn.utils.rnn.pack_padded_sequence(texts, lengths, batch_first=True, enforce_sorted=False)
        output, _ = self.gru(out)
        out, _ = torch.nn.utils.rnn.pad_packed_sequence(output, batch_first=True)  # -> batch_size, max_length, gru_hidden_size
        out = self.dropout(out)
        out = self.relu(out)
        out = self.fc(out)
        return out


def train(model, loader, optimizer):
    model.train()
    total, total_acc, total_loss = 0, 0, 0
    for text_seqs, labels_seqs, lengths in tqdm.tqdm(loader):
        optimizer.zero_grad()
        outputs = model(text_seqs, lengths)

        loss = 0
        for idx, labels in enumerate(labels_seqs):
            mask = torch.tensor([torch.sum(label) for label in labels], dtype=torch.bool)
            labels = labels[mask]
            if labels.size(0) == 0: # no punctuation
                continue

            output = outputs[idx]
            mask = torch.nn.functional.pad(mask, (0, len(output)-len(mask)), value=False)
            output = output[mask]
            loss_one = loss_fn(output, labels.float())

            loss += loss_one

            total += len(labels)
            total_loss += loss_one.item()

            acc = torch.sum(torch.argmax(labels, dim=1) == torch.argmax(output, dim=1)).float()
            total_acc += acc.item()
        
        if loss == 0:
            continue
        loss.backward()
        optimizer.step()
    
    return total_acc/total, total_loss/total


def collate_batch(batch):
    lengths = torch.tensor([len(item[0]) for item in batch]) # cpu
    features_seqs = torch.nn.utils.rnn.pad_sequence([torch.tensor(item[0], device=DEVICE) for item in batch], batch_first=True)
    labels_seqs = [torch.tensor(item[1], device=DEVICE) for item in batch]

    return features_seqs, labels_seqs, lengths

torch.multiprocessing.set_start_method(method='forkserver', force=True)

gru_hidden_size = 16
num_gru_layers = 2
batch_size = 2048
num_workers = min(os.cpu_count() // 2, 10)

num_epochs = 100

model = NormModule(gru_hidden_size=gru_hidden_size, num_gru_layers=num_gru_layers, out_dim=label_dim, dropout=0.2)
model = model.to(DEVICE)
log(model)

loss_fn = torch.nn.CrossEntropyLoss()
optimizer = torch.optim.AdamW(model.parameters(), lr=0.005)

train_loader = torch.utils.data.DataLoader(train_set, batch_size, shuffle=True, num_workers=num_workers, collate_fn=collate_batch)
valid_loader = torch.utils.data.DataLoader(valid_set, batch_size, shuffle=True, num_workers=num_workers, collate_fn=collate_batch)
test_loader = torch.utils.data.DataLoader(test_set, batch_size, shuffle=True, num_workers=num_workers, collate_fn=collate_batch)



```

### Versions

PyTorch version: 2.1.1+cu121
Is debug build: False
CUDA used to build PyTorch: 12.1
ROCM used to build PyTorch: N/A

OS: Debian GNU/Linux 12 (bookworm) (x86_64)
GCC version: (Debian 12.2.0-14) 12.2.0
Clang version: Could not collect
CMake version: version 3.27.6
Libc version: glibc-2.36

Python version: 3.11.2 (main, Mar 13 2023, 12:18:29) [GCC 12.2.0] (64-bit runtime)
Python platform: Linux-6.1.0-17-amd64-x86_64-with-glibc2.36
Is CUDA available: True
CUDA runtime version: 11.8.89
CUDA_MODULE_LOADING set to: LAZY
GPU models and configuration: GPU 0: NVIDIA GeForce GTX 1080 Ti
Nvidia driver version: 525.147.05
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
Address sizes:                      43 bits physical, 48 bits virtual
Byte Order:                         Little Endian
CPU(s):                             16
On-line CPU(s) list:                0-15
Vendor ID:                          AuthenticAMD
Model name:                         AMD Ryzen 7 1800X Eight-Core Processor
CPU family:                         23
Model:                              1
Thread(s) per core:                 2
Core(s) per socket:                 8
Socket(s):                          1
Stepping:                           1
Frequency boost:                    enabled
CPU(s) scaling MHz:                 74%
CPU max MHz:                        3600.0000
CPU min MHz:                        2200.0000
BogoMIPS:                           7185.66
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 nonstop_tsc cpuid extd_apicid aperfmperf rapl 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 skinit wdt tce topoext perfctr_core perfctr_nb bpext perfctr_llc mwaitx cpb hw_pstate ssbd ibpb vmmcall fsgsbase bmi1 avx2 smep bmi2 rdseed adx smap clflushopt sha_ni xsaveopt xsavec xgetbv1 clzero irperf xsaveerptr arat npt lbrv svm_lock nrip_save tsc_scale vmcb_clean flushbyasid decodeassists pausefilter pfthreshold avic v_vmsave_vmload vgif overflow_recov succor smca sev
Virtualization:                     AMD-V
L1d cache:                          256 KiB (8 instances)
L1i cache:                          512 KiB (8 instances)
L2 cache:                           4 MiB (8 instances)
L3 cache:                           16 MiB (2 instances)
NUMA node(s):                       1
NUMA node0 CPU(s):                  0-15
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:      Not affected
Vulnerability Retbleed:             Mitigation; untrained return thunk; SMT vulnerable
Vulnerability Spec rstack overflow: Mitigation; safe RET
Vulnerability Spec store bypass:    Mitigation; Speculative Store Bypass disabled via prctl
Vulnerability Spectre v1:           Mitigation; usercopy/swapgs barriers and __user pointer sanitization
Vulnerability Spectre v2:           Mitigation; Retpolines, IBPB conditional, STIBP disabled, RSB filling, PBRSB-eIBRS Not affected
Vulnerability Srbds:                Not affected
Vulnerability Tsx async abort:      Not affected

Versions of relevant libraries:
[pip3] numpy==1.26.0
[pip3] onnx==1.14.1
[pip3] paddle2onnx==1.0.8
[pip3] pytorch-crf==0.7.2
[pip3] torch==2.1.1
[pip3] torchaudio==2.1.2
[pip3] torchdata==0.7.1
[pip3] torchtext==0.16.1
[pip3] torchvision==0.16.1
[pip3] triton==2.1.0
[conda] Could not collect

cc @VitalyFedyunin @ptrblck