# 资源耗尽错误：函数 'train_step' 已被重跟踪 1000 次。已达到跟踪限制。这可能是由于传递 Python 字面量或形状变化的张量导致的。

- **ID:** `tensorflow/tf-function-recompilation-cache-limit`
- **领域:** tensorflow
- **类别:** resource_error
- **错误码:** `ERTL`
- **验证级别:** ai_generated
- **修复率:** 88%

## 根因

被 tf.function 装饰的函数（例如 train_step）因接收形状变化或 Python 值的参数而被过度重跟踪，这些参数未作为函数输入签名的一部分被缓存，耗尽了跟踪缓存。

## 版本兼容性

| 版本 | 状态 | 引入 | 弃用 |
|------|------|------|------|
| TensorFlow 2.6.0 | active | — | — |
| TensorFlow 2.10.0 | active | — | — |

## 解决方案

1. ```
   确保传递给 tf.function 的所有张量参数具有一致的形状。在传递之前将输入填充或调整为固定形状。对于 Python 参数，将其转换为张量或使用 tf.constant() 使其成为图签名的一部分。
   ```
2. ```
   使用 tf.TensorSpec 显式定义输入签名，以防止因形状或数据类型变化而重跟踪。这告诉 TensorFlow 对匹配签名的所有调用使用单个图。
   ```
3. ```
   如果函数使用变化的 Python 整数或布尔参数，将其转换为张量，或使用 tf.cond() 或 tf.switch_case() 进行控制流，将其移出 tf.function。
   ```

## 无效尝试

- **** — Running eagerly defeats the purpose of tf.function (performance), and increasing the limit only delays the error without fixing the root cause of shape variability. (90% 失败率)
- **** — While this can reduce retracing for shape changes, it does not address retracing caused by changing Python literal values (e.g., integer arguments), and may still hit the limit. (70% 失败率)
- **** — This eliminates retracing but also removes the performance benefits of graph compilation, potentially slowing training significantly. (60% 失败率)
