add deployment tools of pytorch2onnx

This commit is contained in:
Sen Liang committed 2022-04-12 11:24:38 +08:00
1 parent 28810e9ed3
commit 91cdd0d678
8 files changed
+461 -71

No files matched your search

+104
View File
@@ -0,0 +1,104 @@
# Copyright (c) OpenMMLab. All rights reserved.
import os
import sys
import argparse
from pathlib import Path
import torch
import numpy as np
import onnx
import onnxruntime as rt
sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '../audio2motion')))
from src.config import config as opt
from src.config import update_config
from src.datasets import create_dataset
from src.models import create_model, calculate_model_params
from common.logger import Logger
def parse_args():
parser = argparse.ArgumentParser(description='Convert DigitalHuman models to ONNX')
parser.add_argument("--opt", type=str, default="experiments/infer_audio2mesh_CN_20220312.yaml", help="experiment configure file name")
args, _ = parser.parse_known_args()
update_config(args.opt)
# parser.add_argument('checkpoint', help='checkpoint file')
# parser.add_argument('--show', action='store_true', help='show onnx graph')
# parser.add_argument('--output-file', type=str, default='tmp.onnx')
# parser.add_argument('--opset-version', type=int, default=11)
# parser.add_argument('--verify', action='store_true', help='verify the onnx model output against pytorch output')
# parser.add_argument('--is-localizer', action='store_true', help='whether it is a localizer')
# parser.add_argument('--shape', type=int, nargs='+', default=[1, 3, 8, 224, 224], help='input video size')
# parser.add_argument('--softmax', action='store_true', help='wheter to add softmax layer at the end of recognizers')
args = parser.parse_args()
return args
if __name__ == '__main__':
args = parse_args()
path_config = Path(args.opt)
postfix = opt.TRAIN.resume_suffix if opt.TRAIN.resume else None # if resume, resume to resume_suffix folder
logger = Logger(opt.OUTPUT_DIR, path_config=path_config, postfix=postfix)
# build the model
model = create_model(opt, logger)
model.setup(opt) # load checkpoints
# export model
netG = model.netG
netG.eval() # set inference model
path_ckpt = Path(opt.MODEL.path_checkpoint)
path_onnx = Path(f"checkpoints/audio2mesh-{path_ckpt.stem}-{opt.MODEL.load_epoch}.onnx")
if not path_onnx.exists():
# forward
batch_input = torch.randn((20, 35, 16, 1024)).float().to(model.device) # (B, nseq, nseqlen, nc_condit)
batch_otput = model.netG.forward(batch_input).detach().cpu().numpy() # (B, nseq, 5023, 3)
print(f"cond shape = {batch_input.shape}, batch_otput shape = {batch_otput.shape}")
# cond shape = torch.Size([20, 35, 16, 1024]), batch_otput shape = (20, 35, 5023, 3)
torch.onnx.export(
netG.module, # model being run
batch_input,
str(path_onnx),
export_params=True,
verbose=True,
opset_version=11,
input_names=["input"],
output_names=["output"],
dynamic_axes = {
"input": {0: "batch_size", 1: "nseqlen"},
"output": {0: "batch_size"}
}
)
print(f'Successfully exported ONNX model: {path_onnx}')
else:
print(f'Have existed exported ONNX model: {path_onnx}')
############################################ valify
onnx_model = onnx.load(path_onnx)
onnx.checker.check_model(onnx_model)
# check the numerical value
batch_input = torch.randn((20, 35, 16, 1024)).float().to(model.device) # (B, nseq, nseqlen, nc_condit)
batch_otput = model.netG.forward(batch_input).detach().cpu().numpy() # (B, nseq, 5023, 3)
print(f"cond shape = {batch_input.shape}, batch_otput shape = {batch_otput.shape}")
# get onnx output
sess = rt.InferenceSession(str(path_onnx), providers=['CUDAExecutionProvider', 'CPUExecutionProvider'])
batch_onnx = sess.run(["output"], {"input": batch_input.cpu().numpy()})[0]
print(f"batch_onnx = {batch_onnx.shape}, dtype={batch_onnx.dtype}, ")
assert np.allclose(batch_otput, batch_onnx, atol=1e-4), 'The outputs are different between Pytorch and ONNX'
print(f"output[0,0,100:120,0] = \n{batch_otput[0,0,100:120,0]} \
batch_onnx[0][0,0,100:120,0]=\n{batch_onnx[0,0,100:120,0]}")
print('The numerical values are same between Pytorch and ONNX')
+85
View File
@@ -0,0 +1,85 @@
# Copyright (c) OpenMMLab. All rights reserved.
import argparse
from pathlib import Path
import torch
import numpy as np
from torch.utils.data import DataLoader
import onnx
import onnxruntime as rt
import os, sys
sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '../')))
from lsp.options.test_feature2face_options import TestOptions as RenderOptions
from lsp.models import create_model
from lsp.models import feature2face_model
from lsp.models.feature2face_G import Feature2Face_G
if __name__ == '__main__':
# create m2f model
gen_opt = RenderOptions().parse()
gen_opt.name = "ljj" #args.name
gen_opt.batch_size = 64 #args.batch_size_m2f
path_ckpt_m2f = f'./data/render/models/{gen_opt.name}/render_g.pkl'
device = torch.device("cuda:0")
# model_m2f = create_model(gen_opt)
# model_m2f.Feature2Face_G.eval()
# model_m2f.Feature2Face_G.load_state_dict(torch.load(path_ckpt_m2f), strict = True)
netG = Feature2Face_G(gen_opt).to(device)
netG = torch.nn.DataParallel(netG, [device,])
netG.load_state_dict(torch.load(path_ckpt_m2f), strict = True)
netG.eval()
path_onnx = Path(f"checkpoints/render/{gen_opt.name}/render_g.onnx")
path_onnx.parent.mkdir(parents=True, exist_ok=True)
if not path_onnx.exists():
# forward test
batch_input = torch.randn(size=(1, 6, 512, 512)).float().to(device) # (B, 6, 512, 512)
batch_otput = netG(batch_input) # (B, 3, 512, 512)
print(f"batch_input shape = {batch_input.shape}, batch_otput shape = {batch_otput.shape}")
torch.onnx.export(
netG.module, # model being run
batch_input,
str(path_onnx),
export_params=True,
verbose=True,
opset_version=11,
input_names=["input"],
output_names=["output"],
dynamic_axes = {
"input": {0: "batch_size"},
"output": {0: "batch_size"}
}
)
print(f'Successfully exported ONNX model: {path_onnx}')
else:
print(f'Have existed exported ONNX model: {path_onnx}')
############################################ valify onnx
onnx_model = onnx.load(path_onnx)
onnx.checker.check_model(onnx_model)
# check the numerical value
batch_input = torch.randn(size=(1, 6, 512, 512)).float().to(device) # (B, 6, 512, 512)
batch_otput = netG(batch_input).detach().cpu().numpy() # (B, 3, 512, 512)
print(f"batch_input shape = {batch_input.shape}, batch_otput shape = {batch_otput.shape}")
# get onnx output
sess = rt.InferenceSession(str(path_onnx), providers=['CUDAExecutionProvider', 'CPUExecutionProvider'])
batch_onnx = sess.run(["output"], {"input": batch_input.cpu().numpy()})[0]
print(f"batch_onnx = {batch_onnx.shape}, dtype={batch_onnx.dtype}, ")
assert np.allclose(batch_otput, batch_onnx, atol=1e-4), 'The outputs are different between Pytorch and ONNX'
print(f"output[0, :, 100] = \n{batch_otput[0, 0, 100:120, 100]} \batch_onnx[0][0, :, 100]=\n{batch_onnx[0, 0, 100:120, 100]}")
print('The numerical values are same between Pytorch and ONNX')
+108
View File
@@ -0,0 +1,108 @@
import argparse
from pathlib import Path
import torch
import numpy as np
from torch.utils.data import DataLoader
from torchaudio.models.wav2vec2.utils import import_huggingface_model
import onnx
import onnxruntime as rt
import os, sys
sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '../audio2motion')))
from src.config import config as opt
from src.config import update_config
from src.datasets import create_dataset
from common.logger import Logger
from transformers import Wav2Vec2FeatureExtractor, Wav2Vec2Model
# https://github.com/ccoreilly/wav2vec2-service/blob/master/convert_torch_to_onnx.py
# https://huggingface.co/docs/transformers/serialization
# https://huggingface.co/docs/transformers/main/en/model_doc/wav2vec2#transformers.Wav2Vec2Model
if __name__ == "__main__":
print("load Wav2Vec2Model ...")
MODEL_ID = "jonatasgrosman/wav2vec2-large-xlsr-53-chinese-zh-cn"
# self.processor = Wav2Vec2FeatureExtractor.from_pretrained(MODEL_ID)
# self.extractor = Wav2Vec2Model.from_pretrained(MODEL_ID).to(self.device)
# build the model
device = "cuda:9"
path_ckpt_wav2vec = "./checkpoints/wav2vec2"
processor = Wav2Vec2FeatureExtractor.from_pretrained(path_ckpt_wav2vec)
extractor = Wav2Vec2Model.from_pretrained(path_ckpt_wav2vec).to(device)
# import
model_extractor = import_huggingface_model(extractor)
model_extractor.eval() # set the model to inference mode
model_extractor.to(device)
# print(f"model_extractor device = {model_extractor.device}")
# forward
raw_speech = np.random.randn(1, 16000*10) # (B, nsegments)
print(f"raw_speech = {raw_speech.shape}, dtype={raw_speech.dtype}")
# padding half frame length for bed and end
npad = int(0.5 * 16000 * ( 1 / 50) + 0.5)
raw_speech = np.pad(raw_speech, pad_width=((0,0), (npad, npad)), mode="edge")
print(f"after padding raw_speech = {raw_speech.shape}, dtype={raw_speech.dtype}")
speech = list(raw_speech)
inputs = processor(speech, sampling_rate=16000, return_tensors="pt")
inputs = inputs.to(device)
print(f"inputs keys = {inputs.keys()}")
with torch.no_grad():
# output = extractor(**inputs)
output = extractor(**inputs).last_hidden_state
output = output.cpu().numpy()
print(f"self.output shape = {output.shape}")
print(f"input_values shape = {inputs['input_values'].shape}, attention_mask shape = {inputs['attention_mask'].shape}")
# x_input = (inputs["input_values"], inputs["attention_mask"])
raw_speech = torch.from_numpy(raw_speech).float().to(device)
path_onnx = Path(f"checkpoints/wav2vec2/{MODEL_ID.split('/')[-1]}.onnx")
if not path_onnx.exists():
torch.onnx.export(
model_extractor, # model being run
raw_speech, # model input (or a tuple for multiple inputs)
str(path_onnx), # where to save the model (can be a file or file-like object)
export_params=True, # store the trained parameter weights inside the model file
opset_version=11, # the ONNX version to export the model to
do_constant_folding=True, # whether to execute constant folding for optimization
input_names = ['input'], # the model's input names
output_names = ['output'], # the model's output names
dynamic_axes={'input' : {0: "batch_size", 1 : 'audio_len'}, # variable length axes
'output' : {0: "batch_size", 1 : 'nseqlen'}
})
print(f'Successfully exported ONNX model: {path_onnx}')
else:
print(f'Have existed exported ONNX model: {path_onnx}')
############################################ valify onnx
onnx_model = onnx.load(path_onnx)
onnx.checker.check_model(onnx_model)
# check the numerical value
raw_speech = inputs['input_values']
print(f"raw_speech = {raw_speech.shape}, inputs['input_values'] = {inputs['input_values'].shape}")
sess = rt.InferenceSession(str(path_onnx), providers=['CUDAExecutionProvider', 'CPUExecutionProvider'])
batch_onnx = sess.run(['output'], {"input": raw_speech.detach().cpu().numpy()})[0]
print(f"batch_onnx = {batch_onnx.shape}, dtype={batch_onnx.dtype}, ")
assert np.allclose(output, batch_onnx, atol=1e-3), 'The outputs are different between Pytorch and ONNX'
print(f"output[0, :20, 100] = \n{output[0, :20, 100]} \batch_onnx[0, :20, 100]=\n{batch_onnx[0,:20,100]}")
print('The numerical values are same between Pytorch and ONNX')
+5 -4
View File
@@ -8,8 +8,10 @@ if __name__ == '__main__':
# path_root = Path("/yrfs/lsen/DATA/Actor1") # path_root = Path("/yrfs/lsen/DATA/Actor1")
path_raw = Path("/ssdata1/cf/data/raw/20220319") # path_raw = Path("/ssdata1/cf/data/raw/20220319")
path_root = Path("/yrfs/lsen/DATA/Actor2") path_raw = Path("/ssdata1/cf/data/raw/20220408")
# path_root = Path("/mfs/lsen/DATA/Actor2/processing")
path_root = Path("/mfs/lsen/DATA/Actor2/happy")
vpath_videos = sorted(path_raw.glob("*.MP4"), reverse=False) vpath_videos = sorted(path_raw.glob("*.MP4"), reverse=False)
print(f"Have {len(vpath_videos)} dir files") print(f"Have {len(vpath_videos)} dir files")
@@ -25,7 +27,7 @@ if __name__ == '__main__':
# if iname not in IDs: continue # if iname not in IDs: continue
# data path # data path
ipath_data = path_root.joinpath("processing", ipath_item.stem) ipath_data = path_root.joinpath(ipath_item.stem)
ipath_frame = ipath_data.joinpath("frames") ipath_frame = ipath_data.joinpath("frames")
ipath_video = ipath_data.joinpath("video") ipath_video = ipath_data.joinpath("video")
@@ -91,7 +93,6 @@ if __name__ == '__main__':
nframes = len(list(video.iter_frames())) nframes = len(list(video.iter_frames()))
# get audio # get audio
audio_sub = video.audio audio_sub = video.audio
if audio_sub is None: if audio_sub is None:
@@ -24,7 +24,8 @@ def main(args):
deca = DECA(config = deca_cfg, device=device) deca = DECA(config = deca_cfg, device=device)
# path_data = Path("/yrfs/lsen/DATA/TestData/processing") # path_data = Path("/yrfs/lsen/DATA/TestData/processing")
path_data = Path("/yrfs/lsen/DATA/Actor2/processing") # path_data = Path("/mfs/lsen/DATA/Actor2/processing")
path_data = Path("/mfs/lsen/DATA/Actor2/happy")
v_dir_videos = sorted(path_data.glob("*"), reverse=False) v_dir_videos = sorted(path_data.glob("*"), reverse=False)
print(f"Have {len(v_dir_videos)} dir files") print(f"Have {len(v_dir_videos)} dir files")
@@ -39,7 +40,6 @@ def main(args):
# if ivideo_name not in IDs: continue # if ivideo_name not in IDs: continue
# if i > 25: break # if i > 25: break
ipath_infor = ipath_data.joinpath("video/info.json") ipath_infor = ipath_data.joinpath("video/info.json")
ipath_frame = ipath_data.joinpath("frames") ipath_frame = ipath_data.joinpath("frames")
+73 -64
View File
@@ -1,5 +1,6 @@
from pathlib import Path from pathlib import Path
import json import json
import os
import moviepy import moviepy
from moviepy.editor import VideoFileClip, AudioFileClip from moviepy.editor import VideoFileClip, AudioFileClip
@@ -36,18 +37,18 @@ if __name__ == '__main__':
ipath_video.mkdir(parents=True, exist_ok=True) ipath_video.mkdir(parents=True, exist_ok=True)
ipath_audio.mkdir(parents=True, exist_ok=True) ipath_audio.mkdir(parents=True, exist_ok=True)
# # load video info & check # # # load video info & check
if ipath_infor.exists(): # if ipath_infor.exists():
# continue # # continue
with open(str(ipath_infor), "r") as f: # with open(str(ipath_infor), "r") as f:
info = json.load(f) # info = json.load(f)
nframe_info = info['nframes'] # nframe_info = info['nframes']
# check frames # # check frames
nframe_real = len(list(ipath_frame.glob("*.jpg"))) # nframe_real = len(list(ipath_frame.glob("*.jpg")))
if nframe_real == nframe_info: # if nframe_real == nframe_info:
print(f"\n Skip: have already done!") # print(f"\n Skip: have already done!")
continue # continue
# load video # load video
video = VideoFileClip(str(ipath_item)) video = VideoFileClip(str(ipath_item))
@@ -61,71 +62,79 @@ if __name__ == '__main__':
print(f"\n\t -> Total durations = ({durations / 60 } min) ({durations / 3600 } h))") print(f"\n\t -> Total durations = ({durations / 60 } min) ({durations / 3600 } h))")
# continue # continue
# Trim # add
# video = video.subclip(t_start=5.0, t_end=int(video.duration)-5.0) before 03.14
video = video.subclip(t_start=15.0, t_end=int(video.duration)-15.0)
# video = video.subclip(t_start=5.0, t_end=60.0)
print(f"after cut video duration = {video.duration}, fps = {video.fps}, (start, end)=({video.start},{video.end}), nframes={int(video.duration * video.fps)}")
nframes = int(video.duration * video.fps)
# nframes = len(list(video.iter_frames()))
# print(f"after cut video duration = {video.duration}, fps = {video.fps}, (start, end)=({video.start},{video.end}), nframes={int(video.duration * video.fps)}")
# if fps != 50
if video.fps != 50:
print("FPS NOT = 50!! ")
# save sub video fps=50
ipath_video_sub = ipath_video.joinpath("video_trim.mp4") ipath_video_sub = ipath_video.joinpath("video_trim.mp4")
if ipath_video_sub.exists(): if not ipath_video_sub.exists():
print("\nERROR: ipath_video_sub.exists()") cmd = f"ffmpeg -y -ss 15 -t {int(video.duration)-15.0} -i {str(ipath_item)} -vcodec copy -acodec copy {str(ipath_video_sub)}"
continue os.system(cmd)
else:
video.write_videofile(str(ipath_video_sub), fps=50, audio=True)
print(f"save video > {ipath_video_sub}") print(f"save video > {ipath_video_sub}")
# reload video
video.close() # # Trim
video = VideoFileClip(str(ipath_video_sub)) # # video = video.subclip(t_start=5.0, t_end=int(video.duration)-5.0) before 03.14
print(f"video reload duration = {video.duration}, fps = {video.fps}, (start, end)=({video.start},{video.end}), nframes={int(video.duration * video.fps)}") # video = video.subclip(t_start=15.0, t_end=int(video.duration)-15.0)
nframes = len(list(video.iter_frames()))
# # video = video.subclip(t_start=5.0, t_end=60.0)
# print(f"after cut video duration = {video.duration}, fps = {video.fps}, (start, end)=({video.start},{video.end}), nframes={int(video.duration * video.fps)}")
# nframes = int(video.duration * video.fps)
# # nframes = len(list(video.iter_frames()))
# # print(f"after cut video duration = {video.duration}, fps = {video.fps}, (start, end)=({video.start},{video.end}), nframes={int(video.duration * video.fps)}")
# # if fps != 50
# if video.fps != 50:
# print("FPS NOT = 50!! ")
# # save sub video fps=50
# ipath_video_sub = ipath_video.joinpath("video_trim.mp4")
# if ipath_video_sub.exists():
# print("\nERROR: ipath_video_sub.exists()")
# continue
# else:
# video.write_videofile(str(ipath_video_sub), fps=50, audio=True)
# print(f"save video > {ipath_video_sub}")
# # reload video
# video.close()
# video = VideoFileClip(str(ipath_video_sub))
# print(f"video reload duration = {video.duration}, fps = {video.fps}, (start, end)=({video.start},{video.end}), nframes={int(video.duration * video.fps)}")
# nframes = len(list(video.iter_frames()))
# get audio # # get audio
audio_sub = video.audio # audio_sub = video.audio
if audio_sub is None: # if audio_sub is None:
print("\nERROR: audio info is None") # print("\nERROR: audio info is None")
print(f"audio_sub duration = {audio_sub.duration}, fps = {audio_sub.fps}, (start, end)=({audio_sub.start},{audio_sub.end}), nframes={int(audio_sub.duration * audio_sub.fps)}") # print(f"audio_sub duration = {audio_sub.duration}, fps = {audio_sub.fps}, (start, end)=({audio_sub.start},{audio_sub.end}), nframes={int(audio_sub.duration * audio_sub.fps)}")
# save audio_sub # # save audio_sub
ipath_audio_sub = ipath_audio.joinpath("audio_trim.wav") # ipath_audio_sub = ipath_audio.joinpath("audio_trim.wav")
audio_sub.write_audiofile(str(ipath_audio_sub), fps=audio_sub.fps) # audio_sub.write_audiofile(str(ipath_audio_sub), fps=audio_sub.fps)
print(f"save audio > {ipath_audio_sub}") # print(f"save audio > {ipath_audio_sub}")
# # check fps # # # check fps
# if int(video.fps) != 50: # # if int(video.fps) != 50:
# print(f"\n Skip: fps != 50 realy fps={video.fps}, convert to 50fps") # # print(f"\n Skip: fps != 50 realy fps={video.fps}, convert to 50fps")
# ipath_video_save = ipath_data.joinpath("video", f"video_50fps.mp4") # # ipath_video_save = ipath_data.joinpath("video", f"video_50fps.mp4")
# video.write_videofile(str(ipath_video_save), fps=50.0) # # video.write_videofile(str(ipath_video_save), fps=50.0)
# print(f"save video to > {ipath_video_save}...") # # print(f"save video to > {ipath_video_save}...")
# save video feature # # save video feature
info = {"nframes": nframes, # info = {"nframes": nframes,
"fps": video.fps, # "fps": video.fps,
"width": video.w, # "width": video.w,
"height": video.h} # "height": video.h}
with open(str(ipath_infor), 'w+') as f: # with open(str(ipath_infor), 'w+') as f:
json.dump(info, f) # json.dump(info, f)
print(info) # print(info)
print(f"save video info in -> {ipath_infor}\n") # print(f"save video info in -> {ipath_infor}\n")
# save trim video # # save trim video
print(f"write_images_sequence...") # print(f"write_images_sequence...")
ipath_format = str(ipath_frame) + "/frame-%06d.jpg" # ipath_format = str(ipath_frame) + "/frame-%06d.jpg"
video.write_images_sequence(ipath_format, fps=50) # video.write_images_sequence(ipath_format, fps=50)
@@ -45,7 +45,7 @@ def _convert_batchnorm(module):
def parse_args(): def parse_args():
parser = argparse.ArgumentParser(description='Convert DigitalHuman models to ONNX') parser = argparse.ArgumentParser(description='Convert DigitalHuman models to ONNX')
parser.add_argument("--opt", type=str, default="experiments/xxx.yaml", help="experiment configure file name") parser.add_argument("--opt", type=str, default="experiments/audio2mesh/infer_audio2mesh_CN_20220312.yaml", help="experiment configure file name")
args, _ = parser.parse_known_args() args, _ = parser.parse_known_args()
update_config(args.opt) update_config(args.opt)
@@ -0,0 +1,83 @@
# Copyright (c) OpenMMLab. All rights reserved.
import argparse
from pathlib import Path
import torch
import numpy as np
from torch.utils.data import DataLoader
import onnx
import onnxruntime as rt
import os, sys
sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '../')))
from lsp.options.test_feature2face_options import TestOptions as RenderOptions
from lsp.models import create_model
from lsp.models import feature2face_model
from lsp.models.feature2face_G import Feature2Face_G
if __name__ == '__main__':
# create m2f model
gen_opt = RenderOptions().parse()
gen_opt.name = "ljj" #args.name
gen_opt.batch_size = 64 #args.batch_size_m2f
path_ckpt_m2f = f'./data/render/models/{gen_opt.name}/render_g.pkl'
device = torch.device("cuda:0")
# model_m2f = create_model(gen_opt)
# model_m2f.Feature2Face_G.eval()
# model_m2f.Feature2Face_G.load_state_dict(torch.load(path_ckpt_m2f), strict = True)
netG = Feature2Face_G(gen_opt).to(device)
netG = torch.nn.DataParallel(netG, [device,])
netG.load_state_dict(torch.load(path_ckpt_m2f), strict = True)
netG.eval()
path_onnx = Path(f"./data/render/models/{gen_opt.name}/render_g.onnx")
if not path_onnx.exists():
# forward test
batch_input = torch.randn(size=(1, 6, 512, 512)).float().to(device) # (B, 6, 512, 512)
batch_otput = netG(batch_input) # (B, 3, 512, 512)
print(f"batch_input shape = {batch_input.shape}, batch_otput shape = {batch_otput.shape}")
torch.onnx.export(
netG.module, # model being run
batch_input,
str(path_onnx),
export_params=True,
verbose=True,
opset_version=11,
input_names=["input"],
output_names=["output"],
dynamic_axes = {
"input": {0: "batch_size"},
"output": {0: "batch_size"}
}
)
print(f'Successfully exported ONNX model: {path_onnx}')
else:
print(f'Have existed exported ONNX model: {path_onnx}')
# valify
onnx_model = onnx.load(path_onnx)
onnx.checker.check_model(onnx_model)
# check the numerical value
batch_input = torch.randn(size=(1, 6, 512, 512)).float().to(device) # (B, 6, 512, 512)
batch_otput = netG(batch_input).detach().cpu().numpy() # (B, 3, 512, 512)
print(f"batch_input shape = {batch_input.shape}, batch_otput shape = {batch_otput.shape}")
# get onnx output
sess = rt.InferenceSession(str(path_onnx), providers=['CUDAExecutionProvider', 'CPUExecutionProvider'])
batch_onnx = sess.run(["output"], {"input": batch_input.cpu().numpy()})[0]
print(f"batch_onnx = {batch_onnx.shape}, dtype={batch_onnx.dtype}, ")
assert np.allclose(batch_otput, batch_onnx, atol=1e-4), 'The outputs are different between Pytorch and ONNX'
print('The numerical values are same between Pytorch and ONNX')
print(f"output[0, :, 100] = \n{batch_otput[0, 0, 100:120, 100]} \batch_onnx[0][0, :, 100]=\n{batch_onnx[0, 0, 100:120, 100]}")