pytorch - 💡(How to fix) Fix Missing CSE in TorchInductor [1 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#180957Fetched 2026-04-22 07:43:21
View on GitHub
Comments
0
Participants
1
Timeline
82
Reactions
0
Participants
Timeline (top)
mentioned ×38subscribed ×38labeled ×6

Error Message

import argparse import time import torch import torch.nn.functional as F import torch.nn as nn

def compute_var_and_std(x: torch.Tensor) -> torch.Tensor: var = torch.var(x, dim=-1) std = torch.std(x, dim=-1) return var + std

def benchmark(fn, *args, warmup=20, iters=100): for _ in range(warmup): fn(*args) if torch.cuda.is_available(): torch.cuda.synchronize() start_time = time.perf_counter() for _ in range(iters): fn(*args) if torch.cuda.is_available(): torch.cuda.synchronize() end_time = time.perf_counter() return ((end_time - start_time) / iters) * 1000

def main() -> None: parser = argparse.ArgumentParser() parser.add_argument("--batch-size", type=int, default=64) parser.add_argument("--vocab-size", type=int, default=32768) parser.add_argument("--device", type=str, default="cuda" if torch.cuda.is_available() else "cpu") parser.add_argument("--dtype", type=str, default="float16") args = parser.parse_args()

device = torch.device(args.device)
dtype = torch.float16 if args.dtype == "float16" else torch.float32
B, V = args.batch_size, args.vocab_size

print(f"Device: {device} | Dtype: {dtype} | Batch: {B} | Vocab: {V}\n")

x      = torch.randn(B, V, device=device, dtype=dtype)
x_pair = (torch.randn(B, V, device=device, dtype=dtype),
          torch.randn(B, V, device=device, dtype=dtype))
labels = torch.randint(0, V, (B,), device=device)

cases = [
    ("var_std",           compute_var_and_std,             (x,)),
]

compile_modes = [
    ("Eager",        None),
    ("Default",      {}),
    ("ReduceOH",     {"mode": "reduce-overhead"}),
    ("MaxAutotune",  {"mode": "max-autotune"}),
]

for case_name, fn, fn_args in cases:
    print(f"{'='*20} {case_name} {'='*20}")
    eager_ms = None
    for mode_name, compile_kwargs in compile_modes:
        if compile_kwargs is None:
            compiled_fn = fn
        else:
            compiled_fn = torch.compile(fn, **compile_kwargs)
        try:
            compiled_fn(*fn_args)   # trigger compilation
            ms = benchmark(compiled_fn, *fn_args)
            if mode_name == "Eager":
                eager_ms = ms
            speedup = eager_ms / ms if eager_ms else float("nan")
            print(f"  {mode_name:12s}: {ms:8.4f} ms  speedup={speedup:.3f}x")
        except Exception as e:
            print(f"  {mode_name:12s}: FAILED -> {str(e)[:60]}")
    print()

if name == "main": main()

Fix Action

Fix / Workaround

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): 96 On-line CPU(s) list: 0-95 Vendor ID: GenuineIntel Model name: Intel(R) Xeon(R) Gold 6248R CPU @ 3.00GHz CPU family: 6 Model: 85 Thread(s) per core: 2 Core(s) per socket: 24 Socket(s): 2 Stepping: 7 BogoMIPS: 6000.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 intel_ppin ssbd mba ibrs ibpb stibp ibrs_enhanced tpr_shadow 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 vnmi pku ospke avx512_vnni md_clear flush_l1d arch_capabilities Virtualization: VT-x L1d cache: 1.5 MiB (48 instances) L1i cache: 1.5 MiB (48 instances) L2 cache: 48 MiB (48 instances) L3 cache: 71.5 MiB (2 instances) NUMA node(s): 2 NUMA node0 CPU(s): 0,2,4,6,8,10,12,14,16,18,20,22,24,26,28,30,32,34,36,38,40,42,44,46,48,50,52,54,56,58,60,62,64,66,68,70,72,74,76,78,80,82,84,86,88,90,92,94 NUMA node1 CPU(s): 1,3,5,7,9,11,13,15,17,19,21,23,25,27,29,31,33,35,37,39,41,43,45,47,49,51,53,55,57,59,61,63,65,67,69,71,73,75,77,79,81,83,85,87,89,91,93,95 Vulnerability Gather data sampling: Mitigation; Microcode 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 vulnerable Vulnerability Reg file data sampling: Not affected Vulnerability Retbleed: Mitigation; Enhanced IBRS Vulnerability Spec rstack overflow: Not affected 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; RSB filling; PBRSB-eIBRS SW sequence; BHI SW loop, KVM SW loop Vulnerability Srbds: Not affected Vulnerability Tsx async abort: Mitigation; TSX disabled

