# RuntimeError: torch.compile: function 'forward' failed with a graph break. Falling back to eager mode. Consider rewriting the function to avoid Python control flow.

- **ID:** `pytorch/torch-compile-graph-break-fallback`
- **Domain:** pytorch
- **Category:** runtime_error
- **Verification:** ai_generated
- **Fix Rate:** 70%

## Root Cause

torch.compile encountered Python control flow (e.g., if statements, loops) that cannot be captured in a single computation graph, causing a graph break and fallback to eager mode.

## Version Compatibility

| Version | Status | Introduced | Deprecated |
|---------|--------|------------|------------|
| pytorch>=2.0 | active | — | — |
| torch.compile | active | — | — |

## Workarounds

1. **Refactor the forward method to replace Python control flow with tensor operations. For example, use `torch.where(condition, x, y)` instead of `if condition: ... else: ...`** (85% success)
   ```
   Refactor the forward method to replace Python control flow with tensor operations. For example, use `torch.where(condition, x, y)` instead of `if condition: ... else: ...`
   ```
2. **Use torch.compiler.disable() decorator on specific submodules that require dynamic control flow: `@torch.compiler.disable`** (80% success)
   ```
   Use torch.compiler.disable() decorator on specific submodules that require dynamic control flow: `@torch.compiler.disable`
   ```
3. **Enable the 'fullgraph' option in torch.compile to get a detailed trace of where graph breaks occur: `torch.compile(model, fullgraph=True)`** (75% success)
   ```
   Enable the 'fullgraph' option in torch.compile to get a detailed trace of where graph breaks occur: `torch.compile(model, fullgraph=True)`
   ```

## Dead Ends

- **Using torch.jit.script instead of torch.compile** — torch.jit.script also has limitations with dynamic control flow and may produce similar errors. (80% fail)
- **Disabling torch.compile entirely and using eager mode** — Avoids the error but loses all performance benefits of compilation. (50% fail)
- **Adding more decorators like @torch.jit.ignore** — May suppress the error but can lead to incorrect graph construction. (70% fail)
