pytorch - 💡(How to fix) Fix torch.compile (Inductor) generates invalid C++ kernel: tmp8 used outside its declared scope when torch.gather index is a self-referential expression [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#181621Fetched 2026-04-28 06:24:26
View on GitHub
Comments
0
Participants
1
Timeline
179
Reactions
0
Participants
Timeline (top)
mentioned ×75subscribed ×75unsubscribed ×23labeled ×6

Error Message

error: 'tmp8' was not declared in this scope

Compiled: crashes with C++ compile error

Error logs

Traceback (most recent call last): torch._inductor.exc.InductorError: CppCompileError: C++ compile error /tmp/inductor_kd03_cpe/oh/cohy4mewes36pu2n2iphi2zialu6dxbh6ptfjrhl5eyrutlbtgqx.main.cpp:78:151: error: ‘tmp8’ was not declared in this scope ... (total error log cannot fit in

Fix Action

Fix / Workaround

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

Code Example

import torch
import torch.nn as nn

_m_linear = nn.Linear(13, 29)

torch.manual_seed(0)
x = torch.randn([14, 15, 5, 13])

def model():
    out = _m_linear(x)
    idx = (torch.abs(out) * 5).long().clamp(0, 4)
    out = torch.gather(out, 2, idx)
    return out

# Eager: works fine
eager_out = model()

# Compiled: crashes with C++ compile error
compiled = torch.compile(model, backend='inductor')
compiled_out = compiled()
RAW_BUFFERClick to expand / collapse

🐛 Describe the bug

When compiling a model that uses torch.gather with a dynamically computed index derived from the same tensor being gathered (e.g., (torch.abs(x) * 5).long().clamp(0, 4)), the Inductor C++ backend emits a kernel where an intermediate variable (tmp8) is referenced in a transpose_mxn call that falls outside the scope in which tmp8 was declared. This causes the C++ compilation step to fail with:

error: 'tmp8' was not declared in this scope The eager forward pass runs correctly; only torch.compile(..., backend='inductor') fails. Minimal Reproducer:

import torch
import torch.nn as nn

_m_linear = nn.Linear(13, 29)

torch.manual_seed(0)
x = torch.randn([14, 15, 5, 13])

def model():
    out = _m_linear(x)
    idx = (torch.abs(out) * 5).long().clamp(0, 4)
    out = torch.gather(out, 2, idx)
    return out

# Eager: works fine
eager_out = model()

# Compiled: crashes with C++ compile error
compiled = torch.compile(model, backend='inductor')
compiled_out = compiled()

Error logs

Traceback (most recent call last): File "/home/bugs/crash_eef68041.py", line 34, in <module> _compiled_out = _compiled() File "/home/.venv/lib/python3.10/site-packages/torch/_dynamo/eval_frame.py", line 1038, in compile_wrapper raise e.remove_dynamo_frames() from None # see TORCHDYNAMO_VERBOSE=1 File "/home/.venv/lib/python3.10/site-packages/torch/_inductor/compile_fx.py", line 1053, in _compile_fx_inner raise InductorError(e, currentframe()).with_traceback( File "/home/.venv/lib/python3.10/site-packages/torch/_inductor/compile_fx.py", line 1037, in _compile_fx_inner mb_compiled_graph = fx_codegen_and_compile( File "/home/.venv/lib/python3.10/site-packages/torch/_inductor/compile_fx.py", line 1798, in fx_codegen_and_compile return scheme.codegen_and_compile(gm, example_inputs, inputs_to_check, graph_kwargs) File "/home/.venv/lib/python3.10/site-packages/torch/_inductor/compile_fx.py", line 1570, in codegen_and_compile compiled_module = graph.compile_to_module() File "/home/.venv/lib/python3.10/site-packages/torch/_inductor/graph.py", line 2499, in compile_to_module return self._compile_to_module() File "/home/.venv/lib/python3.10/site-packages/torch/_inductor/graph.py", line 2509, in _compile_to_module mod = self._compile_to_module_lines(wrapper_code) File "/home/.venv/lib/python3.10/site-packages/torch/_inductor/graph.py", line 2584, in _compile_to_module_lines mod = PyCodeCache.load_by_key_path( File "/home/.venv/lib/python3.10/site-packages/torch/_inductor/codecache.py", line 3764, in load_by_key_path mod = _reload_python_module(key, path, set_sys_modules=in_toplevel) File "/home/.venv/lib/python3.10/site-packages/torch/_inductor/runtime/compile_tasks.py", line 35, in _reload_python_module exec(code, mod.dict, mod.dict) File "/tmp/inductor_kd03_cpe/y2/cy25abnhwjhz2vzoq4owmjlwyfpq2degivjdawmlfdpxrau76qfx.py", line 313, in <module> async_compile.wait(globals()) File "/home/.venv/lib/python3.10/site-packages/torch/_inductor/async_compile.py", line 699, in wait self._wait_futures(scope) File "/home/.venv/lib/python3.10/site-packages/torch/_inductor/async_compile.py", line 719, in _wait_futures kernel = result.result() File "/home/.venv/lib/python3.10/site-packages/torch/_inductor/codecache.py", line 4361, in result return self.result_fn() File "/home/.venv/lib/python3.10/site-packages/torch/_inductor/codecache.py", line 3237, in future result = get_result() File "/home/.venv/lib/python3.10/site-packages/torch/_inductor/codecache.py", line 3020, in load_fn future.result() File "/usr/lib/python3.10/concurrent/futures/_base.py", line 451, in result return self.__get_result() File "/usr/lib/python3.10/concurrent/futures/_base.py", line 403, in __get_result raise self._exception File "/usr/lib/python3.10/concurrent/futures/thread.py", line 58, in run result = self.fn(*self.args, **self.kwargs) File "/home/.venv/lib/python3.10/site-packages/torch/_inductor/codecache.py", line 3050, in _worker_compile_cpp builder.build() File "/home/.venv/lib/python3.10/site-packages/torch/_inductor/cpp_builder.py", line 2146, in build run_compile_cmd(build_cmd, cwd=_build_tmp_dir) File "/home/.venv/lib/python3.10/site-packages/torch/_inductor/cpp_builder.py", line 638, in run_compile_cmd _run_compile_cmd(cmd_line, cwd) File "/home/.venv/lib/python3.10/site-packages/torch/_inductor/cpp_builder.py", line 633, in _run_compile_cmd raise exc.CppCompileError(cmd, output) from e torch._inductor.exc.InductorError: CppCompileError: C++ compile error

Command: g++ /tmp/inductor_kd03_cpe/oh/cohy4mewes36pu2n2iphi2zialu6dxbh6ptfjrhl5eyrutlbtgqx.main.cpp -D TORCH_INDUCTOR_CPP_WRAPPER -D STANDALONE_TORCH_HEADER -D C10_USING_CUSTOM_GENERATED_MACROS -D CPU_CAPABILITY_AVX512 -O3 -DNDEBUG -fno-trapping-math -funsafe-math-optimizations -ffinite-math-only -fno-signed-zeros -fno-math-errno -fno-finite-math-only -fno-unsafe-math-optimizations -ffp-contract=off -fexcess-precision=fast -fno-tree-loop-vectorize -march=native -shared -fPIC -Wall -std=c++17 -Wno-unused-variable -Wno-unknown-pragmas -pedantic -fopenmp -include /tmp/torchinductor_/precompiled_headers/cl4bqkys72ys3rmj2qmq5cpo3mccbh7c3mvomoxggavvr4izorg3.h -I/usr/include/python3.10 -I/home/.venv/lib/python3.10/site-packages/torch/include -I/home/.venv/lib/python3.10/site-packages/torch/include/torch/csrc/api/include -mavx512f -mavx512dq -mavx512vl -mavx512bw -mfma -mavx512vnni -mavx512vl -o /tmp/inductor_kd03_cpe/oh/cohy4mewes36pu2n2iphi2zialu6dxbh6ptfjrhl5eyrutlbtgqx.main.so -ltorch -ltorch_cpu -ltorch_python -lgomp -L/usr/lib/x86_64-linux-gnu -L/home/.venv/lib/python3.10/site-packages/torch/lib

Output: /tmp/inductor_kd03_cpe/oh/cohy4mewes36pu2n2iphi2zialu6dxbh6ptfjrhl5eyrutlbtgqx.main.cpp: In function ‘void kernel(const float*, int64_t*, float*)’: /tmp/inductor_kd03_cpe/oh/cohy4mewes36pu2n2iphi2zialu6dxbh6ptfjrhl5eyrutlbtgqx.main.cpp:78:151: error: ‘tmp8’ was not declared in this scope 78 | transpose_mxn<float,static_cast<int64_t>(15L),static_cast<int64_t>(16),false>(in_ptr0 + static_cast<int64_t>(x2 + 29Ltmp8 + 145Lx3 + 2175L*x0), static_cast<int64_t>(145L), tmp12, static_cast<int64_t>(15L)); |
... (total error log cannot fit in

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 ([email protected]: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 @chauhang @penguinwu

extent analysis

TL;DR

The issue can be worked around by avoiding the use of torch.compile with the inductor backend for models that utilize torch.gather with dynamically computed indices.

Guidance

  • The error occurs due to the Inductor C++ backend incorrectly referencing an intermediate variable tmp8 outside its scope when compiling a model with torch.gather and dynamic indices.
  • To verify the issue, try running the model without compilation using torch.compile and check if it runs correctly.
  • As a temporary workaround, avoid using torch.compile with the inductor backend for affected models or consider using an alternative backend.
  • The root cause of the issue seems to be related to the Inductor backend's handling of dynamic indices in torch.gather, which may require updates to the PyTorch or Inductor codebase to fix.

Example

No code example is provided as the issue is related to a specific PyTorch backend and requires changes to the backend or workaround in the model code.

Notes

This workaround may not be applicable to all use cases, especially those relying on the performance benefits of torch.compile with the inductor backend. The issue highlights the need for careful testing of models with different backends and compilation settings.

Recommendation

Apply workaround: Avoid using torch.compile with the inductor backend for models that utilize torch.gather with dynamically computed indices until the issue is resolved in the Inductor backend.

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

pytorch - 💡(How to fix) Fix torch.compile (Inductor) generates invalid C++ kernel: tmp8 used outside its declared scope when torch.gather index is a self-referential expression [1 participants]