Exporting the operator hardsigmoid to ONNX opset version 11 is not supported

问题:

在将 MobileNetv3 模型从 PyTorch 转为 ONNX 时报错:

Error: RuntimeError: Exporting the operator hardsigmoid to ONNX opset version 11 is not supported. Please feel free to request support or submit a pull request on PyTorch GitHub.

运行环境:

PyTorch 版本:1.8.0

在网上找了很多文章,大部分都是写的一样的,就是将nn.Hardswish替换为自己实现的 Hardswitch,实际上,这个版本的 PyTorch 中,nn.Hardswish是可以转换成功的(老版本成不成功不清楚),报错的根本原因是 mobilenetv3 代码中使用了 F.hardsigmoid函数,解决办法是将代码中的 hardsigmoid 函数替换为 hardtanh 函数,如下:

class SqueezeExcitation(nn.Module):

    def __init__(self, input_channels: int, squeeze_factor: int = 4):
        super().__init__()
        squeeze_channels = _make_divisible(input_channels // squeeze_factor, 8)
        self.fc1 = nn.Conv2d(input_channels, squeeze_channels, 1)
        self.relu = nn.ReLU(inplace=True)
        self.fc2 = nn.Conv2d(squeeze_channels, input_channels, 1)

    def _scale(self, input: Tensor, inplace: bool) -> Tensor:
        scale = F.adaptive_avg_pool2d(input, 1)
        scale = self.fc1(scale)
        scale = self.relu(scale)
        scale = self.fc2(scale)
        return F.hardsigmoid(scale, inplace=inplace)  # 此行报错
        # return F.hardtanh(scale + 3, 0., 6., inplace=inplace) / 6.  # 更换为此行

    def forward(self, input: Tensor) -> Tensor:
        scale = self._scale(input, True)
        return scale * input

你可能感兴趣的:(算法,pytorch,深度学习,人工智能)