pytorch runtime_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 (e.g., if/else or loops).

ID: pytorch/torchscript-dynamic-control-flow

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

版本兼容性

版本状态引入弃用备注
torch 1.9.0 active
torch 2.0.0 active
python 3.9 active

根因分析

TorchScript 跟踪(torch.jit.trace)无法处理依赖于张量值的 Python 控制流;它记录特定输入上的操作,并在路径更改时失败。

English

TorchScript tracing (torch.jit.trace) cannot handle Python control flow that depends on tensor values; it records operations on specific inputs and fails when the path changes.

generic

官方文档

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

解决方案

  1. Use torch.jit.script instead of trace for models with dynamic control flow:
    @torch.jit.script
    def forward(self, x):
        if x.sum() > 0:
            return x * 2
        else:
            return x / 2
    # Then script the model: scripted_model = torch.jit.script(model)
  2. Refactor the model to avoid dynamic control flow in the traced function, e.g., use torch.where or masked operations:
    def forward(self, x):
        mask = (x.sum(dim=1, keepdim=True) > 0).float()
        return x * (1 + mask)  # equivalent to if-else

无效尝试

常见但无效的做法:

  1. 80% 失败

    Using torch.jit.trace with a large set of example inputs may still fail if control flow depends on runtime values not present in examples.

  2. 70% 失败

    Adding more concrete inputs to trace may cover some paths but not all, leading to incomplete traces.