Code Example

import argparse
import time
import torch
import torch.nn.functional as F
import torch.nn as nn

def compute_var_and_std(x: torch.Tensor) -> torch.Tensor:
    var = torch.var(x, dim=-1)
    std = torch.std(x, dim=-1)
    return var + std

def benchmark(fn, *args, warmup=20, iters=100):
    for _ in range(warmup):
        fn(*args)
    if torch.cuda.is_available():
        torch.cuda.synchronize()
    start_time = time.perf_counter()
    for _ in range(iters):
        fn(*args)
    if torch.cuda.is_available():
        torch.cuda.synchronize()
    end_time = time.perf_counter()
    return ((end_time - start_time) / iters) * 1000


def main() -> None:
    parser = argparse.ArgumentParser()
    parser.add_argument("--batch-size", type=int, default=64)
    parser.add_argument("--vocab-size", type=int, default=32768)
    parser.add_argument("--device", type=str, default="cuda" if torch.cuda.is_available() else "cpu")
    parser.add_argument("--dtype", type=str, default="float16")
    args = parser.parse_args()

    device = torch.device(args.device)
    dtype = torch.float16 if args.dtype == "float16" else torch.float32
    B, V = args.batch_size, args.vocab_size

    print(f"Device: {device} | Dtype: {dtype} | Batch: {B} | Vocab: {V}\n")

    x      = torch.randn(B, V, device=device, dtype=dtype)
    x_pair = (torch.randn(B, V, device=device, dtype=dtype),
              torch.randn(B, V, device=device, dtype=dtype))
    labels = torch.randint(0, V, (B,), device=device)

    cases = [
        ("var_std",           compute_var_and_std,             (x,)),
    ]

    compile_modes = [
        ("Eager",        None),
        ("Default",      {}),
        ("ReduceOH",     {"mode": "reduce-overhead"}),
        ("MaxAutotune",  {"mode": "max-autotune"}),
    ]

    for case_name, fn, fn_args in cases:
        print(f"{'='*20} {case_name} {'='*20}")
        eager_ms = None
        for mode_name, compile_kwargs in compile_modes:
            if compile_kwargs is None:
                compiled_fn = fn
            else:
                compiled_fn = torch.compile(fn, **compile_kwargs)
            try:
                compiled_fn(*fn_args)   # trigger compilation
                ms = benchmark(compiled_fn, *fn_args)
                if mode_name == "Eager":
                    eager_ms = ms
                speedup = eager_ms / ms if eager_ms else float("nan")
                print(f"  {mode_name:12s}: {ms:8.4f} ms  speedup={speedup:.3f}x")
            except Exception as e:
                print(f"  {mode_name:12s}: FAILED -> {str(e)[:60]}")
        print()


if __name__ == "__main__":
    main()

---

Device: cuda | Dtype: torch.float16 | Batch: 64 | Vocab: 32768

==================== var_std ====================
  Eager       :   0.0289 ms  speedup=1.000x
  Default     :   0.0866 ms  speedup=0.334x
  ReduceOH    :   0.0691 ms  speedup=0.418x
  MaxAutotune :   0.0688 ms  speedup=0.420x

---

tmp2_mean = tl.zeros([XBLOCK, RBLOCK], tl.float32)
tmp2_m2 = tl.zeros([XBLOCK, RBLOCK], tl.float32)

# Second set (for std)
tmp7_mean = tl.zeros([XBLOCK, RBLOCK], tl.float32)
tmp7_m2 = tl.zeros([XBLOCK, RBLOCK], tl.float32)

---

--- Validate Correctness --- 
Correctness: Pass 

