pytorch - ✅(Solved) Fix [dynamo] bool() on user-defined objects mishandles __bool__=None, non-bool returns, and negative __len__ [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#181101Fetched 2026-04-23 07:22:39
View on GitHub
Comments
0
Participants
1
Timeline
69
Reactions
0
Participants
Timeline (top)
mentioned ×32subscribed ×32labeled ×4cross-referenced ×1

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): 160 On-line CPU(s) list: 0-159 Vendor ID: GenuineIntel Model name: Intel Xeon Processor (SapphireRapids) CPU family: 6 Model: 143 Thread(s) per core: 2 Core(s) per socket: 40 Socket(s): 2 Stepping: 4 BogoMIPS: 4200.00 Flags: fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush mmx fxsr sse sse2 ss ht syscall nx pdpe1gb rdtscp lm constant_tsc rep_good nopl xtopology cpuid tsc_known_freq pni pclmulqdq vmx ssse3 fma cx16 pcid sse4_1 sse4_2 x2apic movbe popcnt tsc_deadline_timer aes xsave avx f16c rdrand hypervisor lahf_lm abm 3dnowprefetch cpuid_fault ssbd ibrs ibpb stibp ibrs_enhanced tpr_shadow flexpriority ept vpid ept_ad fsgsbase tsc_adjust bmi1 avx2 smep bmi2 erms invpcid avx512f avx512dq rdseed adx smap avx512ifma clflushopt clwb avx512cd sha_ni avx512bw avx512vl xsaveopt xsavec xgetbv1 xsaves avx_vnni avx512_bf16 wbnoinvd arat vnmi avx512vbmi umip pku ospke waitpkg avx512_vbmi2 gfni vaes vpclmulqdq avx512_vnni avx512_bitalg avx512_vpopcntdq la57 rdpid bus_lock_detect cldemote movdiri movdir64b fsrm md_clear serialize tsxldtrk amx_bf16 avx512_fp16 amx_tile amx_int8 arch_capabilities Virtualization: VT-x Hypervisor vendor: KVM Virtualization type: full L1d cache: 5 MiB (160 instances) L1i cache: 5 MiB (160 instances) L2 cache: 320 MiB (80 instances) L3 cache: 32 MiB (2 instances) NUMA node(s): 2 NUMA node0 CPU(s): 0-79 NUMA node1 CPU(s): 80-159 Vulnerability Gather data sampling: Not affected Vulnerability Indirect target selection: Mitigation; Aligned branch/return thunks Vulnerability Itlb multihit: Not affected Vulnerability L1tf: Not affected Vulnerability Mds: Not affected Vulnerability Meltdown: Not affected 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: 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; PBRSB-eIBRS SW sequence; BHI SW loop, KVM SW loop Vulnerability Srbds: Not affected Vulnerability Tsx async abort: Not affected

PR fix notes

PR #181104: [dynamo] Fix bool() edge cases for bool=None, bad returns, negati…

Description (problem / solution / changelog)

Fixes #181101

bool() on user-defined objects had three gaps vs CPython:

  • bool = None silently fell through to len instead of raising TypeError, because the old lookup couldn't distinguish "missing" from "explicitly None". Switched to lookup_class_mro_attr which uses a sentinel for missing attrs.
  • bool returning non-bool (like self) bypassed validation when the result wasn't a python constant. Now uses python_type() which works on all VariableTrackers.
  • Negative len returned False instead of raising ValueError. Also bool() on constants that raise was unhandled.

NOTE: This touches code recently refactored in #179114 by @azahed98 (nb_bool tp_slot implementation). The generic_bool resolution order and type_implements_nb_bool gate from that PR are preserved. Changes here only improve edge-case handling inside bool_impl and the constant/length paths. I have tried to keep it close to CPython semantics and original tp_slot refactor implementation and ensure no new regressions got added.

Test plan

