pytorch / pytorch/pytorch

Eval-mode `BatchNorm`/`GroupNorm` produces wrong output under `torch.compile(backend='inductor')`

Open
#181,696 5 comments 0 reactions 0 assignees View on GitHub
bot-triaged high priority module: aotdispatch module: correctness (silent) module: decompositions module: norms and normalization module: pt2-dispatcher oncall: pt2 repro:agent:h100:repro_success:reproduced triaged
Dominant language
Python
Stars
103k
Forks
29.6k
PR merge metrics
PR metrics pending

Description

### 🐛 Describe the bug

When a model contains `nn.BatchNorm1d`/`BatchNorm2d` or `nn.GroupNorm` in **eval mode** (`.eval()`), `torch.compile(backend='inductor')` produces output that is numerically wrong compared to eager execution, with `max_diff >= 1.0`.

In eval mode, `BatchNorm` normalises using frozen `running_mean` and `running_var` statistics rather than the current batch statistics. Inductor performs **constant folding** on eval-mode normalisation layers, pre-computing the effective scale and bias from these frozen statistics. When this fold is incorrect — for example when it uses the wrong statistics, applies the fold in the wrong order, or interacts incorrectly with a subsequent `GroupNorm` — the compiled output diverges significantly from eager.

## Minimal Reproducer

```python
import torch
import torch.nn as nn

bn = nn.BatchNorm1d(10).eval() # running_mean=0, running_var=1 (default init)
elu = nn.ELU()
gn = nn.GroupNorm(10, 10).eval()

def model():
x = torch.ones([6, 10, 12])
t = bn(x) # eval: normalise with running_mean/var, apply weight/bias
t = elu(t)
t = gn(t) # ← mismatch appears after this second norm layer
t = torch.log(torch.clamp(t, min=1e-6))
return t

eager_out = model()
compiled_out = torch.compile(model, backend='inductor')()

print("max diff:", (eager_out - compiled_out).abs().max().item())
# Expected: ~0.0
# Actual: 1.288699
```

**Variant with `F.scaled_dot_product_attention`**:

```python
import torch
import torch.nn as nn
import torch.nn.functional as F

conv = nn.Conv2d(10, 3, 3)
ln = nn.LayerNorm([7])

def model():
x = torch.ones([11, 10, 3, 9])
t = F.scaled_dot_product_attention(x, x, x)
t = conv(t)
t = ln(t)
t = torch.log(torch.clamp(t, min=1e-6))
return t

eager_out = model()
compiled_out = torch.compile(model, backend='inductor')()

assert torch.allclose(eager_out, compiled_out, atol=1e-4), \
f"max_diff={(eager_out - compiled_out).abs().max().item():.6f}"
```

### Error logs

```
Traceback (most recent call last):
File "program.py", line 34, in
assert torch.allclose(_eager_out, _compiled_out, atol=1e-4, rtol=1e-4), (
AssertionError: eager/compiled mismatch: max_diff=1.288699
```

Other observed `max_diff` values across the 15 programs:

```
max_diff=1.288699
max_diff=1.821913
max_diff=1.070833
max_diff=1.000000 (multiple cases)
```

### Versions

Collecting environment information...
PyTorch version: 2.11.0+cu130
Is debug build: False
CUDA used to build PyTorch: 13.0
ROCM used to build PyTorch: N/A

OS: Ubuntu 22.04.5 LTS (x86_64)
GCC version: (Ubuntu 11.4.0-1ubuntu1~22.04.3) 11.4.0
Clang version: 15.0.0 ([git@github.com](mailto:git@github.com):llvm/llvm-project.git 4ba6a9c9f65bbc8bd06e3652cb20fd4dfc846137)
CMake version: version 3.22.1
Libc version: glibc-2.35

Python version: 3.10.12 (main, Mar 3 2026, 11:56:32) [GCC 11.4.0] (64-bit runtime)
Python platform: Linux-6.8.0-94-generic-x86_64-with-glibc2.35
Is CUDA available: False
CUDA runtime version: No CUDA
CUDA_MODULE_LOADING set to: N/A
GPU models and configuration: No CUDA
Nvidia driver version: No CUDA
cuDNN version: No CUDA
Is XPU available: False
HIP runtime version: N/A
MIOpen runtime version: N/A
Is XNNPACK available: True
Caching allocator config: N/A

