# RuntimeError: Tracing failed: Recursive trace of function 'forward' is not allowed

- **ID:** `pytorch/torchscript-recursive-trace`
- **Domain:** pytorch
- **Category:** module_error
- **Verification:** ai_generated
- **Fix Rate:** 85%

## Root Cause

TorchScript tracing detected a recursive call to the traced function, which is not supported in graph-based tracing; the model uses dynamic control flow or self-referential layers.

## Version Compatibility

| Version | Status | Introduced | Deprecated |
|---------|--------|------------|------------|
| pytorch>=2.0.0 | active | — | — |

## Workarounds

1. **Refactor the model to avoid recursion: replace recursive calls with iterative loops using `torch.jit.script` and explicit type annotations. Example: change a recursive RNN to use `torch.nn.RNN` or a loop over time steps.** (90% success)
   ```
   Refactor the model to avoid recursion: replace recursive calls with iterative loops using `torch.jit.script` and explicit type annotations. Example: change a recursive RNN to use `torch.nn.RNN` or a loop over time steps.
   ```
2. **Use `torch.jit.script` with `@torch.jit.script` decorator and annotate all tensor types. If recursion is unavoidable, use `torch.jit.ignore` on the recursive helper function.** (80% success)
   ```
   Use `torch.jit.script` with `@torch.jit.script` decorator and annotate all tensor types. If recursion is unavoidable, use `torch.jit.ignore` on the recursive helper function.
   ```
3. **Export the model using ONNX instead of TorchScript, as ONNX may handle certain recursive patterns via explicit unrolling.** (75% success)
   ```
   Export the model using ONNX instead of TorchScript, as ONNX may handle certain recursive patterns via explicit unrolling.
   ```

## Dead Ends

- **** — Suppressing the error does not fix the underlying issue; the traced model may produce incorrect results. (90% fail)
- **** — Tracing unrolls loops but still cannot handle recursive calls within the traced function. (85% fail)
- **** — Script may fail with the same recursion error if the model is not scriptable; it requires explicit type annotations. (70% fail)
