157 lines
6.9 KiB
Python
157 lines
6.9 KiB
Python
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__), '../../')))
|
|
|
|
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
|
|
|
|
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
|
|
|
|
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)}")
|
|
|
|
|
|
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}")
|
|
|
|
path_ckpt = Path(opt.MODEL.path_checkpoint)
|
|
path_onnx = Path(f"checkpoints/wav2vec2/{MODEL_ID.split('/')[-1]}.onnx")
|
|
|
|
# forward
|
|
batch_input = next(iter(test_loader))
|
|
raw_speech = batch_input["cond"].numpy() # (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)
|
|
|
|
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_model = onnx.load(path_onnx)
|
|
onnx.checker.check_model(onnx_model)
|
|
|
|
# check the numerical value
|
|
# get pytorch output
|
|
# batch_input = next(iter(test_loader))
|
|
# model.set_input(batch_input)
|
|
# print(f"cond shape = {model.cond.shape}")
|
|
|
|
# get onnx output
|
|
sess = rt.InferenceSession(str(path_onnx), providers=['CUDAExecutionProvider', 'CPUExecutionProvider'])
|
|
|
|
# x_input = {
|
|
# "input_values": model.inputs["input_values"].cpu().numpy(),
|
|
# "attention_mask": model.inputs["attention_mask"].cpu().numpy()
|
|
# }
|
|
print(f"raw_speech = {raw_speech.shape}, inputs['input_values'] = {inputs['input_values'].shape}")
|
|
|
|
raw_speech = inputs['input_values']
|
|
batch_onnx = sess.run(['output'], {"input": raw_speech.detach().cpu().numpy()})
|
|
|
|
print(f"batch_onnx len= {len(batch_onnx)}, [0] shape = {batch_onnx[0].shape}")
|
|
|
|
assert np.allclose(output, batch_onnx[0], atol=1e-3), 'The outputs are different between Pytorch and ONNX'
|
|
print(f"output[0, :, 100] = \n{output[0, :, 100]} \batch_onnx[0][0, :, 100]=\n{batch_onnx[0][0,:,100]}")
|
|
print('The numerical values are same between Pytorch and ONNX') |