Repository: pytorch
Issue: Major perf regression with `BatchNorm2d` + `torch.compile` with `reduce-overhead` + DDP
Labels: high priority,oncall: distributed,triaged,module: ddp,module: cuda graphs,oncall: pt2,pt2d-triage-nov2024

### 🐛 Describe the bug

Since PyTorch 2.5.0, there is a massive (more than 10x) performance regression when using `BatchNorm2d` with `torch.compile` set to `reduce-overhead` and `DistributedDataParallel`. The following warning is also printed multiple times: `skipping cudagraphs due to mutated inputs (27 instances)`. Sometimes, seemingly randomly there's a crash too at the very end.

Performance is good with PyTorch 2.4.1, without any cudagraph warnings or crashes. Replacing `BatchNorm2d` with `GroupNorm` fixes the issue and results in good performance with PyTorch 2.5.1 as well. Without `DistributedDataParallel` there are no issues with `BatchNorm2d` with any tested version of PyTorch. So it seems the issue happens only if `BatchNorm2d` and `DistributedDataParallel` are used together.

Here's a small reproducer (U-Net):

```python
import torch
import torch.distributed as dist
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from tqdm import tqdm

from torch.nn.parallel import DistributedDataParallel as DDP

SHAPE = [16, 3, 256, 256]
TRAIN_STEPS = 100

class ConvBlock(nn.Module):
  def __init__(self, in_channels, out_channels, kernel_size=3, padding='same'):
    super().__init__()
    self.conv = nn.Conv2d(in_channels, out_channels, kernel_size, padding=padding, bias=False)
    #self.norm = nn.GroupNorm(1, out_channels) # no issues
    self.norm = nn.BatchNorm2d(out_channels)   # skipping cudagraphs due to mutated inputs

  def forward(self, x):
    return self.norm(self.conv(x)) # relu removed for simplicity

def pool(x):
  return F.max_pool2d(x, 2, 2)

def upsample(x):
  return F.interpolate(x, scale_factor=2, mode='nearest')

def concat(a, b):
  return torch.cat((a, b), 1)

class UNet(nn.Module):
  def __init__(self, ic=3, oc=3):
    super(UNet, self).__init__()

    ec1, ec2, ec3, ec4, ec5, dc4, dc3, dc2, dc1a, dc1b = 32, 48, 64, 80, 96, 112, 96, 64, 64, 32

    self.enc_conv0  = ConvBlock(ic,      ec1)
    self.enc_conv1  = ConvBlock(ec1,     ec1)
    self.enc_conv2  = ConvBlock(ec1,     ec2)
    self.enc_conv3  = ConvBlock(ec2,     ec3)
    self.enc_conv4  = ConvBlock(ec3,     ec4)
    self.enc_conv5a = ConvBlock(ec4,     ec5)
    self.enc_conv5b = ConvBlock(ec5,     ec5)
    self.dec_conv4a = ConvBlock(ec5+ec3, dc4)
    self.dec_conv4b = ConvBlock(dc4,     dc4)
    self.dec_conv3a = ConvBlock(dc4+ec2, dc3)
    self.dec_conv3b = ConvBlock(dc3,     dc3)
    self.dec_conv2a = ConvBlock(dc3+ec1, dc2)
    self.dec_conv2b = ConvBlock(dc2,     dc2)
    self.dec_conv1a = ConvBlock(dc2+ic,  dc1a)
    self.dec_conv1b = ConvBlock(dc1a,    dc1b)
    self.dec_conv0  = ConvBlock(dc1b,    oc)

  def forward(self, input):
    x = self.enc_conv0(input)
    x = self.enc_conv1(x)
    x = pool1 = pool(x)
    x = self.enc_conv2(x)
    x = pool2 = pool(x)
    x = self.enc_conv3(x)
    x = pool3 = pool(x)
    x = self.enc_conv4(x)
    x = pool(x)
    x = self.enc_conv5a(x)
    x = self.enc_conv5b(x)
    x = upsample(x)
    x = concat(x, pool3)
    x = self.dec_conv4a(x)
    x = self.dec_conv4b(x)
    x = upsample(x)
    x = concat(x, pool2)
    x = self.dec_conv3a(x)
    x = self.dec_conv3b(x)
    x = upsample(x)
    x = concat(x, pool1)
    x = self.dec_conv2a(x)
    x = self.dec_conv2b(x)
    x = upsample(x)
    x = concat(x, input)
    x = self.dec_conv1a(x)
    x = self.dec_conv1b(x)
    x = self.dec_conv0(x)
    return x

def demo_basic():
  dist.init_process_group("nccl")
  rank = dist.get_rank()
  print(f"Start on rank {rank}.")

  device_id = rank % torch.cuda.device_count()
  model = UNet().to(device_id)
  model = torch.compile(model, mode='reduce-overhead')
  ddp_model = DDP(model, device_ids=[device_id])

  loss_fn = nn.MSELoss()
  loss_fn = torch.compile(loss_fn, mode='reduce-overhead')
  optimizer = optim.Adam(ddp_model.parameters(), lr=0.001)

  for i in tqdm(range(TRAIN_STEPS), disable=(rank != 0)):
    torch.compiler.cudagraph_mark_step_begin()

    input  = torch.randn(SHAPE, dtype=torch.float32, device=device_id)
    target = torch.randn(SHAPE, dtype=torch.float32, device=device_id)

    optimizer.zero_grad()
    output = ddp_model(input)
    loss_fn(output, target).backward()
    optimizer.step()

  dist.destroy_process_group()

if __name__ == "__main__":
  demo_basic()
```

