pytorch
module_error
ai_generated
true
运行时错误:跟踪失败:不允许递归跟踪函数 'forward'
RuntimeError: Tracing failed: Recursive trace of function 'forward' is not allowed
ID: pytorch/torchscript-recursive-trace
85%修复率
87%置信度
1证据数
2023-11-05首次发现
版本兼容性
| 版本 | 状态 | 引入 | 弃用 | 备注 |
|---|---|---|---|---|
| pytorch>=2.0.0 | active | — | — | — |
根因分析
TorchScript 跟踪检测到对已跟踪函数的递归调用,这在基于图的跟踪中不受支持;模型使用了动态控制流或自引用层。
English
TorchScript tracing detected a recursive call to the traced function, which is not supported in graph-based tracing; the model uses dynamic control flow or self-referential layers.
官方文档
https://pytorch.org/docs/stable/jit.html#tracing解决方案
-
重构模型以避免递归:使用 `torch.jit.script` 和显式类型注释,用迭代循环替换递归调用。例如:将递归 RNN 改为使用 `torch.nn.RNN` 或时间步循环。
-
使用带有 `@torch.jit.script` 装饰器的 `torch.jit.script` 并注释所有张量类型。如果递归不可避免,则在递归辅助函数上使用 `torch.jit.ignore`。
-
使用 ONNX 而不是 TorchScript 导出模型,因为 ONNX 可能通过显式展开处理某些递归模式。
无效尝试
常见但无效的做法:
-
90% 失败
Suppressing the error does not fix the underlying issue; the traced model may produce incorrect results.
-
85% 失败
Tracing unrolls loops but still cannot handle recursive calls within the traced function.
-
70% 失败
Script may fail with the same recursion error if the model is not scriptable; it requires explicit type annotations.