# 运行时错误：TorchScript 仅支持对张量进行追踪。此函数无法追踪，因为它使用了依赖于张量数据的动态控制流（if/else 或循环）。

- **ID:** `pytorch/torchscript-unsupported-dynamic-control-flow`
- **领域:** pytorch
- **类别:** type_error
- **验证级别:** ai_generated
- **修复率:** 90%

## 根因

模型包含依赖于张量值的控制流（如 if x.sum() > 0），torch.jit.trace 不支持；需要使用 torch.jit.script。

## 版本兼容性

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

## 解决方案

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

## 无效尝试

- **** — Tracing captures the operations executed for given inputs; it cannot handle branches not taken. (90% 失败率)
- **** — Ignoring the function means it won't be compiled, leading to missing operations in the exported graph. (70% 失败率)
- **** — Removing control flow changes model logic; it may work but is error-prone and not always feasible. (50% 失败率)
