pytorch - 💡(How to fix) Fix torch.compile(dynamic=True) on CUDA: large eager vs compiled mismatch for BatchNorm2d + Conv2d [2 comments, 3 participants]

Official PRs (…)
ON THIS PAGE

Recommended Tools

×6

Utilities matched from this issue’s tags and category — try them while you read without losing context.

GitHub issue graph ai analysis

Paste a GitHub issue URL. We fetch that issue, discover linked issues from bodies/comments/timeline, collect linked pull requests, and produce a structured English report.

The report is written in English Markdown for sharing and archival.

Helpful · Quick feedback

Loading…
GitHub stats
pytorch/pytorch#178096Fetched 2026-04-08 01:16:39
View on GitHub
Comments
2
Participants
3
Timeline
120
Reactions
0
Author
Timeline (top)
subscribed ×52mentioned ×51labeled ×8referenced ×3

Error Message

import random

import torch import torch.nn as nn

THRESHOLD = 1.19e-7 DEVICE = torch.device("cuda") SEED = 0 INPUT_SHAPE = (4, 96, 8, 8)

def set_seed(seed: int) -> None: random.seed(seed) torch.manual_seed(seed) torch.backends.cudnn.deterministic = True torch.backends.cudnn.benchmark = False

class Bn1Conv2(nn.Module): def init(self, sd: dict): super().init() self.bn1 = nn.BatchNorm2d(96) self.conv2 = nn.Conv2d(96, 256, kernel_size=5, padding=2, bias=True) self.load_state_dict(sd, strict=True)

def forward(self, x: torch.Tensor) -> torch.Tensor:
    x = self.bn1(x)
    return self.conv2(x)

def random_state_dict() -> dict: bn1 = nn.BatchNorm2d(96) conv2 = nn.Conv2d(96, 256, kernel_size=5, padding=2, bias=True) with torch.no_grad(): bn1.weight.normal(0, 1) bn1.bias.normal_(0, 1) bn1.running_mean.normal_(0, 0.1) bn1.running_var.uniform_(0.5, 1.5) conv2.weight.normal_(0, 0.02) conv2.bias.normal_(0, 0.02) sd = {} for k, v in bn1.state_dict().items(): sd[f"bn1.{k}"] = v.float().cpu().clone() for k, v in conv2.state_dict().items(): sd[f"conv2.{k}"] = v.float().cpu().clone() return sd

def main(): set_seed(SEED) x = torch.randn(INPUT_SHAPE, dtype=torch.float32, device="cpu") print(f"input min={x.min().item():.6g} max={x.max().item():.6g}") x = x.to(DEVICE) sd = _random_state_dict() wmin = float("inf") wmax = float("-inf") for v in sd.values(): if torch.is_tensor(v): t = v.float().cpu() wmin = min(wmin, float(t.min().item())) wmax = max(wmax, float(t.max().item())) print(f"weights min={wmin:.6g} max={wmax:.6g}")

m0 = Bn1Conv2(sd).to(DEVICE).eval()
with torch.no_grad():
    y0 = m0(x)

m1 = torch.compile(Bn1Conv2(sd).to(DEVICE).eval(), dynamic=True)
with torch.no_grad():
    y1 = m1(x)

o = y0.detach().float().cpu().reshape(y0.shape[0], -1)
s = y1.detach().float().cpu().reshape(y1.shape[0], -1)
eps = 1e-12
valid = torch.isfinite(o) & torch.isfinite(s)
diff = torch.where(valid, (s - o).abs() / (o.abs() + eps), torch.zeros_like(o))
per = diff.max(dim=1).values
gmax = float(per.max().item())

print("modes: eager  vs  torch.compile(dynamic=True)")
print(
    f"relative error: max_rel={gmax:.6e}  "
    f"threshold={THRESHOLD:.2e}"
)

if name == "main": main()

Fix Action

Fix / Workaround

CPU: Architecture: x86_64 CPU op-mode(s): 32-bit, 64-bit Address sizes: 40 bits physical, 48 bits virtual Byte Order: Little Endian CPU(s): 48 On-line CPU(s) list: 0-47 Vendor ID: GenuineIntel Model name: QEMU Virtual CPU version 2.5+ CPU family: 15 Model: 107 Thread(s) per core: 1 Core(s) per socket: 48 Socket(s): 1 Stepping: 1 BogoMIPS: 4190.15 Flags: fpu de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush mmx fxsr sse sse2 ht syscall nx lm constant_tsc nopl xtopology cpuid tsc_known_freq pni ssse3 fma cx16 sse4_1 sse4_2 x2apic movbe popcnt aes xsave avx f16c hypervisor lahf_lm abm cpuid_fault pti bmi1 avx2 bmi2 avx512f avx512dq avx512cd avx512bw avx512vl Hypervisor vendor: KVM Virtualization type: full L1d cache: 1.5 MiB (48 instances) L1i cache: 1.5 MiB (48 instances) L2 cache: 192 MiB (48 instances) L3 cache: 16 MiB (1 instance) NUMA node(s): 1 NUMA node0 CPU(s): 0-47 Vulnerability Gather data sampling: Not affected Vulnerability Itlb multihit: KVM: Mitigation: VMX unsupported Vulnerability L1tf: Mitigation; PTE Inversion Vulnerability Mds: Vulnerable: Clear CPU buffers attempted, no microcode; SMT Host state unknown Vulnerability Meltdown: Mitigation; PTI Vulnerability Mmio stale data: Unknown: No mitigations Vulnerability Reg file data sampling: Not affected Vulnerability Retbleed: Not affected Vulnerability Spec rstack overflow: Not affected Vulnerability Spec store bypass: Vulnerable Vulnerability Spectre v1: Mitigation; usercopy/swapgs barriers and __user pointer sanitization Vulnerability Spectre v2: Mitigation; Retpolines; STIBP disabled; RSB filling; PBRSB-eIBRS Not affected; BHI Retpoline Vulnerability Srbds: Not affected Vulnerability Tsx async abort: Not affected Vulnerability Vmscape: Not affected

Code Example

import random

import torch
import torch.nn as nn

THRESHOLD = 1.19e-7
DEVICE = torch.device("cuda")
SEED = 0
INPUT_SHAPE = (4, 96, 8, 8)


def set_seed(seed: int) -> None:
    random.seed(seed)
    torch.manual_seed(seed)
    torch.backends.cudnn.deterministic = True
    torch.backends.cudnn.benchmark = False


class Bn1Conv2(nn.Module):
    def __init__(self, sd: dict):
        super().__init__()
        self.bn1 = nn.BatchNorm2d(96)
        self.conv2 = nn.Conv2d(96, 256, kernel_size=5, padding=2, bias=True)
        self.load_state_dict(sd, strict=True)

    def forward(self, x: torch.Tensor) -> torch.Tensor:
        x = self.bn1(x)
        return self.conv2(x)


def _random_state_dict() -> dict:
    bn1 = nn.BatchNorm2d(96)
    conv2 = nn.Conv2d(96, 256, kernel_size=5, padding=2, bias=True)
    with torch.no_grad():
        bn1.weight.normal_(0, 1)
        bn1.bias.normal_(0, 1)
        bn1.running_mean.normal_(0, 0.1)
        bn1.running_var.uniform_(0.5, 1.5)
        conv2.weight.normal_(0, 0.02)
        conv2.bias.normal_(0, 0.02)
    sd = {}
    for k, v in bn1.state_dict().items():
        sd[f"bn1.{k}"] = v.float().cpu().clone()
    for k, v in conv2.state_dict().items():
        sd[f"conv2.{k}"] = v.float().cpu().clone()
    return sd


def main():
    set_seed(SEED)
    x = torch.randn(INPUT_SHAPE, dtype=torch.float32, device="cpu")
    print(f"input min={x.min().item():.6g}  max={x.max().item():.6g}")
    x = x.to(DEVICE)
    sd = _random_state_dict()
    wmin = float("inf")
    wmax = float("-inf")
    for v in sd.values():
        if torch.is_tensor(v):
            t = v.float().cpu()
            wmin = min(wmin, float(t.min().item()))
            wmax = max(wmax, float(t.max().item()))
    print(f"weights min={wmin:.6g}  max={wmax:.6g}")

    m0 = Bn1Conv2(sd).to(DEVICE).eval()
    with torch.no_grad():
        y0 = m0(x)

    m1 = torch.compile(Bn1Conv2(sd).to(DEVICE).eval(), dynamic=True)
    with torch.no_grad():
        y1 = m1(x)

    o = y0.detach().float().cpu().reshape(y0.shape[0], -1)
    s = y1.detach().float().cpu().reshape(y1.shape[0], -1)
    eps = 1e-12
    valid = torch.isfinite(o) & torch.isfinite(s)
    diff = torch.where(valid, (s - o).abs() / (o.abs() + eps), torch.zeros_like(o))
    per = diff.max(dim=1).values
    gmax = float(per.max().item())

    print("modes: eager  vs  torch.compile(dynamic=True)")
    print(
        f"relative error: max_rel={gmax:.6e}  "
        f"threshold={THRESHOLD:.2e}"
    )


if __name__ == "__main__":
    main()

---

input min=-4.34328  max=4.10149
weights min=-2.43843  max=3.20326
modes: eager  vs  torch.compile(dynamic=True)
relative error: max_rel=9.454369e-02  threshold=1.19e-07
RAW_BUFFERClick to expand / collapse

🐛 Describe the bug

A minimal module BatchNorm2d(96) → Conv2d(96→256, k=5, p=2) in eval mode on CUDA shows a large output gap between eager and torch.compile(..., dynamic=True) on the conv2 output. Max per-element relative error vs eager is ~9.5×10⁻², while tight float agreement would be ~1×10⁻⁷ (same order as 1.19e-7).

Repro: Fixed random seed; random float32 input (4, 96, 8, 8) on CPU then moved to CUDA; random state_dict for bn1.* and conv2.*; compare eager forward to compiled forward with the same x and sd (two module instances).

Expected: Compiled output matches eager within a small FP tolerance. Actual: Relative error ~9.45e-2 (example run: input min/max [-4.34, 4.10], weights min/max [-2.44, 3.20]).

import random

import torch
import torch.nn as nn

THRESHOLD = 1.19e-7
DEVICE = torch.device("cuda")
SEED = 0
INPUT_SHAPE = (4, 96, 8, 8)


def set_seed(seed: int) -> None:
    random.seed(seed)
    torch.manual_seed(seed)
    torch.backends.cudnn.deterministic = True
    torch.backends.cudnn.benchmark = False


class Bn1Conv2(nn.Module):
    def __init__(self, sd: dict):
        super().__init__()
        self.bn1 = nn.BatchNorm2d(96)
        self.conv2 = nn.Conv2d(96, 256, kernel_size=5, padding=2, bias=True)
        self.load_state_dict(sd, strict=True)

    def forward(self, x: torch.Tensor) -> torch.Tensor:
        x = self.bn1(x)
        return self.conv2(x)


def _random_state_dict() -> dict:
    bn1 = nn.BatchNorm2d(96)
    conv2 = nn.Conv2d(96, 256, kernel_size=5, padding=2, bias=True)
    with torch.no_grad():
        bn1.weight.normal_(0, 1)
        bn1.bias.normal_(0, 1)
        bn1.running_mean.normal_(0, 0.1)
        bn1.running_var.uniform_(0.5, 1.5)
        conv2.weight.normal_(0, 0.02)
        conv2.bias.normal_(0, 0.02)
    sd = {}
    for k, v in bn1.state_dict().items():
        sd[f"bn1.{k}"] = v.float().cpu().clone()
    for k, v in conv2.state_dict().items():
        sd[f"conv2.{k}"] = v.float().cpu().clone()
    return sd


def main():
    set_seed(SEED)
    x = torch.randn(INPUT_SHAPE, dtype=torch.float32, device="cpu")
    print(f"input min={x.min().item():.6g}  max={x.max().item():.6g}")
    x = x.to(DEVICE)
    sd = _random_state_dict()
    wmin = float("inf")
    wmax = float("-inf")
    for v in sd.values():
        if torch.is_tensor(v):
            t = v.float().cpu()
            wmin = min(wmin, float(t.min().item()))
            wmax = max(wmax, float(t.max().item()))
    print(f"weights min={wmin:.6g}  max={wmax:.6g}")

    m0 = Bn1Conv2(sd).to(DEVICE).eval()
    with torch.no_grad():
        y0 = m0(x)

    m1 = torch.compile(Bn1Conv2(sd).to(DEVICE).eval(), dynamic=True)
    with torch.no_grad():
        y1 = m1(x)

    o = y0.detach().float().cpu().reshape(y0.shape[0], -1)
    s = y1.detach().float().cpu().reshape(y1.shape[0], -1)
    eps = 1e-12
    valid = torch.isfinite(o) & torch.isfinite(s)
    diff = torch.where(valid, (s - o).abs() / (o.abs() + eps), torch.zeros_like(o))
    per = diff.max(dim=1).values
    gmax = float(per.max().item())

    print("modes: eager  vs  torch.compile(dynamic=True)")
    print(
        f"relative error: max_rel={gmax:.6e}  "
        f"threshold={THRESHOLD:.2e}"
    )


if __name__ == "__main__":
    main()
input min=-4.34328  max=4.10149
weights min=-2.43843  max=3.20326
modes: eager  vs  torch.compile(dynamic=True)
relative error: max_rel=9.454369e-02  threshold=1.19e-07

Versions

PyTorch version: 2.10.0+cu126 Is debug build: False CUDA used to build PyTorch: 12.6 ROCM used to build PyTorch: N/A

OS: Ubuntu 24.04.3 LTS (x86_64) GCC version: (Ubuntu 13.3.0-6ubuntu2~24.04) 13.3.0 Clang version: Could not collect CMake version: Could not collect Libc version: glibc-2.39

Python version: 3.10.19 | packaged by conda-forge | (main, Jan 26 2026, 23:45:08) [GCC 14.3.0] (64-bit runtime) Python platform: Linux-6.8.0-90-generic-x86_64-with-glibc2.39 Is CUDA available: True CUDA runtime version: 12.6.20 CUDA_MODULE_LOADING set to: GPU models and configuration: GPU 0: NVIDIA GeForce RTX 3090 GPU 1: NVIDIA GeForce RTX 3090

Nvidia driver version: 560.35.03 cuDNN version: Could not collect 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: 40 bits physical, 48 bits virtual Byte Order: Little Endian CPU(s): 48 On-line CPU(s) list: 0-47 Vendor ID: GenuineIntel Model name: QEMU Virtual CPU version 2.5+ CPU family: 15 Model: 107 Thread(s) per core: 1 Core(s) per socket: 48 Socket(s): 1 Stepping: 1 BogoMIPS: 4190.15 Flags: fpu de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush mmx fxsr sse sse2 ht syscall nx lm constant_tsc nopl xtopology cpuid tsc_known_freq pni ssse3 fma cx16 sse4_1 sse4_2 x2apic movbe popcnt aes xsave avx f16c hypervisor lahf_lm abm cpuid_fault pti bmi1 avx2 bmi2 avx512f avx512dq avx512cd avx512bw avx512vl Hypervisor vendor: KVM Virtualization type: full L1d cache: 1.5 MiB (48 instances) L1i cache: 1.5 MiB (48 instances) L2 cache: 192 MiB (48 instances) L3 cache: 16 MiB (1 instance) NUMA node(s): 1 NUMA node0 CPU(s): 0-47 Vulnerability Gather data sampling: Not affected Vulnerability Itlb multihit: KVM: Mitigation: VMX unsupported Vulnerability L1tf: Mitigation; PTE Inversion Vulnerability Mds: Vulnerable: Clear CPU buffers attempted, no microcode; SMT Host state unknown Vulnerability Meltdown: Mitigation; PTI Vulnerability Mmio stale data: Unknown: No mitigations Vulnerability Reg file data sampling: Not affected Vulnerability Retbleed: Not affected Vulnerability Spec rstack overflow: Not affected Vulnerability Spec store bypass: Vulnerable Vulnerability Spectre v1: Mitigation; usercopy/swapgs barriers and __user pointer sanitization Vulnerability Spectre v2: Mitigation; Retpolines; STIBP disabled; RSB filling; PBRSB-eIBRS Not affected; BHI Retpoline Vulnerability Srbds: Not affected Vulnerability Tsx async abort: Not affected Vulnerability Vmscape: Not affected

Versions of relevant libraries: [pip3] numpy==1.26.4 [pip3] nvidia-cublas-cu12==12.6.4.1 [pip3] nvidia-cuda-cupti-cu12==12.6.80 [pip3] nvidia-cuda-nvrtc-cu12==12.6.77 [pip3] nvidia-cuda-runtime-cu12==12.6.77 [pip3] nvidia-cudnn-cu12==9.10.2.21 [pip3] nvidia-cufft-cu12==11.3.0.4 [pip3] nvidia-curand-cu12==10.3.7.77 [pip3] nvidia-cusolver-cu12==11.7.1.2 [pip3] nvidia-cusparse-cu12==12.5.4.2 [pip3] nvidia-cusparselt-cu12==0.7.1 [pip3] nvidia-nccl-cu12==2.27.5 [pip3] nvidia-nvjitlink-cu12==12.6.85 [pip3] nvidia-nvtx-cu12==12.6.77 [pip3] onnxruntime-gpu==1.23.2 [pip3] optree==0.18.0 [pip3] pytorch-triton==3.2.0+git4b3bb1f8 [pip3] torch==2.10.0+cu126 [pip3] torchaudio==2.11.0.dev20260127+cu126 [pip3] torchvision==0.25.0+cu126 [pip3] triton==3.6.0+git9844da95 [conda] numpy 1.26.4 pypi_0 pypi [conda] nvidia-cublas-cu12 12.6.4.1 pypi_0 pypi [conda] nvidia-cuda-cupti-cu12 12.6.80 pypi_0 pypi [conda] nvidia-cuda-nvrtc-cu12 12.6.77 pypi_0 pypi [conda] nvidia-cuda-runtime-cu12 12.6.77 pypi_0 pypi [conda] nvidia-cudnn-cu12 9.10.2.21 pypi_0 pypi [conda] nvidia-cufft-cu12 11.3.0.4 pypi_0 pypi [conda] nvidia-curand-cu12 10.3.7.77 pypi_0 pypi [conda] nvidia-cusolver-cu12 11.7.1.2 pypi_0 pypi [conda] nvidia-cusparse-cu12 12.5.4.2 pypi_0 pypi [conda] nvidia-cusparselt-cu12 0.7.1 pypi_0 pypi [conda] nvidia-nccl-cu12 2.27.5 pypi_0 pypi [conda] nvidia-nvjitlink-cu12 12.6.85 pypi_0 pypi [conda] nvidia-nvtx-cu12 12.6.77 pypi_0 pypi [conda] optree 0.18.0 pypi_0 pypi [conda] pytorch-triton 3.2.0+git4b3bb1f8 pypi_0 pypi [conda] torch 2.10.0+cu126 pypi_0 pypi [conda] torchaudio 2.11.0.dev20260127+cu126 pypi_0 pypi [conda] torchvision 0.25.0+cu126 pypi_0 pypi [conda] triton 3.6.0+git9844da95 pypi_0 pypi

cc @ptrblck @msaroufim @eqy @jerryzh168 @tinglvv @nWEIdia @chauhang @penguinwu @voznesenskym @EikanWang @jgong5 @Guobing-Chen @XiaobingSuper @zhuhaozhe @blzheng @wenzhe-nrv @jiayisunx @ipiszy @kadeng @muchulee8 @amjames @aakhundov @coconutruben @jataylo

extent analysis

Fix Plan

To address the issue of large output gaps between eager and torch.compile modes, we need to ensure that the compilation process is correctly handling the floating-point operations.

Here are the steps to fix the issue:

  • Step 1: Disable torch.backends.cudnn.deterministic and torch.backends.cudnn.benchmark: These flags can affect the reproducibility of the results. Try setting them to False to see if it resolves the issue.
  • Step 2: Use torch.use_deterministic_algorithms(True): This flag ensures that PyTorch uses deterministic algorithms, which can help in reducing the differences between eager and compiled modes.
  • Step 3: Verify the Numerical Stability: Numerical instability can cause differences between eager and compiled modes. Try to add a small value to the denominator to avoid division by zero.

Example code:

import torch
import torch.nn as nn

# Step 1: Disable torch.backends.cudnn.deterministic and torch.backends.cudnn.benchmark
torch.backends.cudnn.deterministic = False
torch.backends.cudnn.benchmark = False

# Step 2: Use torch.use_deterministic_algorithms(True)
torch.use_deterministic_algorithms(True)

class Bn1Conv2(nn.Module):
    def __init__(self, sd: dict):
        super().__init__()
        self.bn1 = nn.BatchNorm2d(96)
        self.conv2 = nn.Conv2d(96, 256, kernel_size=5, padding=2, bias=True)
        self.load_state_dict(sd, strict=True)

    def forward(self, x: torch.Tensor) -> torch.Tensor:
        x = self.bn1(x)
        # Step 3: Verify the numerical stability
        x = self.conv2(x)
        return x

Verification

To verify that the fix worked, compare the outputs of the eager and compiled modes using the following code:

m0 = Bn1Conv2(sd).to(DEVICE).eval()
with torch.no_grad():
    y0 = m0(x)

m1 = torch.compile(Bn1Conv2(sd).to(DEVICE).eval(), dynamic=True)
with torch.no_grad():
    y1 = m1(x)

# Calculate the relative error
o = y0.detach().float().cpu().reshape(y0.shape[0], -1)
s = y1.detach().float().cpu().reshape(y1.shape[0], -1)
eps = 1e-12
valid = torch.isfinite(o) & torch.isfinite(s)
diff = torch.where(valid, (s - o).abs() / (o.abs() + eps), torch.zeros_like(o))
per = diff.max(dim=1).values
gmax = float(per.max().item())

print("modes: eager  vs

Vote matrix · Quick signals

Works
Did the solution work? Tap to confirm.
Easy Fix
Was it a quick fix?
Time Saver
Did it save you time?
Blocking
Was it severely blocking?
Common Issue
Are others likely hitting this too?
Flaky / Intermittent
Is it intermittent?
Verified / Reproducible
Can you reproduce it reliably?
Loading…

Still need to ship something?

×6

Another batch ranked right after the header list — different links, same matching logic.

Back to top recommendations

TRENDING