使用Pytorch導出自定義ONNX算子的示例代碼
在實際部署模型時有時可能會遇到想用的算子無法導出onnx,但實際部署的框架是支持該算子的。此時可以通過自定義onnx算子的方式導出onnx模型(注:自定義onnx算子導出onnx模型后是無法使用onnxruntime推理的)。下面給出個具體應用中的示例:需要導出pytorch的affine_grid算子,但在pytorch的2.0.1版本中又無法正常導出該算子,故可通過如下自定義算子代碼導出。
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.autograd import Function
from torch.onnx import OperatorExportTypes
class CustomAffineGrid(Function):
@staticmethod
def forward(ctx, theta: torch.Tensor, size: torch.Tensor):
grid = F.affine_grid(theta=theta, size=size.cpu().tolist())
return grid
@staticmethod
def symbolic(g: torch.Graph, theta: torch.Tensor, size: torch.Tensor):
return g.op("AffineGrid", theta, size)
class MyModel(nn.Module):
def __init__(self) -> None:
super().__init__()
def forward(self, x: torch.Tensor, theta: torch.Tensor, size: torch.Tensor):
grid = CustomAffineGrid.apply(theta, size)
x = F.grid_sample(x, grid=grid, mode="bilinear", padding_mode="zeros")
return x
def main():
with torch.inference_mode():
custum_model = MyModel()
x = torch.randn(1, 3, 224, 224)
theta = torch.randn(1, 2, 3)
size = torch.as_tensor([1, 3, 512, 512])
torch.onnx.export(model=custum_model,
args=(x, theta, size),
f="custom.onnx",
input_names=["input0_x", "input1_theta", "input2_size"],
output_names=["output"],
dynamic_axes={"input0_x": {2: "h0", 3: "w0"},
"output": {2: "h1", 3: "w1"}},
opset_version=16,
operator_export_type=OperatorExportTypes.ONNX_FALLTHROUGH)
if __name__ == '__main__':
main()在上面代碼中,通過繼承torch.autograd.Function父類的方式實現(xiàn)導出自定義算子,繼承該父類后需要用戶自己實現(xiàn)forward以及symbolic兩個靜態(tài)方法,其中forward方法是在pytorch正常推理時調(diào)用的函數(shù),而symbolic方法是在導出onnx時調(diào)用的函數(shù)。對于forward方法需要按照正常的pytorch語法來實現(xiàn),其中第一個參數(shù)必須是ctx但對于當前導出onnx場景可以不用管它,后面的參數(shù)是實際自己傳入的參數(shù)。對于symbolic方法的第一個必須是g,后面的參數(shù)任為實際自己傳入的參數(shù),然后通過g.op方法指定具體導出自定義算子的名稱,以及輸入的參數(shù)(注:上面示例中傳入的都是Tensor所以可以直接傳入,對與非Tensor的參數(shù)可見下面一個示例)。最后在使用時直接調(diào)用自己實現(xiàn)類的apply方法即可。使用netron打開自己導出的onnx文件,可以看到如下所示網(wǎng)絡結構。

有時按照使用的推理框架導出自定義算子時還需要設置一些參數(shù)(非Tensor)那么可以參考如下示例,例如要導出int型的參數(shù)k那么可以通過傳入k_i來指定,要導出float型的參數(shù)scale那么可以通過傳入scale_f來指定,要導出string型的參數(shù)clockwise那么可以通過傳入clockwise_s來指定:
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.autograd import Function
from torch.onnx import OperatorExportTypes
class CustomRot90AndScale(Function):
@staticmethod
def forward(ctx, x: torch.Tensor):
x = torch.rot90(x, k=1, dims=(3, 2)) # clockwise 90
x *= 1.2
return x
@staticmethod
def symbolic(g: torch.Graph, x: torch.Tensor):
return g.op("Rot90AndScale", x, k_i=1, scale_f=1.2, clockwise_s="yes")
class MyModel(nn.Module):
def __init__(self) -> None:
super().__init__()
def forward(self, x: torch.Tensor):
return CustomRot90AndScale.apply(x)
def main():
with torch.inference_mode():
custum_model = MyModel()
x = torch.randn(1, 3, 224, 224)
torch.onnx.export(model=custum_model,
args=(x,),
f="custom_rot90.onnx",
input_names=["input"],
output_names=["output"],
dynamic_axes={"input": {2: "h0", 3: "w0"},
"output": {2: "w0", 3: "h0"}},
opset_version=16,
operator_export_type=OperatorExportTypes.ONNX_FALLTHROUGH)
if __name__ == '__main__':
main()使用netron打開自己導出的onnx文件,可以看到如下所示信息。

到此這篇關于使用Pytorch導出自定義ONNX算子的文章就介紹到這了,更多相關使用Pytorch導出自定義ONNX算子內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
Python基于Pymssql模塊實現(xiàn)連接SQL Server數(shù)據(jù)庫的方法詳解
這篇文章主要介紹了Python基于Pymssql模塊實現(xiàn)連接SQL Server數(shù)據(jù)庫的方法,較為詳細的分析了pymssql模塊的下載、安裝及連接、操作SQL Server數(shù)據(jù)庫的相關實現(xiàn)技巧,需要的朋友可以參考下2017-07-07
Python解析Excel圖表Chart的信息實戰(zhàn)指南
在數(shù)據(jù)分析與報表自動化場景中,Excel圖表往往承載著關鍵業(yè)務信息,本文將基于OpenXML規(guī)范,通過將.xlsx文件視為ZIP壓縮包,直接解析?xl/charts/chart*.xml,實現(xiàn)了對?Excel?圖表元數(shù)據(jù)的精準提取,感興趣的小伙伴可以了解下2026-01-01
使用python采集Excel表中某一格數(shù)據(jù)
這篇文章主要介紹了使用python采集Excel表中某一格數(shù)據(jù),文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下2020-05-05
Python tkinter實現(xiàn)桌面軟件流程詳解
這篇文章主要介紹了Python tkinter做一個好用的桌面軟件,100%你會愛上它,文中的示例代碼講解詳細,快跟小編一起動手試一試吧2022-10-10
從np.random.normal()到正態(tài)分布的擬合操作
這篇文章主要介紹了從np.random.normal()到正態(tài)分布的擬合操作,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-06-06
python服務器與android客戶端socket通信實例
這篇文章主要介紹了python服務器與android客戶端socket通信的實現(xiàn)方法,實例形式詳細講述了Python的服務器端實現(xiàn)原理與方法,以及對應的Android客戶端實現(xiàn)方法,需要的朋友可以參考下2014-11-11

