pytorch转onnx的过程中,模型的卷积层激活函数用的是hardswish,转换时报错:
RuntimeError: Exporting the operator hardswish to ONNX opset version 12 is not supported. Please open a bug to request ONNX export support for the missing operator.
提示我们去ONNX上反馈,显然等他们来写已经来不及了,还是自己动手吧。
因为模型定义的时候,激活函数用的是 nn.Hardswish() ,是不被 onnx 12支持的operator,用Function重写一个,hardswish是MobileNetV3架构中提出的,感兴趣的同学可以看一下(https://arxiv.org/pdf/1905.02244.pdf),形式如下:
代码如下:
import torch.nn.functional as F
class myHardswish(nn.Module):
@staticmethod
def forward(x):
return x * F.hardtanh(x + 3, 0., 6.) / 6.
然后转换的时候刷一遍模型就可以了:
for k, m in model.named_modules():
if isinstance(m.act, nn.Hardswish):
m.act = Hardswish()