Repository: pytorch
Issue: When I use the DDP model, I use a custom loss function, when the batch size changes during training, the process will be stuck.
Labels: oncall: distributed,triaged

### 🐛 Describe the bug

For some reasons, I need to discard part of the data in the collate_fn of the dataloader, which makes my batch size change. My program gets stuck in the loss function when the batch size is changed. It doesn't report an error, it just keeps stuck there and never proceeds to the next step.

You can run the code below and you will get output similar to mine.

You can observe that when the batch size changes, the 0 rank will be stuck in the sentence 
`p_dist, n_dist = self.compute_triplet_dist(dist, p_mask, n_mask)`
Because 0 rank outputs loss 1 but not loss 2.


Since it doesn't report an error, I don't know what happened. I tried to use debug to trace, but I am not familiar with multi-process debugging. Every time I reach the stuck position, debug doesn't work anymore.

```python
import os
import numpy as np
import torch
import torch.nn.functional as F
from torch import nn, Tensor, optim, distributed
from torch.cuda.amp import autocast, GradScaler
from torch.nn import Conv2d, LeakyReLU, MaxPool2d
from torch.nn.parallel import DistributedDataParallel as DDP
import torch.multiprocessing as mp
from typing import Dict, Tuple


class ToyMoulde(nn.Module):
    def __init__(self) -> None:
        super().__init__()
        self.layer1 = nn.Sequential(
            Conv2d(1, 32, (5, 5), padding=2, bias=False),
            LeakyReLU(inplace=True),
            MaxPool2d(kernel_size=2, stride=2),
            Conv2d(32, 64, (3, 3), padding=1, bias=False),
            LeakyReLU(inplace=True),
            MaxPool2d(kernel_size=2, stride=2),
            Conv2d(64, 128, (3, 3), padding=1, bias=False),
            LeakyReLU(inplace=True),
            Conv2d(128, 128, (3, 3), padding=1, bias=False),
            LeakyReLU(inplace=True),
        )
        self.linear1 = nn.Linear(128, 1024)

    def forward(self, input_):
        x = self.layer1(input_)
        x = torch.max(x, dim=-1)[0]
        x = torch.max(x, dim=-1, keepdim=True)[0]
        x = x.permute(0, 2, 1).contiguous()
        x = self.linear1(x)
        x = x.permute(0, 2, 1).contiguous()
        return x


def parallel_network(network: nn.Module) -> DDP:
    distributed.barrier()
    network_ = torch.nn.SyncBatchNorm.convert_sync_batchnorm(network)
    network_ = DDP(
        network_,
        device_ids=[distributed.get_rank()],
        output_device=distributed.get_rank(),
    )
    return network_


def generateInput(batch_size):

    x = torch.rand(batch_size, 1, 64, 64)
    y = torch.rand(batch_size) * 8
    return (x, y)


def main(local_rank):
    if distributed.is_nccl_available():
        backend = "nccl"
    else:
        backend = "gloo"

    print(f"backend is {backend}")

    distributed.init_process_group(
        backend=backend,
        init_method="env://",
        world_size=torch.cuda.device_count(),
        rank=local_rank,
    )
    distributed.barrier()
    DistInfo.init()
    torch.cuda.set_device(local_rank)
    device = torch.cuda.current_device()

    network = ToyMoulde()
    network.to(device)
    network = parallel_network(network)

    scaler = GradScaler(enabled=True)
    optimizer = optim.Adam(network.parameters(), lr=1.0e-4)

    Loss = TripletLoss(0.2)

    for train_iter in range(10):
        distributed.barrier()
        print("------------------------", end="")

        if train_iter < 1:
            samples, lables = generateInput(64)
        else:
            samples, lables = generateInput(64 - local_rank * 5)

        samples = samples.to(device)
        lables = lables.to(device).long()

        with autocast(enabled=True):
            predict = network(samples)

        print(f"\n{DistInfo.local_rank} rank, {train_iter} iter\n", end="")
        distributed.barrier()

        loss = Loss(predict, lables)
        scaler.scale(loss).backward()
        scaler.step(optimizer)
        scaler.update()


if __name__ == "__main__":
    os.environ["MASTER_ADDR"] = "127.0.0.1"
    os.environ["MASTER_PORT"] = "8888"
    mp.spawn(
        main,
        nprocs=torch.cuda.device_count(),
    )


class TripletLoss(nn.Module):
    def __init__(self, margin):
        super().__init__()
        self.dist_info = DistInfo()
        self.margin = margin
        self.metric_func = euclidean

    def forward(self, feature_: Tensor, label_: Tensor) -> Tuple[Tensor, Dict]:

        feature = cat_all_gather(feature_)
        label = cat_all_gather(label_)
        feature = feature.permute(2, 0, 1).contiguous()

        dist: Tensor = self.metric_func(feature, feature)

        p_mask, n_mask = self.get_mask(label)
        print(f"{DistInfo.local_rank} rank, loss 1")

        p_dist, n_dist = self.compute_triplet_dist(dist, p_mask, n_mask)
        print(f"{DistInfo.local_rank} rank, loss 2")

        triplet_loss = F.relu(p_dist - n_dist + self.margin)
        batch_loss, loss_num = self.compute_batch_loss(triplet_loss)

        return batch_loss.mean()

    @staticmethod
    def get_mask(label: Tensor) -> Tuple[torch.BoolTensor, torch.BoolTensor]:
        row_label: Tensor = label.unsqueeze(0)
        col_label: Tensor = label.unsqueeze(1)
        p_mask: torch.BoolTensor = row_label == col_label
        n_mask: torch.BoolTensor = ~p_mask
        return p_mask, n_mask

    @staticmethod
    def compute_triplet_dist(
        dist: Tensor, p_mask: torch.BoolTensor, n_mask: torch.BoolTensor
    ):
        pmask: Tensor = p_mask.byte()
        nmask: Tensor = n_mask.byte()

        pmask = pmask.fill_diagonal_(0)

        pmask = pmask.unsqueeze(2)
        nmask = nmask.unsqueeze(1)

        triplet = pmask * nmask
        a_idx, p_idx, n_idx = torch.where(triplet)

        p_dist = dist[:, a_idx, p_idx]
        n_dist = dist[:, a_idx, n_idx]
        return p_dist, n_dist

    @staticmethod
    def compute_batch_loss(triplet_loss):
        eps = 1.0e-9
        loss_sum = triplet_loss.sum(-1)
        loss_num = (triplet_loss != 0).sum(-1).float()

        batch_loss = loss_sum / (loss_num + eps)
        batch_loss[loss_num == 0] = 0
        return batch_loss, loss_num


def cat_all_gather(input_: torch.Tensor):
    if not isinstance(input_, torch.Tensor):
        raise TypeError(f"input must is a torch.Tensor, but input is {type(input_)}")
    if DistInfo.world_size == 1:
        return input_
    gather_list = [torch.empty_like(input_) for _ in range(DistInfo.world_size)]
    distributed.all_gather(gather_list, input_)
    gather_list[DistInfo.local_rank] = input_
    output = torch.cat(gather_list, 0).contiguous()
    return output


class DistInfo:
    is_parallel = False
    local_rank = 0
    world_size = 1

    def __init__(self):
        if distributed.is_initialized():
            DistInfo.is_parallel = True
            DistInfo.local_rank = distributed.get_rank()
            DistInfo.world_size = distributed.get_world_size()

    @classmethod
    def init(cls):
        if distributed.is_initialized():
            cls.is_parallel = True
            cls.local_rank = distributed.get_rank()
            cls.world_size = distributed.get_world_size()


def euclidean(probe: torch.Tensor, gallery: torch.Tensor) -> torch.Tensor:
    x2 = torch.sum(probe**2, -1).unsqueeze(-1)
    y2 = torch.sum(gallery**2, -1).unsqueeze(-2)
    inner = probe.matmul(gallery.transpose(-1, -2))
    dist = x2 + y2 - 2 * inner
    dist = torch.sqrt(F.relu(dist))
    return dist

```

