pytorch type_error ai_generated true

运行时错误: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

其他格式: JSON · Markdown 中文 · English
90%修复率
90%置信度
1证据数
2024-04-10首次发现

版本兼容性

版本状态引入弃用备注
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.

generic

官方文档

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

解决方案

  1. 将 torch.jit.trace 替换为 torch.jit.script 用于整个模型或包含控制流的特定模块。Script 支持动态控制流。
  2. 如果必须使用 tracing,将控制流重构到单独的函数中,并使用 torch.jit.script 处理该函数,然后从 traced 模块中调用它。

无效尝试

常见但无效的做法:

  1. 90% 失败

    Tracing captures the operations executed for given inputs; it cannot handle branches not taken.

  2. 70% 失败

    Ignoring the function means it won't be compiled, leading to missing operations in the exported graph.

  3. 50% 失败

    Removing control flow changes model logic; it may work but is error-prone and not always feasible.