python test/dynamo/test_nb_bool.py -v
python test/dynamo/test_misc.py -v -k "test_if_cond_user_defined_object_returns_self or test_bool_user_defined_object_raises_typeerror"
PYTORCH_TEST_WITH_DYNAMO=1 pytest test/dynamo/cpython/3_13/test_bool.py::BoolTest::test_blocked test/dynamo/cpython/3_13/test_bool.py::BoolTest::test_convert_to_bool -v
PYTORCH_TEST_WITH_DYNAMO=1 pytest test/dynamo/cpython/3_13/test_bool.py -v
python test/dynamo/test_misc.py
python test/dynamo/test_repros.py

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

Changed files

  • test/dynamo/test_nb_bool.py (modified, +31/-0)
  • test/dynamo_expected_failures/CPython313-test_bool-BoolTest.test_blocked (removed, +0/-0)
  • test/dynamo_expected_failures/CPython313-test_bool-BoolTest.test_convert_to_bool (removed, +0/-0)
  • torch/_dynamo/variables/object_protocol.py (modified, +10/-2)
  • torch/_dynamo/variables/user_defined.py (modified, +13/-14)

Code Example

PYTORCH_TEST_WITH_DYNAMO=1 pytest \
  test/dynamo/cpython/3_13/test_bool.py::BoolTest::test_convert_to_bool \
  test/dynamo/cpython/3_13/test_bool.py::BoolTest::test_blocked
RAW_BUFFERClick to expand / collapse

🐛 Describe the bug

Dynamo's bool() / PyObject_IsTrue emulation does not match CPython semantics in three edge cases involving user-defined objects. These cause wrong results or missing exceptions where CPython would raise TypeError or ValueError.

Failing CPython 3.13 conformance tests:

PYTORCH_TEST_WITH_DYNAMO=1 pytest \
  test/dynamo/cpython/3_13/test_bool.py::BoolTest::test_convert_to_bool \
  test/dynamo/cpython/3_13/test_bool.py::BoolTest::test_blocked

Versions

Collecting environment information... PyTorch version: 2.13.0a0+git3d1e839 Is debug build: False CUDA used to build PyTorch: 12.8 ROCM used to build PyTorch: N/A

OS: Fedora Linux 41 (Container Image) (x86_64) GCC version: (GCC) 14.3.1 20251022 (Red Hat 14.3.1-4) Clang version: Could not collect CMake version: version 4.3.1 Libc version: glibc-2.40

Python version: 3.13.9 (main, Oct 14 2025, 00:00:00) [GCC 14.3.1 20250808 (Red Hat 14.3.1-3)] (64-bit runtime) Python platform: Linux-5.14.0-615.el9.x86_64-x86_64-with-glibc2.40 Is CUDA available: True CUDA runtime version: 12.8.93 CUDA_MODULE_LOADING set to: GPU models and configuration: GPU 0: NVIDIA H200 GPU 1: NVIDIA H200 GPU 2: NVIDIA H200 GPU 3: NVIDIA H200 GPU 4: NVIDIA H200 GPU 5: NVIDIA H200 GPU 6: NVIDIA H200 GPU 7: NVIDIA H200

