Pytorch導(dǎo)出ONNX踩坑指南

相對(duì)與ONNX模型,Pytorch模型經(jīng)常較為松散朝刊,API的限制也往往較為寬松耀里。因此,在導(dǎo)出的過程中拾氓,不可避免地會(huì)遇到導(dǎo)出失敗的問題冯挎。可以預(yù)見到咙鞍,這塊API可能在不久的將來會(huì)發(fā)生變化房官。

ONNX導(dǎo)出

ONNX導(dǎo)出的基本操作比較簡單。官網(wǎng)上的例子是:

import torch
import torchvision

dummy_input = torch.randn(10, 3, 224, 224, device='cuda')
model = torchvision.models.alexnet(pretrained=True).cuda()

# Providing input and output names sets the display names for values
# within the model's graph. Setting these does not change the semantics
# of the graph; it is only for readability.
#
# The inputs to the network consist of the flat list of inputs (i.e.
# the values you would pass to the forward() method) followed by the
# flat list of parameters. You can partially specify names, i.e. provide
# a list here shorter than the number of inputs to the model, and we will
# only set that subset of names, starting from the beginning.
input_names = [ "actual_input_1" ] + [ "learned_%d" % i for i in range(16) ]
output_names = [ "output1" ]

torch.onnx.export(model, dummy_input, "alexnet.onnx", verbose=True, input_names=input_names, output_names=output_names)

可惜真要這么容易就好了

ONNX導(dǎo)出驗(yàn)證腳本

import onnxruntime
import numpy as np

sess = onnxruntime.InferenceSession('./model.onnx', None)

# 以圖像分類為例续滋,batchsize設(shè)為2測試導(dǎo)出模型支持batching翰守。
sess.run(None, {'input_1': np.random.rand(2, 3, img_height, img_width).astype('float32')})

讓導(dǎo)出模型支持同時(shí)處理多個(gè)數(shù)據(jù)(Batching)

支持Batching需要制定Dynamic Axes,即可變的維度疲酌。

案例:

torch.export(...,
  input_names=['input_1'],
  output_names=['output_1'],
  dynamic_axes={
    'input_1': [0],  # 第0維是batch dimension
    'output_1': [0],
  })

解決Caffe2運(yùn)行報(bào)錯(cuò)

keep_initializers_as_inputs 這個(gè)參數(shù)是False的情況下蜡峰,在Caffe2中報(bào)錯(cuò):IndexError: _Map_base::at. 參考https://github.com/onnx/onnx/issues/2458

opset 11在onnxruntime中運(yùn)行時(shí)沒使用GPU

問題比較復(fù)雜。貌似tensorflow也有類似問題。導(dǎo)出時(shí)添加參數(shù)do_constant_folding=True或許可以解決事示。
參考https://github.com/NVIDIA/triton-inference-server/issues/1080

List of tensor的導(dǎo)出

定長list

定長list會(huì)導(dǎo)出為一個(gè)tuple

變長list

Pytorch 1.4早像,ONNX 9不支持變長List的導(dǎo)出。之后的Pytorch版本有支持肖爵,需要更高版本的ONNX

不支持的操作

  • Tensor in-place indexed assignment like data[index] = new_data is currently not supported in exporting. One way to resolve this kind of issue is to use operator scatter, explicitly updating the original tensor.

  • There is no concept of tensor list in ONNX. Without this concept, it is very hard to export operators that consume or produce tensor list, especially when the length of the tensor list is not known at export time.

  • Only tuples, lists and Variables are supported as JIT inputs/outputs. Dictionaries and strings are also accepted but their usage is not recommended. Users need to verify their dict inputs carefully, and keep in mind that dynamic lookups are not available.

  • PyTorch and ONNX backends(Caffe2, ONNX Runtime, etc) often have implementations of operators with some numeric differences. Depending on model structure, these differences may be negligible, but they can also cause major divergences in behavior (especially on untrained models.) We allow Caffe2 to call directly to Torch implementations of operators, to help you smooth over these differences when precision is important, and to also document these differences.

不一致的Operator

Expand

Pytorch中卢鹦,Expand未改動(dòng)的dim可以指定為-1,導(dǎo)出到ONNX中時(shí)劝堪,需要手動(dòng)指定每個(gè)dim的值冀自。如:

Pytorch:
a = a.expand(10, -1, -1)
ONNX:
a = a.expand(10, a.size(1), a.size(2))

