pytorch type_error ai_generated true

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

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

ID: pytorch/script-optional-type-error

其他格式: JSON · Markdown 中文 · English
90%修复率
82%置信度
1证据数
2023-11-20首次发现

版本兼容性

版本状态引入弃用备注
torch>=1.8 active
torch<=2.5.1 active

根因分析

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

English

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

generic

官方文档

https://pytorch.org/docs/stable/jit.html#torch.jit.script

解决方案

  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.

无效尝试

常见但无效的做法:

  1. Adding type hints to all variables without changing the function signature 50% 失败

    Type hints alone do not change the runtime type; the function signature must explicitly declare the argument as Optional[Tensor].

  2. Using torch.jit.ignore decorator on the entire function 60% 失败

    This disables TorchScript compilation entirely, which may degrade performance or break model deployment.