--- Test Performance --- 
Original Code Avg Latency: 0.0515 ms 
Manual CSE Code Avg Latency: 0.0411 ms 
Speedup: 20.24%

---

PyTorch version: 2.10.0.dev20251021+cu128
Is debug build: False
CUDA used to build PyTorch: 12.8
ROCM used to build PyTorch: N/A

OS: Ubuntu 22.04.4 LTS (x86_64)
GCC version: (Ubuntu 11.4.0-1ubuntu1~22.04) 11.4.0
Clang version: Could not collect
CMake version: version 3.22.1
Libc version: glibc-2.35

Python version: 3.10.19 (main, Oct 21 2025, 16:43:05) [GCC 11.2.0] (64-bit runtime)
Python platform: Linux-6.8.0-40-generic-x86_64-with-glibc2.35
Is CUDA available: True
CUDA runtime version: 11.8.89
CUDA_MODULE_LOADING set to:
GPU models and configuration:
GPU 0: NVIDIA RTX A6000
GPU 1: NVIDIA RTX A6000

Nvidia driver version: 570.211.01
cuDNN version: Could not collect
Is XPU available: False
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):                               96
On-line CPU(s) list:                  0-95
Vendor ID:                            GenuineIntel
Model name:                           Intel(R) Xeon(R) Gold 6248R CPU @ 3.00GHz
CPU family:                           6
Model:                                85
Thread(s) per core:                   2
Core(s) per socket:                   24
Socket(s):                            2
Stepping:                             7
BogoMIPS:                             6000.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 intel_ppin ssbd mba ibrs ibpb stibp ibrs_enhanced tpr_shadow 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 vnmi pku ospke avx512_vnni md_clear flush_l1d arch_capabilities
Virtualization:                       VT-x
L1d cache:                            1.5 MiB (48 instances)
L1i cache:                            1.5 MiB (48 instances)
L2 cache:                             48 MiB (48 instances)
L3 cache:                             71.5 MiB (2 instances)
NUMA node(s):                         2
NUMA node0 CPU(s):                    0,2,4,6,8,10,12,14,16,18,20,22,24,26,28,30,32,34,36,38,40,42,44,46,48,50,52,54,56,58,60,62,64,66,68,70,72,74,76,78,80,82,84,86,88,90,92,94
NUMA node1 CPU(s):                    1,3,5,7,9,11,13,15,17,19,21,23,25,27,29,31,33,35,37,39,41,43,45,47,49,51,53,55,57,59,61,63,65,67,69,71,73,75,77,79,81,83,85,87,89,91,93,95
Vulnerability Gather data sampling:   Mitigation; Microcode
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 vulnerable
Vulnerability Reg file data sampling: Not affected
Vulnerability Retbleed:               Mitigation; Enhanced IBRS
Vulnerability Spec rstack overflow:   Not affected
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; RSB filling; PBRSB-eIBRS SW sequence; BHI SW loop, KVM SW loop
Vulnerability Srbds:                  Not affected
Vulnerability Tsx async abort:        Mitigation; TSX disabled