Squeeze

Pytorch中,Squeeze一個(gè)不為1維的dim不會(huì)有任何效果秒啦。ONNX會(huì)報(bào)錯(cuò)

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末熬粗,一起剝皮案震驚了整個(gè)濱河市,隨后出現(xiàn)的幾起案子余境,更是在濱河造成了極大的恐慌驻呐,老刑警劉巖,帶你破解...
    沈念sama閱讀 216,402評(píng)論 6 499
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件芳来,死亡現(xiàn)場離奇詭異含末,居然都是意外死亡,警方通過查閱死者的電腦和手機(jī)即舌,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,377評(píng)論 3 392
  • 文/潘曉璐 我一進(jìn)店門佣盒,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人顽聂,你說我怎么就攤上這事肥惭。” “怎么了紊搪?”我有些...
    開封第一講書人閱讀 162,483評(píng)論 0 353
  • 文/不壞的土叔 我叫張陵蜜葱,是天一觀的道長。 經(jīng)常有香客問我耀石,道長笼沥,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 58,165評(píng)論 1 292
  • 正文 為了忘掉前任娶牌,我火速辦了婚禮奔浅,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘诗良。我一直安慰自己汹桦,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,176評(píng)論 6 388
  • 文/花漫 我一把揭開白布鉴裹。 她就那樣靜靜地躺著舞骆,像睡著了一般钥弯。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上督禽,一...
    開封第一講書人閱讀 51,146評(píng)論 1 297
  • 那天脆霎,我揣著相機(jī)與錄音,去河邊找鬼狈惫。 笑死睛蛛,一個(gè)胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的胧谈。 我是一名探鬼主播忆肾,決...
    沈念sama閱讀 40,032評(píng)論 3 417
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼菱肖!你這毒婦竟也來了客冈?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 38,896評(píng)論 0 274
  • 序言:老撾萬榮一對(duì)情侶失蹤稳强,失蹤者是張志新(化名)和其女友劉穎场仲,沒想到半個(gè)月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體退疫,經(jīng)...
    沈念sama閱讀 45,311評(píng)論 1 310
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡渠缕,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,536評(píng)論 2 332
  • 正文 我和宋清朗相戀三年,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了蹄咖。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片褐健。...
    茶點(diǎn)故事閱讀 39,696評(píng)論 1 348
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡付鹿,死狀恐怖澜汤,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情舵匾,我是刑警寧澤俊抵,帶...
    沈念sama閱讀 35,413評(píng)論 5 343
  • 正文 年R本政府宣布,位于F島的核電站坐梯,受9級(jí)特大地震影響徽诲,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜吵血,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,008評(píng)論 3 325
  • 文/蒙蒙 一谎替、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧蹋辅,春花似錦钱贯、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,659評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽尉共。三九已至,卻和暖如春弃锐,著一層夾襖步出監(jiān)牢的瞬間袄友,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 32,815評(píng)論 1 269
  • 我被黑心中介騙來泰國打工霹菊, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留剧蚣,地道東北人。 一個(gè)月前我還...
    沈念sama閱讀 47,698評(píng)論 2 368
  • 正文 我出身青樓浇辜,卻偏偏與公主長得像券敌,于是被迫代替她去往敵國和親。 傳聞我的和親對(duì)象是個(gè)殘疾皇子柳洋,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,592評(píng)論 2 353

推薦閱讀更多精彩內(nèi)容

  • tensorflow開發(fā)API 架構(gòu) Modules app module: Generic entry poin...
    sennchi閱讀 1,348評(píng)論 0 2
  • NAME dnsmasq - A lightweight DHCP and caching DNS server....
    ximitc閱讀 2,844評(píng)論 0 0
  • This is a pre-print version. Official version: http://rsi...
    hydro閱讀 606評(píng)論 0 0
  • 啥都入門一下待诅,啥都不精。所有的都是按著廖雪峰大神的腳步走熊镣。從Node.js官網(wǎng)下載對(duì)應(yīng)平臺(tái)的安裝程序卑雁,網(wǎng)速慢的童鞋...
    mild_chen閱讀 259評(píng)論 0 0
  • 格式 顯示普通字符(雙引號(hào)可以忽略) 顯示轉(zhuǎn)移字符 結(jié)果: 顯示變量reed命令從標(biāo)準(zhǔn)輸入中讀取一行,并把輸入行的...
    AsaGuo閱讀 567評(píng)論 0 1