add onnx export

This commit is contained in:
Sen Liang committed 2022-04-08 11:58:11 +08:00
1 parent e2e8d8baf8
commit 28810e9ed3
22 files changed
+828 -335

No files matched your search

+1 -2
View File
@@ -187,7 +187,7 @@ def save_animation_with_gt2(images_pt, images_gt, path_save, fps=None, path_audi
"""
# print(f"images_pt shape = {len(images_pt)}, shape[0]={images_pt[0].shape}")
fps = fps if fps else 30
fps = fps if fps else 50
N = len(images_pt)
duration = N / fps
@@ -216,7 +216,6 @@ def save_animation_with_gt2(images_pt, images_gt, path_save, fps=None, path_audi
animation = animation.set_audio(audioclip)
animation = animation.set_duration(duration)
animation.write_videofile(str(path_save), fps=fps)
# close
@@ -1,4 +1,4 @@
GPUS: '5'
GPUS: '9'
WORKERS: 4
OUTPUT_DIR: 'experiments/audio2mesh'
@@ -45,28 +45,31 @@ MODEL:
DATASET:
fps: 50
sr: 16000
# name: "motion_live"
name: "motion_eval"
name_train: "motion_live"
name_valid: "motion_eval"
flip: False
shifting_speed: True
# root: './data/Actor2/Actor2-raw-7h' # obama-deca-3-5-08-mini
root: './data/Actor2/Actor2-raw-2h' # obama-deca-3-5-08-mini
root: './data/Actor2/Actor2-raw-1h' # obama-deca-3-5-08-mini
root_raw: '/yrfs/lsen/DATA/Actor2/processing'
root_raw: '/mfs/lsen/DATA/Actor2/processing'
path_mean_dict: './data/Actor2/DECA_Actor2_mean.npy'
filter: 'savgol'
speech_extractor: 'wav2vec'
nwind_second_train: 3
nwind_second_valid: 3
nwind_second_test: 15
nwind_second_train: 1 # 3
nwind_second_valid: 1 # 3
nwind_second_test: 1 # 15
TRAIN:
apply_testing: True
apply_validation: True
TEST:
batch_size: 20
LOSS:
names: ["rec_geo", "vel_geo", "rec_ldmk", "closure_x", "closure_y"]
@@ -2,7 +2,7 @@ GPUS: '8'
WORKERS: 4
OUTPUT_DIR: 'experiments/audio2mesh'
DEBUG: False
DEBUG: True
verbose: False
isTrain: False
@@ -0,0 +1,48 @@
GPUS: '9'
WORKERS: 4
OUTPUT_DIR: 'experiments/audio2mesh'
DEBUG: False
verbose: False
isTrain: False
MODEL:
name: 'audio2mesh2'
name_netG: "audio2mesh"
dim_motion: 53 # 68*2
dim_speech: 1024
num_vertices: 5023
pretrain: True
# 2h, rec-vel, load_epoch 145
path_checkpoint: "experiments/audio2mesh/train_audio2mesh_CN_20220322/20220405-19H39M26S"
load_epoch: 145
DATASET:
fps: 50
sr: 16000
name_train: "motion_live"
name_valid: "motion_eval"
flip: False
shifting_speed: True
root: './data/Actor3/Actor3-raw-2h' # obama-deca-3-5-08-mini
root_raw: '/mfs/lsen/DATA/Actor3/processing'
path_mean_dict: './data/Actor3/DECA_Actor3_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", "all"]
@@ -1,4 +1,4 @@
GPUS: '8'
GPUS: '9'
WORKERS: 4
OUTPUT_DIR: 'experiments/audio2mesh'
@@ -1,4 +1,4 @@
GPUS: '9'
GPUS: '8'
WORKERS: 4
OUTPUT_DIR: 'experiments/audio2mesh'
@@ -11,16 +11,16 @@ VISUAL:
use_visdom: True
vsdm_port: 9930
vsdm_ncol: 4
vsdm_env: "audio2mesh-actor1-5h-110"
vsdm_env: "audio2mesh-actor1-16h-closure"
FREQ:
epoch_save: 5
epoch_valid: 1
epoch_valid: 2
batch_print: 20
epoch_test: 5
MODEL:
name: 'audio2mesh'
name: 'audio2mesh2'
name_netG: "audio2mesh"
dim_motion: 53 # 68*2
@@ -31,16 +31,16 @@ MODEL:
path_checkpoint: "experiments/audio2mesh/train_audio2mesh_CN_20220314/20220315-18H24M47S"
load_epoch: 0
DATASET:
fps: 50
sr: 16000
name: "motion_live"
name_train: "motion_live"
name_valid: "motion_eval"
flip: False
shifting_speed: True
root: './data/Actor1/Actor1-raw-5h' # obama-deca-3-5-08-mini
root_raw: '/yrfs/lsen/DATA/Actor1/processing'
root: './data/Actor1/Actor1-raw-16h' # obama-deca-3-5-08-mini
root_raw: '/mfs/lsen/DATA/Actor1/processing'
path_mean_dict: './data/Actor1/DECA_Actor1_mean.npy'
filter: 'savgol'
speech_extractor: 'wav2vec'
@@ -68,18 +68,20 @@ TRAIN:
weight_decay: 0.0001
nesterov: True
grad_clip_norm: False
lr_policy: 'multistep'
lr_milestones: [10, 50]
# lr_policy: 'plateau'
# lr_policy: 'multistep'
# lr_milestones: [10, 50]
lr_policy: 'plateau'
resume: False
reset_lr: False
resume_suffix: "20220128-10H10M10S"
epoch_begin: 0 # 5000 # 2300 # 2600
epoch_end: 100
epoch_end: 300
LOSS:
names: ["all", "rec_geo", "rec_geo_w", "vel_geo", "vel_geo_w"]
names: ["rec_geo", "vel_geo", "rec_ldmk", "closure_x", "closure_y", "all"]
lambda_rec_geo: 1
lambda_vel_geo: 10
lambda_rec_ldmk: 0
lambda_closure_x: 0
lambda_closure_y: 10
@@ -1,4 +1,4 @@
GPUS: '3'
GPUS: '4'
WORKERS: 4
OUTPUT_DIR: 'experiments/audio2mesh'
@@ -6,7 +6,7 @@ DEBUG: False
verbose: False
VISUAL:
vsdm_env: "audio2mesh-actor3-2h-ldmk"
vsdm_env: "audio2mesh-actor3-2h"
FREQ:
epoch_save: 5
@@ -22,9 +22,10 @@ MODEL:
dim_speech: 1024
num_vertices: 5023
pretrain: False
path_checkpoint: "experiments/audio2mesh/train_audio2mesh_CN_20220312/20220321-15H10M14S"
load_epoch: 0
pretrain: True
path_checkpoint: "experiments/audio2mesh/train_audio2mesh_CN_20220314/20220407-10H07M49S"
load_epoch: 35
DATASET:
fps: 50
@@ -49,14 +50,14 @@ TEST:
TRAIN:
lr: 0.0001
batch_size: 100
lr: 0.00005
batch_size: 128
shuffle: True
apply_testing: True
apply_validation: True
optimizer: 'Adam'
optimizer: 'SGD'
momentum: 0.9
beta1: 0.5
beta2: 0.999
@@ -71,13 +72,13 @@ TRAIN:
reset_lr: False
resume_suffix: "20220403-00H39M11S"
epoch_begin: 0 # 5000 # 2300 # 2600
epoch_end: 500
epoch_end: 300
LOSS:
names: ["rec_geo", "vel_geo", "rec_ldmk", "closure_x", "closure_y", "all"]
lambda_rec_geo: 1
lambda_vel_geo: 10
lambda_rec_ldmk: 1
lambda_rec_ldmk: 0
lambda_closure_x: 1
lambda_closure_y: 1
+5 -1
View File
@@ -49,7 +49,11 @@ if __name__ == "__main__":
# path_audio = Path("/yrfs/lsen/DATA/LuoXData/processing2/2021-P09/audio/audio_trim_60_120s.wav")
path_audio = Path("/yrfs/lsen/DATA/Actor2/processing/AA7A9568/audio/audio_trim_120s.wav")
# path_audio = Path("/yrfs/lsen/DATA/Actor2/processing/AA7A9568/audio/audio_trim_120s.wav")
# vid_valid = set(["BU6A9965","BU6A9978"])
path_audio = Path("/mfs/lsen/DATA/Actor3/processing/BU6A9965/audio/audio_trim_60s.wav")
# path_audio = Path("/mfs/lsen/DATA/Actor3/processing/BU6A9978/audio/audio_trim_60s.wav")
# path_audio = Path("/yrfs/lsen/DATA/Actor1/processing/2-23min/audio/audio_trim_120_120s.wav")
# path_audio = Path("data/test/outputs20220319.wav")
+152
View File
@@ -0,0 +1,152 @@
import sys
import pprint
import argparse
import numpy as np
from pathlib import Path
import torch.nn.functional as F
from scipy.signal import savgol_filter
import torch
import torchaudio
from src.models import create_model
from src.config import config as opt
from src.config import update_config
import warnings
warnings.filterwarnings("ignore")
from common.logger import Logger
from transformers import Wav2Vec2FeatureExtractor, Wav2Vec2Model
torch.autograd.set_detect_anomaly(True)
def parese_args():
pareser = argparse.ArgumentParser(description='Audio2Expression Network')
# general
pareser.add_argument("--opt", type=str, default="experiments/xxx.yaml", help="experiment configure file name")
args, _ = pareser.parse_known_args()
update_config(args.opt)
pareser.add_argument("--gpus", type=str, default="0", help="gpus")
args = pareser.parse_args()
return args
if __name__ == "__main__":
args = parese_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)
device = torch.device(f'cuda:{opt.GPUS[0]}') # get device name: CPU or GPU
# logger.info(pprint.pformat(opt))
opt.OUTPUT_DIR = logger.path_output
# path_audio = Path("/yrfs/lsen/DATA/LuoXData/processing2/2021-P09/audio/audio_trim_60_120s.wav")
# path_audio = Path("/yrfs/lsen/DATA/Actor2/processing/AA7A9568/audio/audio_trim_120s.wav")
# vid_valid = set(["BU6A9965","BU6A9978"])
# path_audio = Path("/mfs/lsen/DATA/Actor3/processing/BU6A9965/audio/audio_trim_60s.wav")
fID = "BU6A9965"
ipath_data = Path(f"/mfs/lsen/DATA/Actor3/processing/{fID}/")
ipath_audio = ipath_data.joinpath("audio/audio_trim_60s.wav")
# laod motion
ipath_feat_exp = ipath_data.joinpath("audio/feat_DECA_exp_trim.npy")
ipath_feat_pos = ipath_data.joinpath("audio/feat_DECA_pos_trim.npy")
data_exp = np.load(ipath_feat_exp) # (nframe, 50)
data_pos = np.load(ipath_feat_pos) # (nframe, 6)
data_motion = np.concatenate([data_exp, data_pos[:, 3:]], axis=1) # (nframe, 53) --> fps=30
data_motion = savgol_filter(data_motion, window_length=5, polyorder=3, axis=0, mode='nearest')
# path_audio = Path("/yrfs/lsen/DATA/Actor1/processing/2-23min/audio/audio_trim_120_120s.wav")
# path_audio = Path("data/test/outputs20220319.wav")
# path_audio = Path("./data/47e6d985dc11469ab7f6f47cc0b5e625_trim.wav")
# path_audio = Path("./data/test/cut_NVP.wav")
# path_audio = Path("./data/test/cut_LSP.wav")
# path_audio = Path("/yrfs/cf/data/render/obama_train.wav")
# path_audio = Path("/yrfs/lsen/DATA/Obama/processing/Bringing-Our-Workplace-Policies-into-the-21st-Century/audio/audio_trim_120s.wav")
# path_audio = Path("/yrfs/lsen/DATA/Obama/processing/Celebrating-Independence-Day/audio/audio_trim_60_120s.wav")
# wav2vec 2.0
# path_audio = Path("/yrfs/lsen/DATA/LuoXData/processing2/2021-P09/audio/audio_trim_120s.wav")
# path_audio = Path("/yrfs/lsen/DATA/LuoXData/processing2/2021-P22/audio/audio_trim.wav")
# path_audio = Path("/ssdata1/lsen/CODE/Audio2Motion/data/test/test_pangzi_zh_cut15.wav")
# path_audio = Path("/ssdata1/lsen/CODE/Audio2Motion/data/test/P74_lite.mp3")
# path_audio = Path("/ssdata1/lsen/CODE/voca/data/audio/test_video_15.wav")
# path_audio = Path("/ssdata1/lsen/CODE/voca/data/audio/cut_lsz.wav")
# path_audio = Path("/ssdata1/lsen/CODE/voca/data/audio/obama.wav")
# data extract audio
# Load data_audio and extract features
# load raw speech
audio_raw, sample_rate = torchaudio.load(ipath_audio)
print(f"audio_raw shape = {audio_raw.shape}, sr = {sample_rate}, duration = {(len(audio_raw[0])/sample_rate)}")
if len(audio_raw.shape) == 2:
audio_raw = audio_raw[0]
if sample_rate != 16000:
resampler = torchaudio.transforms.Resample(sample_rate, 16_000)
sample_rate = 16000
audio_raw = resampler(audio_raw).squeeze().numpy()
print(f"resampling: audio_raw shape = {audio_raw.shape}, sr = {16000}, duration = {(len(audio_raw)/16000)}")
# padding to
len_align = (audio_raw.shape[0] // 16000 ) * 16000
audio_raw = audio_raw[: len_align]
print(f"after audio_raw shape = {audio_raw.shape}, sr = {sample_rate}, duration = {(len(audio_raw)/sample_rate)}")
nwinds = 30
data_motion = torch.from_numpy(data_motion[np.newaxis, :50*nwinds, :]) # (1, 3000, 53)
audio_raw = audio_raw[:nwinds * sample_rate]
# load wav2Vec model
print("load Wav2Vec2Model ...")
MODEL_ID = "jonatasgrosman/wav2vec2-large-xlsr-53-chinese-zh-cn"
# MODEL_ID_PATH = "./data/wav2vec2-large-xlsr-53-chinese-zh-cn.json"
processor = Wav2Vec2FeatureExtractor.from_pretrained(MODEL_ID, cache_dir="/home/liangsen/.cache/huggingface/transformers")
extractor = Wav2Vec2Model.from_pretrained(pretrained_model_name_or_path=MODEL_ID, cache_dir="/home/liangsen/.cache/huggingface/transformers").to(device)
# padding half frame length for bed and end
npad = int(0.5 * 16000* ( 1 / 50) + 0.5)
audio_pad = np.pad(audio_raw, pad_width=((npad, npad)), mode="edge")
print(f"after padding audio_pad = {audio_pad.shape}, dtype={audio_pad.dtype}")
inputs = processor(audio_pad, sampling_rate=16000, return_tensors="pt")
inputs = inputs.to(device)
with torch.no_grad():
output = extractor(**inputs)
cond = output.last_hidden_state
print(f"cond shape = {cond.shape}")
# convert to windows
cond = F.pad(cond, pad=(0, 0, 8, 7), mode="replicate")
cond = cond.unfold(dimension=1, size=16, step=1) # (B, nseqs, nc_motion, 16)
cond = cond.permute(0, 1, 3, 2) # (B, nseqs, 16, 53)
nseq = cond.size(1)
print(f"after convert window cond shape = {cond.shape}")
# self.data = self.data[:, 7:7+nseq, :]
# get model
model = create_model(opt, logger)
model.setup(opt) # load model
suffix = f"{ipath_audio.stem}_infer_{Path(opt.MODEL.path_checkpoint).stem}_epoch_{opt.MODEL.load_epoch:03d}"
model.infer_with_gt(cond, data_motion, audio_raw, suffix)
@@ -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)})")
View File
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')
+157
View File
@@ -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()
@@ -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"]
@@ -0,0 +1 @@
[2022-04-06 16:22:02,962][INFO] device set to cuda:8
-7
View File
@@ -10,13 +10,6 @@ class MotionEvalDataset(Dataset):
Prepares conditioning information (previous poses + control signal) and the corresponding next poses"""
def __init__(self, opt, phase="train"):
# self,
# path_data = "./data_valid.npz", # opt.DATASET.root
# fps = 50, # opt.DATASET.fps
# sr = 16000, # opt.DATASET.sr
# num_windows = 3, # eval(f"opt.DATASET.nwind_second_{phase}")
# filter = "savgol",
# ):
super(MotionEvalDataset, self).__init__()
self.opt = opt
+6 -135
View File
@@ -25,16 +25,8 @@ class MotionLiveDataset(Dataset):
self.phase = phase
path_data= Path(opt.DATASET.root).joinpath(f"data_{phase}.npz")
# for test
# if phase == "valid":
# path_data= Path(opt.DATASET.root).joinpath(f"data_train.npz")
# if phase == "test":
# path_data= Path(opt.DATASET.root).joinpath(f"data_train.npz")
print(f"[{self.phase}] load data ... --> {path_data}")
# dict vid: {"data_motion", # [nframe, 53]
# "data_speech", # [duration * sample_rate, ] raw deepseep
# "nframe", "fps", "sr"}
self.annodb = np.load(path_data, allow_pickle=True)['data'].item()
self.num_pid = len(self.annodb)
self.pids = list(self.annodb.keys())
@@ -50,22 +42,11 @@ class MotionLiveDataset(Dataset):
f'''nsteps_frame={self.nsteps_frame}\t'''
f'''nsteps_segmt={self.nsteps_segmt} ''')
# path_motion = self.path_data.joinpath(f"motion_{phase}.npz")
# path_speech = self.path_data.joinpath(f"speech_{phase}.npz")
# print(f"load data ... --> {path_motion} | {path_speech}")
# self.data_motion = np.load(path_motion)['data'].astype(np.float32) # (N, nsteps, dim_motion)
# self.data_speech = np.load(path_speech)['data'].astype(np.float32) # (N, nsteps, dim_speech)
# print(f"motion data ={self.data_motion.shape}, output={self.data_speech.shape}")
# self.nc_motion = self.data_motion.shape[-1]
# self.nc_speech = self.data_speech.shape[-1]
# debug(opt, f"nc_motion={self.nc_motion}, nc_speech ={self.nc_speech }")
def __len__(self):
if self.phase == "train":
return 10000
return 20000
elif self.phase == "valid":
return 3000 #3000
else:
@@ -83,10 +64,6 @@ class MotionLiveDataset(Dataset):
np.random.seed(int(idx + time.time()))
vid = self.pids[idx % self.num_pid]
# # filter "2021-P29"
# while vid == "2021-P29":
# vid = self.pids[idx % self.num_pid]
# random select idx
data = self.annodb[vid]
data_motion = data["data_motion"] # (nframes, nc_motion)
@@ -107,7 +84,7 @@ class MotionLiveDataset(Dataset):
data_motion = data_motion[beg_frame:end_frame] # (nteps, 53)
data_speech = data_speech[beg_segmt:end_segmt] # (nsegmt_steps, )
assert data_speech.shape[0] == int(self.nsteps_segmt * speed), f"data_speech shape={data_speech.shape}, vid={vid}"
assert data_speech.shape[0] == int(self.nsteps_segmt * speed), f"data_speech shape={data_speech.shape}, int(self.nsteps_segmt * speed) = {int(self.nsteps_segmt * speed)}, vid={vid}"
assert data_motion.shape[0] == int(self.nsteps_frame * speed), f"data_motion shape={data_motion.shape}, vid={vid}"
# print(f"speed={speed}, data_speech shape={data_speech.shape} data_motion shape={data_motion.shape}")
@@ -126,10 +103,12 @@ class MotionLiveDataset(Dataset):
# print(f"nframe-{self.nsteps_frame:04d} =[{beg_frame:04d},{end_frame:04d})\t nsegmet-{self.nsteps_segmt:04d}=[{beg_segmt:04d},{end_segmt:04d}), vid={vid}")
data_motion = data_motion[beg_frame:end_frame] # (nteps, 53)
data_speech = data_speech[beg_segmt:end_segmt] # (nsegmt_steps, )
assert data_speech.shape[0] == self.nsteps_segmt, f"data_speech shape={data_speech.shape}, vid={vid}"
data_speech = data_speech[beg_segmt:end_segmt] # (nsegmt_steps, )
assert data_speech.shape[0] == self.nsteps_segmt, f"data_speech shape={data_speech.shape}, vid={vid}, [{beg_segmt:04d},{end_segmt:04d})"
assert data_motion.shape[0] == self.nsteps_frame, f"data_motion shape={data_motion.shape}, vid={vid}"
# filter, explore doc: ./notebook/explore_pose.ipynb
if self.opt.DATASET.filter == "savgol":
data_motion = savgol_filter(data_motion, window_length=5, polyorder=3, axis=0, mode='nearest')
@@ -186,112 +165,4 @@ class MotionLiveDataset(Dataset):
data_speech = data_speech[:nsteps_speech*speed]
return data_motion, data_speech
class MotionLiveEvalDataset(Dataset):
"""
Motion dataset.
Prepares conditioning information (previous poses + control signal) and the corresponding next poses"""
def __init__(self, opt, phase="train"):
"""
phase = "valid | test "
"""
super(MotionLiveEvalDataset, self).__init__()
self.opt = opt
self.phase = phase
path_data= Path(opt.DATASET.root).joinpath(f"data_{phase}.npz")
print(f"\n [{self.phase}] load data ... --> {path_data}")
self.annodb = np.load(path_data, allow_pickle=True)['data'].item()
self.num_pid = len(self.annodb)
self.pids = list(self.annodb.keys())
self.annodb_accums = self.count_annotations()
self.overlap = 0.5
self.fps = opt.DATASET.fps # 50
self.sr = opt.DATASET.sr # 16000
self.nwind = eval(f"opt.DATASET.nwind_second_{phase}")
self.nsteps_frame = self.nwind * self.fps
self.nsteps_segmt = self.nwind * self.sr
print(f'''len(annodb)={len(self.annodb)}\t'''
f'''nsteps_frame={self.nsteps_frame}\t'''
f'''nsteps_segmt={self.nsteps_segmt} ''')
def __len__(self):
return self.annodb_accums[-1]
def count_annotations(self):
acc = 0
annodb_accums = np.zeros(self.num_pid + 1, dtype=int) # the first element set 0
for i, anno_dict in enumerate(self.annodb.values()):
acc += anno_dict["data_motion"].shape[0] // (self.nsteps_frame * self.overlap) - 1 # ncount_windows
annodb_accums[i+1] = acc # 2
return annodb_accums
def __getitem__(self, idx):
"""
Returns poses and conditioning.
If data-dropout sould be applied, a random selection of the previous poses is masked.
The control is not masked
return:
motion: (nsteps, nc_motion), current frame's pose (15 joint, xyz position)
speech: (nsteps, nc_speech), conditional data = previous motion data + full windows contrl data
"""
for i, iacc in enumerate(self.annodb_accums):
if idx > iacc -1 and idx < self.annodb_accums[i+1]:
pid, new_idx = i, idx - iacc
break
print(f"DEBUG: idx={idx}, pid = {pid}, iacc ={self.annodb_accums[i]}, new_idx = {new_idx}")
# return item
vid = self.pids[pid]
data = self.annodb[vid]
data_motion = data["data_motion"] # (nframes, nc_motion)
data_speech = data["data_speech"] # (nsegemts, )
nframe = data_motion.shape[0]
nsegmt = data_speech.shape[0]
# random select beg:end frame
beg_frame = new_idx
end_frame = beg_frame + self.nsteps_frame
beg_segmt = int((1.0 * beg_frame / nframe) * nsegmt)
end_segmt = beg_segmt + self.nsteps_segmt
print(f"nframe-{self.nsteps_frame:04d} =[{beg_frame:04d},{end_frame:04d})\nnsegmet-{self.nsteps_segmt:04d}=[{beg_segmt:04d},{end_segmt:04d}), vid={vid}")
data_motion = data_motion[beg_frame:end_frame] # (nteps, 53)
data_speech = data_speech[beg_segmt:end_segmt] # (nsegmt_steps, )
print(f"data_motion-{data_motion.shape} data_speech={data_speech.shape}")
# filter, explore doc: ./notebook/explore_pose.ipynb
if self.opt.DATASET.filter == "savgol":
data_motion = savgol_filter(data_motion, window_length=5, polyorder=3, axis=0, mode='nearest')
result = {
"data": data_motion, # (nsteps_frame, dim_motion)
"cond": data_speech, # (nsteps_frame, dim_speech)
"vid": vid,
"nframe": nframe,
"frame_interval": [beg_frame, end_frame],
# "duration_interval": [beg_frame/nframe, end_frame/nframe]
}
assert data_speech.shape[0] == self.nsteps_segmt, f"data_speech shape={data_speech.shape}, vid={vid}"
return result
+120 -86
View File
@@ -1,10 +1,12 @@
from collections import OrderedDict
import sys
import numpy as np
from collections import OrderedDict
import tempfile
from scipy.io import wavfile
import torch
import torch.nn as nn
import torch.nn.functional as F
from pathlib import Path
from src.models.info import flame_mouth_idx
@@ -16,8 +18,6 @@ from src.models.base import Base
from src.optims import get_optimizer, get_scheduler
from src.utils import util
from torchmetrics import MaxMetric, MeanMetric
# common
from common.animation import save_animation_with_gt2, save_images_with_audio
from common.debug import debug
@@ -41,7 +41,10 @@ class Audio2Mesh2Model(Base):
init_exp_weight = np.load("./data/init_expression_basis.npy")
init_exp_weight = torch.from_numpy(init_exp_weight).float().to(self.device)
init_exp_weight = init_exp_weight[:, :50]
self.netG.module.decoder_mesh.weight.data = init_exp_weight
if isinstance(self.netG, torch.nn.DataParallel):
self.netG.module.decoder_mesh.weight.data = init_exp_weight
else:
self.netG.decoder_mesh.weight.data = init_exp_weight
print(f"init_exp_weight shape = {init_exp_weight.shape}")
# # print network parameters
@@ -96,6 +99,7 @@ class Audio2Mesh2Model(Base):
self.processor = Wav2Vec2FeatureExtractor.from_pretrained(path_ckpt_wav2vec)
self.extractor = Wav2Vec2Model.from_pretrained(path_ckpt_wav2vec).to(self.device)
def set_input(self, batch_input):
# motion data
@@ -133,7 +137,7 @@ class Audio2Mesh2Model(Base):
with torch.no_grad():
output = self.extractor(**inputs)
cond = output.last_hidden_state
# cond = output.extract_features
else:
assert 0, "opt.DATASET.speech_extractor should be 'wav2vec | deepspeech | mfcc ' "
@@ -142,8 +146,8 @@ class Audio2Mesh2Model(Base):
debug(self.opt, f"cond = {cond.shape}, dtype={cond.dtype}, device={cond.device}", verbose=False)
# unfold speech data
cond = cond.unfold(dimension=1, size=16, step=1) # (nseqs, nc_motion, 16)
cond = cond.permute(0, 1, 3, 2) # (nseqs, 16, 53)
cond = cond.unfold(dimension=1, size=16, step=1) # (B, nseqs, nc_codit, 16)
cond = cond.permute(0, 1, 3, 2) # (B, nseqs, 16, nc_condit)
self.cond = cond
self.nseq = cond.size(1)
@@ -155,6 +159,17 @@ class Audio2Mesh2Model(Base):
debug(self.opt, f"[set_input] ldmk2d = {self.ldmk2d.shape}, dtype={self.ldmk2d.dtype}, device={self.ldmk2d.device}", verbose=False)
debug(self.opt, f"[set_input] ldmk3d = {self.ldmk3d.shape}, dtype={self.ldmk3d.dtype}, device={self.ldmk3d.device}", verbose=False)
def forward(self, batch_input):
self.set_input(batch_input)
# forward
pred = self.netG(self.cond)
debug(self.opt, f"traing pred = {pred.shape}", verbose=False)
return pred
def training(self, batch_input):
self.train() # set train model
self.set_input(batch_input)
@@ -193,12 +208,41 @@ class Audio2Mesh2Model(Base):
return loss_dict
def infer_with_gt(self, batch_cond, batch_data, audio_raw, suffix="", save_npy=True):
self.eval()
cond = batch_cond.float().to(self.device) # (nsteps, dim_cond)
data = batch_data.float().to(self.device) # (B, nframe, 53)
vert, ldmk2d, ldmk3d = self.get_vertices(data)
with torch.no_grad():
batch_pdt_geo = self.netG(cond) # B x N x dim_motion
batch_pdt_geo += self.temp_verts # B x N x 5023 x 3
print(f"testing pt shape = {batch_pdt_geo.shape}")
# !! add specific when render & output !!
batch_pdt_geo = batch_pdt_geo - self.temp_verts + self.temp_verts_specific
# render & and save
print(f"testing pt shape = {batch_pdt_geo.shape}, gt shape = {vert.shape}")
self.save_reconstruct_with_gt2(batch_pdt_geo, vert, audio_raw,
path_save=Path(self.opt.OUTPUT_DIR),
suffix=suffix)
if save_npy:
# save result
batch_pdt_geo = batch_pdt_geo.cpu().numpy()
path_save_npy = Path(self.opt.OUTPUT_DIR).joinpath(f"{suffix}.npy")
np.save(path_save_npy, batch_pdt_geo)
print(f"save infer_result shape = {batch_pdt_geo.shape} -> {path_save_npy}")
def infer(self, batch_cond, path_audio, suffix="", save_npy=True):
self.eval()
self.cond = batch_cond.float().to(self.device) # (nsteps, dim_cond)
with torch.no_grad():
batch_pdt_geo = self.netG(self.cond) # B x N x dim_motion
batch_pdt_geo = self.netG(self.cond) # B x N x dim_motion
batch_pdt_geo += self.temp_verts # B x N x 5023 x 3
print(f"testing pt shape = {batch_pdt_geo.shape}")
@@ -270,11 +314,11 @@ class Audio2Mesh2Model(Base):
batch_pos_mouth = batch_motion[..., 50:]
nbatch, seqlen = batch_exp.size(0), batch_exp.size(1)
batch_exp = batch_exp.reshape(nbatch * seqlen, -1) # nbatch * seqlen x 50
batch_exp = batch_exp.reshape(nbatch * seqlen, -1) # nbatch * seqlen x 50
batch_pos_mouth = batch_pos_mouth.reshape(nbatch * seqlen, -1) # nbatch * seqlen x 3
batch_shape= torch.zeros(nbatch * seqlen, 100).to(self.device) # nbatch * seqlen x 50
batch_pose = torch.zeros(nbatch * seqlen, 6).to(self.device) # nbatch * seqlen x 6
batch_shape= torch.zeros(nbatch * seqlen, 100).to(self.device) # nbatch * seqlen x 50
batch_pose = torch.zeros(nbatch * seqlen, 6).to(self.device) # nbatch * seqlen x 6
batch_pose[:, 3:6] = batch_pos_mouth
with torch.no_grad():
@@ -286,74 +330,6 @@ class Audio2Mesh2Model(Base):
return verts, ldmk2d, ldmk3d
def eval_losses_for_valid(self, batch_pdt_geo, batch_tgt_geo):
""" Computes the VAE loss function.
pramas:
batch_tgt_geo, (nbatch, seqlen, num_vertices, 3)
batch_pdt_geo, (nbatch, seqlen, num_vertices, 3)
"""
loss_dict = {}
# synthesis geo rec
loss_rec_geo = self.loss_func_wing(batch_pdt_geo, batch_tgt_geo) # (B, N, num_vertices, 3)
loss_dict["rec_geo"] = loss_rec_geo.mean().detach()
# synthesis geo volocity
diff_pdt_geo = batch_pdt_geo[:, 1:, :] - batch_pdt_geo[:, :-1, :]
diff_tgt_geo = batch_tgt_geo[:, 1:, :] - batch_tgt_geo[:, :-1, :]
loss_vel_geo = self.loss_func_wing(diff_pdt_geo, diff_tgt_geo) # (B, N-1, num_vertices, 3)
loss_dict["vel_geo"] = loss_vel_geo.mean().detach()
# landmarks loss
ldmk3d_pdt = self.netF.seletec_3d68(batch_pdt_geo.reshape(-1, self.opt.MODEL.num_vertices, 3)) # (B*N, 68, 3)
ldmk3d_tgt = self.netF.seletec_3d68(batch_tgt_geo.reshape(-1, self.opt.MODEL.num_vertices, 3)) # (B*N, 68, 3)
loss_rec_ldmk = torch.sqrt(((ldmk3d_pdt - ldmk3d_tgt)**2).sum(2)) # (B*N, 68, 3) => (B*N, 68)
loss_dict["rec_ldmk"] = loss_rec_ldmk.mean().detach()
# ldmk3d_pdt_dis = torch.sqrt(((ldmk3d_pdt)**2).sum(2)) # (B*N, 68, 3) => (B*N, 68)
# ldmk3d_tgt_dis = torch.sqrt(((ldmk3d_tgt)**2).sum(2)) # (B*N, 68, 3) => (B*N, 68)
# loss_rec_ldmk = (ldmk3d_pdt_dis - ldmk3d_tgt_dis).abs().mean() # (B*N, 68) ==> (1,)
# loss_rec_ldmk= self.loss_func_wing(ldmk3d_pdt_dis, ldmk3d_tgt_dis)
# loss_dict["rec_ldmk"] = loss_rec_ldmk.mean().detach()
# mouth closure_x loss (left/right mouth)
ldmk3d_pdt_left, ldmk3d_pdt_right = ldmk3d_pdt[:, idx_left_mouth_68ldmk], ldmk3d_pdt[:, idx_right_mouth_68ldmk]
ldmk3d_tgt_left, ldmk3d_tgt_right = ldmk3d_tgt[:, idx_left_mouth_68ldmk], ldmk3d_tgt[:, idx_right_mouth_68ldmk]
diff_pdt_mouth_x = torch.sqrt(((ldmk3d_pdt_left - ldmk3d_pdt_right)**2).sum(2)) # (B*N, 8, 3) => (B*N, 8)
diff_tgt_mouth_x = torch.sqrt(((ldmk3d_tgt_left - ldmk3d_tgt_right)**2).sum(2)) # (B*N, 8, 3) => (B*N, 8)
loss_closure_x = (diff_pdt_mouth_x - diff_tgt_mouth_x).abs().mean() # (B*N, 8) ==> (1,)
loss_dict["closure_x"] = loss_closure_x.mean().detach()
# mouth closure_y loss (upper/lower mouth)
ldmk3d_pdt_upper, ldmk3d_pdt_lower = ldmk3d_pdt[:, idx_upper_mouth_68ldmk], ldmk3d_pdt[:, idx_lower_mouth_68ldmk]
ldmk3d_tgt_upper, ldmk3d_tgt_lower = ldmk3d_tgt[:, idx_upper_mouth_68ldmk], ldmk3d_tgt[:, idx_lower_mouth_68ldmk]
diff_pdt_mouth_y = torch.sqrt(((ldmk3d_pdt_upper - ldmk3d_pdt_lower)**2).sum(2)) # (B*N, 8, 3) => (B*N, 8)
diff_tgt_mouth_y = torch.sqrt(((ldmk3d_tgt_upper - ldmk3d_tgt_lower)**2).sum(2)) # (B*N, 8, 3) => (B*N, 8)
loss_closure_y = (diff_pdt_mouth_y - diff_tgt_mouth_y).abs().mean() # (B*N, 8) ==> (1,)
loss_dict["closure_y"] = loss_closure_y.mean().detach()
# # closure loss
# diff_pdf_closure = batch_pdt_geo[:,:,flame_mouth_upper_idx].sum(dim=[2,3]) / len(flame_mouth_upper_idx) \
# - batch_pdt_geo[:,:,flame_mouth_lower_idx].sum(dim=[2,3]) / len(flame_mouth_upper_idx)
# diff_tgt_closure = batch_tgt_geo[:,:,flame_mouth_upper_idx].sum(dim=[2,3]) / len(flame_mouth_upper_idx) \
# - batch_tgt_geo[:,:,flame_mouth_lower_idx].sum(dim=[2,3]) / len(flame_mouth_upper_idx)
# loss_closure = self.loss_func_wing(diff_pdf_closure, diff_tgt_closure)
# loss_dict["closure"] = loss_closure.mean().detach()
# if self.opt.LOSS.lambda_closure > 0:
# loss += loss_closure.mean() * self.opt.LOSS.lambda_closure
return loss_dict
def eval_losses(self, batch_pdt_geo, batch_tgt_geo):
""" Computes the VAE loss function.
pramas:
@@ -451,6 +427,7 @@ class Audio2Mesh2Model(Base):
# render
render_pt = self.render_geometry(kgeo_pt, cam, self.device) # (nbatch_real, 3, 512, 512)
render_pt = render_pt.cpu()
# print(f"render_pt ={render_pt.shape}, render_gt={render_gt.shape}")
# append each frame
@@ -481,6 +458,64 @@ class Audio2Mesh2Model(Base):
return images
@torch.no_grad()
def save_reconstruct_with_gt2(self, batch_pdt_geo, batch_tgt_geo, raw_speech, path_save, suffix=""):
# batch_pdt_geo, [1 x N x 5023 x 3]
# batch_tgt_geo, [1 x N x 5023 x 3]
B, N, *_ = batch_pdt_geo.shape
igeo_pt = batch_pdt_geo[0, ...] # [N x 5023 x 3]
igeo_gt = batch_tgt_geo[0, ...] # [N x 5023 x 3]
ipath_save = path_save.joinpath(f"{suffix}_{0:02d}.mp4")
v_render_pt = []
v_render_gt = []
nbatch_render = 10
for k in range(0, N, nbatch_render):
# split
kgeo_pt = igeo_pt[k:k+nbatch_render, ...] # [nbatch_real x 5023 x 3]
kgeo_gt = igeo_gt[k:k+nbatch_render, ...] # [nbatch_real x 5023 x 3]
nbatch_real = kgeo_pt.size(0)
# cam
cam = torch.tensor([5, 0, 0], device=self.device).repeat(nbatch_real, 1) # (nbatch_real, 3)
# print(f"cam shape = {cam.shape}")
# render
render_pt = self.render_geometry(kgeo_pt, cam, self.device) # (nbatch_real, 3, 512, 512)
render_gt = self.render_geometry(kgeo_gt, cam, self.device) # (nbatch_real, 3, 512, 512)
# print(f"render_pt ={render_pt.shape}, render_gt={render_gt.shape}")
# landmarks 3d
kldmk3d_pt = self.netF.seletec_3d68(kgeo_pt) # [nbatch_real x 68 x 3]
kldmk3d_gt = self.netF.seletec_3d68(kgeo_gt) # [nbatch_real x 68 x 3]
kldmk3d_pt = util.batch_orth_proj(kldmk3d_pt, cam);
kldmk3d_pt[:,:,1:] = -kldmk3d_pt[:,:,1:];
kldmk3d_gt = util.batch_orth_proj(kldmk3d_gt, cam);
kldmk3d_gt[:,:,1:] = -kldmk3d_gt[:,:,1:];
render_pt = util.tensor_vis_landmarks(render_pt, kldmk3d_pt, gt_landmarks=kldmk3d_gt, isScale=True, color = (255, 0, 0), color_gt=(0, 255, 0))
render_gt = util.tensor_vis_landmarks(render_gt, kldmk3d_gt, isScale=True, color = (0, 255, 0))
# append each frame
for m in range(nbatch_real):
v_render_pt.append(tensor2image(render_pt[m, ...]))
v_render_gt.append(tensor2image(render_gt[m, ...]))
# write tmp audio
tmp_audio = tempfile.NamedTemporaryFile(suffix='.wav')
wavfile.write(tmp_audio.name, rate=16000, data=raw_speech)
# save animation
# print(f"testing v_render_pt = {len(v_render_pt)}, gt shape = {len(v_render_gt)}")
save_animation_with_gt2(v_render_pt, v_render_gt, ipath_save, fps=50, path_audio=tmp_audio.name)
@torch.no_grad()
def save_reconstruct_with_gt(self, batch_pdt_geo, batch_tgt_geo, path_save, suffix=""):
# batch_pdt_geo, [B x N x 5023 x 3]
@@ -529,9 +564,8 @@ class Audio2Mesh2Model(Base):
# write to image
# render_pt = tensor2image(render_pt) # (nbatch_real, 3, 512, 512), on cpu
# render_gt = tensor2image(render_gt) # (nbatch_real, 3, 512, 512), on cpu
render_pt = util.tensor_vis_landmarks(render_pt, kldmk3d_pt, gt_landmarks=kldmk3d_gt, isScale=True, color = 'r', gt_color='g')
render_gt = util.tensor_vis_landmarks(render_gt, kldmk3d_gt, isScale=True, color = 'g')
render_pt = util.tensor_vis_landmarks(render_pt, kldmk3d_pt, gt_landmarks=kldmk3d_gt, isScale=True, color = (255, 0, 0), color_gt=(0, 255, 0))
render_gt = util.tensor_vis_landmarks(render_gt, kldmk3d_gt, isScale=True, color = (0, 255, 0))
# append each frame
for m in range(nbatch_real):
@@ -586,12 +620,12 @@ def define_netG(opt):
# to GPU
netG.to(f"cuda:{opt.GPUS[0]}")
netG = torch.nn.DataParallel(netG, opt.GPUS) # multi-GPUs
if len(opt.GPUS) > 1:
netG = torch.nn.DataParallel(netG, opt.GPUS) # multi-GPUs
return netG
def define_FLAME(opt, device):
from src.nn.FLAME import FLAME
-2
View File
@@ -29,13 +29,11 @@ class Audio2Mesh(nn.Module):
nn.Conv2d(512, 512, kernel_size=(3,1), stride=(1,1), padding=(1,0), bias=True), # 32 x 8 x 1
nn.LeakyReLU(0.02, True),
nn.Conv2d(512, 256, kernel_size=(3,1), stride=(2,1), padding=(1,0), bias=True), # 64 x 2 x 1
nn.LeakyReLU(0.02, True),
nn.Conv2d(256, 256, kernel_size=(3,1), stride=(1,1), padding=(1,0), bias=True), # 32 x 8 x 1
nn.LeakyReLU(0.02, True),
nn.Conv2d(256, 256, kernel_size=(3,1), stride=(2,1), padding=(1,0), bias=True), # 64 x 1 x 1
nn.LeakyReLU(0.02, True),
nn.Conv2d(256, 256, kernel_size=(3,1), stride=(1,1), padding=(1,0), bias=True), # 32 x 8 x 1
+36 -47
View File
@@ -577,95 +577,84 @@ def dict_tensor2npy(tensor_dict):
# ---------------------------------- visualization
# end_list = np.array([17, 22, 27, 42, 48, 31, 36, 68], dtype = np.int32) - 1
end_list = np.array([17, 22, 27, 31, 36], dtype = np.int32) - 1
def plot_kpts(image, kpts, color = 'r'):
def plot_kpts(image, kpts, color = (255,0,0), color_line=(255,255,255)):
''' Draw 68 key points
Args:
image: the input image
kpt: (68, 3).
'''
if color == 'r':
c = (255, 0, 0)
elif color == 'g':
c = (0, 255, 0)
elif color == 'b':
c = (255, 0, 0)
image = image.copy()
kpts = kpts.copy()
# radius = max(int(min(image.shape[0], image.shape[1])/200), 1)
radius = 1
for i in range(kpts.shape[0]):
st = kpts[i, :2]
if kpts.shape[1]==4:
if kpts[i, 3] > 0.5:
c = (0, 255, 0)
else:
c = (0, 0, 255)
# draw cicle
image = cv2.circle(image,(int(st[0]), int(st[1])), radius, c, -1)
# draw line
if i not in end_list:
ed = kpts[i + 1, :2] if i != 67 else kpts[60, :2]
ed = kpts[36, :2] if i == 41 else ed
ed = kpts[42, :2] if i == 47 else ed
image = cv2.line(image, (int(st[0]), int(st[1])), (int(ed[0]), int(ed[1])), (255, 255, 255), radius)
image = cv2.line(image, (int(st[0]), int(st[1])), (int(ed[0]), int(ed[1])), color_line, radius)
# draw cicle
image = cv2.circle(image,(int(st[0]), int(st[1])), radius, color, -1)
return image
def plot_verts(image, kpts, color = 'r'):
def plot_verts(image, kpts, color = (255,0,0)):
''' Draw 68 key points
Args:
image: the input image
kpt: (68, 3).
'''
c = (0, 0, 0)
c = (255, 0, 0) if color == 'r' else c
c = (0, 255, 0) if color == 'g' else c
c = (0, 0, 255) if color == 'b' else c
c = (0, 255, 255) if color == 'y' else c
image = image.copy()
for i in range(kpts.shape[0]):
st = kpts[i, :2]
image = cv2.circle(image,(int(st[0]), int(st[1])), 1, c, -1)
image = cv2.circle(image,(int(st[0]), int(st[1])), 1, color, -1)
return image
def tensor_vis_landmarks(images, landmarks, gt_landmarks=None, color = 'g', isScale=True, gt_color = 'r'):
def tensor_vis_landmarks(images, landmarks, gt_landmarks=None, color = (0, 255, 0), isScale=True, color_gt = (255, 0, 0)):
# visualize landmarks
vis_landmarks = []
images = images.cpu().numpy()
predicted_landmarks = landmarks.detach().cpu().numpy()
if gt_landmarks is not None:
gt_landmarks_np = gt_landmarks.detach().cpu().numpy()
ldmks_pt = landmarks.detach().cpu().numpy()
ldmks_gt = gt_landmarks.detach().cpu().numpy() if gt_landmarks is not None else None
vis_landmarks = []
for i in range(images.shape[0]):
image = images[i]
image = image.transpose(1,2,0)[:,:,[2,1,0]].copy(); image = (image*255)
image = images[i].transpose(1,2,0)[:,:,[2,1,0]].copy()
image = image*255
# if landmarks is scale
ildmks_pt = ldmks_pt[i]
if isScale:
predicted_landmark = predicted_landmarks[i]
predicted_landmark[...,0] = predicted_landmark[...,0]*image.shape[1]/2 + image.shape[1]/2
predicted_landmark[...,1] = predicted_landmark[...,1]*image.shape[0]/2 + image.shape[0]/2
else:
predicted_landmark = predicted_landmarks[i]
ildmks_pt[...,0] = ildmks_pt[...,0]*image.shape[1]/2 + image.shape[1]/2
ildmks_pt[...,1] = ildmks_pt[...,1]*image.shape[0]/2 + image.shape[0]/2
#
if predicted_landmark.shape[0] == 68:
image_landmarks = plot_kpts(image, predicted_landmark, color)
if gt_landmarks is not None:
image_landmarks = plot_verts(image_landmarks, gt_landmarks_np[i]*image.shape[0]/2 + image.shape[0]/2, gt_color)
if ildmks_pt.shape[0] == 68:
image_landmarks = plot_kpts(image, ildmks_pt, color, color_line=color)
else:
image_landmarks = plot_verts(image, predicted_landmark, color)
if gt_landmarks is not None:
image_landmarks = plot_verts(image_landmarks, gt_landmarks_np[i]*image.shape[0]/2 + image.shape[0]/2, gt_color)
image_landmarks = plot_verts(image, ildmks_pt, color, color_line=color)
# if have landmarks gt
if ldmks_gt is not None:
ildmks_gt = ldmks_gt[i]
if isScale:
ildmks_gt[...,0] = ildmks_gt[...,0]*image.shape[1]/2 + image.shape[1]/2
ildmks_gt[...,1] = ildmks_gt[...,1]*image.shape[0]/2 + image.shape[0]/2
if ildmks_gt.shape[0] == 68:
image_landmarks = plot_kpts(image_landmarks, ildmks_gt, color_gt, color_line=color_gt)
else:
image_landmarks = plot_verts(image_landmarks, ildmks_gt, color_gt, color_line=color_gt)
vis_landmarks.append(image_landmarks)
+9 -12
View File
@@ -47,9 +47,9 @@ def logger_loss(logger, epoch, batch, loss_dict):
msg_loss = "".join([f" {k}= {v:0.5f} " for k,v in loss_dict.items()])
logger.info(msg_head + msg_loss)
def plot_loss(visor, iter, loss_dict):
def plot_loss(visor, iter, loss_dict, suffix="train"):
for k,v in loss_dict.items():
visor.add_scalar(f"loss/loss_{k}", v, iter)
visor.add_scalar(f"{suffix}/loss_{k}", v, iter)
if __name__ == "__main__":
@@ -117,18 +117,13 @@ if __name__ == "__main__":
# print logger
if (i+1) % opt.FREQ.batch_print == 0 and epoch % opt.FREQ.epoch_print == 0:
logger_loss(logger, epoch, i, train_loss_dict)
plot_loss(visor, epoch + (i/len(train_loader)), train_loss_dict)
plot_loss(visor, epoch + (i/len(train_loader)), train_loss_dict, suffix="train")
# log toatl of each epoch
train_loss_dict = train_metric.compute_to_dict() # compute mean value
logger_loss(logger, epoch, "mean", train_loss_dict)
################ upate learning rate
model.update_learning_rate(train_loss_dict["all"])
if opt.TRAIN.apply_update_parameters:
model.update_parameters(epoch)
################ validation
if opt.TRAIN.apply_validation and (epoch+1) % opt.FREQ.epoch_valid == 0:
logger.info("validation...")
@@ -145,10 +140,14 @@ if __name__ == "__main__":
logger_loss(logger, epoch, iv, valid_loss_dict)
# print total
valid_loss_dict = valid_metric.compute_to_dict() # compute mean value
valid_loss_dict = valid_metric.compute_to_dict() # compute mean value
logger_loss(logger, epoch, "mean", valid_loss_dict)
plot_loss(visor, epoch+1, valid_loss_dict)
plot_loss(visor, epoch+1, valid_loss_dict, suffix="valid")
################ upate learning rate by validataion
model.update_learning_rate(valid_loss_dict["all"])
if opt.TRAIN.apply_update_parameters:
model.update_parameters(epoch)
################# testing
if opt.TRAIN.apply_testing and (epoch+1) % opt.FREQ.epoch_test == 0:
@@ -161,5 +160,3 @@ if __name__ == "__main__":
if (epoch + 1) % opt.FREQ.epoch_save == 0:
logger.info(f"saving the model at the end of epoch {epoch:04d}, iters {i:06d}")
model.save_networks(epoch+1)