```
backend is nccl
backend is nccl
------------------------------------------------
0 rank, 0 iter

1 rank, 0 iter
1 rank, loss 1
0 rank, loss 1
1 rank, loss 2
0 rank, loss 2
------------------------------------------------
0 rank, 1 iter

1 rank, 1 iter
0 rank, loss 1
1 rank, loss 1

1 rank, loss 2
```

### Versions

```
Collecting environment information...
PyTorch version: 1.13.0+cu117
Is debug build: False
CUDA used to build PyTorch: 11.7
ROCM used to build PyTorch: N/A

OS: Ubuntu 22.04.2 LTS (x86_64)
GCC version: (Ubuntu 11.3.0-1ubuntu1~22.04) 11.3.0
Clang version: Could not collect
CMake version: Could not collect
Libc version: glibc-2.35

Python version: 3.10.8 (main, Nov  4 2022, 13:48:29) [GCC 11.2.0] (64-bit runtime)
Python platform: Linux-5.15.0-67-generic-x86_64-with-glibc2.35
Is CUDA available: True
CUDA runtime version: Could not collect
CUDA_MODULE_LOADING set to: LAZY
GPU models and configuration:
GPU 0: NVIDIA GeForce RTX 3090
GPU 1: NVIDIA GeForce RTX 3090

Nvidia driver version: 525.89.02
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:                   46 bits physical, 48 bits virtual
Byte Order:                      Little Endian
CPU(s):                          20
On-line CPU(s) list:             0-19
Vendor ID:                       GenuineIntel
Model name:                      Intel(R) Xeon(R) Silver 4210R CPU @ 2.40GHz
CPU family:                      6
Model:                           85
Thread(s) per core:              1
Core(s) per socket:              10
Socket(s):                       2
Stepping:                        7
CPU max MHz:                     3200.0000
CPU min MHz:                     1000.0000
BogoMIPS:                        4800.00
Flags:                           fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush dts acpi mmx fxsr sse sse2 ss ht tm pbe syscall nx pdpe1gb rdtscp lm constant_tsc art arch_perfmon pebs bts rep_good nopl xtopology nonstop_tsc cpuid aperfmperf pni pclmulqdq dtes64 monitor ds_cpl vmx smx est tm2 ssse3 sdbg fma cx16 xtpr pdcm pcid dca sse4_1 sse4_2 x2apic movbe popcnt tsc_deadline_timer aes xsave avx f16c rdrand lahf_lm abm 3dnowprefetch cpuid_fault epb cat_l3 cdp_l3 invpcid_single intel_ppin ssbd mba ibrs ibpb stibp ibrs_enhanced tpr_shadow vnmi flexpriority ept vpid ept_ad fsgsbase tsc_adjust bmi1 avx2 smep bmi2 erms invpcid cqm mpx rdt_a avx512f avx512dq rdseed adx smap clflushopt clwb intel_pt avx512cd avx512bw avx512vl xsaveopt xsavec xgetbv1 xsaves cqm_llc cqm_occup_llc cqm_mbm_total cqm_mbm_local dtherm ida arat pln pts hwp hwp_act_window hwp_epp hwp_pkg_req pku ospke avx512_vnni md_clear flush_l1d arch_capabilities
Virtualization:                  VT-x
L1d cache:                       640 KiB (20 instances)
L1i cache:                       640 KiB (20 instances)
L2 cache:                        20 MiB (20 instances)
L3 cache:                        27.5 MiB (2 instances)
NUMA node(s):                    2
NUMA node0 CPU(s):               0-9
NUMA node1 CPU(s):               10-19
Vulnerability Itlb multihit:     KVM: Mitigation: VMX disabled
Vulnerability L1tf:              Not affected
Vulnerability Mds:               Not affected
Vulnerability Meltdown:          Not affected
Vulnerability Mmio stale data:   Mitigation; Clear CPU buffers; SMT disabled
Vulnerability Retbleed:          Mitigation; Enhanced IBRS
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] mypy-extensions==0.4.3
[pip3] numpy==1.23.4
[pip3] torch==1.13.0+cu117
[pip3] torchaudio==0.13.0+cu117
[pip3] torchvision==0.14.0+cu117
[conda] numpy                     1.23.4                   pypi_0    pypi
[conda] torch                     1.13.0+cu117             pypi_0    pypi
[conda] torchaudio                0.13.0+cu117             pypi_0    pypi
[conda] torchvision               0.14.0+cu117             pypi_0    pypi
```

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