Versions of relevant libraries:
[pip3] numpy==2.2.6
[pip3] nvidia-cublas-cu11==11.11.3.6
[pip3] nvidia-cublas-cu12==12.8.4.1
[pip3] nvidia-cuda-cupti-cu11==11.8.87
[pip3] nvidia-cuda-cupti-cu12==12.8.90
[pip3] nvidia-cuda-nvrtc-cu11==11.8.89
[pip3] nvidia-cuda-nvrtc-cu12==12.8.93
[pip3] nvidia-cuda-runtime-cu11==11.8.89
[pip3] nvidia-cuda-runtime-cu12==12.8.90
[pip3] nvidia-cudnn-cu11==9.1.0.70
[pip3] nvidia-cudnn-cu12==9.10.2.21
[pip3] nvidia-cufft-cu11==10.9.0.58
[pip3] nvidia-cufft-cu12==11.3.3.83
[pip3] nvidia-curand-cu11==10.3.0.86
[pip3] nvidia-curand-cu12==10.3.9.90
[pip3] nvidia-cusolver-cu11==11.4.1.48
[pip3] nvidia-cusolver-cu12==11.7.3.90
[pip3] nvidia-cusparse-cu11==11.7.5.86
[pip3] nvidia-cusparse-cu12==12.5.8.93
[pip3] nvidia-cusparselt-cu12==0.7.1
[pip3] nvidia-nccl-cu11==2.21.5
[pip3] nvidia-nccl-cu12==2.27.5
[pip3] nvidia-nvjitlink-cu12==12.8.93
[pip3] nvidia-nvtx-cu11==11.8.86
[pip3] nvidia-nvtx-cu12==12.8.90
[pip3] pytorch-triton==3.5.0+git7416ffcb
[pip3] torch==2.10.0.dev20251021+cu128
[pip3] torchaudio==2.10.0.dev20251021+cu128
[pip3] torchvision==0.25.0.dev20251021+cu128
[pip3] triton==3.0.0
[conda] numpy                     2.2.6                    pypi_0    pypi
[conda] nvidia-cublas-cu11        11.11.3.6                pypi_0    pypi
[conda] nvidia-cublas-cu12        12.8.4.1                 pypi_0    pypi
[conda] nvidia-cuda-cupti-cu11    11.8.87                  pypi_0    pypi
[conda] nvidia-cuda-cupti-cu12    12.8.90                  pypi_0    pypi
[conda] nvidia-cuda-nvrtc-cu11    11.8.89                  pypi_0    pypi
[conda] nvidia-cuda-nvrtc-cu12    12.8.93                  pypi_0    pypi
[conda] nvidia-cuda-runtime-cu11  11.8.89                  pypi_0    pypi
[conda] nvidia-cuda-runtime-cu12  12.8.90                  pypi_0    pypi
[conda] nvidia-cudnn-cu11         9.1.0.70                 pypi_0    pypi
[conda] nvidia-cudnn-cu12         9.10.2.21                pypi_0    pypi
[conda] nvidia-cufft-cu11         10.9.0.58                pypi_0    pypi
[conda] nvidia-cufft-cu12         11.3.3.83                pypi_0    pypi
[conda] nvidia-curand-cu11        10.3.0.86                pypi_0    pypi
[conda] nvidia-curand-cu12        10.3.9.90                pypi_0    pypi
[conda] nvidia-cusolver-cu11      11.4.1.48                pypi_0    pypi
[conda] nvidia-cusolver-cu12      11.7.3.90                pypi_0    pypi
[conda] nvidia-cusparse-cu11      11.7.5.86                pypi_0    pypi
[conda] nvidia-cusparse-cu12      12.5.8.93                pypi_0    pypi
[conda] nvidia-cusparselt-cu12    0.7.1                    pypi_0    pypi
[conda] nvidia-nccl-cu11          2.21.5                   pypi_0    pypi
[conda] nvidia-nccl-cu12          2.27.5                   pypi_0    pypi
[conda] nvidia-nvjitlink-cu12     12.8.93                  pypi_0    pypi
[conda] nvidia-nvtx-cu11          11.8.86                  pypi_0    pypi
[conda] nvidia-nvtx-cu12          12.8.90                  pypi_0    pypi
[conda] pytorch-triton            3.5.0+git7416ffcb          pypi_0    pypi
[conda] torch                     2.10.0.dev20251021+cu128          pypi_0    pypi
[conda] torchaudio                2.10.0.dev20251021+cu128          pypi_0    pypi
[conda] torchvision               0.25.0.dev20251021+cu128          pypi_0    pypi
RAW_BUFFERClick to expand / collapse

🐛 Describe the bug

A performance issue when using torch.compile. The compiled kernel introduces redundant computations that should be eliminated by common subexpression elimination (CSE).

Minimal reproducer:

import argparse
import time
import torch
import torch.nn.functional as F
import torch.nn as nn

def compute_var_and_std(x: torch.Tensor) -> torch.Tensor:
    var = torch.var(x, dim=-1)
    std = torch.std(x, dim=-1)
    return var + std

def benchmark(fn, *args, warmup=20, iters=100):
    for _ in range(warmup):
        fn(*args)
    if torch.cuda.is_available():
        torch.cuda.synchronize()
    start_time = time.perf_counter()
    for _ in range(iters):
        fn(*args)
    if torch.cuda.is_available():
        torch.cuda.synchronize()
    end_time = time.perf_counter()
    return ((end_time - start_time) / iters) * 1000


