# 运行时错误：torch.compile：函数 'forward' 的重新编译次数达到上限（100 次）。考虑使用 dynamic=True 或减少张量形状变化。

- **ID:** `pytorch/compile-recompilation-limit`
- **领域:** pytorch
- **类别:** runtime_error
- **验证级别:** ai_generated
- **修复率:** 90%

## 根因

torch.compile 的守卫机制在张量形状变化时触发重新编译，经过 100 次重新编译后停止，以防止无限循环或性能下降。

## 版本兼容性

| 版本 | 状态 | 引入 | 弃用 |
|------|------|------|------|
| torch>=2.0 | active | — | — |
| torch<=2.5.1 | active | — | — |

## 解决方案

1. ```
   Use dynamic=True in torch.compile to handle dynamic shapes: torch.compile(model, dynamic=True). This allows the compiler to handle shape variations without recompiling.
   ```
2. ```
   Pad or resize tensors to a fixed set of shapes during training to reduce shape variability. For example, use torch.nn.utils.rnn.pad_sequence to pad sequences to a fixed length.
   ```

## 无效尝试

- **Disabling torch.compile entirely to avoid recompilation** — This removes the performance benefits of compilation, which may be critical for large models. (60% 失败率)
- **Setting torch._dynamo.config.recompile_limit = 0 to disable the limit** — This can lead to infinite recompilation loops, causing severe performance degradation or crashes. (90% 失败率)
