pytorch - ✅(Solved) Fix [torch.compile] Data-dependent guard fails when printing a boolean value derived from tensor [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#178382Fetched 2026-04-08 01:30:47
View on GitHub
Comments
0
Participants
1
Timeline
25
Reactions
0
Participants
Timeline (top)
mentioned ×6referenced ×6subscribed ×6labeled ×5

Error Message

import torch import torch.nn as nn import torch._dynamo

torch._dynamo.config.suppress_errors = False torch._dynamo.config.verbose = True

class BoolTensorModel(nn.Module): def forward(self, x, mask): make_causal = bool((mask == 0).all()) print(f"[Forward] make_causal={make_causal}") return x + 1

def main(): x = torch.randn(2, 3) mask = torch.zeros(2, 3)

model = BoolTensorModel()

eager_out = model(x, mask)
print("Eager mode output shape::\n", eager_out)

try:
    compiled_model = torch.compile(model, fullgraph=True)
    compile_out = compiled_model(x, mask)
    print("Compiled mode output shape:\n", compile_out)
except Exception as e:
    print("Compile error:\n", e)

if name == "main": main()

Root Cause

A data-dependent guard failure occurs:

Could not guard on data-dependent expression Eq(u0, 1)
Caused by: print(f"...{make_causal}...")

Pytorch Version 2.2.0 code:

import torch
import torch.nn as nn
import torch._dynamo

Fix Action

Fix / Workaround

CPU: Architecture: x86_64 CPU op-mode(s): 32-bit, 64-bit Address sizes: 39 bits physical, 48 bits virtual Byte Order: Little Endian CPU(s): 32 On-line CPU(s) list: 0-31 Vendor ID: GenuineIntel Model name: Intel(R) Core(TM) i9-14900HX CPU family: 6 Model: 183 Thread(s) per core: 2 Core(s) per socket: 24 Socket(s): 1 Stepping: 1 CPU(s) scaling MHz: 31% CPU max MHz: 5800.0000 CPU min MHz: 800.0000 BogoMIPS: 4838.40 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 tsc_known_freq pni pclmulqdq dtes64 monitor ds_cpl vmx est tm2 ssse3 sdbg fma cx16 xtpr pdcm pcid sse4_1 sse4_2 x2apic movbe popcnt tsc_deadline_timer aes xsave avx f16c rdrand lahf_lm abm 3dnowprefetch cpuid_fault epb ssbd ibrs ibpb stibp ibrs_enhanced tpr_shadow flexpriority ept vpid ept_ad fsgsbase tsc_adjust bmi1 avx2 smep bmi2 erms invpcid rdseed adx smap clflushopt clwb intel_pt sha_ni xsaveopt xsavec xgetbv1 xsaves split_lock_detect user_shstk avx_vnni dtherm ida arat pln pts hwp hwp_notify hwp_act_window hwp_epp hwp_pkg_req hfi vnmi umip pku ospke waitpkg gfni vaes vpclmulqdq rdpid movdiri movdir64b fsrm md_clear serialize arch_lbr ibt flush_l1d arch_capabilities Virtualization: VT-x L1d cache: 896 KiB (24 instances) L1i cache: 1.3 MiB (24 instances) L2 cache: 32 MiB (12 instances) L3 cache: 36 MiB (1 instance) NUMA node(s): 1 NUMA node0 CPU(s): 0-31 Vulnerability Gather data sampling: Not affected Vulnerability Ghostwrite: Not affected Vulnerability Indirect target selection: 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: Mitigation; Clear Register File 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 BHI_DIS_S Vulnerability Srbds: Not affected Vulnerability Tsx async abort: Not affected

PR fix notes

PR #178406: [Bugfix] Fallback to StringFormat for better support, error message

Description (problem / solution / changelog)

Fixes #178382

Summary

The error message complains that there is a data dependent error; however, given the call is in a F string, we could support this with a StringFormatVariable if there is an exception in the constant string

Further, this gives a direct error message that print is not supported, suggesting reordering the logs which will make this code pass

Testplan

python test/dynamo/test_reorder_logs.py ReorderLogsTests.test_reorder_print_data_dependent_fstring

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

Changed files

  • test/dynamo/test_reorder_logs.py (modified, +29/-0)
  • torch/_dynamo/variables/builder.py (modified, +14/-1)

Code Example

Could not guard on data-dependent expression Eq(u0, 1)
Caused by: print(f"...{make_causal}...")

---

import torch
import torch.nn as nn
import torch._dynamo

torch._dynamo.config.suppress_errors = False
torch._dynamo.config.verbose = True

class BoolTensorModel(nn.Module):
    def forward(self, x, mask):
        make_causal = bool((mask == 0).all())
        print(f"[Forward] make_causal={make_causal}")
        return x + 1

def main():
    x = torch.randn(2, 3)
    mask = torch.zeros(2, 3)

    model = BoolTensorModel()

    eager_out = model(x, mask)
    print("Eager mode output shape::\n", eager_out)

    try:
        compiled_model = torch.compile(model, fullgraph=True)
        compile_out = compiled_model(x, mask)
        print("Compiled mode output shape:\n", compile_out)
    except Exception as e:
        print("Compile error:\n", e)

if __name__ == "__main__":
    main()

---

Eager mode output shape::
 tensor([[ 1.5368, -0.4057,  1.7398],
        [ 2.1480,  1.6336,  1.2052]])
Compile error:
 Consider annotating your code using torch._check*(). Could not guard on data-dependent expression Eq(u0, 1) (unhinted: Eq(u0, 1)).  (Size-like symbols: none)

consider using data-dependent friendly APIs such as guard_or_false, guard_or_true and statically_known_true.
Caused by: print(f"[Forward] make_causal={make_causal}")  ...1951 in evaluate_expr)
For more information, run with TORCH_LOGS="dynamic"
For extended logs when we create symbols, also add TORCHDYNAMO_EXTENDED_DEBUG_CREATE_SYMBOL="u0"
If you suspect the guard was triggered from C++, add TORCHDYNAMO_EXTENDED_DEBUG_CPP=1
For more debugging help, see https://docs.google.com/document/d/1HSuTTVvYH1pTew89Rtpeu84Ht3nQEFTYhAX3Ypa_xJs/edit?usp=sharing