def main() -> None:
    parser = argparse.ArgumentParser()
    parser.add_argument("--batch-size", type=int, default=64)
    parser.add_argument("--vocab-size", type=int, default=32768)
    parser.add_argument("--device", type=str, default="cuda" if torch.cuda.is_available() else "cpu")
    parser.add_argument("--dtype", type=str, default="float16")
    args = parser.parse_args()

    device = torch.device(args.device)
    dtype = torch.float16 if args.dtype == "float16" else torch.float32
    B, V = args.batch_size, args.vocab_size

    print(f"Device: {device} | Dtype: {dtype} | Batch: {B} | Vocab: {V}\n")

    x      = torch.randn(B, V, device=device, dtype=dtype)
    x_pair = (torch.randn(B, V, device=device, dtype=dtype),
              torch.randn(B, V, device=device, dtype=dtype))
    labels = torch.randint(0, V, (B,), device=device)

    cases = [
        ("var_std",           compute_var_and_std,             (x,)),
    ]

    compile_modes = [
        ("Eager",        None),
        ("Default",      {}),
        ("ReduceOH",     {"mode": "reduce-overhead"}),
        ("MaxAutotune",  {"mode": "max-autotune"}),
    ]

    for case_name, fn, fn_args in cases:
        print(f"{'='*20} {case_name} {'='*20}")
        eager_ms = None
        for mode_name, compile_kwargs in compile_modes:
            if compile_kwargs is None:
                compiled_fn = fn
            else:
                compiled_fn = torch.compile(fn, **compile_kwargs)
            try:
                compiled_fn(*fn_args)   # trigger compilation
                ms = benchmark(compiled_fn, *fn_args)
                if mode_name == "Eager":
                    eager_ms = ms
                speedup = eager_ms / ms if eager_ms else float("nan")
                print(f"  {mode_name:12s}: {ms:8.4f} ms  speedup={speedup:.3f}x")
            except Exception as e:
                print(f"  {mode_name:12s}: FAILED -> {str(e)[:60]}")
        print()


if __name__ == "__main__":
    main()

Performance Rresult:

Device: cuda | Dtype: torch.float16 | Batch: 64 | Vocab: 32768

==================== var_std ====================
  Eager       :   0.0289 ms  speedup=1.000x
  Default     :   0.0866 ms  speedup=0.334x
  ReduceOH    :   0.0691 ms  speedup=0.418x
  MaxAutotune :   0.0688 ms  speedup=0.420x

Inspecting the generated output_code.py, the fused Triton kernel (e.g., triton_red_fused_std_var_0) initializes two independent Welford state machines:

tmp2_mean = tl.zeros([XBLOCK, RBLOCK], tl.float32)
tmp2_m2 = tl.zeros([XBLOCK, RBLOCK], tl.float32)

# Second set (for std)
tmp7_mean = tl.zeros([XBLOCK, RBLOCK], tl.float32)
tmp7_m2 = tl.zeros([XBLOCK, RBLOCK], tl.float32)

However, TorchInductor should detect that torch.var(x) and torch.std(x) share the same reduction statistics. The intermediate results can be computed once and reused. By manually editing the generated Triton kernel, we prove the importance of CSE:

--- Validate Correctness --- 
Correctness: Pass 

--- Test Performance --- 
Original Code Avg Latency: 0.0515 ms 
Manual CSE Code Avg Latency: 0.0411 ms 
Speedup: 20.24%
<img width="1600" height="1000" alt="Image" src="https://github.com/user-attachments/assets/7ca08b91-0d79-41c5-9b22-9421a58da773" />

I noticed that PyTorch Inductor has a design intent for CSE, but it does not seem to be well-implemented here. Is this expected behavior, or a missing optimization in TorchInductor?

Versions

PyTorch version: 2.10.0.dev20251021+cu128
Is debug build: False
CUDA used to build PyTorch: 12.8
ROCM used to build PyTorch: N/A

OS: Ubuntu 22.04.4 LTS (x86_64)
GCC version: (Ubuntu 11.4.0-1ubuntu1~22.04) 11.4.0
Clang version: Could not collect
CMake version: version 3.22.1
Libc version: glibc-2.35