CPU:
Architecture: x86_64
CPU op-mode(s): 32-bit, 64-bit
Address sizes: 52 bits physical, 57 bits virtual
Byte Order: Little Endian
CPU(s): 384
On-line CPU(s) list: 0-383
Vendor ID: AuthenticAMD
Model name: AMD EPYC 9684X 96-Core Processor
CPU family: 25
Model: 17
Thread(s) per core: 2
Core(s) per socket: 96
Socket(s): 2
Stepping: 2
BogoMIPS: 5099.98
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 amd_lbr_v2 nopl nonstop_tsc cpuid extd_apicid aperfmperf rapl pni pclmulqdq monitor ssse3 fma cx16 pcid sse4_1 sse4_2 x2apic 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 ssbd mba perfmon_v2 ibrs ibpb stibp ibrs_enhanced vmmcall fsgsbase bmi1 avx2 smep bmi2 erms invpcid cqm rdt_a avx512f avx512dq rdseed adx smap avx512ifma clflushopt clwb avx512cd sha_ni avx512bw avx512vl xsaveopt xsavec xgetbv1 xsaves cqm_llc cqm_occup_llc cqm_mbm_total cqm_mbm_local user_shstk avx512_bf16 clzero irperf xsaveerptr rdpru wbnoinvd amd_ppin cppc amd_ibpb_ret arat npt lbrv svm_lock nrip_save tsc_scale vmcb_clean flushbyasid decodeassists pausefilter pfthreshold avic v_vmsave_vmload vgif x2avic v_spec_ctrl vnmi avx512vbmi umip pku ospke avx512_vbmi2 gfni vaes vpclmulqdq avx512_vnni avx512_bitalg avx512_vpopcntdq la57 rdpid overflow_recov succor smca fsrm flush_l1d debug_swap ibpb_exit_to_user
Virtualization: AMD-V
L1d cache: 6 MiB (192 instances)
L1i cache: 6 MiB (192 instances)
L2 cache: 192 MiB (192 instances)
L3 cache: 2.3 GiB (24 instances)
NUMA node(s): 2
NUMA node0 CPU(s): 0-95,192-287
NUMA node1 CPU(s): 96-191,288-383
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 Reg file data sampling: Not affected
Vulnerability Retbleed: Not affected
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; Enhanced / Automatic IBRS; IBPB conditional; STIBP always-on; RSB filling; PBRSB-eIBRS Not affected; BHI Not affected
Vulnerability Srbds: Not affected
Vulnerability Tsx async abort: Not affected
Vulnerability Vmscape: Mitigation; IBPB before exit to userspace

Versions of relevant libraries:
[pip3] numpy==2.2.6
[pip3] nvidia-cublas==13.1.0.3
[pip3] nvidia-cuda-cupti==13.0.85
[pip3] nvidia-cuda-nvrtc==13.0.88
[pip3] nvidia-cuda-runtime==13.0.96
[pip3] nvidia-cudnn-cu13==9.19.0.56
[pip3] nvidia-cufft==12.0.0.61
[pip3] nvidia-curand==10.4.0.35
[pip3] nvidia-cusolver==12.0.4.66
[pip3] nvidia-cusparse==12.6.3.3
[pip3] nvidia-cusparselt-cu13==0.8.0
[pip3] nvidia-nccl-cu13==2.28.9
[pip3] nvidia-nvjitlink==13.0.88
[pip3] nvidia-nvtx==13.0.85
[pip3] torch==2.11.0
[pip3] triton==3.6.0
[conda] Could not collect

cc @ezyang @gchanan @kadeng @msaroufim @chauhang @penguinwu @voznesenskym @EikanWang @jgong5 @Guobing-Chen @XiaobingSuper @zhuhaozhe @blzheng @wenzhe-nrv @jiayisunx @ipiszy @muchulee8 @amjames @aakhundov @coconutruben @jataylo @bdhirsh @bobrenjc93 @aorenste

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.