add onnx export
This commit is contained in:
1 parent
e2e8d8baf8
commit
28810e9ed3
22 files changed
+835
-342
No files matched your search
@@ -32,7 +32,7 @@ if __name__ == "__main__":
|
||||
|
||||
path_data = Path("/mfs/lsen/DATA/Actor1/processing")
|
||||
|
||||
path_save = Path('data/Actor1/Actor1-raw-7h') # processing
|
||||
path_save = Path('data/Actor1/Actor1-raw-16h') # processing
|
||||
path_save.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
v_dir_videos = sorted(path_data.glob("*/audio/feat_DECA_exp_trim.npy"))
|
||||
@@ -63,6 +63,7 @@ if __name__ == "__main__":
|
||||
print(f"vid test= {vid_test} \nvalid= {vid_valid}")
|
||||
print(f"vid train= {vid_train}")
|
||||
|
||||
# vid_tmp = ["34-28min"]
|
||||
# for each video
|
||||
data_train, data_valid, data_test = {}, {}, {}
|
||||
durations_train, durations_valid, durations_test = 0, 0, 0
|
||||
@@ -71,8 +72,10 @@ if __name__ == "__main__":
|
||||
|
||||
# if vid not in vids: continue
|
||||
# if vid in vid_test: continue
|
||||
# if vid in vid_valid:continue
|
||||
# if durations_train / 3600 > 5: break
|
||||
|
||||
# if vid in vid_tmp:continue
|
||||
|
||||
if durations_train / 3600 > 8: break
|
||||
# if durations_valid / 3600 > 4: break
|
||||
|
||||
print(f"\n processing the {i}-th video {vid} ... ")
|
||||
@@ -100,14 +103,13 @@ if __name__ == "__main__":
|
||||
print(f"info={info}, duration = {nframes/fps}")
|
||||
assert fps == 50, "fps should be 50"
|
||||
|
||||
|
||||
# laod motion
|
||||
data_exp = np.load(ipath_feat_exp) # (nframe, 50)
|
||||
data_pos = np.load(ipath_feat_pos) # (nframe, 6)
|
||||
data_idn = np.load(ipath_feat_idn) # (nframe, 100)
|
||||
# data_idn = np.load(ipath_feat_idn) # (nframe, 100)
|
||||
|
||||
assert data_exp.shape[0] == data_pos.shape[0], f"data_exp shape={data_exp.shape}, data_pos shape={data_pos.shape}"
|
||||
assert data_exp.shape[0] == data_idn.shape[0], f"data_exp shape={data_exp.shape}, data_idn shape={data_idn.shape}"
|
||||
# assert data_exp.shape[0] == data_idn.shape[0], f"data_exp shape={data_exp.shape}, data_idn shape={data_idn.shape}"
|
||||
|
||||
data_pos_head = data_pos[:, :3] # (nframe, 3)
|
||||
data_pos_lips = data_pos[:, 3:] # (nframe, 3)
|
||||
@@ -146,7 +148,7 @@ if __name__ == "__main__":
|
||||
"nframe": nframes,
|
||||
"data_motion": data_motion,
|
||||
"data_speech": audio_raw,
|
||||
"data_shape": data_idn,
|
||||
# "data_shape": data_idn,
|
||||
}
|
||||
|
||||
|
||||
@@ -159,7 +161,7 @@ if __name__ == "__main__":
|
||||
"nframe": nframes,
|
||||
"data_motion": data_motion,
|
||||
"data_speech": audio_raw,
|
||||
"data_shape": data_idn,
|
||||
# "data_shape": data_idn,
|
||||
}
|
||||
|
||||
|
||||
@@ -172,7 +174,7 @@ if __name__ == "__main__":
|
||||
"nframe": nframes,
|
||||
"data_motion": data_motion,
|
||||
"data_speech": audio_raw,
|
||||
"data_shape": data_idn,
|
||||
# "data_shape": data_idn,
|
||||
}
|
||||
|
||||
print(f"frames: data_train ({durations_train / 60 } min) ({durations_train / 3600 } h) , ids = ({len(data_train)})")
|
||||
|
||||
Whitespace-only changes.
@@ -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')
|
||||
|
||||
|
||||
@@ -0,0 +1,157 @@
|
||||
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')
|
||||
@@ -0,0 +1,36 @@
|
||||
import onnx
|
||||
import argparse
|
||||
|
||||
|
||||
def get_args():
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument("--input", required=True, help="input model")
|
||||
parser.add_argument("--output", required=True, help="output model")
|
||||
args = parser.parse_args()
|
||||
return args
|
||||
|
||||
|
||||
def remove_initializer_from_input():
|
||||
args = get_args()
|
||||
|
||||
model = onnx.load(args.input)
|
||||
if model.ir_version < 4:
|
||||
print(
|
||||
'Model with ir_version below 4 requires to include initilizer in graph input'
|
||||
)
|
||||
return
|
||||
|
||||
inputs = model.graph.input
|
||||
name_to_input = {}
|
||||
for input in inputs:
|
||||
name_to_input[input.name] = input
|
||||
|
||||
for initializer in model.graph.initializer:
|
||||
if initializer.name in name_to_input:
|
||||
inputs.remove(name_to_input[initializer.name])
|
||||
|
||||
onnx.save(model, args.output)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
remove_initializer_from_input()
|
||||
+65
@@ -0,0 +1,65 @@
|
||||
GPUS: '8'
|
||||
WORKERS: 4
|
||||
OUTPUT_DIR: 'experiments/audio2mesh'
|
||||
|
||||
DEBUG: True
|
||||
verbose: False
|
||||
isTrain: False
|
||||
|
||||
FREQ:
|
||||
epoch_save: 5
|
||||
epoch_valid: 1
|
||||
batch_print: 20
|
||||
epoch_test: 5
|
||||
|
||||
|
||||
MODEL:
|
||||
name: 'audio2mesh2'
|
||||
name_netG: "audio2mesh"
|
||||
|
||||
dim_motion: 53 # 68*2
|
||||
dim_speech: 1024
|
||||
num_vertices: 5023
|
||||
|
||||
pretrain: True
|
||||
|
||||
# # # 1h 1:10
|
||||
path_checkpoint: "experiments/audio2mesh/train_audio2mesh_CN_20220314/20220315-02H14M47S"
|
||||
load_epoch: 100
|
||||
|
||||
# # # 2h 1:10
|
||||
# path_checkpoint: "experiments/audio2mesh/train_audio2mesh_CN_20220314/20220315-18H22M47S"
|
||||
# load_epoch: 100
|
||||
|
||||
# # 3h 1:100
|
||||
# path_checkpoint: "experiments/audio2mesh/train_audio2mesh_CN_20220314/20220316-16H38M26S"
|
||||
# load_epoch: 100
|
||||
|
||||
# # 5h
|
||||
# path_checkpoint: "experiments/audio2mesh/train_audio2mesh_CN_20220314/20220321-17H42M19S"
|
||||
# load_epoch: 100
|
||||
|
||||
|
||||
DATASET:
|
||||
fps: 50
|
||||
sr: 16000
|
||||
# name: "motion_live"
|
||||
name: "motion_eval"
|
||||
|
||||
root: './data/Actor1/Actor1-raw-1h' # obama-deca-3-5-08-mini
|
||||
root_raw: '/yrfs/lsen/DATA/Actor1/processing'
|
||||
path_mean_dict: './data/Actor1/DECA_Actor1_mean.npy'
|
||||
filter: 'savgol'
|
||||
speech_extractor: 'wav2vec'
|
||||
|
||||
nwind_second_train: 3
|
||||
nwind_second_valid: 3
|
||||
nwind_second_test: 15
|
||||
|
||||
TRAIN:
|
||||
apply_testing: True
|
||||
apply_validation: True
|
||||
|
||||
|
||||
LOSS:
|
||||
names: ["rec_geo", "vel_geo", "rec_ldmk", "closure_x", "closure_y"]
|
||||
+1
@@ -0,0 +1 @@
|
||||
[2022-04-06 16:22:02,962][INFO] device set to cuda:8
|
||||
Reference in new issue
Block a user