User Stack (most recent call last):
  (snipped, see stack below for prefix)
  ... line 11, in forward
    print(f"[Forward] make_causal={make_causal}")

For C++ stack trace, run with TORCHDYNAMO_EXTENDED_DEBUG_CPP=1
For more information about this error, see: https://pytorch.org/docs/main/generated/exportdb/index.html#constrain-as-size-example
RAW_BUFFERClick to expand / collapse

🐛 Describe the bug

Description:

When compiling a model with torch.compile(fullgraph=True), if the code contains:

A Python bool derived from a tensor computation (e.g., bool((mask == 0).all()))

That bool is then used in a print statement

A data-dependent guard failure occurs:

Could not guard on data-dependent expression Eq(u0, 1)
Caused by: print(f"...{make_causal}...")

Pytorch Version 2.2.0 code:

import torch
import torch.nn as nn
import torch._dynamo

torch._dynamo.config.suppress_errors = False
torch._dynamo.config.verbose = True

class BoolTensorModel(nn.Module):
    def forward(self, x, mask):
        make_causal = bool((mask == 0).all())
        print(f"[Forward] make_causal={make_causal}")
        return x + 1

def main():
    x = torch.randn(2, 3)
    mask = torch.zeros(2, 3)

    model = BoolTensorModel()

    eager_out = model(x, mask)
    print("Eager mode output shape::\n", eager_out)

    try:
        compiled_model = torch.compile(model, fullgraph=True)
        compile_out = compiled_model(x, mask)
        print("Compiled mode output shape:\n", compile_out)
    except Exception as e:
        print("Compile error:\n", e)

if __name__ == "__main__":
    main()

output:

Eager mode output shape::
 tensor([[ 1.5368, -0.4057,  1.7398],
        [ 2.1480,  1.6336,  1.2052]])
Compile error:
 Consider annotating your code using torch._check*(). Could not guard on data-dependent expression Eq(u0, 1) (unhinted: Eq(u0, 1)).  (Size-like symbols: none)

consider using data-dependent friendly APIs such as guard_or_false, guard_or_true and statically_known_true.
Caused by: print(f"[Forward] make_causal={make_causal}")  ...1951 in evaluate_expr)
For more information, run with TORCH_LOGS="dynamic"
For extended logs when we create symbols, also add TORCHDYNAMO_EXTENDED_DEBUG_CREATE_SYMBOL="u0"
If you suspect the guard was triggered from C++, add TORCHDYNAMO_EXTENDED_DEBUG_CPP=1
For more debugging help, see https://docs.google.com/document/d/1HSuTTVvYH1pTew89Rtpeu84Ht3nQEFTYhAX3Ypa_xJs/edit?usp=sharing

User Stack (most recent call last):
  (snipped, see stack below for prefix)
  ... line 11, in forward
    print(f"[Forward] make_causal={make_causal}")

For C++ stack trace, run with TORCHDYNAMO_EXTENDED_DEBUG_CPP=1
For more information about this error, see: https://pytorch.org/docs/main/generated/exportdb/index.html#constrain-as-size-example

