pytorch upsample層到onnx,以及到tensorRT的轉換(二)


之前的博客介紹了upsample層轉換到tensorRT出錯的解決方法,就是回退onnx版本到1.5.0。雖然暫時解決了問題,但無法使用高版本的pytorch和onnx,https://www.cnblogs.com/hypnus-ly/p/12932110.html

最近又上github,發現更簡單的解決方法,就是修改下upsample層初始化時的參數就可以了。 突然發現之前的博客好low啊,還是需要多多學習,發現問題的根源,找到本質解決方法。

if self.training:
    x = F.interpolate(x, scale_factor=2, mode="nearest") 
else: # hack in order to generate a simpler onnx 
    x = F.interpolate(x, size=[int(2 * x.shape[2]), int(2 * x.shape[3])], mode='nearest') # 如要轉換tensorRT模型的話,需要使用 size 參數,靜態的指定圖片大小

 upsample函數修改方式和上述代碼一樣

在使用upsample函數時,經常會先定義upsample module

m = nn.Upsample(scale_factor=2, mode="nearest")

然后在前向推理時,才動態的輸入數據,此時沒法預先設置 size 大小,解決方法:

在進行前向推理時,先獲取輸入的大小,再改變函數參數:

n,c,h,w = input.size()
size = (h*2, w*2)
m.scale_factor=None
m.size = (h * 2, w * 2)
output = m(input)

注意:scale_factor 參數 和 size 參數不能同時存在,所以要將 scale_factor 設置為 None

我的環境:

pytorch-1.5, onnx-1.7, tensorRT-7.0, cuda-10.0

參考鏈接:

https://github.com/onnx/onnx-tensorrt/issues/457

https://github.com/onnx/onnx-tensorrt/issues/361

https://github.com/pytorch/pytorch/issues/27376 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM