pytorch - 💡(How to fix) Fix torch.compile (CUDA fp32) vs eager gives large max relative error for Conv2d [5 comments, 4 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#178134Fetched 2026-04-08 01:16:25
View on GitHub
Comments
5
Participants
4
Timeline
258
Reactions
0
Author
Timeline (top)
mentioned ×122subscribed ×122labeled ×8commented ×5

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 os
import torch
import torch.nn as nn

EPS = 1e-12
THRESHOLD = 1.19e-7

SEED = 1
torch.manual_seed(SEED)
if torch.cuda.is_available():
    torch.cuda.manual_seed_all(SEED)
X = torch.randn((64, 3, 224, 224), dtype=torch.float32)
w = torch.randn((64, 3, 3, 3), dtype=torch.float32) * 0.02
b = torch.randn((64,), dtype=torch.float32) * 0.02

print(f"input min={X.min().item():.6g} max={X.max().item():.6g}")
print(f"weight min={w.min().item():.6g} max={w.max().item():.6g}")

def has_nan_inf(t):
    t = t.detach()
    return bool(torch.isnan(t).any().item()), bool(torch.isinf(t).any().item())

def build_conv(device, compile_flag):
    m = nn.Conv2d(3, 64, kernel_size=3, padding=1, bias=True).to(device=device, dtype=torch.float32).eval()
    with torch.no_grad():
        m.weight.copy_(w.to(device=device, dtype=torch.float32))
        m.bias.copy_(b.to(device=device, dtype=torch.float32))
    if compile_flag:
        m = torch.compile(m, dynamic=False)
    return m

def run(device, compile_flag):
    m = build_conv(device, compile_flag)
    x = X.to(device=device, dtype=torch.float32)
    with torch.no_grad():
        y = m(x).detach().float().cpu()
    return y

def stats(ref, new):
    abs_max = (new - ref).abs().max().item()
    ref_f = ref.reshape(ref.shape[0], -1)
    new_f = new.reshape(new.shape[0], -1)
    valid = torch.isfinite(ref_f) & torch.isfinite(new_f)
    rel = torch.where(valid, (new_f - ref_f).abs() / (ref_f.abs() + EPS), torch.zeros_like(ref_f))
    rel_max = rel.max().item()
    return abs_max, rel_max

y_cuda_eager = run("cuda", compile_flag=False)
y_cuda_compile = run("cuda", compile_flag=True)

abs_max, rel_max = stats(y_cuda_eager, y_cuda_compile)
en, ei = has_nan_inf(y_cuda_eager)
cn, ci = has_nan_inf(y_cuda_compile)
print("cuda fp32 eager vs cuda fp32 compile")
print(f"base(has_nan={en},has_inf={ei}) switch(has_nan={cn},has_inf={ci}) abs_max={abs_max:.6e} rel_max={rel_max:.6e} threshold={THRESHOLD:.2e}")

---

input min=-5.18789 max=5.24161
weight min=-0.0675059 max=0.0759694
cuda fp32 eager vs cuda fp32 compile
base(has_nan=False,has_inf=False) switch(has_nan=False,has_inf=False) abs_max=3.014058e-04 rel_max=2.653775e+04 threshold=1.19e-07
RAW_BUFFERClick to expand / collapse

🐛 Describe the bug

I created a minimal reproduction for a single Conv2d(3->64, k=3, padding=1) layer on CUDA (fp32) and compared eager vs torch.compile using the same fixed random input tensor and the same fixed random weights (deterministic seed).

Modes: cuda fp32 eager vs cuda fp32 compile input min/max: -5.18789 / 5.24161 weight min/max: -0.0675059 / 0.0759694 Observed: outputs differ significantly between the two modes. Metrics (max over all elements): abs_max=3.014058e-04 rel_max=2.653775e+04 threshold used in the repro: 1.19e-07 Even though both executions produce finite outputs, the compiled execution is not numerically consistent with eager for this convolution layer, exceeding the expected fp32 tolerance.

import os
import torch
import torch.nn as nn

EPS = 1e-12
THRESHOLD = 1.19e-7

SEED = 1
torch.manual_seed(SEED)
if torch.cuda.is_available():
    torch.cuda.manual_seed_all(SEED)
X = torch.randn((64, 3, 224, 224), dtype=torch.float32)
w = torch.randn((64, 3, 3, 3), dtype=torch.float32) * 0.02
b = torch.randn((64,), dtype=torch.float32) * 0.02

print(f"input min={X.min().item():.6g} max={X.max().item():.6g}")
print(f"weight min={w.min().item():.6g} max={w.max().item():.6g}")

def has_nan_inf(t):
    t = t.detach()
    return bool(torch.isnan(t).any().item()), bool(torch.isinf(t).any().item())

def build_conv(device, compile_flag):
    m = nn.Conv2d(3, 64, kernel_size=3, padding=1, bias=True).to(device=device, dtype=torch.float32).eval()
    with torch.no_grad():
        m.weight.copy_(w.to(device=device, dtype=torch.float32))
        m.bias.copy_(b.to(device=device, dtype=torch.float32))
    if compile_flag:
        m = torch.compile(m, dynamic=False)
    return m

def run(device, compile_flag):
    m = build_conv(device, compile_flag)
    x = X.to(device=device, dtype=torch.float32)
    with torch.no_grad():
        y = m(x).detach().float().cpu()
    return y

def stats(ref, new):
    abs_max = (new - ref).abs().max().item()
    ref_f = ref.reshape(ref.shape[0], -1)
    new_f = new.reshape(new.shape[0], -1)
    valid = torch.isfinite(ref_f) & torch.isfinite(new_f)
    rel = torch.where(valid, (new_f - ref_f).abs() / (ref_f.abs() + EPS), torch.zeros_like(ref_f))
    rel_max = rel.max().item()
    return abs_max, rel_max

y_cuda_eager = run("cuda", compile_flag=False)
y_cuda_compile = run("cuda", compile_flag=True)

abs_max, rel_max = stats(y_cuda_eager, y_cuda_compile)
en, ei = has_nan_inf(y_cuda_eager)
cn, ci = has_nan_inf(y_cuda_compile)
print("cuda fp32 eager vs cuda fp32 compile")
print(f"base(has_nan={en},has_inf={ei}) switch(has_nan={cn},has_inf={ci}) abs_max={abs_max:.6e} rel_max={rel_max:.6e} threshold={THRESHOLD:.2e}")
input min=-5.18789 max=5.24161
weight min=-0.0675059 max=0.0759694
cuda fp32 eager vs cuda fp32 compile
base(has_nan=False,has_inf=False) switch(has_nan=False,has_inf=False) abs_max=3.014058e-04 rel_max=2.653775e+04 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 numerical inconsistency between eager and compiled execution of a Conv2d layer in PyTorch, we can try the following steps:

  • Disable Fusion: Try disabling fusion in the compiled mode to see if it resolves the issue.
  • Check Numerical Stability: Ensure that the inputs and weights are numerically stable and do not cause overflow or underflow issues.
  • Use Lower Precision: If possible, try using lower precision (e.g., float16) to see if the issue persists.

Here's an example code snippet that demonstrates how to disable fusion:

import torch
from torch import compile

# Create a Conv2d module
m = torch.nn.Conv2d(3, 64, kernel_size=3, padding=1, bias=True)

# Compile the module with fusion disabled
m_compiled = compile(m, mode="default", dynamic=False, disable_fusion=True)

Verification

To verify that the fix worked, you can compare the outputs of the eager and compiled executions using the stats function provided in the issue body:

def stats(ref, new):
    abs_max = (new - ref).abs().max().item()
    ref_f = ref.reshape(ref.shape[0], -1)
    new_f = new.reshape(new.shape[0], -1)
    valid = torch.isfinite(ref_f) & torch.isfinite(new_f)
    rel = torch.where(valid, (new_f - ref_f).abs() / (ref_f.abs() + 1e-12), torch.zeros_like(ref_f))
    rel_max = rel.max().item()
    return abs_max, rel_max

y_cuda_eager = run("cuda", compile_flag=False)
y_cuda_compile = run("cuda", compile_flag=True, disable_fusion=True)

abs_max, rel_max = stats(y_cuda_eager, y_cuda_compile)
print(f"abs_max={abs_max:.6e} rel_max={rel_max:.6e}")

Extra Tips

  • When working with compiled modules, ensure that the inputs and weights are properly synchronized to the device (e.g., CUDA) to avoid numerical inconsistencies.
  • If the issue persists, try updating PyTorch and its dependencies to the latest versions.
  • Consider filing a bug report with PyTorch if the issue is not resolved after trying the above steps.

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