运行时错误:TorchScript 仅支持对张量进行追踪。此函数无法追踪,因为它使用了依赖于张量数据的动态控制流(if/else 或循环)。
RuntimeError: TorchScript supports tracing only for tensors. This function cannot be traced because it uses dynamic control flow (if/else or loops) that depends on tensor data.
ID: pytorch/torchscript-unsupported-dynamic-control-flow
版本兼容性
| 版本 | 状态 | 引入 | 弃用 | 备注 |
|---|---|---|---|---|
| pytorch>=1.8.0 | active | — | — | — |
根因分析
模型包含依赖于张量值的控制流(如 if x.sum() > 0),torch.jit.trace 不支持;需要使用 torch.jit.script。
English
The model contains control flow (e.g., if x.sum() > 0) that depends on tensor values, which is not supported by torch.jit.trace; torch.jit.script is required instead.
官方文档
https://pytorch.org/docs/stable/jit.html#mixing-tracing-and-scripting解决方案
-
将 torch.jit.trace 替换为 torch.jit.script 用于整个模型或包含控制流的特定模块。Script 支持动态控制流。
-
如果必须使用 tracing,将控制流重构到单独的函数中,并使用 torch.jit.script 处理该函数,然后从 traced 模块中调用它。
无效尝试
常见但无效的做法:
-
90% 失败
Tracing captures the operations executed for given inputs; it cannot handle branches not taken.
-
70% 失败
Ignoring the function means it won't be compiled, leading to missing operations in the exported graph.
-
50% 失败
Removing control flow changes model logic; it may work but is error-prone and not always feasible.