add onnx export
This commit is contained in:
1 parent
e2e8d8baf8
commit
28810e9ed3
22 files changed
+835
-342
No files matched your search
@@ -0,0 +1,141 @@
|
||||
# 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 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 _convert_batchnorm(module):
|
||||
"""Convert the syncBNs into normal BN3ds."""
|
||||
module_output = module
|
||||
if isinstance(module, torch.nn.SyncBatchNorm):
|
||||
module_output = torch.nn.BatchNorm3d(module.num_features, module.eps,
|
||||
module.momentum, module.affine,
|
||||
module.track_running_stats)
|
||||
if module.affine:
|
||||
module_output.weight.data = module.weight.data.clone().detach()
|
||||
module_output.bias.data = module.bias.data.clone().detach()
|
||||
# keep requires_grad unchanged
|
||||
module_output.weight.requires_grad = module.weight.requires_grad
|
||||
module_output.bias.requires_grad = module.bias.requires_grad
|
||||
module_output.running_mean = module.running_mean
|
||||
module_output.running_var = module.running_var
|
||||
module_output.num_batches_tracked = module.num_batches_tracked
|
||||
for name, child in module.named_children():
|
||||
module_output.add_module(name, _convert_batchnorm(child))
|
||||
del module
|
||||
return module_output
|
||||
|
||||
|
||||
def parse_args():
|
||||
parser = argparse.ArgumentParser(description='Convert DigitalHuman models to ONNX')
|
||||
|
||||
parser.add_argument("--opt", type=str, default="experiments/xxx.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)
|
||||
|
||||
|
||||
# load dataset
|
||||
test_dataset = create_dataset(opt, phase='valid')
|
||||
test_loader = DataLoader(test_dataset,
|
||||
batch_size=opt.TEST.batch_size * len(opt.GPUS),
|
||||
shuffle=True, # NOTE: usually set False
|
||||
num_workers=opt.WORKERS,
|
||||
pin_memory=False)
|
||||
logger.info(f"Test dataset size = {len(test_dataset)}, batch = {len(test_loader)}")
|
||||
|
||||
# for _, ibatch_test in enumerate(test_loader):
|
||||
# model.testing(batch_input=ibatch_test, cur_epoch=epoch) # forward and backward
|
||||
# break
|
||||
|
||||
# build the model
|
||||
model = create_model(opt, logger)
|
||||
model.setup(opt) # load checkpoints
|
||||
model.eval()
|
||||
|
||||
# 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 = next(iter(test_loader))
|
||||
batch_otput = model.forward(batch_input)
|
||||
print(f"cond shape = {model.cond.shape}, batch_otput shape = {batch_otput.shape}")
|
||||
|
||||
torch.onnx.export(
|
||||
netG, # model being run
|
||||
model.cond,
|
||||
str(path_onnx),
|
||||
export_params=True,
|
||||
verbose=True,
|
||||
opset_version=11,
|
||||
input_names=["cond"],
|
||||
output_names=["mesh"],
|
||||
dynamic_axes = {
|
||||
"cond": {0: "batch_size", 1: "nseqlen"},
|
||||
"mesh": {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
|
||||
# get pytorch output
|
||||
batch_input = next(iter(test_loader))
|
||||
batch_otput = model.forward(batch_input).detach().cpu().numpy()
|
||||
print(f"cond shape = {model.cond.shape}, batch_otput shape = {batch_otput.shape}")
|
||||
|
||||
# get onnx output
|
||||
sess = rt.InferenceSession(str(path_onnx), providers=['CUDAExecutionProvider', 'CPUExecutionProvider'])
|
||||
batch_onnx = sess.run(["mesh"], {"cond": model.cond.cpu().numpy()})[0]
|
||||
|
||||
print(f"batch_onnx = {batch_onnx.shape}, dtype={batch_onnx.dtype}, ")
|
||||
|
||||
assert np.allclose(batch_otput, batch_onnx), 'The outputs are different between Pytorch and ONNX'
|
||||
print('The numerical values are same between Pytorch and ONNX')
|
||||
|
||||
|
||||
Reference in new issue
Block a user