Nvidia driver version: 580.82.07 cuDNN version: Probably one of the following: /usr/local/cuda-12.8/targets/x86_64-linux/lib/libcudnn.so.9.6.0 /usr/local/cuda-12.8/targets/x86_64-linux/lib/libcudnn_adv.so.9.6.0 /usr/local/cuda-12.8/targets/x86_64-linux/lib/libcudnn_cnn.so.9.6.0 /usr/local/cuda-12.8/targets/x86_64-linux/lib/libcudnn_engines_precompiled.so.9.6.0 /usr/local/cuda-12.8/targets/x86_64-linux/lib/libcudnn_engines_runtime_compiled.so.9.6.0 /usr/local/cuda-12.8/targets/x86_64-linux/lib/libcudnn_graph.so.9.6.0 /usr/local/cuda-12.8/targets/x86_64-linux/lib/libcudnn_heuristic.so.9.6.0 /usr/local/cuda-12.8/targets/x86_64-linux/lib/libcudnn_ops.so.9.6.0 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): 160 On-line CPU(s) list: 0-159 Vendor ID: GenuineIntel Model name: Intel Xeon Processor (SapphireRapids) CPU family: 6 Model: 143 Thread(s) per core: 2 Core(s) per socket: 40 Socket(s): 2 Stepping: 4 BogoMIPS: 4200.00 Flags: fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush mmx fxsr sse sse2 ss ht syscall nx pdpe1gb rdtscp lm constant_tsc rep_good nopl xtopology cpuid tsc_known_freq pni pclmulqdq vmx ssse3 fma cx16 pcid sse4_1 sse4_2 x2apic movbe popcnt tsc_deadline_timer aes xsave avx f16c rdrand hypervisor lahf_lm abm 3dnowprefetch cpuid_fault ssbd ibrs ibpb stibp ibrs_enhanced tpr_shadow flexpriority ept vpid ept_ad fsgsbase tsc_adjust bmi1 avx2 smep bmi2 erms invpcid avx512f avx512dq rdseed adx smap avx512ifma clflushopt clwb avx512cd sha_ni avx512bw avx512vl xsaveopt xsavec xgetbv1 xsaves avx_vnni avx512_bf16 wbnoinvd arat vnmi avx512vbmi umip pku ospke waitpkg avx512_vbmi2 gfni vaes vpclmulqdq avx512_vnni avx512_bitalg avx512_vpopcntdq la57 rdpid bus_lock_detect cldemote movdiri movdir64b fsrm md_clear serialize tsxldtrk amx_bf16 avx512_fp16 amx_tile amx_int8 arch_capabilities Virtualization: VT-x Hypervisor vendor: KVM Virtualization type: full L1d cache: 5 MiB (160 instances) L1i cache: 5 MiB (160 instances) L2 cache: 320 MiB (80 instances) L3 cache: 32 MiB (2 instances) NUMA node(s): 2 NUMA node0 CPU(s): 0-79 NUMA node1 CPU(s): 80-159 Vulnerability Gather data sampling: Not affected Vulnerability Indirect target selection: Mitigation; Aligned branch/return thunks Vulnerability Itlb multihit: Not affected Vulnerability L1tf: Not affected Vulnerability Mds: Not affected Vulnerability Meltdown: Not affected 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: 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; PBRSB-eIBRS SW sequence; BHI SW loop, KVM SW loop Vulnerability Srbds: Not affected Vulnerability Tsx async abort: Not affected

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

extent analysis

TL;DR

The issue can be addressed by modifying Dynamo's bool() emulation to match CPython semantics for user-defined objects, specifically handling edge cases that cause wrong results or missing exceptions.

Guidance

  • Identify and modify the specific edge cases in Dynamo's bool() emulation that are causing the discrepancies with CPython semantics.
  • Review the CPython 3.13 conformance tests, specifically test_bool.py, to ensure that the modifications align with the expected behavior.
  • Implement additional error handling to raise TypeError or ValueError as required by CPython semantics for user-defined objects.
  • Run the CPython 3.13 conformance tests, including test_convert_to_bool and test_blocked, to verify the fixes.

Example

No specific code snippet can be provided without more details on the current implementation of Dynamo's bool() emulation. However, the fix would involve adjusting the emulation to correctly handle user-defined objects and raise exceptions as necessary.

Notes

The solution requires a deep understanding of both Dynamo's bool() emulation and CPython's semantics for user-defined objects. The modifications should be thoroughly tested to ensure compatibility and correctness.

Recommendation

Apply a workaround by modifying Dynamo's bool() emulation to match CPython semantics, as the issue seems to stem from discrepancies in handling user-defined objects. This approach allows for a targeted fix without requiring a version upgrade, which may not be immediately available or feasible.

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