TORCH_SCRIPT_TRACE_DYNAMIC_CF pytorch runtime_error ai_generated partial

运行时错误:跟踪器警告:将张量用作Python布尔值可能导致跟踪不正确。我们无法记录此循环的控制流。

RuntimeError: TracerWarning: Using a tensor as a Python bool might cause the trace to be incorrect. We can't record the control flow of this loop.

ID: pytorch/jit-trace-dynamic-control-flow

其他格式: JSON · Markdown 中文 · English
75%修复率
83%置信度
1证据数
2023-05-01首次发现

版本兼容性

版本状态引入弃用备注
torch>=1.0 active
torch>=1.8 for improved warnings active

根因分析

TorchScript跟踪遇到了数据相关的控制流(例如,if tensor > 0),无法静态捕获;跟踪将其转换为常量。

English

TorchScript tracing encountered a data-dependent control flow (e.g., if tensor > 0), which cannot be captured statically; tracing converts it to a constant.

generic

官方文档

https://pytorch.org/docs/stable/jit.html#tracing-vs-scripting

解决方案

  1. 用torch.where或掩码操作替换动态控制流:不用'if x > 0: y = a else: y = b',而用'y = torch.where(x > 0, a, b)'。这保持图静态。
  2. 使用带类型注解的torch.jit.script:@torch.jit.script; def forward(self, x: torch.Tensor) -> torch.Tensor: ... 这支持动态控制流。

无效尝试

常见但无效的做法:

  1. @torch.jit.script 60% 失败

    Using @torch.jit.script instead of tracing may still fail if the function uses dynamic shapes; scripting requires full type annotations.

  2. torch.jit._state.disable_tracing() 90% 失败

    Suppressing the warning with torch.jit._state.disable_tracing() hides the issue but the exported model will produce wrong results for different inputs.