Files
audio2motion/deployment/pytorch2onnx_wav2vect.py

108 lines
4.7 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__), '../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')