add deployment tools of pytorch2onnx
This commit is contained in:
1 parent
28810e9ed3
commit
91cdd0d678
9 files changed
+461
-71
No files matched your search
@@ -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')
|
||||
|
||||
@@ -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')
|
||||
@@ -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')
|
||||
Reference in new issue
Block a user