Example invocation: `torchrun --nnodes=1 --nproc_per_node=7 --rdzv_id=100 --rdzv_backend=c10d --rdzv_endpoint=localhost:29400 bn_cudagraph_ddp.py`

Output (there isn't always a crash at the end, otherwise the output is the same):

```
torchrun --nnodes=1 --nproc_per_node=7 --rdzv_id=100 --rdzv_backend=c10d --rdzv_endpoint=localhost:29400 bn_cudagraph_ddp.py 
W1030 11:53:19.354000 287697 torch/distributed/run.py:793] 
W1030 11:53:19.354000 287697 torch/distributed/run.py:793] *****************************************
W1030 11:53:19.354000 287697 torch/distributed/run.py:793] Setting OMP_NUM_THREADS environment variable for each process to be 1 in default, to avoid your system being overloaded, please further tune the variable for optimal performance in your application as needed. 
W1030 11:53:19.354000 287697 torch/distributed/run.py:793] *****************************************
Start on rank 4.
Start on rank 0.
Start on rank 3.
Start on rank 1.
Start on rank 5.
Start on rank 2.
Start on rank 6.
  0%|                                                                                                                                                                                                                     | 0/100 [00:00<?, ?it/s]skipping cudagraphs due to mutated inputs (27 instances)
skipping cudagraphs due to mutated inputs (21 instances)
skipping cudagraphs due to mutated inputs (27 instances)
skipping cudagraphs due to mutated inputs (21 instances)
skipping cudagraphs due to mutated inputs (27 instances)
skipping cudagraphs due to mutated inputs (21 instances)
skipping cudagraphs due to mutated inputs (27 instances)
skipping cudagraphs due to mutated inputs (21 instances)
skipping cudagraphs due to mutated inputs (27 instances)
skipping cudagraphs due to mutated inputs (27 instances)
skipping cudagraphs due to mutated inputs (21 instances)
skipping cudagraphs due to mutated inputs (27 instances)
skipping cudagraphs due to mutated inputs (21 instances)
skipping cudagraphs due to mutated inputs (21 instances)
100%|███████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████| 100/100 [00:44<00:00,  2.26it/s]
[E1030 11:54:10.724317899 ProcessGroupNCCL.cpp:542] [Rank 1] Collective WorkNCCL(SeqNum=405, OpType=ALLREDUCE, NumelIn=608352, NumelOut=608352, Timeout(ms)=600000) raised the following async exception: NCCL error: unhandled system error (run with NCCL_DEBUG=INFO for details), NCCL version 2.21.5
ncclSystemError: System call (e.g. socket, malloc) or external library call failed or device error. 
Last error:

Exception raised from checkForNCCLErrorsInternal at ../torch/csrc/distributed/c10d/ProcessGroupNCCL.cpp:2027 (most recent call first):
frame #0: c10::Error::Error(c10::SourceLocation, std::string) + 0x96 (0x7f0f5f4b9446 in /home/aafra/.venv/lib/python3.10/site-packages/torch/lib/libc10.so)
frame #1: c10d::ProcessGroupNCCL::checkForNCCLErrorsInternal(std::shared_ptr<c10d::NCCLComm>&) + 0x220 (0x7f0f15429f80 in /home/aafra/.venv/lib/python3.10/site-packages/torch/lib/libtorch_cuda.so)
frame #2: c10d::ProcessGroupNCCL::WorkNCCL::checkAndSetException() + 0x7c (0x7f0f1542a1cc in /home/aafra/.venv/lib/python3.10/site-packages/torch/lib/libtorch_cuda.so)
frame #3: c10d::ProcessGroupNCCL::WorkNCCL::isCompleted() + 0x90 (0x7f0f1542a3e0 in /home/aafra/.venv/lib/python3.10/site-packages/torch/lib/libtorch_cuda.so)
frame #4: c10d::ProcessGroupNCCL::watchdogHandler() + 0x1da (0x7f0f15431b5a in /home/aafra/.venv/lib/python3.10/site-packages/torch/lib/libtorch_cuda.so)
frame #5: c10d::ProcessGroupNCCL::ncclCommWatchdog() + 0x14d (0x7f0f1543361d in /home/aafra/.venv/lib/python3.10/site-packages/torch/lib/libtorch_cuda.so)
frame #6: <unknown function> + 0x145c0 (0x7f0f5f91e5c0 in /home/aafra/.venv/lib/python3.10/site-packages/torch/lib/libtorch.so)
frame #7: <unknown function> + 0x94ac3 (0x7f0f60401ac3 in /lib/x86_64-linux-gnu/libc.so.6)
frame #8: <unknown function> + 0x126850 (0x7f0f60493850 in /lib/x86_64-linux-gnu/libc.so.6)
```

The issue can be reproduced with PyTorch 2.5.0 and 2.5.1 as well.

### Versions

PyTorch version: 2.5.1+cu124
Is debug build: False
CUDA used to build PyTorch: 12.4
ROCM used to build PyTorch: N/A

OS: Ubuntu 22.04.5 LTS (x86_64)
GCC version: (Ubuntu 11.4.0-1ubuntu1~22.04) 11.4.0
Clang version: Could not collect
CMake version: Could not collect
Libc version: glibc-2.35

Python version: 3.10.12 (main, Sep 11 2024, 15:47:36) [GCC 11.4.0] (64-bit runtime)
Python platform: Linux-5.15.0-124-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 RTX 6000 Ada Generation
GPU 1: NVIDIA RTX 6000 Ada Generation
GPU 2: NVIDIA RTX 6000 Ada Generation
GPU 3: NVIDIA RTX 6000 Ada Generation
GPU 4: NVIDIA RTX 6000 Ada Generation
GPU 5: NVIDIA RTX 6000 Ada Generation
GPU 6: NVIDIA RTX 6000 Ada Generation

Nvidia driver version: 550.120
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, 57 bits virtual
Byte Order:                           Little Endian
CPU(s):                               160
On-line CPU(s) list:                  0-159
Vendor ID:                            GenuineIntel
Model name:                           Intel(R) Xeon(R) Platinum 8380 CPU @ 2.30GHz
CPU family:                           6
Model:                                106
Thread(s) per core:                   2
Core(s) per socket:                   40
Socket(s):                            2
Stepping:                             6
CPU max MHz:                          3400.0000
CPU min MHz:                          800.0000
BogoMIPS:                             4600.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 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 rdt_a avx512f avx512dq rdseed adx smap avx512ifma clflushopt clwb intel_pt avx512cd sha_ni avx512bw avx512vl xsaveopt xsavec xgetbv1 xsaves cqm_llc cqm_occup_llc cqm_mbm_total cqm_mbm_local split_lock_detect wbnoinvd dtherm ida arat pln pts hwp hwp_act_window hwp_epp hwp_pkg_req avx512vbmi umip pku ospke avx512_vbmi2 gfni vaes vpclmulqdq avx512_vnni avx512_bitalg tme avx512_vpopcntdq la57 rdpid fsrm md_clear pconfig flush_l1d arch_capabilities
Virtualization:                       VT-x
L1d cache:                            3.8 MiB (80 instances)
L1i cache:                            2.5 MiB (80 instances)
L2 cache:                             100 MiB (80 instances)
L3 cache:                             120 MiB (2 instances)
NUMA node(s):                         4
NUMA node0 CPU(s):                    0-19,80-99
NUMA node1 CPU(s):                    20-39,100-119
NUMA node2 CPU(s):                    40-59,120-139
NUMA node3 CPU(s):                    60-79,140-159
Vulnerability Gather data sampling:   Mitigation; Microcode
Vulnerability Itlb multihit:          Not affected
Vulnerability L1tf:                   Not affected
Vulnerability Mds:                    Not affected
Vulnerability Meltdown:               Not affected
Vulnerability Mmio stale data:        Mitigation; Clear CPU buffers; SMT vulnerable
Vulnerability Reg file data sampling: Not affected
Vulnerability Retbleed:               Not affected
Vulnerability Spec rstack overflow:   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; Enhanced / Automatic IBRS; IBPB conditional; RSB filling; PBRSB-eIBRS SW sequence; BHI SW loop, KVM SW loop
Vulnerability Srbds:                  Not affected
Vulnerability Tsx async abort:        Not affected

Versions of relevant libraries:
[pip3] numpy==1.26.3
[pip3] nvidia-cublas-cu12==12.4.5.8
[pip3] nvidia-cuda-cupti-cu12==12.4.127
[pip3] nvidia-cuda-nvrtc-cu12==12.4.127
[pip3] nvidia-cuda-runtime-cu12==12.4.127
[pip3] nvidia-cudnn-cu12==9.1.0.70
[pip3] nvidia-cufft-cu12==11.2.1.3
[pip3] nvidia-curand-cu12==10.3.5.147
[pip3] nvidia-cusolver-cu12==11.6.1.9
[pip3] nvidia-cusparse-cu12==12.3.1.170
[pip3] nvidia-nccl-cu12==2.21.5
[pip3] nvidia-nvjitlink-cu12==12.4.127
[pip3] nvidia-nvtx-cu12==12.4.127
[pip3] torch==2.5.1+cu124
[pip3] torchvision==0.20.1+cu124
[pip3] triton==3.1.0
[conda] Could not collect


cc @ezyang @gchanan @zou3519 @kadeng @msaroufim @H-Huang @awgu @kwen2501 @wanchaol @fegin @fduwjj @wz337 @wconstab @d4l3k @c-p-i-o @mcarilli @eellison @penguinwu @chauhang