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
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.
官方文档
https://pytorch.org/docs/stable/jit.html#tracing-vs-scripting解决方案
-
用torch.where或掩码操作替换动态控制流:不用'if x > 0: y = a else: y = b',而用'y = torch.where(x > 0, a, b)'。这保持图静态。
-
使用带类型注解的torch.jit.script:@torch.jit.script; def forward(self, x: torch.Tensor) -> torch.Tensor: ... 这支持动态控制流。
无效尝试
常见但无效的做法:
-
@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.
-
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.