Python version: 3.10.19 (main, Oct 21 2025, 16:43:05) [GCC 11.2.0] (64-bit runtime)
Python platform: Linux-6.8.0-40-generic-x86_64-with-glibc2.35
Is CUDA available: True
CUDA runtime version: 11.8.89
CUDA_MODULE_LOADING set to:
GPU models and configuration:
GPU 0: NVIDIA RTX A6000
GPU 1: NVIDIA RTX A6000

Nvidia driver version: 570.211.01
cuDNN version: Could not collect
Is XPU available: False
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):                               96
On-line CPU(s) list:                  0-95
Vendor ID:                            GenuineIntel
Model name:                           Intel(R) Xeon(R) Gold 6248R CPU @ 3.00GHz
CPU family:                           6
Model:                                85
Thread(s) per core:                   2
Core(s) per socket:                   24
Socket(s):                            2
Stepping:                             7
BogoMIPS:                             6000.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 intel_ppin ssbd mba ibrs ibpb stibp ibrs_enhanced tpr_shadow 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 vnmi pku ospke avx512_vnni md_clear flush_l1d arch_capabilities
Virtualization:                       VT-x
L1d cache:                            1.5 MiB (48 instances)
L1i cache:                            1.5 MiB (48 instances)
L2 cache:                             48 MiB (48 instances)
L3 cache:                             71.5 MiB (2 instances)
NUMA node(s):                         2
NUMA node0 CPU(s):                    0,2,4,6,8,10,12,14,16,18,20,22,24,26,28,30,32,34,36,38,40,42,44,46,48,50,52,54,56,58,60,62,64,66,68,70,72,74,76,78,80,82,84,86,88,90,92,94
NUMA node1 CPU(s):                    1,3,5,7,9,11,13,15,17,19,21,23,25,27,29,31,33,35,37,39,41,43,45,47,49,51,53,55,57,59,61,63,65,67,69,71,73,75,77,79,81,83,85,87,89,91,93,95
Vulnerability Gather data sampling:   Mitigation; Microcode
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 vulnerable
Vulnerability Reg file data sampling: Not affected
Vulnerability Retbleed:               Mitigation; Enhanced IBRS
Vulnerability Spec rstack overflow:   Not affected
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; RSB filling; PBRSB-eIBRS SW sequence; BHI SW loop, KVM SW loop
Vulnerability Srbds:                  Not affected
Vulnerability Tsx async abort:        Mitigation; TSX disabled

