# RuntimeError: TracerWarning: Using a tensor as a Python bool might cause the trace to be incorrect. We can't record the control flow of this loop.

- **ID:** `pytorch/jit-trace-dynamic-control-flow`
- **Domain:** pytorch
- **Category:** runtime_error
- **Error Code:** `TORCH_SCRIPT_TRACE_DYNAMIC_CF`
- **Verification:** ai_generated
- **Fix Rate:** 75%

## Root Cause

TorchScript tracing encountered a data-dependent control flow (e.g., if tensor > 0), which cannot be captured statically; tracing converts it to a constant.

## Version Compatibility

| Version | Status | Introduced | Deprecated |
|---------|--------|------------|------------|
| torch>=1.0 | active | — | — |
| torch>=1.8 for improved warnings | active | — | — |

## Workarounds

1. **Replace dynamic control flow with torch.where or masked operations: instead of 'if x > 0: y = a else: y = b', use 'y = torch.where(x > 0, a, b)'. This keeps the graph static.** (85% success)
   ```
   Replace dynamic control flow with torch.where or masked operations: instead of 'if x > 0: y = a else: y = b', use 'y = torch.where(x > 0, a, b)'. This keeps the graph static.
   ```
2. **Use torch.jit.script with type annotations: @torch.jit.script; def forward(self, x: torch.Tensor) -> torch.Tensor: ... This supports dynamic control flow.** (80% success)
   ```
   Use torch.jit.script with type annotations: @torch.jit.script; def forward(self, x: torch.Tensor) -> torch.Tensor: ... This supports dynamic control flow.
   ```

## Dead Ends

- **@torch.jit.script** — Using @torch.jit.script instead of tracing may still fail if the function uses dynamic shapes; scripting requires full type annotations. (60% fail)
- **torch.jit._state.disable_tracing()** — Suppressing the warning with torch.jit._state.disable_tracing() hides the issue but the exported model will produce wrong results for different inputs. (90% fail)
