# 未实现错误：急切模式不支持while_loop

- **ID:** `tensorflow/not-implemented-error-graph-mode-while-loop`
- **领域:** tensorflow
- **类别:** runtime_error
- **错误码:** `NIE`
- **验证级别:** ai_generated
- **修复率:** 78%

## 根因

在未正确追踪的tf.function内部使用tf.while_loop，或将急切执行与仅图操作混合使用。

## 版本兼容性

| 版本 | 状态 | 引入 | 弃用 |
|------|------|------|------|
| tensorflow 2.10.0 | active | — | — |
| tensorflow 2.11.0 | active | — | — |

## 解决方案

1. ```
   Replace tf.while_loop with a Python while loop inside a tf.function that uses tf.constant for bounds:
@tf.function
def my_loop(n):
    i = tf.constant(0)
    while i < n:
        # loop body
        i += 1
    return i
result = my_loop(tf.constant(5))
   ```
2. ```
   Use tf.range and tf.map_fn for vectorized operations instead of explicit loops:
@tf.function
def my_fn(n):
    return tf.map_fn(lambda x: x*2, tf.range(n))
result = my_fn(tf.constant(5))
   ```

## 无效尝试

- **** — tf.function requires all loop variables to be tensors; Python objects cause tracing errors. (70% 失败率)
- **** — TF2 is designed for eager mode; disabling it is not recommended and can cause compatibility issues. (90% 失败率)
