# 运行时错误：TorchScript 类型不匹配：参数 'mask' 期望 Optional[Tensor] 但得到 Tensor

- **ID:** `pytorch/script-optional-type-error`
- **领域:** pytorch
- **类别:** type_error
- **验证级别:** ai_generated
- **修复率:** 90%

## 根因

TorchScript 函数期望一个可选的张量参数，但传入了一个非可选张量，导致编译或执行期间类型不匹配。

## 版本兼容性

| 版本 | 状态 | 引入 | 弃用 |
|------|------|------|------|
| torch>=1.8 | active | — | — |
| torch<=2.5.1 | active | — | — |

## 解决方案

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: ...
   ```
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.
   ```

## 无效尝试

- **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% 失败率)
- **Using torch.jit.ignore decorator on the entire function** — This disables TorchScript compilation entirely, which may degrade performance or break model deployment. (60% 失败率)
