From 7fb22e475040d83345ee52e27e83f19c4a6a5cbd Mon Sep 17 00:00:00 2001 From: liangsen Date: Mon, 25 Apr 2022 22:22:55 +0800 Subject: [PATCH] update audio2mesh with write_video, remove from path_raw --- .../infer_audio2mesh_CN_20220425.yaml | 45 ++++ .../train_audio2mesh_CN_20220425.yaml | 82 +++++++ .../audio2pose/train_luox_20220415.yaml | 24 +- .../audio2pose/train_obama_20220423.yaml | 33 ++- infer_one_live.py | 12 +- scripts/Actor4Data/run-00-mean-coeff.py | 6 +- .../Actor4Data/run-20-deca-reconstruction.py | 2 +- scripts/Actor4Data/run-21-features-3dmm.py | 4 +- .../run-41-train-dict-data-raw-deca.py | 46 +--- scripts/BG_Actor4Data/run-02-ssim-batch.py | 51 +++++ src/config.py | 2 + src/models/model_audio2mesh.py | 207 ++++++------------ src/models/model_audio2pose.py | 20 +- src/optims/__init__.py | 6 +- train.py | 7 +- 15 files changed, 302 insertions(+), 245 deletions(-) create mode 100644 experiments/audio2mesh/infer_audio2mesh_CN_20220425.yaml create mode 100644 experiments/audio2mesh/train_audio2mesh_CN_20220425.yaml create mode 100644 scripts/BG_Actor4Data/run-02-ssim-batch.py diff --git a/experiments/audio2mesh/infer_audio2mesh_CN_20220425.yaml b/experiments/audio2mesh/infer_audio2mesh_CN_20220425.yaml new file mode 100644 index 0000000..be76158 --- /dev/null +++ b/experiments/audio2mesh/infer_audio2mesh_CN_20220425.yaml @@ -0,0 +1,45 @@ +GPUS: '0' +WORKERS: 4 +OUTPUT_DIR: 'experiments/audio2mesh' + +DEBUG: False +verbose: False +isTrain: False + + +MODEL: + name: 'audio2mesh' + name_netG: "audio2mesh" + + dim_motion: 53 # 68*2 + dim_speech: 1024 + num_vertices: 5023 + + pretrain: True + + # 1h, rec-vel, load_epoch 20 + path_checkpoint: "experiments/audio2mesh/train_audio2mesh_CN_20220425/20220425-12H26M34S" + load_epoch: 20 + + +DATASET: + fps: 50 + sr: 16000 + name_train: "motion_live" + name_valid: "motion_eval" + + root: './data/Actor4/Actor4-raw-1h' # obama-deca-3-5-08-mini + path_mean_dict: './data/Actor4/DECA_Actor4_mean.npy' + filter: 'savgol' + + 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"] \ No newline at end of file diff --git a/experiments/audio2mesh/train_audio2mesh_CN_20220425.yaml b/experiments/audio2mesh/train_audio2mesh_CN_20220425.yaml new file mode 100644 index 0000000..1e8c636 --- /dev/null +++ b/experiments/audio2mesh/train_audio2mesh_CN_20220425.yaml @@ -0,0 +1,82 @@ +GPUS: '9' +WORKERS: 4 +OUTPUT_DIR: 'experiments/audio2mesh' + +DEBUG: False +verbose: False + +VISUAL: + vsdm_env: "audio2mesh-actor4-1h" + +FREQ: + epoch_save: 5 + epoch_valid: 1 + batch_print: 20 + epoch_test: 5 + +MODEL: + name: 'audio2mesh' + name_netG: "audio2mesh" + + dim_motion: 53 # 68*2 + dim_speech: 1024 + num_vertices: 5023 + + pretrain: False + path_checkpoint: "experiments/audio2mesh/train_audio2mesh_CN_20220314/20220407-10H07M49S" + load_epoch: 0 + + +DATASET: + fps: 50 + sr: 16000 + name_train: "motion_live" + name_valid: "motion_eval" + flip: False + shifting_speed: False + + root: './data/Actor4/Actor4-raw-1h' # obama-deca-3-5-08-mini + path_mean_dict: './data/Actor4/DECA_Actor4_mean.npy' + filter: 'savgol' + speech_extractor: 'wav2vec' + + nwind_second_train: 3 + nwind_second_valid: 3 + nwind_second_test: 15 + +TEST: + batch_size: 2 + + +TRAIN: + lr: 0.0001 + batch_size: 128 + shuffle: True + + apply_testing: True + apply_validation: True + + optimizer: 'Adam' + momentum: 0.9 + beta1: 0.5 + beta2: 0.999 + weight_decay: 0.0001 + nesterov: True + lr_policy: 'plateau' + # lr_policy: 'multistep' + # lr_milestones: [20, 50] + + resume: False + reset_lr: False + resume_suffix: "20220403-00H39M11S" + epoch_begin: 0 # 5000 # 2300 # 2600 + epoch_end: 300 + + +LOSS: + names: ["rec_geo", "vel_geo", "rec_ldmk", "closure_x", "closure_y", "all"] + lambda_rec_geo: 1 + lambda_vel_geo: 100 + lambda_rec_ldmk: 0 + lambda_closure_x: 0 + lambda_closure_y: 0 \ No newline at end of file diff --git a/experiments/audio2pose/train_luox_20220415.yaml b/experiments/audio2pose/train_luox_20220415.yaml index 42b4ed5..81fa584 100644 --- a/experiments/audio2pose/train_luox_20220415.yaml +++ b/experiments/audio2pose/train_luox_20220415.yaml @@ -25,8 +25,8 @@ MODEL: n_lookprevs_motion: 1 pretrain: True - path_checkpoint: "experiments/audio2pose/train_audio2pose_luox_20220415/20220416-02H02M55S" - load_epoch: 300 + path_checkpoint: "experiments/audio2pose/train_luox_20220415/20220424-15H50M15S" + load_epoch: 75 DATASET: @@ -64,24 +64,24 @@ TRAIN: beta2: 0.999 weight_decay: 0.0001 nesterov: True - grad_clip_norm: False - # lr_policy: 'multistep' - # lr_milestones: [20, 50] - # lr_policy: 'plateau' - resume: False - reset_lr: False - resume_suffix: "20220128-10H10M10S" - epoch_begin: 0 # 5000 # 2300 # 2600 - epoch_end: 300 + lr_step_gamma: 0.5 + lr_policy: 'multistep' + lr_milestones: [25, 50, 75, 100] + # lr_policy: 'plateau' # for cyclical schedule apply_update_parameters: True n_cycle_period: 25 - epoch_teacher: 50 epoch_sampling: 50 + resume: False + reset_lr: False + resume_suffix: "20220424-15H50M15S" + epoch_begin: 0 # 5000 # 2300 # 2600 + epoch_end: 300 + LOSS: names: ["rec", "kl", "vel", "all"] diff --git a/experiments/audio2pose/train_obama_20220423.yaml b/experiments/audio2pose/train_obama_20220423.yaml index 88d6e05..8fdf31f 100644 --- a/experiments/audio2pose/train_obama_20220423.yaml +++ b/experiments/audio2pose/train_obama_20220423.yaml @@ -1,4 +1,4 @@ -GPUS: '3' +GPUS: '7' WORKERS: 4 OUTPUT_DIR: 'experiments/audio2pose' @@ -24,10 +24,9 @@ MODEL: n_lookahead_motion: 1 n_lookprevs_motion: 1 - pretrain: False - path_checkpoint: "experiments/audio2pose/train_audio2pose_luox_20220415/20220416-02H02M55S" - load_epoch: 300 - + pretrain: True + path_checkpoint: "experiments/audio2pose/train_obama_20220423/20220424-15H39M44S" + load_epoch: 90 DATASET: fps: 50 @@ -48,7 +47,6 @@ DATASET: TEST: batch_size: 2 - TRAIN: lr: 0.0001 batch_size: 128 @@ -65,24 +63,23 @@ TRAIN: beta2: 0.999 weight_decay: 0.0001 nesterov: True - grad_clip_norm: False - # lr_policy: 'multistep' - # lr_milestones: [20, 50] - # lr_policy: 'plateau' - - resume: False - reset_lr: False - resume_suffix: "20220128-10H10M10S" - epoch_begin: 0 # 5000 # 2300 # 2600 - epoch_end: 300 + lr_step_gamma: 0.5 + lr_policy: 'multistep' + lr_milestones: [25, 50, 75, 100] # for cyclical schedule apply_update_parameters: True n_cycle_period: 25 - epoch_teacher: 50 - epoch_sampling: 100 + epoch_sampling: 50 + + + resume: False + reset_lr: False + resume_suffix: "20220424-15H39M44S" + epoch_begin: 0 # 5000 # 2300 # 2600 + epoch_end: 300 LOSS: diff --git a/infer_one_live.py b/infer_one_live.py index 635dae6..971acf7 100644 --- a/infer_one_live.py +++ b/infer_one_live.py @@ -1,4 +1,4 @@ -import sys +import sys,os import pprint import argparse import numpy as np @@ -56,8 +56,9 @@ if __name__ == "__main__": # path_audio = Path("/mfs/lsen/DATA/Actor3/processing/BU6A9978/audio/audio_trim_60s.wav") # path_audio = Path("data/ali_test_d.wav") - - path_audio = Path("data/bank-demo.wav") + # path_audio = Path("data/bank-demo.wav") + path_audio = Path("/mfs/lsen/DATA/Actor4/processing/4R3A0024/audio/audio_trim_60_60s.wav") + # path_audio = Path("/mfs/lsen/DATA/Actor2/happy/4R3A0004/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") @@ -84,6 +85,7 @@ if __name__ == "__main__": # data extract audio # Load data_audio and extract features + # load raw speech raw_speech, sample_rate = torchaudio.load(path_audio) print(f"raw_speech shape = {raw_speech.shape}, sr = {sample_rate}, duration = {(len(raw_speech[0])/sample_rate)}") @@ -136,5 +138,9 @@ if __name__ == "__main__": model.setup(opt) # load model # model.remove_weightnorm() + # copy wav + cmd = f"cp {str(path_audio)} {str(Path(opt.OUTPUT_DIR).joinpath('audio_input.wav'))}" + os.system(cmd) + path_save = f"{path_audio.stem}_infer_{Path(opt.MODEL.path_checkpoint).stem}_epoch_{opt.MODEL.load_epoch:03d}" model.infer(cond, raw_speech, path_save) diff --git a/scripts/Actor4Data/run-00-mean-coeff.py b/scripts/Actor4Data/run-00-mean-coeff.py index b87150d..322233e 100644 --- a/scripts/Actor4Data/run-00-mean-coeff.py +++ b/scripts/Actor4Data/run-00-mean-coeff.py @@ -5,9 +5,9 @@ from pathlib import Path if __name__ == "__main__": # fid = "Bringing-Our-Workplace-Policies-into-the-21st-Century" - fid = "BU6A9965" - path_root = Path("/mfs/lsen/DATA/Actor3/processing") - path_save = Path("./data/Actor3/DECA_Actor3_mean.npy") + fid = "4R3A0024" + path_root = Path("/mfs/lsen/DATA/Actor4/processing") + path_save = Path("./data/Actor4/DECA_Actor4_mean.npy") path_save.parent.mkdir(parents=True, exist_ok=True) path_data = path_root.joinpath(fid) diff --git a/scripts/Actor4Data/run-20-deca-reconstruction.py b/scripts/Actor4Data/run-20-deca-reconstruction.py index 4f2b10d..67f098b 100644 --- a/scripts/Actor4Data/run-20-deca-reconstruction.py +++ b/scripts/Actor4Data/run-20-deca-reconstruction.py @@ -33,7 +33,7 @@ def main(args): # IDs = ["clip_full"] # for each video - for i, ipath_data in enumerate(v_dir_videos): + for i, ipath_data in enumerate(v_dir_videos[1:]): ivideo_name = ipath_data.stem print(f"\n processing {i}/{len(v_dir_videos)} ...", ivideo_name) # if ivideo_name not in IDs: continue diff --git a/scripts/Actor4Data/run-21-features-3dmm.py b/scripts/Actor4Data/run-21-features-3dmm.py index 28a28ce..88be071 100644 --- a/scripts/Actor4Data/run-21-features-3dmm.py +++ b/scripts/Actor4Data/run-21-features-3dmm.py @@ -7,8 +7,8 @@ from pathlib import Path if __name__ == "__main__": - path_data = Path("/mfs/lsen/DATA/Actor3/processing") - v_dir_videos = sorted(path_data.glob("*")) + path_data = Path("/mfs/lsen/DATA/Actor4/processing") + v_dir_videos = sorted(path_data.glob("*"), reverse=True) print(f"Have {len(v_dir_videos)} dir files") # for each video diff --git a/scripts/Actor4Data/run-41-train-dict-data-raw-deca.py b/scripts/Actor4Data/run-41-train-dict-data-raw-deca.py index 664c62a..1f02d80 100644 --- a/scripts/Actor4Data/run-41-train-dict-data-raw-deca.py +++ b/scripts/Actor4Data/run-41-train-dict-data-raw-deca.py @@ -1,36 +1,12 @@ -import os -import sys import json -import librosa import numpy as np from pathlib2 import Path -from scipy import interpolate - import torchaudio -def landmark_resample_fps(y, source_fps = 30, target_fps=25): - """ y, N x 136, with 30fps - """ - - nsteps = y.shape[0] - x = np.arange(0, nsteps, 1) - # print("x:", x[::30], x[-10:]) - func = interpolate.interp1d(x, y=y, axis=0) - - x_new = np.arange(0, nsteps-1, 1.0*source_fps/target_fps) - # print("x_new", x_new[::30], x_new[-10:]) - y_new = func(x_new) - - if source_fps < target_fps: - y_new = np.concatenate([y_new, y[-1:]]) - - return y_new - - if __name__ == "__main__": - path_data = Path("/mfs/lsen/DATA/Actor3/processing") - path_save = Path('data/Actor3/Actor3-raw-2h') # processing + path_data = Path("/mfs/lsen/DATA/Actor4/processing") + path_save = Path('data/Actor4/Actor4-raw-1h') # processing path_save.mkdir(parents=True, exist_ok=True) v_dir_videos = sorted(path_data.glob("*/audio/feat_DECA_exp_trim.npy")) @@ -40,22 +16,9 @@ if __name__ == "__main__": vids = set([ipath.stem for ipath in v_dir_videos]) # print(f"vids total= {vids}") - vid_test = set(["BU6A9978"]) - vid_valid = set(["BU6A9965","BU6A9980","BU6A9978"]) - # vid_train = set(['AA7A9570', 'AA7A9571', 'AA7A9572', 'AA7A9573', 'AA7A9574', 'AA7A9575', 'AA7A9576', 'AA7A9579', - # 'AA7A9580', 'AA7A9582', 'AA7A9583', 'AA7A9584', 'AA7A9585', 'AA7A9600', 'AA7A9601', 'AA7A9602', - # 'AA7A9603', 'AA7A9604', 'AA7A9605', 'AA7A9606', 'AA7A9607', 'AA7A9608', 'AA7A9609', 'AA7A9610', - # 'AA7A9611', 'AA7A9612', 'AA7A9613', 'AA7A9614', 'AA7A9615', 'AA7A9616', 'AA7A9617', 'AA7A9618', - # 'AA7A9619', 'AA7A9620', 'AA7A9621', 'AA7A9622', 'AA7A9623', 'AA7A9625', 'AA7A9626', 'AA7A9627', - # 'AA7A9628']) - + vid_test = set(["4R3A0024"]) + vid_valid = set(["4R3A0024"]) vid_train = vids - vid_test - vid_valid - # vid_valid = vids - vid_test - vid_train - - # vids = set(["2021-P09", "2021-P14", "2021-P22"]) - # vid_test = set(["2021-P09" ]) - # vid_valid = set(["2021-P14" ]) - # vid_train = set(["2021-P22" ]) print(f"vid test= {vid_test} \nvalid= {vid_valid}") print(f"vid train= {vid_train}") @@ -171,7 +134,6 @@ if __name__ == "__main__": } - print(f"Total frames: data_train ({durations_train / 60 } min) ({durations_train / 3600 } h) , ids = ({len(data_train)})") print(f"Total frames: data_valid ({durations_valid / 60 } min) ({durations_valid / 3600 } h) , ids = ({len(data_valid)})") print(f"Total frames: data_test ({durations_test / 60 } min) ({durations_test / 3600 } h) , ids = ({len(data_test)})") diff --git a/scripts/BG_Actor4Data/run-02-ssim-batch.py b/scripts/BG_Actor4Data/run-02-ssim-batch.py new file mode 100644 index 0000000..401af8d --- /dev/null +++ b/scripts/BG_Actor4Data/run-02-ssim-batch.py @@ -0,0 +1,51 @@ +from pathlib import Path +from skimage.metrics import structural_similarity +from imageio import imread + +import numpy as np +from pathlib import Path + +import multiprocessing +from os import getpid + + +path_root = Path("/mfs/lsen/DATA/Actor4/bg") + +# idx_frame = 3530 +# fname = "body1" +idx_frame = 3740 #100 +fname = "head" +path_frames = path_root.joinpath(fname, "frames") + +# read inference images +path_frame_ref = path_frames.joinpath(f"frame-{idx_frame:06d}.jpg") +img_ref = imread(str(path_frame_ref)) + + +def worker_ssim(i): + if i % 100 == 0: print(f"[{getpid()}] procssing the {i:06d}-th... ") + + ipath_frame = path_frames.joinpath(f"frame-{i:06d}.jpg") + img = imread(str(ipath_frame)) + ssim = structural_similarity(img_ref, img, multichannel = True) + return ssim + + +if __name__ == '__main__': + + # save path + path_save = path_root.joinpath(fname, "video", f"ssim_ref_{idx_frame}.npy") + path_save.parent.mkdir(parents=True, exist_ok=True) + + # check frames + nframe = len(list(path_frames.glob("*.jpg"))) + + # multi-processing + pool = multiprocessing.Pool(24) + results = list(pool.map(worker_ssim, range(nframe))) + + # print(results) + + # save to npy + np.save(path_save, np.array(results)) + diff --git a/src/config.py b/src/config.py index 1cf4c13..37beccc 100644 --- a/src/config.py +++ b/src/config.py @@ -192,7 +192,9 @@ config.TRAIN.beta2 = 0.999 config.TRAIN.lambda1 = 100 config.TRAIN.lr_policy = '' config.TRAIN.lr_decay_iters = 0 +config.TRAIN.lr_step_gamma = 0.1 config.TRAIN.lr_milestones = [10,100,1000] + config.TRAIN.grad_clip_norm = False config.TRAIN.max_grad_clip = 0 config.TRAIN.max_grad_norm = 0 diff --git a/src/models/model_audio2mesh.py b/src/models/model_audio2mesh.py index f0f3c77..a1b5a49 100644 --- a/src/models/model_audio2mesh.py +++ b/src/models/model_audio2mesh.py @@ -16,7 +16,7 @@ from src.optims import get_optimizer, get_scheduler from src.utils import util # common -from common.animation import save_animation_with_gt2, write_video, write_video_with_gt +from common.animation import write_video, write_video_with_gt from common.debug import debug from common.losses import WingLoss @@ -44,16 +44,9 @@ class Audio2MeshModel(Base): self.netG.decoder_mesh.weight.data = init_exp_weight print(f"init_exp_weight shape = {init_exp_weight.shape}") - # # print network parameters - # for name, param in self.netG.named_parameters(): - # print(name, '\t\t', param.size()) - - # load mean lighting & shape - # self.netR, self.flame = define_netR(device=self.device) - # self.netG.init_reconstruct_model(self.netR) - self.netF = define_FLAME(opt, self.device) self.netR = define_render(opt, self.device) + self.processor, self.extractor = define_extractor(opt, self.device) # path_deca_mean = Path("./data/DECA_obama_mean.npy") path_deca_mean = self.opt.DATASET.path_mean_dict @@ -66,11 +59,9 @@ class Audio2MeshModel(Base): self.temp_verts_specific, self.temp_ldmk2d_specific, self.temp_ldmk3d_specific \ = self.get_template_vertices(self.mean_dict) # verts: (1 x 1 x 5023 x 3), ldmk: (1 x 1 x 68 x 3) - # if filter outlier - # if self.opt.LOSS.filter_outlier: + # loss function self.loss_func_wing = WingLoss(reduction="none") # return (B, ) self.loss_func_l1 = nn.L1Loss(reduction="none") - self.names_loss = opt.LOSS.names # define loss weight @@ -85,18 +76,7 @@ class Audio2MeshModel(Base): self.scheduler_G = get_scheduler(self.optimizer_G, opt) self.schedulers.append(self.scheduler_G) - if self.opt.DATASET.speech_extractor == "wav2vec": - from transformers import Wav2Vec2FeatureExtractor, Wav2Vec2Model - 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) - - path_ckpt_wav2vec = "./checkpoints/wav2vec2" - self.processor = Wav2Vec2FeatureExtractor.from_pretrained(path_ckpt_wav2vec) - self.extractor = Wav2Vec2Model.from_pretrained(path_ckpt_wav2vec).to(self.device) - - + @torch.no_grad() def set_input(self, batch_input): """ """ # motion data @@ -105,7 +85,6 @@ class Audio2MeshModel(Base): self.batch_vid = batch_input['vid'] self.batch_nframe = batch_input['nframe'] self.batch_interv = batch_input['frame_interval'] - self.B, self.nsteps = data.size(0), data.size(1) debug(self.opt, f"data = {data.shape}, dtype={data.dtype}", verbose=False) debug(self.opt, f"batch_vid = {self.batch_vid[:2]}", verbose=False) @@ -118,39 +97,30 @@ class Audio2MeshModel(Base): raw_speech = batch_input["cond"].numpy() # (B, nsegments) debug(self.opt, f"raw_speech = {raw_speech.shape}, dtype={raw_speech.dtype}", verbose=False) - if self.opt.DATASET.speech_extractor == "wav2vec": - # raw_speech = raw_speech.reshape(self.B * self.nsteps, -1) # (B*nsteps, nsegments) - # debug(self.opt, f"raw_speech = {raw_speech.shape}, dtype={raw_speech.dtype}", verbose=False) + # padding half frame length for bed and end + npad = int(0.5 * self.opt.DATASET.sr * ( 1 / self.opt.DATASET.fps) + 0.5) + pad_speech = np.pad(raw_speech, pad_width=((0,0), (npad, npad)), mode="edge") + debug(self.opt, f"after padding pad_speech = {pad_speech.shape}, dtype={pad_speech.dtype}", verbose=False) - # padding half frame length for bed and end - npad = int(0.5 * self.opt.DATASET.sr * ( 1 / self.opt.DATASET.fps) + 0.5) - raw_speech = np.pad(raw_speech, pad_width=((0,0), (npad, npad)), mode="edge") - debug(self.opt, f"after padding raw_speech = {raw_speech.shape}, dtype={raw_speech.dtype}", verbose=False) - - raw_speech = list(raw_speech) - inputs = self.processor(raw_speech, sampling_rate=16000, return_tensors="pt") - inputs = inputs.to(self.device) - - with torch.no_grad(): - output = self.extractor(**inputs) - cond = output.last_hidden_state - - else: - assert 0, "opt.DATASET.speech_extractor should be 'wav2vec | deepspeech | mfcc ' " - - # B x nsteps x nc_feat - debug(self.opt, f"data = {data.shape}, dtype={data.dtype}, device={data.device}", verbose=False) + inputs = self.processor(list(pad_speech), sampling_rate=16000, return_tensors="pt") + cond = self.extractor(**inputs.to(self.device)).last_hidden_state # B x nsteps x nc_feat 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) # (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) - data = data[:, 7:7+self.nseq, :] + # setup + self.cond = cond + self.B, self.nsteps, self.nwind, self.dim_speech = cond.size() + data = data[:, 7:7+self.nsteps, :] self.vert, self.ldmk2d, self.ldmk3d = self.get_vertices(data) + # cut audio clips + idx_beg = int(7 * self.opt.DATASET.sr / self.opt.DATASET.fps + 0.5) + idx_end = int((7 + self.nsteps) * self.opt.DATASET.sr / self.opt.DATASET.fps + 0.5) + self.raw_speech = raw_speech[:, idx_beg: idx_end] # (B, nsteps * sr / fps) + debug(self.opt, f"[set_input] vert = {self.vert.shape}, dtype={self.vert.dtype}, device={self.vert.device}", verbose=False) debug(self.opt, f"[set_input] cond = {self.cond.shape}, dtype={self.cond.dtype}, device={self.cond.device}", verbose=False) debug(self.opt, f"[set_input] ldmk2d = {self.ldmk2d.shape}, dtype={self.ldmk2d.dtype}, device={self.ldmk2d.device}", verbose=False) @@ -205,13 +175,17 @@ class Audio2MeshModel(Base): return loss_dict - def infer_with_gt(self, batch_cond, batch_data, audio_raw, suffix="", save_npy=True): + def infer_with_gt(self, batch_cond, batch_data, batch_speech, 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) + # add a dimensions + if batch_speech.dims == 1: + batch_speech = batch_speech.unsqueeze(0) # (B, nsegmt) + with torch.no_grad(): batch_pdt_geo = self.netG(cond) # B x N x dim_motion @@ -222,13 +196,14 @@ class Audio2MeshModel(Base): batch_pdt_geo = batch_pdt_geo - self.temp_verts + self.temp_verts_specific # render & and save - self.save_reconstruct(batch_pdt_geo, audio_raw, + + self.save_reconstruct(batch_pdt_geo, batch_speech, path_save=Path(self.opt.OUTPUT_DIR), suffix=suffix, vis_landmarks=False) # 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, + self.save_reconstruct_with_gt(batch_pdt_geo, vert, batch_speech, path_save=Path(self.opt.OUTPUT_DIR), suffix=suffix,vis_landmarks=False) @@ -278,7 +253,7 @@ class Audio2MeshModel(Base): batch_pdt_geo = batch_pdt_geo - self.temp_verts + self.temp_verts_specific print(f"testing pt shape = {batch_pdt_geo.shape}, gt shape = {self.vert.shape}") - self.save_reconstruct_with_gt(batch_pdt_geo, self.vert, + self.save_reconstruct_with_gt(batch_pdt_geo, self.vert, self.raw_speech, path_save=Path(self.opt.OUTPUT_DIR), suffix=f'sampled_{idx_epoch:05d}_{idx_batch:03d}') @@ -403,7 +378,8 @@ class Audio2MeshModel(Base): return loss, loss_dict def save_reconstruct(self, batch_pdt_geo, batch_speech, path_save, suffix="", vis_landmarks=False): - # batch_pdt_geo, [B x N x dim_motion] + # batch_pdt_pos, [B x N x dim_motion] + # batch_speech, [B x N*sr/fps ] B, N, *_ = batch_pdt_geo.shape nbatch_render = 10 @@ -464,68 +440,13 @@ class Audio2MeshModel(Base): return images - @torch.no_grad() - def save_reconstruct_with_gt2(self, batch_pdt_geo, batch_tgt_geo, batch_speech, path_save, suffix="", vis_landmarks=True): - # 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}_pt_gt.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}") - - if vis_landmarks: - # 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)) - else: - render_pt = render_pt.cpu() - render_gt = render_gt.cpu() - - # 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, ...])) - - - # save animation - write_video_with_gt(v_render_pt, v_render_gt, batch_speech, ipath_save, fps=50, sr=16000) - # print(f"testing v_render_pt = {len(v_render_pt)}, gt shape = {len(v_render_gt)}") - @torch.no_grad() - def save_reconstruct_with_gt(self, batch_pdt_geo, batch_tgt_geo, path_save, suffix=""): + def save_reconstruct_with_gt(self, batch_pdt_geo, batch_tgt_geo, batch_speech, path_save, suffix="", vis_landmarks=True): # batch_pdt_geo, [B x N x 5023 x 3] # batch_tgt_geo, [B x N x 5023 x 3] + # batch_speech, [B x N*sr/fps ] + B, N, *_ = batch_pdt_geo.shape nbatch_render = 10 @@ -555,47 +476,30 @@ class Audio2MeshModel(Base): 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_pt = kldmk3d_pt * self.opt.RENDER.image_size/2 + self.opt.RENDER.image_size/2 - - kldmk3d_gt = util.batch_orth_proj(kldmk3d_gt, cam); - kldmk3d_gt[:,:,1:] = -kldmk3d_gt[:,:,1:]; - # kldmk3d_gt = kldmk3d_gt * self.opt.RENDER.image_size/2 + self.opt.RENDER.image_size/2 - - # 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 = (255, 0, 0), color_gt=(0, 255, 0)) - render_gt = util.tensor_vis_landmarks(render_gt, kldmk3d_gt, isScale=True, color = (0, 255, 0)) + if vis_landmarks: + # 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)) + else: + render_pt = render_pt.cpu() + render_gt = render_gt.cpu() # 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, ...])) - # get audio - jvid = self.batch_vid[i] - jnframe = self.batch_nframe[i].numpy() - jstart_frame = self.batch_interv[0][i].numpy() - - jpath_audio = f"{self.opt.DATASET.root_raw}/{jvid}/audio/audio_trim.wav" - jstart_time = (jstart_frame + 7) / self.opt.DATASET.fps # xxx.yyy min - jend_time = (jstart_frame + 7 + self.nseq) / self.opt.DATASET.fps # xxx.yyy min - # print(f"jvid={jvid}, jnfram={jnframe}, jstart_frame={jstart_frame}, jpath_audio={jpath_audio}") - # print(f"jstart_time={jstart_time}, jend_time={jend_time}") - # 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=self.opt.DATASET.fps,\ - path_audio=jpath_audio, start_time=jstart_time, end_time=jend_time) - - - + write_video_with_gt(v_render_pt, v_render_gt, batch_speech[i], ipath_save, fps=50, sr=16000) ######################################### def tensor2image(tensor): @@ -655,4 +559,15 @@ def define_render(opt, device): return model +def define_extractor(opt, device): + from transformers import Wav2Vec2FeatureExtractor, Wav2Vec2Model + 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) + path_ckpt_wav2vec = "./checkpoints/wav2vec2" + processor = Wav2Vec2FeatureExtractor.from_pretrained(path_ckpt_wav2vec) + extractor = Wav2Vec2Model.from_pretrained(path_ckpt_wav2vec).to(device) + + return processor, extractor diff --git a/src/models/model_audio2pose.py b/src/models/model_audio2pose.py index 0b7750c..838bcf0 100644 --- a/src/models/model_audio2pose.py +++ b/src/models/model_audio2pose.py @@ -2,9 +2,6 @@ import numpy as np from collections import OrderedDict -import tempfile -from scipy.io import wavfile - import torch import torch.nn as nn from pathlib import Path @@ -77,7 +74,7 @@ class Audio2PoseModel(Base): torch.ones(self.opt.TRAIN.epoch_end - self.opt.TRAIN.epoch_sampling - self.opt.TRAIN.epoch_teacher), )) - + @torch.no_grad() def set_input(self, batch_input): # motion data @@ -108,13 +105,12 @@ class Audio2PoseModel(Base): debug(self.opt, f"after padding pad_speech = {pad_speech.shape}, dtype={pad_speech.dtype}", verbose=False) inputs = self.processor(list(pad_speech), sampling_rate=16000, return_tensors="pt") - with torch.no_grad(): - cond = self.extractor(**inputs.to(self.device)).last_hidden_state # B x nsteps x nc_feat - debug(self.opt, f"cond = {cond.shape}, dtype={cond.dtype}, device={cond.device}", verbose=False) + cond = self.extractor(**inputs.to(self.device)).last_hidden_state # B x nsteps x nc_feat + 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) # (B, nsteps, nc_codit, 16) - cond = cond.permute(0, 1, 3, 2) # (B, nsteps, 16, nc_speech) + # unfold speech data + cond = cond.unfold(dimension=1, size=16, step=1) # (B, nsteps, nc_codit, 16) + cond = cond.permute(0, 1, 3, 2) # (B, nsteps, 16, nc_speech) # setup self.c = cond # (B, nsteps, 16, nc_speech) @@ -203,7 +199,7 @@ class Audio2PoseModel(Base): ibatch_pt, ibatch_mu, ibatch_lv = self.netG(ibatch_x, ibatch_x_prev, ibatch_c) # [B, nc_motion] debug(self.opt, f"[test] ibatch_pt = {ibatch_pt.shape}") - batch_pt[:, istep] = ibatch_pt.detach().clone() # update batch_pt + batch_pt[:, istep] = ibatch_pt # update batch_pt batch_mu.append(ibatch_mu) batch_lv.append(ibatch_lv) @@ -461,7 +457,7 @@ class Audio2PoseModel(Base): def save_reconstruct_with_gt(self, batch_pdt_pos, batch_tgt_pos, batch_speech, path_save, suffix=""): # batch_pdt_pos, [B x N x nc_motion=6] # batch_pdt_pos, [B x N x nc_motion=6] - # batch_speech, [B x N*sr ] + # batch_speech, [B x N*sr/fps ] B, N, *_ = batch_pdt_pos.shape nbatch_render = 10 diff --git a/src/optims/__init__.py b/src/optims/__init__.py index fbb0c1d..fcd9d6e 100644 --- a/src/optims/__init__.py +++ b/src/optims/__init__.py @@ -47,15 +47,15 @@ def get_scheduler(optimizer, opt): scheduler = lr_scheduler.LambdaLR(optimizer, lr_lambda=lambda_rule) elif opt.TRAIN.lr_policy == 'step': - scheduler = lr_scheduler.StepLR(optimizer, step_size=opt.TRAIN.lr_decay_iters, gamma=0.1) + scheduler = lr_scheduler.StepLR(optimizer, step_size=opt.TRAIN.lr_decay_iters, gamma=opt.TRAIN.lr_step_gamma) elif opt.TRAIN.lr_policy == 'multistep': - scheduler = lr_scheduler.MultiStepLR(optimizer, milestones=opt.TRAIN.lr_milestones, gamma=0.1) + scheduler = lr_scheduler.MultiStepLR(optimizer, milestones=opt.TRAIN.lr_milestones, gamma=opt.TRAIN.lr_step_gamma) elif opt.TRAIN.lr_policy == 'plateau': scheduler = lr_scheduler.ReduceLROnPlateau(optimizer, mode='min', # In min mode, lr will be reduced when the quantity monitored has stopped decreasing; - factor=0.5, # new_lr = lr * factor. Default: 0.1., Factor by which the learning rate will be reduced. + factor=opt.TRAIN.lr_step_gamma, # new_lr = lr * factor. Default: 0.1., Factor by which the learning rate will be reduced. threshold=1e-4, # Threshold for measuring the new optimum min_lr=1e-6, # A lower bound on the learning rate patience=5, # Number of epochs with no improvement after which learning rate will be reduced diff --git a/train.py b/train.py index 6f3db40..c1c5ec1 100644 --- a/train.py +++ b/train.py @@ -110,7 +110,8 @@ if __name__ == "__main__": train_metric.reset() if opt.TRAIN.apply_update_parameters: model.update_parameters(epoch) - + model.update_learning_rate() + for i, ibatch_data in enumerate(train_loader): train_loss_dict = model.training(ibatch_data, epoch, i) # forward and backward @@ -147,8 +148,8 @@ if __name__ == "__main__": plot_loss(visor, epoch+1, valid_loss_dict, suffix="valid") ################ upate learning rate by validataion - if opt.TRAIN.apply_lr_scheduler: - model.update_learning_rate(valid_loss_dict["all"]) + # if opt.TRAIN.apply_lr_scheduler: + # model.update_learning_rate(valid_loss_dict["all"]) ################# testing if opt.TRAIN.apply_testing and (epoch+1) % opt.FREQ.epoch_test == 0: