关于pytorch转onnx经常出现的问题

1. F.avg_pool2d以及F.max_pool2d的转换

直接转会出现以下的错误:

RuntimeError: Failed to export an ONNX attribute 'onnx::Gather', since it's not constant, please try to make things (e.g., kernel size) static if possible

解决办法:

  • nn.AdaptiveAvgPool2d(1)替换 F.avg_pool2d
  • nn.AdaptiveMaxPool2d(1)替换F.max_pool2d

2. 转换过程种不能有动态的非tensor的数值

我的模型有一段是需要将scale在channel维度split成不均等的份数,代码是这么写的:

        scale = F.sigmoid(channel_att_sum).unsqueeze(2).unsqueeze(3)
        start = 0
        out = []
        for x in inputs:
            x = x * scale[:,start:start+x.size(1),:,:]
            start = start + x.size(1)
            out.append(x)

然后再转onnx的时候会出现:

RuntimeError: Unsupported: ONNX export of Slice with dynamic inputs. DynamicSlice is a deprecated experimental op. Please use statically allocated variables or export to a higher opset version.

主要就是start是一个int的数值,在for循环种是迭代的。最后修改代码为如下,即固定好每一个split的份数。

        x1, x2, x3, x4, x5 = inputs 
        x1 = x1 *scale[:,self.start[0]:self.end[0],:,:]
        x2 = x2* scale[:,self.start[1]:self.end[1],:,:]
        x3 = x3* scale[:,self.start[2]:self.end[2],:,:]
        x4 = x4* scale[:,self.start[3]:self.end[3],:,:]
        x5 = x5* scale[:,self.start[4]:self.end[4],:,:]
        return x1, x2, x3, x4, x5

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值