Versions of relevant libraries:
[pip3] numpy==2.2.6
[pip3] nvidia-cublas-cu11==11.11.3.6
[pip3] nvidia-cublas-cu12==12.8.4.1
[pip3] nvidia-cuda-cupti-cu11==11.8.87
[pip3] nvidia-cuda-cupti-cu12==12.8.90
[pip3] nvidia-cuda-nvrtc-cu11==11.8.89
[pip3] nvidia-cuda-nvrtc-cu12==12.8.93
[pip3] nvidia-cuda-runtime-cu11==11.8.89
[pip3] nvidia-cuda-runtime-cu12==12.8.90
[pip3] nvidia-cudnn-cu11==9.1.0.70
[pip3] nvidia-cudnn-cu12==9.10.2.21
[pip3] nvidia-cufft-cu11==10.9.0.58
[pip3] nvidia-cufft-cu12==11.3.3.83
[pip3] nvidia-curand-cu11==10.3.0.86
[pip3] nvidia-curand-cu12==10.3.9.90
[pip3] nvidia-cusolver-cu11==11.4.1.48
[pip3] nvidia-cusolver-cu12==11.7.3.90
[pip3] nvidia-cusparse-cu11==11.7.5.86
[pip3] nvidia-cusparse-cu12==12.5.8.93
[pip3] nvidia-cusparselt-cu12==0.7.1
[pip3] nvidia-nccl-cu11==2.21.5
[pip3] nvidia-nccl-cu12==2.27.5
[pip3] nvidia-nvjitlink-cu12==12.8.93
[pip3] nvidia-nvtx-cu11==11.8.86
[pip3] nvidia-nvtx-cu12==12.8.90
[pip3] pytorch-triton==3.5.0+git7416ffcb
[pip3] torch==2.10.0.dev20251021+cu128
[pip3] torchaudio==2.10.0.dev20251021+cu128
[pip3] torchvision==0.25.0.dev20251021+cu128
[pip3] triton==3.0.0
[conda] numpy                     2.2.6                    pypi_0    pypi
[conda] nvidia-cublas-cu11        11.11.3.6                pypi_0    pypi
[conda] nvidia-cublas-cu12        12.8.4.1                 pypi_0    pypi
[conda] nvidia-cuda-cupti-cu11    11.8.87                  pypi_0    pypi
[conda] nvidia-cuda-cupti-cu12    12.8.90                  pypi_0    pypi
[conda] nvidia-cuda-nvrtc-cu11    11.8.89                  pypi_0    pypi
[conda] nvidia-cuda-nvrtc-cu12    12.8.93                  pypi_0    pypi
[conda] nvidia-cuda-runtime-cu11  11.8.89                  pypi_0    pypi
[conda] nvidia-cuda-runtime-cu12  12.8.90                  pypi_0    pypi
[conda] nvidia-cudnn-cu11         9.1.0.70                 pypi_0    pypi
[conda] nvidia-cudnn-cu12         9.10.2.21                pypi_0    pypi
[conda] nvidia-cufft-cu11         10.9.0.58                pypi_0    pypi
[conda] nvidia-cufft-cu12         11.3.3.83                pypi_0    pypi
[conda] nvidia-curand-cu11        10.3.0.86                pypi_0    pypi
[conda] nvidia-curand-cu12        10.3.9.90                pypi_0    pypi
[conda] nvidia-cusolver-cu11      11.4.1.48                pypi_0    pypi
[conda] nvidia-cusolver-cu12      11.7.3.90                pypi_0    pypi
[conda] nvidia-cusparse-cu11      11.7.5.86                pypi_0    pypi
[conda] nvidia-cusparse-cu12      12.5.8.93                pypi_0    pypi
[conda] nvidia-cusparselt-cu12    0.7.1                    pypi_0    pypi
[conda] nvidia-nccl-cu11          2.21.5                   pypi_0    pypi
[conda] nvidia-nccl-cu12          2.27.5                   pypi_0    pypi
[conda] nvidia-nvjitlink-cu12     12.8.93                  pypi_0    pypi
[conda] nvidia-nvtx-cu11          11.8.86                  pypi_0    pypi
[conda] nvidia-nvtx-cu12          12.8.90                  pypi_0    pypi
[conda] pytorch-triton            3.5.0+git7416ffcb          pypi_0    pypi
[conda] torch                     2.10.0.dev20251021+cu128          pypi_0    pypi
[conda] torchaudio                2.10.0.dev20251021+cu128          pypi_0    pypi
[conda] torchvision               0.25.0.dev20251021+cu128          pypi_0    pypi

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

extent analysis

TL;DR

The performance issue with torch.compile can be mitigated by manually editing the generated Triton kernel to apply common subexpression elimination (CSE) and reuse intermediate results.

Guidance

  • The issue is caused by the compiled kernel introducing redundant computations that should be eliminated by CSE.
  • To fix this, manually edit the generated Triton kernel to reuse intermediate results, as demonstrated in the provided example.
  • The torch.compile function should be able to detect and eliminate common subexpressions, but it appears to be not well-implemented in this case.
  • Further investigation is needed to determine why torch.compile is not applying CSE correctly.

Example

# Manually edited Triton kernel
tmp2_mean = tl.zeros([XBLOCK, RBLOCK], tl.float32)
tmp2_m2 = tl.zeros([XBLOCK, RBLOCK], tl.float32)

# Reuse intermediate results
var = tmp2_mean
std = tmp2_m2

Notes

  • The provided example demonstrates a 20.24% speedup after applying manual CSE.
  • The issue may be specific to the torch.compile function and the generated Triton kernel.
  • Further testing and investigation are needed to determine the root cause and to develop a more robust solution.

Recommendation

Apply workaround: Manually edit the generated Triton kernel to apply CSE and reuse intermediate results, as this has been shown to improve performance in the provided example.

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