# RuntimeError: TorchScript type mismatch: Expected Optional[Tensor] but got Tensor for argument 'mask'

- **ID:** `pytorch/script-optional-type-error`
- **Domain:** pytorch
- **Category:** type_error
- **Verification:** ai_generated
- **Fix Rate:** 90%

## Root Cause

A TorchScript function expects an optional tensor argument, but a non-optional tensor is passed, causing a type mismatch during compilation or execution.

## Version Compatibility

| Version | Status | Introduced | Deprecated |
|---------|--------|------------|------------|
| torch>=1.8 | active | — | — |
| torch<=2.5.1 | active | — | — |

## Workarounds

1. **Update the function signature to accept Optional[Tensor] and handle None inside. For example: def forward(self, x: torch.Tensor, mask: Optional[torch.Tensor] = None) -> torch.Tensor: if mask is not None: ...** (95% success)
   ```
   Update the function signature to accept Optional[Tensor] and handle None inside. For example: def forward(self, x: torch.Tensor, mask: Optional[torch.Tensor] = None) -> torch.Tensor: if mask is not None: ...
   ```
2. **Wrap the argument in a conditional that returns None if not provided: mask = mask if mask is not None else torch.empty(0) but ensure the function handles empty tensors.** (85% success)
   ```
   Wrap the argument in a conditional that returns None if not provided: mask = mask if mask is not None else torch.empty(0) but ensure the function handles empty tensors.
   ```

## Dead Ends

- **Adding type hints to all variables without changing the function signature** — Type hints alone do not change the runtime type; the function signature must explicitly declare the argument as Optional[Tensor]. (50% fail)
- **Using torch.jit.ignore decorator on the entire function** — This disables TorchScript compilation entirely, which may degrade performance or break model deployment. (60% fail)
