# RuntimeError: TorchScript supports tracing only for tensors. This function cannot be traced because it uses dynamic control flow (e.g., if/else or loops).

- **ID:** `pytorch/torchscript-dynamic-control-flow`
- **Domain:** pytorch
- **Category:** runtime_error
- **Verification:** ai_generated
- **Fix Rate:** 90%

## Root Cause

TorchScript tracing (torch.jit.trace) cannot handle Python control flow that depends on tensor values; it records operations on specific inputs and fails when the path changes.

## Version Compatibility

| Version | Status | Introduced | Deprecated |
|---------|--------|------------|------------|
| torch 1.9.0 | active | — | — |
| torch 2.0.0 | active | — | — |
| python 3.9 | active | — | — |

## Workarounds

1. **Use torch.jit.script instead of trace for models with dynamic control flow:
@torch.jit.script
def forward(self, x):
    if x.sum() > 0:
        return x * 2
    else:
        return x / 2
# Then script the model: scripted_model = torch.jit.script(model)** (90% success)
   ```
   Use torch.jit.script instead of trace for models with dynamic control flow:
@torch.jit.script
def forward(self, x):
    if x.sum() > 0:
        return x * 2
    else:
        return x / 2
# Then script the model: scripted_model = torch.jit.script(model)
   ```
2. **Refactor the model to avoid dynamic control flow in the traced function, e.g., use torch.where or masked operations:
def forward(self, x):
    mask = (x.sum(dim=1, keepdim=True) > 0).float()
    return x * (1 + mask)  # equivalent to if-else** (85% success)
   ```
   Refactor the model to avoid dynamic control flow in the traced function, e.g., use torch.where or masked operations:
def forward(self, x):
    mask = (x.sum(dim=1, keepdim=True) > 0).float()
    return x * (1 + mask)  # equivalent to if-else
   ```

## Dead Ends

- **** — Using torch.jit.trace with a large set of example inputs may still fail if control flow depends on runtime values not present in examples. (80% fail)
- **** — Adding more concrete inputs to trace may cover some paths but not all, leading to incomplete traces. (70% fail)