Versions

PyTorch version: 2.2.0 Is debug build: False CUDA used to build PyTorch: 12.6 ROCM used to build PyTorch: N/A

OS: Ubuntu 24.04.1 LTS (x86_64) GCC version: (Ubuntu 9.5.0-6ubuntu2) 9.5.0 Clang version: Could not collect CMake version: version 4.0.3 Libc version: glibc-2.39

Python version: 3.9.7 (default, Jul 16 2025, 16:34:47) [GCC 13.3.0] (64-bit runtime) Python platform: Linux-6.14.0-29-generic-x86_64-with-glibc2.39 Is CUDA available: False CUDA runtime version: Could not collect CUDA_MODULE_LOADING set to: N/A GPU models and configuration: GPU 0: NVIDIA GeForce RTX 4060 Laptop GPU Nvidia driver version: 580.65.06 cuDNN version: Could not collect 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: 39 bits physical, 48 bits virtual Byte Order: Little Endian CPU(s): 32 On-line CPU(s) list: 0-31 Vendor ID: GenuineIntel Model name: Intel(R) Core(TM) i9-14900HX CPU family: 6 Model: 183 Thread(s) per core: 2 Core(s) per socket: 24 Socket(s): 1 Stepping: 1 CPU(s) scaling MHz: 31% CPU max MHz: 5800.0000 CPU min MHz: 800.0000 BogoMIPS: 4838.40 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 tsc_known_freq pni pclmulqdq dtes64 monitor ds_cpl vmx est tm2 ssse3 sdbg fma cx16 xtpr pdcm pcid sse4_1 sse4_2 x2apic movbe popcnt tsc_deadline_timer aes xsave avx f16c rdrand lahf_lm abm 3dnowprefetch cpuid_fault epb ssbd ibrs ibpb stibp ibrs_enhanced tpr_shadow flexpriority ept vpid ept_ad fsgsbase tsc_adjust bmi1 avx2 smep bmi2 erms invpcid rdseed adx smap clflushopt clwb intel_pt sha_ni xsaveopt xsavec xgetbv1 xsaves split_lock_detect user_shstk avx_vnni dtherm ida arat pln pts hwp hwp_notify hwp_act_window hwp_epp hwp_pkg_req hfi vnmi umip pku ospke waitpkg gfni vaes vpclmulqdq rdpid movdiri movdir64b fsrm md_clear serialize arch_lbr ibt flush_l1d arch_capabilities Virtualization: VT-x L1d cache: 896 KiB (24 instances) L1i cache: 1.3 MiB (24 instances) L2 cache: 32 MiB (12 instances) L3 cache: 36 MiB (1 instance) NUMA node(s): 1 NUMA node0 CPU(s): 0-31 Vulnerability Gather data sampling: Not affected Vulnerability Ghostwrite: Not affected Vulnerability Indirect target selection: 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: Mitigation; Clear Register File 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 BHI_DIS_S Vulnerability Srbds: Not affected Vulnerability Tsx async abort: Not affected

cc @chauhang @penguinwu @ezyang @bobrenjc93 @aditvenk @laithsakka

extent analysis

Fix Plan

To resolve the data-dependent guard failure, we need to avoid using the bool function on a tensor computation result in a way that PyTorch's torch.compile with fullgraph=True cannot handle. The error occurs because the print statement is trying to use a data-dependent boolean value, which torch.compile cannot guard against.

Here are the steps to fix the issue:

  1. Avoid using bool on tensor computations: Instead of directly converting the result of a tensor computation to a boolean using bool(), use PyTorch's built-in functions that can be handled by torch.compile.
  2. Use torch.all with item(): If you need to check if all elements in a tensor are true, use torch.all and then call item() on the result to get a Python boolean value. However, be cautious with this approach as it can still cause issues if the tensor's value depends on the input data.

Example code changes:

class BoolTensorModel(nn.Module):
    def forward(self, x, mask):
        # Use torch.all and item() to get a Python boolean
        make_causal = torch.all(mask == 0).item()
        print(f"[Forward] make_causal={make_causal}")
        return x + 1

Alternatively, you can use torch.compile with fullgraph=False to avoid this issue, but this might impact performance.

Verification

To verify that the fix worked, run your model with the modified code and check that it compiles successfully with torch.compile(fullgraph=True) and produces the expected output.

Extra Tips

  • When using torch.compile, be mindful of the limitations and constraints it imposes on your code, especially regarding data-dependent computations.
  • Consider using torch._check functions as suggested in the error message to annotate your code and help torch.compile understand the data dependencies.
  • Keep your PyTorch version up to date, as newer versions may include fixes or improvements for such issues.

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