pytorch - ✅(Solved) Fix [torch.compile] GuardManager destructor may segfault during interpreter shutdown when recursive dict-tag cleanup touches a freed PyCapsule [1 pull requests, 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#178224Fetched 2026-04-08 01:21:09
View on GitHub
Comments
0
Participants
1
Timeline
48
Reactions
0
Author
Participants
Assignees
Timeline (top)
mentioned ×18subscribed ×18labeled ×9assigned ×1

Root Cause

Why this seems to be the root cause:

Fix Action

Fix / Workaround

CPU: Architecture: x86_64 CPU op-mode(s): 32-bit, 64-bit Address sizes: 46 bits physical, 57 bits virtual Byte Order: Little Endian CPU(s): 112 On-line CPU(s) list: 0-111 Vendor ID: GenuineIntel Model name: Intel(R) Xeon(R) Gold 6330 CPU @ 2.00GHz CPU family: 6 Model: 106 Thread(s) per core: 2 Core(s) per socket: 28 Socket(s): 2 Stepping: 6 Frequency boost: enabled CPU max MHz: 3100.0000 CPU min MHz: 800.0000 BogoMIPS: 4000.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 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 invpcid_single ssbd mba ibrs ibpb stibp ibrs_enhanced tpr_shadow vnmi flexpriority ept vpid ept_ad fsgsbase tsc_adjust bmi1 avx2 smep bmi2 erms invpcid cqm rdt_a avx512f avx512dq rdseed adx smap avx512ifma clflushopt clwb intel_pt avx512cd sha_ni avx512bw avx512vl xsaveopt xsavec xgetbv1 xsaves cqm_llc cqm_occup_llc cqm_mbm_total cqm_mbm_local wbnoinvd dtherm ida arat pln pts avx512vbmi umip pku ospke avx512_vbmi2 gfni vaes vpclmulqdq avx512_vnni avx512_bitalg tme avx512_vpopcntdq rdpid md_clear pconfig flush_l1d arch_capabilities Virtualization: VT-x L1d cache: 2.6 MiB (56 instances) L1i cache: 1.8 MiB (56 instances) L2 cache: 70 MiB (56 instances) L3 cache: 84 MiB (2 instances) NUMA node(s): 2 NUMA node0 CPU(s): 0-27,56-83 NUMA node1 CPU(s): 28-55,84-111 Vulnerability Gather data sampling: Mitigation; Microcode Vulnerability Itlb multihit: Not affected Vulnerability L1tf: Not affected Vulnerability Mds: Not affected Vulnerability Meltdown: Not affected Vulnerability Mmio stale data: Mitigation; Clear CPU buffers; SMT vulnerable Vulnerability Retbleed: Not affected Vulnerability Spec store bypass: Mitigation; Speculative Store Bypass disabled via prctl and seccomp Vulnerability Spectre v1: Mitigation; usercopy/swapgs barriers and __user pointer sanitization Vulnerability Spectre v2: Mitigation; Enhanced IBRS, IBPB conditional, RSB filling, PBRSB-eIBRS SW sequence Vulnerability Srbds: Not affected Vulnerability Tsx async abort: Not affected

PR fix notes

PR #178231: [dynamo] Make GuardManager destructor safe during interpreter finalization

Description (problem / solution / changelog)

#178224 Summary

This PR fixes a shutdown-time crash in Dynamo guard cleanup when GuardManager destruction happens after Python has already started interpreter finalization.

Root cause

GuardManager stores weakref/capsule pairs for recursive dict-tag optimization and cleans them up in the destructor.

During normal runtime, destructor cleanup assumes the associated Python objects are still valid:

the weakref callback still owns a live capsule destructor-time cleanup can safely call Python C API dict watcher registrations can still be removed normally That assumption does not always hold during interpreter shutdown.

During Py_Finalize / Py_FinalizeEx, CPython may clear weakrefs and tear down the callback/capsule chain before the corresponding C++ GuardManager is destroyed. If the destructor later calls Python C API on those objects, it can observe freed Python objects and crash.

What this PR changes

Hold an explicit strong reference to the callback capsule while it is stored in _tag_safe_entries register_weakref_callback now Py_INCREFs the capsule before storing it cleanup_tag_safe_entries releases that reference with Py_DECREF Make GuardManager destructor shutdown-safe if Python is no longer initialized or is already finalizing, destructor cleanup skips Python C API entirely in that case we only clear local C++ containers and mark dict-tag matching as disabled Preserve full runtime cleanup behavior outside interpreter finalization, destructor still performs normal cleanup if destruction happens on a thread without the GIL, it acquires the GIL first this keeps the existing cleanup semantics, including dict watcher unregistration on Python 3.12+ Why this shape

The important distinction is between:

interpreter finalization, where Python-side objects may already be torn down and Python C API is no longer safe in destructor cleanup normal runtime destruction without the GIL, where we still want full cleanup rather than silently skipping it Without that distinction, skipping cleanup whenever the current thread lacks the GIL can leave watcher bookkeeping behind during normal execution.

Behavioral impact

normal runtime behavior is preserved shutdown-time cleanup becomes defensive and avoids touching Python objects after finalization has started this prevents crashes caused by destructor-time access to stale weakref/capsule state Files changed

torch/csrc/dynamo/guards.cpp Testing

This change was validated against the reported shutdown crash scenario and by checking that the edited file has no new static errors.

I have not added a dedicated regression test in this PR yet because the failure is shutdown-order dependent and can be difficult to minimize into a deterministic standalone reproducer.

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

Changed files

  • torch/csrc/dynamo/guards.cpp (modified, +108/-15)
RAW_BUFFERClick to expand / collapse

🐛 Describe the bug

When recursive dict-tag optimization is enabled in Dynamo guards, GuardManager stores weakref / capsule pairs in _tag_safe_entries and later cleans them up in GuardManager destructor.

During normal runtime, the destructor path assumes the following order:

GuardManager destructor -> cleanup_tag_safe_entries() -> PyCapsule_SetName(...) -> Py_CLEAR(weakref) -> capsule is still valid during cleanup -> Python shutdown happens later

That ordering is usually fine during normal execution.

However, during interpreter shutdown, this assumption no longer holds. In Py_Finalize / Py_FinalizeEx, Python GC may clear weakrefs first, which can decref the weakref callback and then decref/free the capsule before GuardManager is destroyed. If GuardManager destructor runs afterwards, cleanup_tag_safe_entries() may call PyCapsule_IsValid on a dangling PyObject pointer and crash with SIGSEGV.

A representative failing order is:

Py_FinalizeEx -> GC target -> clear weakrefs -> DECREF(py_cb) -> DECREF(capsule) -> capsule is freed -> GuardManager destructor -> cleanup_tag_safe_entries() -> PyCapsule_IsValid(e.cap) -> SIGSEGV

Why this seems to be the root cause:

GuardManager destructor always runs Python-side cleanup through cleanup_tag_safe_entries() and disable_recursive_dict_tag_optimization(). cleanup_tag_safe_entries() calls Python C API on entries stored in _tag_safe_entries. In the original code, GuardManager kept a strong reference to the weakref object, but only kept a raw pointer to the capsule after ownership had effectively been transferred into the weakref callback chain. If interpreter shutdown clears the weakref / callback chain before GuardManager destruction, e.cap becomes dangling and later Python C API access can segfault. This becomes easier to hit as the number of guards grows, because more _tag_safe_entries means a higher chance that shutdown ordering exposes a stale capsule pointer.

Observed behavior

The process may crash with SIGSEGV in GuardManager destructor during interpreter shutdown, typically around cleanup_tag_safe_entries() / PyCapsule_IsValid(e.cap).

Expected behavior

Interpreter shutdown should not crash even if some GuardManager instances outlive Python objects involved in recursive dict-tag optimization. Destructor-time cleanup should not call Python C API on Python objects that may already have been freed during finalization.

Local fix that resolved it for me

I fixed this locally with two changes:

Hold an explicit strong reference to the capsule while it is stored in _tag_safe_entries, and DECREF it during normal destructor cleanup. In GuardManager destructor, if Python is finalizing or the current thread does not hold the GIL, skip Python C API cleanup and only clear the C++ containers / disable the optimization state. This intentionally avoids destructor-time Python cleanup during interpreter teardown, but it prevents dereferencing freed Python objects after finalization has started.

Reproducer

I do not yet have a minimized standalone Python reproducer.

In our environment, this becomes much more likely when the number of guards increases, especially when recursive dict-tag optimization is active. The crash is observed during interpreter shutdown rather than during normal runtime.

Versions

Collecting environment information... PyTorch version: 2.10.0+cpu Is debug build: False CUDA used to build PyTorch: 4.6.2 ROCM used to build PyTorch: N/A

OS: Ubuntu 22.04.5 LTS (x86_64) GCC version: (Ubuntu 11.4.0-1ubuntu1~22.04) 11.4.0 Clang version: 14.0.0-1ubuntu1.1 CMake version: version 4.2.3 Libc version: glibc-2.35

Python version: 3.10.12 (main, May 27 2025, 17:12:29) [GCC 11.4.0] (64-bit runtime) Python platform: Linux-5.4.0-172-generic-x86_64-with-glibc2.35 Is CUDA available: True CUDA runtime version: Could not collect CUDA_MODULE_LOADING set to: GPU models and configuration: Could not collect Nvidia driver version: Could not collect 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: 46 bits physical, 57 bits virtual Byte Order: Little Endian CPU(s): 112 On-line CPU(s) list: 0-111 Vendor ID: GenuineIntel Model name: Intel(R) Xeon(R) Gold 6330 CPU @ 2.00GHz CPU family: 6 Model: 106 Thread(s) per core: 2 Core(s) per socket: 28 Socket(s): 2 Stepping: 6 Frequency boost: enabled CPU max MHz: 3100.0000 CPU min MHz: 800.0000 BogoMIPS: 4000.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 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 invpcid_single ssbd mba ibrs ibpb stibp ibrs_enhanced tpr_shadow vnmi flexpriority ept vpid ept_ad fsgsbase tsc_adjust bmi1 avx2 smep bmi2 erms invpcid cqm rdt_a avx512f avx512dq rdseed adx smap avx512ifma clflushopt clwb intel_pt avx512cd sha_ni avx512bw avx512vl xsaveopt xsavec xgetbv1 xsaves cqm_llc cqm_occup_llc cqm_mbm_total cqm_mbm_local wbnoinvd dtherm ida arat pln pts avx512vbmi umip pku ospke avx512_vbmi2 gfni vaes vpclmulqdq avx512_vnni avx512_bitalg tme avx512_vpopcntdq rdpid md_clear pconfig flush_l1d arch_capabilities Virtualization: VT-x L1d cache: 2.6 MiB (56 instances) L1i cache: 1.8 MiB (56 instances) L2 cache: 70 MiB (56 instances) L3 cache: 84 MiB (2 instances) NUMA node(s): 2 NUMA node0 CPU(s): 0-27,56-83 NUMA node1 CPU(s): 28-55,84-111 Vulnerability Gather data sampling: Mitigation; Microcode Vulnerability Itlb multihit: Not affected Vulnerability L1tf: Not affected Vulnerability Mds: Not affected Vulnerability Meltdown: Not affected Vulnerability Mmio stale data: Mitigation; Clear CPU buffers; SMT vulnerable Vulnerability Retbleed: Not affected Vulnerability Spec store bypass: Mitigation; Speculative Store Bypass disabled via prctl and seccomp Vulnerability Spectre v1: Mitigation; usercopy/swapgs barriers and __user pointer sanitization Vulnerability Spectre v2: Mitigation; Enhanced IBRS, IBPB conditional, RSB filling, PBRSB-eIBRS SW sequence Vulnerability Srbds: Not affected Vulnerability Tsx async abort: Not affected

Versions of relevant libraries: [pip3] mypy_extensions==1.1.0 [pip3] numpy==1.26.4 [pip3] optree==0.19.0 [pip3] torch==2.10.0+cpu [pip3] torch_mlu==1.31.1+torch2.10.0 [pip3] torch_mlu_ci_overrides==0.0.2 [pip3] torch_mlu_ops==1.10.1+torch2.10.0 [pip3] torchaudio==2.10.0+cpu [pip3] torchvision==0.25.0+cpu [pip3] triton==3.2.0+mlu1.7.6 [conda] Could not collect

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

extent analysis

Fix Plan

To fix the issue, we need to hold an explicit strong reference to the capsule while it is stored in _tag_safe_entries and decrement the reference count during normal destructor cleanup. Additionally, we should skip Python C API cleanup in the GuardManager destructor if Python is finalizing or the current thread does not hold the GIL.

Here are the concrete steps:

  • Hold a strong reference to the capsule:
// In GuardManager constructor
PyObject* capsule = ...;
Py_INCREF(capsule); // Increment reference count
_tag_safe_entries.push_back(std::make_pair(weakref, capsule));
  • Decrement the reference count during normal destructor cleanup:
// In GuardManager destructor (normal cleanup path)
for (auto& entry : _tag_safe_entries) {
    Py_DECREF(entry.second); // Decrement reference count
}
  • Skip Python C API cleanup during interpreter shutdown:
// In GuardManager destructor
if (Py_IsFinalizing() || !PyGILState_Check()) {
    // Skip Python C API cleanup
    _tag_safe_entries.clear();
    disable_recursive_dict_tag_optimization();
    return;
}

Verification

To verify that the fix worked, you can test the following scenarios:

  • Run the program with a large number of guards and recursive dict-tag optimization enabled.
  • Verify that the program does not crash during interpreter shutdown.
  • Use a debugger to step through the GuardManager destructor and verify that the capsule reference count is decremented correctly.

Extra Tips

To prevent similar issues in the future, make sure to:

  • Always hold strong references to Python objects that need to be accessed during cleanup.
  • Use Py_INCREF and Py_DECREF to manage reference counts correctly.
  • Check for Py_IsFinalizing() and PyGILState_Check() in destructors to skip Python C API cleanup during interpreter shutdown.

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 - ✅(Solved) Fix [torch.compile] GuardManager destructor may segfault during interpreter shutdown when recursive dict-tag cleanup touches a freed PyCapsule [1 pull requests, 1 participants]