# 运行时错误：跟踪失败：不允许递归跟踪函数 'forward'

- **ID:** `pytorch/torchscript-recursive-trace`
- **领域:** pytorch
- **类别:** module_error
- **验证级别:** ai_generated
- **修复率:** 85%

## 根因

TorchScript 跟踪检测到对已跟踪函数的递归调用，这在基于图的跟踪中不受支持；模型使用了动态控制流或自引用层。

## 版本兼容性

| 版本 | 状态 | 引入 | 弃用 |
|------|------|------|------|
| pytorch>=2.0.0 | active | — | — |

## 解决方案

1. ```
   重构模型以避免递归：使用 `torch.jit.script` 和显式类型注释，用迭代循环替换递归调用。例如：将递归 RNN 改为使用 `torch.nn.RNN` 或时间步循环。
   ```
2. ```
   使用带有 `@torch.jit.script` 装饰器的 `torch.jit.script` 并注释所有张量类型。如果递归不可避免，则在递归辅助函数上使用 `torch.jit.ignore`。
   ```
3. ```
   使用 ONNX 而不是 TorchScript 导出模型，因为 ONNX 可能通过显式展开处理某些递归模式。
   ```

## 无效尝试

- **** — Suppressing the error does not fix the underlying issue; the traced model may produce incorrect results. (90% 失败率)
- **** — Tracing unrolls loops but still cannot handle recursive calls within the traced function. (85% 失败率)
- **** — Script may fail with the same recursion error if the model is not scriptable; it requires explicit type annotations. (70% 失败率)
