# NotImplementedError: while_loop is not supported in eager mode

- **ID:** `tensorflow/not-implemented-error-graph-mode-while-loop`
- **Domain:** tensorflow
- **Category:** runtime_error
- **Error Code:** `NIE`
- **Verification:** ai_generated
- **Fix Rate:** 78%

## Root Cause

Using tf.while_loop inside a tf.function that is not properly traced, or mixing eager execution with graph-only operations.

## Version Compatibility

| Version | Status | Introduced | Deprecated |
|---------|--------|------------|------------|
| tensorflow 2.10.0 | active | — | — |
| tensorflow 2.11.0 | active | — | — |

## Workarounds

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))** (80% success)
   ```
   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))** (75% success)
   ```
   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))
   ```

## Dead Ends

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