pytorch - ✅(Solved) Fix [Dynamo][Aot Compile] Builtin causes failure in AOT Compile [1 pull requests, 1 comments, 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#177556Fetched 2026-04-08 00:47:30
View on GitHub
Comments
1
Participants
1
Timeline
78
Reactions
0
Participants
Assignees
Timeline (top)
mentioned ×32subscribed ×32labeled ×5referenced ×3

Error Message

File "/home/lucaskabela/pytorch/repo.py", line 15, in <module> loaded = AOTCompiledFunction.deserialize(data.serialized_data) # RuntimeError! ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/home/lucaskabela/pytorch/torch/_dynamo/aot_compile.py", line 304, in deserialize return cls(artifacts, _extra_globals=f_globals) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "<string>", line 6, in init File "/home/lucaskabela/pytorch/torch/_dynamo/aot_compile.py", line 220, in post_init self.fn = self._artifacts.runtime_env.forward_callable( ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/home/lucaskabela/pytorch/torch/_dynamo/convert_frame.py", line 981, in forward_callable self._check_external_refs(f_globals) File "/home/lucaskabela/pytorch/torch/_dynamo/convert_frame.py", line 1001, in _check_external_refs raise RuntimeError( RuntimeError: Missing required external references: ['__builtins_dict___0']. Please load AOT compiled function with f_globals=<enclosing global scope>

Root Cause

This is because while __builtins_dict__ is installed in f_globals while tracing, it is not preserved in serialization, so using a builtin that is not folded will result in error when loading from serialization with an error like:

  File "/home/lucaskabela/pytorch/repo.py", line 15, in <module>
    loaded = AOTCompiledFunction.deserialize(data.serialized_data)  # RuntimeError!
             ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/home/lucaskabela/pytorch/torch/_dynamo/aot_compile.py", line 304, in deserialize
    return cls(artifacts, _extra_globals=f_globals)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "<string>", line 6, in __init__
  File "/home/lucaskabela/pytorch/torch/_dynamo/aot_compile.py", line 220, in __post_init__
    self.fn = self._artifacts.runtime_env.forward_callable(
              ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/home/lucaskabela/pytorch/torch/_dynamo/convert_frame.py", line 981, in forward_callable
    self._check_external_refs(f_globals)
  File "/home/lucaskabela/pytorch/torch/_dynamo/convert_frame.py", line 1001, in _check_external_refs
    raise RuntimeError(
RuntimeError: Missing required external references: ['__builtins_dict___0']. Please load AOT compiled function with `f_globals=<enclosing global scope>`

Fix Action

Fixed

PR fix notes

PR #177558: [Bugfix] Keep builtin for serialization when used in dynamo

Description (problem / solution / changelog)

Fixes https://github.com/pytorch/pytorch/issues/177556

Summary

When we have a builtin used in code dynamo is tracing that is not folded, we recieve an error when loading from the serialized function.

This is because the __builtin_dict__ which dynamo uses is not captured; so in this PR, we update to selectively capture/preserve these so that loading succeeds

Testing

python -m pytest test/dynamo/test_aot_compile.py::TestAOTCompile::test_builtins_dict_survives_serialization -xvs

Results in:

test/dynamo/test_aot_compile.py::TestAOTCompile::test_builtins_dict_survives_serialization PASSED [13.3021s]

cc @voznesenskym @penguinwu @EikanWang @jgong5 @Guobing-Chen @XiaobingSuper @zhuhaozhe @blzheng @wenzhe-nrv @jiayisunx @kadeng @chauhang @amjames @jataylo

Changed files

  • test/dynamo/test_aot_compile.py (modified, +21/-0)
  • torch/_dynamo/convert_frame.py (modified, +25/-0)

Code Example

import torch
from torch._dynamo.aot_compile import AOTCompiledFunction

torch._dynamo.config.enable_aot_compile = True

def fn(x):
    return x + 1, type

x = torch.randn(4)
compiled = torch.compile(fn, fullgraph=True, backend="inductor")
aot_fn = compiled.aot_compile(((x,), {}))

# Serialize and deserialize without passing f_globals
data = AOTCompiledFunction.serialize(aot_fn)
loaded = AOTCompiledFunction.deserialize(data.serialized_data)  # RuntimeError!
loaded_out = loaded(x)
fn_out = fn(x)
assert loaded_out[0].allclose(fn_out[0])
assert loaded_out[1] == fn_out[1]

---

File "/home/lucaskabela/pytorch/repo.py", line 15, in <module>
    loaded = AOTCompiledFunction.deserialize(data.serialized_data)  # RuntimeError!
             ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/home/lucaskabela/pytorch/torch/_dynamo/aot_compile.py", line 304, in deserialize
    return cls(artifacts, _extra_globals=f_globals)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "<string>", line 6, in __init__
  File "/home/lucaskabela/pytorch/torch/_dynamo/aot_compile.py", line 220, in __post_init__
    self.fn = self._artifacts.runtime_env.forward_callable(
              ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/home/lucaskabela/pytorch/torch/_dynamo/convert_frame.py", line 981, in forward_callable
    self._check_external_refs(f_globals)
  File "/home/lucaskabela/pytorch/torch/_dynamo/convert_frame.py", line 1001, in _check_external_refs
    raise RuntimeError(
RuntimeError: Missing required external references: ['__builtins_dict___0']. Please load AOT compiled function with `f_globals=<enclosing global scope>`
RAW_BUFFERClick to expand / collapse

🐛 Describe the bug

Given the following code, serialization will fail:

import torch
from torch._dynamo.aot_compile import AOTCompiledFunction

torch._dynamo.config.enable_aot_compile = True

def fn(x):
    return x + 1, type

x = torch.randn(4)
compiled = torch.compile(fn, fullgraph=True, backend="inductor")
aot_fn = compiled.aot_compile(((x,), {}))

# Serialize and deserialize without passing f_globals
data = AOTCompiledFunction.serialize(aot_fn)
loaded = AOTCompiledFunction.deserialize(data.serialized_data)  # RuntimeError!
loaded_out = loaded(x)
fn_out = fn(x)
assert loaded_out[0].allclose(fn_out[0])
assert loaded_out[1] == fn_out[1]

This is because while __builtins_dict__ is installed in f_globals while tracing, it is not preserved in serialization, so using a builtin that is not folded will result in error when loading from serialization with an error like:

  File "/home/lucaskabela/pytorch/repo.py", line 15, in <module>
    loaded = AOTCompiledFunction.deserialize(data.serialized_data)  # RuntimeError!
             ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/home/lucaskabela/pytorch/torch/_dynamo/aot_compile.py", line 304, in deserialize
    return cls(artifacts, _extra_globals=f_globals)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "<string>", line 6, in __init__
  File "/home/lucaskabela/pytorch/torch/_dynamo/aot_compile.py", line 220, in __post_init__
    self.fn = self._artifacts.runtime_env.forward_callable(
              ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/home/lucaskabela/pytorch/torch/_dynamo/convert_frame.py", line 981, in forward_callable
    self._check_external_refs(f_globals)
  File "/home/lucaskabela/pytorch/torch/_dynamo/convert_frame.py", line 1001, in _check_external_refs
    raise RuntimeError(
RuntimeError: Missing required external references: ['__builtins_dict___0']. Please load AOT compiled function with `f_globals=<enclosing global scope>`

Versions

Collecting environment information... PyTorch version: 2.12.0a0+gita01976a Is debug build: False CUDA used to build PyTorch: 12.9 ROCM used to build PyTorch: N/A

OS: CentOS Stream 9 (x86_64) GCC version: (GCC) 11.5.0 20240719 (Red Hat 11.5.0-14) Clang version: 21.1.7 (CentOS 21.1.7-1.el9) CMake version: version 4.2.1 Libc version: glibc-2.34

Python version: 3.12.12 | packaged by Anaconda, Inc. | (main, Oct 21 2025, 20:16:04) [GCC 11.2.0] (64-bit runtime) Python platform: Linux-6.13.2-0_fbk8_0_g8695f611147d-x86_64-with-glibc2.34 Is CUDA available: True CUDA runtime version: 12.9.86 CUDA_MODULE_LOADING set to: GPU models and configuration: GPU 0: NVIDIA H100 GPU 1: NVIDIA H100 GPU 2: NVIDIA H100 GPU 3: NVIDIA H100 GPU 4: NVIDIA H100 GPU 5: NVIDIA H100 GPU 6: NVIDIA H100 GPU 7: NVIDIA H100

Nvidia driver version: 580.82.07 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: 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 9654 96-Core Processor CPU family: 25 Model: 17 Thread(s) per core: 2 Core(s) per socket: 96 Socket(s): 2 Stepping: 1 Frequency boost: enabled CPU(s) scaling MHz: 100% CPU max MHz: 2400.0000 CPU min MHz: 1500.0000 BogoMIPS: 4792.60 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 xtopology 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 avx512_bf16 clzero irperf xsaveerptr rdpru wbnoinvd amd_ppin cppc 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 rdpid overflow_recov succor smca fsrm flush_l1d debug_swap Virtualization: AMD-V L1d cache: 6 MiB (192 instances) L1i cache: 6 MiB (192 instances) L2 cache: 192 MiB (192 instances) L3 cache: 768 MiB (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: Vulnerable Vulnerability Spec store bypass: Vulnerable Vulnerability Spectre v1: Vulnerable: __user pointer sanitization and usercopy barriers only; no swapgs barriers Vulnerability Spectre v2: Vulnerable; IBPB: disabled; STIBP: disabled; PBRSB-eIBRS: Not affected; BHI: Not affected Vulnerability Srbds: Not affected Vulnerability Tsx async abort: Not affected

Versions of relevant libraries: [pip3] flake8==7.3.0 [pip3] mypy==1.19.1 [pip3] mypy_extensions==1.1.0 [pip3] numpy==2.2.6 [pip3] nvidia-cublas-cu12==12.8.4.1 [pip3] nvidia-cuda-cupti-cu12==12.8.90 [pip3] nvidia-cuda-nvrtc-cu12==12.8.93 [pip3] nvidia-cuda-runtime-cu12==12.8.90 [pip3] nvidia-cudnn-cu12==9.10.2.21 [pip3] nvidia-cudnn-frontend==1.17.0 [pip3] nvidia-cufft-cu12==11.3.3.83 [pip3] nvidia-curand-cu12==10.3.9.90 [pip3] nvidia-cusolver-cu12==11.7.3.90 [pip3] nvidia-cusparse-cu12==12.5.8.93 [pip3] nvidia-cusparselt-cu12==0.7.1 [pip3] nvidia-nccl-cu12==2.27.5 [pip3] nvidia-nvjitlink-cu12==12.8.93 [pip3] nvidia-nvtx-cu12==12.8.90 [pip3] optree==0.18.0 [pip3] torch==2.12.0a0+gita01976a [pip3] torch_c_dlpack_ext==0.1.5 [pip3] torchdata==0.11.0 [pip3] torchmonarch==0.3.0 [pip3] torchtitan==0.2.2 [pip3] torchvision==0.26.0a0+4729419 [pip3] torchx-nightly==2026.1.26 [pip3] triton==3.5.1 [conda] numpy 2.2.6 pypi_0 pypi [conda] nvidia-cublas-cu12 12.8.4.1 pypi_0 pypi [conda] nvidia-cuda-cupti-cu12 12.8.90 pypi_0 pypi [conda] nvidia-cuda-nvrtc-cu12 12.8.93 pypi_0 pypi [conda] nvidia-cuda-runtime-cu12 12.8.90 pypi_0 pypi [conda] nvidia-cudnn-cu12 9.10.2.21 pypi_0 pypi [conda] nvidia-cudnn-frontend 1.17.0 pypi_0 pypi [conda] nvidia-cufft-cu12 11.3.3.83 pypi_0 pypi [conda] nvidia-curand-cu12 10.3.9.90 pypi_0 pypi [conda] nvidia-cusolver-cu12 11.7.3.90 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-cu12 2.27.5 pypi_0 pypi [conda] nvidia-nvjitlink-cu12 12.8.93 pypi_0 pypi [conda] nvidia-nvtx-cu12 12.8.90 pypi_0 pypi [conda] optree 0.18.0 pypi_0 pypi [conda] torch 2.12.0a0+gita01976a pypi_0 pypi [conda] torch-c-dlpack-ext 0.1.5 pypi_0 pypi [conda] torchdata 0.11.0 pypi_0 pypi [conda] torchmonarch 0.3.0 pypi_0 pypi [conda] torchtitan 0.2.2 pypi_0 pypi [conda] torchvision 0.26.0a0+4729419 pypi_0 pypi [conda] torchx-nightly 2026.1.26 pypi_0 pypi [conda] triton 3.5.1 pypi_0 pypi

cc @mruberry @mikaylagawarecki @voznesenskym @penguinwu @EikanWang @jgong5 @Guobing-Chen @XiaobingSuper @zhuhaozhe @blzheng @wenzhe-nrv @jiayisunx @kadeng @chauhang @amjames @jataylo

extent analysis

Fix Plan

To fix the serialization issue, you need to pass the f_globals when deserializing the AOTCompiledFunction.

Here are the steps:

  • When serializing the AOTCompiledFunction, also store the f_globals used during compilation.
  • When deserializing, pass the stored f_globals to the deserialize method.

Example code:

import torch
from torch._dynamo.aot_compile import AOTCompiledFunction

torch._dynamo.config.enable_aot_compile = True

def fn(x):
    return x + 1, type

x = torch.randn(4)
compiled = torch.compile(fn, fullgraph=True, backend="inductor")
aot_fn = compiled.aot_compile(((x,), {}))

# Serialize and deserialize with f_globals
data = AOTCompiledFunction.serialize(aot_fn)
f_globals = globals()  # Store the f_globals
loaded = AOTCompiledFunction.deserialize(data.serialized_data, f_globals=f_globals)

loaded_out = loaded(x)
fn_out = fn(x)
assert loaded_out[0].allclose(fn_out[0])
assert loaded_out[1] == fn_out[1]

Verification

After applying the fix, verify that the deserialization works correctly and the output of the original function and the deserialized function are the same.

Extra Tips

  • Make sure to store the correct f_globals during serialization.
  • When deserializing, use the same f_globals that were used during serialization.
  • This fix assumes that the f_globals are available during deserialization. If the f_globals are not available, you may need to modify the serialization process to store the required information.

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