diff --git a/common/animation.py b/common/animation.py index 1292321..5364dcc 100644 --- a/common/animation.py +++ b/common/animation.py @@ -31,7 +31,6 @@ def save_animation(data_motion, path_save, suffix, w=128*5, h=72*5, dpi=80): animation.write_videofile(str(ipath_save), fps=fps, logger=None) - def save_animation_ws_audio(data_motion, path_save, path_audio=None, start_time=None, end_time=None, fps=30, w=256, h=256, dpi=150): """ convert data_motion to .mp4 animation data_motion, shape [nsteps, 136] @@ -207,7 +206,7 @@ def write_video_with_gt(images_pt, images_gt, raw_speech, path_video, fps=50, sr writer = cv2.VideoWriter(file_video.name, cv2.VideoWriter_fourcc(*'mp4v'), fps, (2*W, H), True) for i in range(num_frame): - concate_image = np.concatenate((images_pt[i], images_gt), axis=1) # (H, 2*W, 3) + concate_image = np.concatenate((images_pt[i], images_gt[i]), axis=1) # (H, 2*W, 3) writer.write(concate_image) # close @@ -308,7 +307,6 @@ def save_animation_with_gt2(images_pt, images_gt, path_save, fps=None, path_audi animation.close() - def save_animation_with_gt(data_motion, data_motion_gt, path_save, suffix, w=128*5, h=72*5, dpi=80, maxsave=3, fps=30): """ convert data_motion to .mp4 animation data_motion, shape [B, N, 68, 2] 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_audio2pose_luox_20220415.yaml b/experiments/audio2pose/train_luox_20220415.yaml similarity index 67% rename from experiments/audio2pose/train_audio2pose_luox_20220415.yaml rename to experiments/audio2pose/train_luox_20220415.yaml index b15a398..81fa584 100644 --- a/experiments/audio2pose/train_audio2pose_luox_20220415.yaml +++ b/experiments/audio2pose/train_luox_20220415.yaml @@ -1,13 +1,10 @@ -GPUS: '9' +GPUS: '6' WORKERS: 4 OUTPUT_DIR: 'experiments/audio2pose' DEBUG: False verbose: False -VISUAL: - vsdm_env: "actor2-1h-happy-pretrain" - FREQ: batch_print: 20 epoch_save: 5 @@ -28,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: @@ -40,11 +37,9 @@ DATASET: flip: False shifting_speed: False - root: './data/LuoXData/LuoXData-pose-16h' # obama-deca-3-5-08-mini - root_raw: '/mfs/lsen/DATA/LuoXData/processing2' + root: './data/LuoXData/LuoXData-pose-16h' path_mean_dict: './data/LuoXData/DECA_LuoXData_mean.npy' filter: 'savgol' - speech_extractor: 'wav2vec' nwind_second_train: 3 nwind_second_valid: 3 @@ -54,12 +49,14 @@ TEST: batch_size: 2 TRAIN: - lr: 0.00005 - batch_size: 100 + lr: 0.0001 + batch_size: 128 shuffle: True apply_testing: True apply_validation: True + apply_lr_scheduler: False + apply_update_parameters: True optimizer: 'Adam' momentum: 0.9 @@ -67,26 +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: 150 + 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 new file mode 100644 index 0000000..8fdf31f --- /dev/null +++ b/experiments/audio2pose/train_obama_20220423.yaml @@ -0,0 +1,88 @@ +GPUS: '7' +WORKERS: 4 +OUTPUT_DIR: 'experiments/audio2pose' + +DEBUG: False +verbose: False + + +FREQ: + batch_print: 20 + epoch_save: 5 + epoch_valid: 1 + epoch_test: 5 + +MODEL: + name: 'audio2pose' + name_netG: "audio2pose_mvae" + + dim_motion: 6 + dim_speech: 1024 + dim_hidden: 64 + num_vertices: 5023 + + n_lookahead_motion: 1 + n_lookprevs_motion: 1 + + pretrain: True + path_checkpoint: "experiments/audio2pose/train_obama_20220423/20220424-15H39M44S" + load_epoch: 90 + +DATASET: + fps: 50 + sr: 16000 + name_train: "motion_pose" + name_valid: "motion_pose" + flip: False + shifting_speed: False + + root: './data/Obama/obama-pose-8h' # obama-deca-3-5-08-mini + path_mean_dict: './data/Obama/DECA_obama_mean_wf.npy' + filter: 'savgol' + + 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 + apply_lr_scheduler: False + apply_update_parameters: True + + optimizer: 'Adam' + momentum: 0.9 + beta1: 0.5 + beta2: 0.999 + weight_decay: 0.0001 + nesterov: True + + 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: 50 + + + resume: False + reset_lr: False + resume_suffix: "20220424-15H39M44S" + epoch_begin: 0 # 5000 # 2300 # 2600 + epoch_end: 300 + + +LOSS: + names: ["rec", "kl", "vel", "all"] + lambda_kl: 1 + lambda_vel: 10 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/Actor1Data/run-00-check-data.py b/scripts/Actor1Data/run-00-check-data.py new file mode 100644 index 0000000..f103a2e --- /dev/null +++ b/scripts/Actor1Data/run-00-check-data.py @@ -0,0 +1,35 @@ +from pathlib import Path +import json +import moviepy +from moviepy.editor import VideoFileClip, AudioFileClip + + +if __name__ == '__main__': + + # path_root = Path("/yrfs/lsen/DATA/Actor1") + path_root = Path("/data1/yrfs/lsen/DATA/bj_chinsee_data") + + vpath_videos = sorted(path_root.glob("**/*.mp4"), reverse=False) + print(f"Have {len(vpath_videos)} dir files") + + durations = 0 + # for each video + for i, ipath_item in enumerate(vpath_videos): + iname = ipath_item.stem + print(f"processing {i}/{len(vpath_videos)} -> {ipath_item} ... ") + + # load video + video = VideoFileClip(str(ipath_item)) + print(f"video duration = {video.duration}, fps = {video.fps}, (start, end)=({video.start},{video.end}), nframes={int(video.duration * video.fps)}") + + # durations += video.duration + # print(f"\t -> Total durations = ({durations / 60 } min) ({durations / 3600 } h))") + # continue + + if video.audio is None: + print("\nERROR: audio info is None") + continue + + durations += video.duration + print(f"\n\t -> Total durations = ({durations / 60 } min) ({durations / 3600 } h))") + # cont \ No newline at end of file diff --git a/scripts/Actor1Data/run-30-extract-landmarks.py b/scripts/Actor1Data/run-30-extract-landmarks.py new file mode 100644 index 0000000..3ad10bf --- /dev/null +++ b/scripts/Actor1Data/run-30-extract-landmarks.py @@ -0,0 +1,74 @@ + +from torch.utils.data import Dataset, DataLoader + +import torch +import numpy as np +from PIL import Image +from pathlib2 import Path +from face_alignment import FaceAlignment, LandmarksType +from zmq import device + + +class ImagesDataset(Dataset): + def __init__(self, path_folder:Path): + + self.path_folder = path_folder + self.list_image = sorted(path_folder.glob("*.jpg"), reverse=False) + print(f"Have {len(self.list_image)} images, like {self.list_image[:3]}") + + + def __len__(self): + return len(self.list_image) + + def __getitem__(self, idx): + path_frame = self.list_image[idx] + image = Image.open(str(path_frame)).convert('RGB') # (h, w, 3) + image = np.asarray(image) + return {"image_name": path_frame.stem, "image": image} + + +if __name__ == "__main__": + + path_data = Path("/mfs/lsen/DATA/Actor1/processing") + vpath_videos = sorted(path_data.glob("*")) + print(f"Have {len(vpath_videos)} dir files") + + device = "cuda:0" + model = FaceAlignment(LandmarksType._2D, device=device, face_detector='sfd') + print(f"load FaceAlignment model in {device}") + + IDs = ["2-23min"] + # for each word + for i, ipath_item in enumerate(vpath_videos): + iname = ipath_item.stem + print(f"processing {i}/{len(vpath_videos)} -> {ipath_item} ... ") + + if iname not in IDs: continue + + ipath_infor = ipath_item.joinpath("video/info.json") + ipath_ldmks = ipath_item.joinpath("landmarks_FAN") + ipath_frame = ipath_item.joinpath("frames") + ipath_ldmks.mkdir(parents=True, exist_ok=True) + + dataset = ImagesDataset(ipath_frame) + dloader = DataLoader(dataset, batch_size=16, num_workers=8) + + for k, ibatch in enumerate(dloader): + ibatch_name = ibatch["image_name"] + ibatch_data = ibatch["image"].to(device) # B x H x W x 3 + ibatch_data = ibatch_data.permute(0, 3, 1, 2) # B x H x W x 3 + # print(f"ibatch_data shape = {ibatch_data.shape}, path={ibatch_name[:3]}") + if k%100 == 0: + print(f"batching {k}/{len(dloader)} ... ") + + pred = model.get_landmarks_from_batch(ibatch_data, return_landmark_score=False) + # print(f"pred len = {len(pred)}, type= {type(pred)}, [0] shape={pred[0].shape}") + + # save landmarks + for jldmk, jname in zip(pred, ibatch_name): + jpath_ldmk = ipath_ldmks.joinpath(jname + ".txt") + np.savetxt(jpath_ldmk, jldmk, fmt=" %3d") + + + + # break \ No newline at end of file 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 bc51d7e..67f098b 100644 --- a/scripts/Actor4Data/run-20-deca-reconstruction.py +++ b/scripts/Actor4Data/run-20-deca-reconstruction.py @@ -16,7 +16,6 @@ from decalib.utils.config import cfg as deca_cfg def main(args): - # device = args.device device = "cuda:7" @@ -25,16 +24,16 @@ def main(args): deca = DECA(config = deca_cfg, device=device) # path_data = Path("/yrfs/lsen/DATA/TestData/processing") - path_data = Path("/mfs/lsen/DATA/Actor3/processing") + path_data = Path("/mfs/lsen/DATA/Actor4/processing") - v_dir_videos = sorted(path_data.glob("*"), reverse=False) + v_dir_videos = sorted(path_data.glob("*"), reverse=True) print(f"Have {len(v_dir_videos)} dir files") # IDs = ["actor-2HD", "actor-3HD"] # 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 b27cdce..37beccc 100644 --- a/src/config.py +++ b/src/config.py @@ -182,6 +182,7 @@ config.TRAIN = edict() config.TRAIN.apply_validation = False config.TRAIN.apply_testing = False config.TRAIN.apply_update_parameters = False +config.TRAIN.apply_lr_scheduler = False config.TRAIN.lr = 0.001 config.TRAIN.lr_step = [50, 100] @@ -191,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 29fe5e2..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) @@ -241,7 +216,7 @@ class Audio2MeshModel(Base): print(f"save infer_result shape = {batch_pdt_geo.shape} -> {path_save_npy}") - def infer(self, batch_cond, raw_speech, suffix="", save_npy=True): + def infer(self, batch_cond, batch_speech, suffix="", save_npy=True): self.eval() self.cond = batch_cond.float().to(self.device) # (nsteps, dim_cond) @@ -255,7 +230,7 @@ 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, raw_speech, path_save=Path(self.opt.OUTPUT_DIR), + self.save_reconstruct(batch_pdt_geo, batch_speech, path_save=Path(self.opt.OUTPUT_DIR), suffix=suffix, vis_landmarks=False) if save_npy: @@ -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}') @@ -402,8 +377,9 @@ class Audio2MeshModel(Base): return loss, loss_dict - def save_reconstruct(self, batch_pdt_geo, raw_speech, path_save, suffix="", vis_landmarks=False): - # batch_pdt_geo, [B x N x dim_motion] + def save_reconstruct(self, batch_pdt_geo, batch_speech, path_save, suffix="", vis_landmarks=False): + # 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 @@ -441,7 +417,7 @@ class Audio2MeshModel(Base): # write video ipath_save = path_save.joinpath(f"{suffix}_{i:02d}_pt.mp4") - write_video(v_render_pt, raw_speech, ipath_save, fps=50) + write_video(v_render_pt, batch_speech, ipath_save, fps=50) self.logger.info(f"save video to -> {str(ipath_save)}") @@ -464,68 +440,13 @@ class Audio2MeshModel(Base): return images - @torch.no_grad() - def save_reconstruct_with_gt2(self, batch_pdt_geo, batch_tgt_geo, raw_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, raw_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,48 +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): @@ -656,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 f27bf69..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 @@ -15,7 +12,7 @@ from src.optims import get_optimizer, get_scheduler from src.utils import util # common -from common.animation import save_animation_with_gt2, save_images_with_audio +from common.animation import write_video, write_video_with_gt from common.debug import debug from common.losses import WingLoss @@ -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 @@ -104,24 +101,26 @@ class Audio2PoseModel(Base): # padding half frame length for bed and end npad = int(0.5 * self.opt.DATASET.sr * ( 1 / self.opt.DATASET.fps) + 0.5) - raw_pad = np.pad(raw_speech, pad_width=((0,0), (npad, npad)), mode="edge") - debug(self.opt, f"after padding raw_pad = {raw_pad.shape}, dtype={raw_pad.dtype}", verbose=False) + 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) - inputs = self.processor(list(raw_pad), 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) + 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, 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) self.B, self.nsteps, self.nwind, self.dim_speech = cond.size() self.x = self.x[:, 7:7+self.nsteps, :] # (B, nsteps, nc_motion) - self.raw_speech = raw_speech[:, 7*self.opt.DATASET.sr: (7+self.nsteps)*self.opt.DATASET.sr] # (B, nsteps * sr) - + + # 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) self.idn = self.idn[:, 7:7+self.nsteps, :] self.exp = self.exp[:, 7:7+self.nsteps, :] @@ -170,7 +169,6 @@ class Audio2PoseModel(Base): self.logger.info(f"\t[UPDATE] lambda_kl = {self.opt.LOSS.lambda_kl}") - def training(self, batch_input, idx_epoch=0, idx_batch=0): self.train() # set train model self.set_input(batch_input) @@ -201,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) @@ -265,61 +263,58 @@ class Audio2PoseModel(Base): return loss_dict - def infer(self, batch_cond, path_audio, suffix="", save_npy=True): + + def infer(self, batch_cond, batch_speech, suffix="", save_npy=True): self.eval() - c = batch_cond.float().to(self.device) # (B, nsteps, 16, nc_speech) - nbtach, nstep, *_ = c.shape + 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.temp_verts # B x N x 5023 x 3 - batch_pos = self.netG(self.cond) # B x N x dim_motion - batch_pos += self.temp_verts # B x N x 5023 x 3 - - print(f"testing pt shape = {batch_pos.shape}") + print(f"testing pt shape = {batch_pdt_geo.shape}") # !! add specific when render & output !! - batch_pos = batch_pos - self.temp_verts + self.temp_verts_specific + batch_pdt_geo = batch_pdt_geo - self.temp_verts + self.temp_verts_specific # render & and save - self.save_reconstruct(batch_pos, path_audio, - path_save=Path(self.opt.OUTPUT_DIR), - suffix=suffix) - + self.save_reconstruct(batch_pdt_geo, batch_speech, path_save=Path(self.opt.OUTPUT_DIR), + suffix=suffix, vis_landmarks=False) + if save_npy: # save result - batch_pos = batch_pos.cpu().numpy() + 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_pos) - print(f"save infer_result shape = {batch_pos.shape} -> {path_save_npy}") - + np.save(path_save_npy, batch_pdt_geo) + print(f"save infer_result shape = {batch_pdt_geo.shape} -> {path_save_npy}") + + + @torch.no_grad() def testing(self, batch_input, idx_epoch=0, idx_batch=0): self.eval() # set eval model self.set_input(batch_input) - with torch.no_grad(): - - batch_pt = torch.zeros_like(self.x) # [B, nsteps, nc_motion] - # batch_pt[:, 0, 3] = self.x[:, 0, 3] # T-pose + first scale from input data - batch_pt[:, 0] = self.x[:, 0] # T-pose + first scale from input data + batch_pt = torch.zeros_like(self.x) # [B, nsteps, nc_motion] + # batch_pt[:, 0, 3] = self.x[:, 0, 3] # T-pose + first scale from input data + batch_pt[:, 0] = self.x[:, 0] # T-pose + first scale from input data - for istep in range(1, self.nsteps): - ibatch_z = torch.randn((self.B, self.dim_latent), device=self.device) # [B, dim_latent] - ibatch_c = self.c[:, istep] # [B, nwind, nc_speech] - ibatch_x_prev = batch_pt[:, istep-1] # [B, nc_motion] + for istep in range(1, self.nsteps): + ibatch_z = torch.randn((self.B, self.dim_latent), device=self.device) # [B, dim_latent] + ibatch_c = self.c[:, istep] # [B, nwind, nc_speech] + ibatch_x_prev = batch_pt[:, istep-1] # [B, nc_motion] - # forward - ibatch_pt = self.netG.sample(ibatch_z, ibatch_x_prev, ibatch_c) # [B, nc_motion] + # forward + ibatch_pt = self.netG.sample(ibatch_z, 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 + debug(self.opt, f"[test] ibatch_pt = {ibatch_pt.shape}") + batch_pt[:, istep] = ibatch_pt.detach().clone() # update batch_pt - # save video - # print(f"testing pt shape = {batch_pt.shape}, gt shape = {self.x.shape}") - - self.save_reconstruct_with_gt(batch_pt, self.x, - path_save=Path(self.opt.OUTPUT_DIR), - suffix=f'sampled_{idx_epoch:05d}_{idx_batch:03d}') + # save video + # print(f"testing pt shape = {batch_pt.shape}, gt shape = {self.x.shape}") + self.save_reconstruct_with_gt(batch_pt, self.x, self.raw_speech, + path_save=Path(self.opt.OUTPUT_DIR), + suffix=f'sampled_{idx_epoch:05d}_{idx_batch:03d}') @torch.no_grad() @@ -345,6 +340,28 @@ class Audio2PoseModel(Base): return verts, ldmk2d, ldmk3d + + @torch.no_grad() + def render_geometry(self, verts, cam=None, device=None): + """ + verts: [N x 5023 x 3] + """ + batch_size = verts.size(0) + + if cam is None: + cam = torch.zeros(batch_size, 3).to(device) # (batch_size, 3) + + # orth_proj + verts_proj = util.batch_orth_proj(verts, cam); + verts_proj[:,:,1:] = -verts_proj[:,:,1:] + + # render + images = self.netR.render_shape(verts, verts_proj) # (batch_size, 3, 512, 512) + + return images + + + def eval_losses(self, batch_pt, batch_gt, batch_mu, batch_lv): """ Computes the VAE loss function. pramas: @@ -387,8 +404,9 @@ class Audio2PoseModel(Base): @torch.no_grad() - def save_reconstruct(self, batch_pdt_pos, raw_speech, path_save, suffix="", vis_landmarks=True): + def save_reconstruct(self, batch_pdt_pos, batch_speech, path_save, suffix="", vis_landmarks=True): # batch_pdt_pos, [B x N x dim_motion] + # batch_speech, [B x N*sr ] B, N, *_ = batch_pdt_pos.shape nbatch_render = 10 @@ -428,99 +446,18 @@ class Audio2PoseModel(Base): for m in range(nbatch_real): v_render_pt.append(tensor2image(render_pt[m, ...])) - # write tmp audio - tmp_audio = tempfile.NamedTemporaryFile(suffix='.wav') - wavfile.write(tmp_audio.name, rate=16000, data=raw_speech) - # save animation - save_images_with_audio(v_render_pt, tmp_audio.name, ipath_save) + # write video + ipath_save = path_save.joinpath(f"{suffix}_{i:02d}_pt.mp4") + write_video(v_render_pt, batch_speech, ipath_save, fps=50) + self.logger.info(f"save video to -> {str(ipath_save)}") @torch.no_grad() - def render_geometry(self, verts, cam=None, device=None): - """ - verts: [N x 5023 x 3] - """ - batch_size = verts.size(0) - - if cam is None: - cam = torch.zeros(batch_size, 3).to(device) # (batch_size, 3) - - # orth_proj - verts_proj = util.batch_orth_proj(verts, cam); - verts_proj[:,:,1:] = -verts_proj[:,:,1:] - - # render - images = self.netR.render_shape(verts, verts_proj) # (batch_size, 3, 512, 512) - - return images - - - @torch.no_grad() - def save_reconstruct_with_gt2(self, batch_pdt_pos, batch_tgt_geo, raw_speech, path_save, suffix="", vis_landmarks=True): - # batch_pdt_pos, [1 x N x 5023 x 3] - # batch_tgt_geo, [1 x N x 5023 x 3] - - B, N, *_ = batch_pdt_pos.shape - - ipos_pt = batch_pdt_pos[0, ...] # [N x 5023 x 3] - ipos_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 - kpos_pt = ipos_pt[k:k+nbatch_render, ...] # [nbatch_real x 5023 x 3] - kpos_gt = ipos_gt[k:k+nbatch_render, ...] # [nbatch_real x 5023 x 3] - - nbatch_real = kpos_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(kpos_pt, cam, self.device) # (nbatch_real, 3, 512, 512) - render_gt = self.render_geometry(kpos_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, ...])) - - - # 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_pos, batch_tgt_pos, path_save, suffix=""): + 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/fps ] B, N, *_ = batch_pdt_pos.shape nbatch_render = 10 @@ -570,19 +507,10 @@ class Audio2PoseModel(Base): # get audio - jvid = self.batch_vid[i] - 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.nsteps) / 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): @@ -645,7 +573,4 @@ def define_extractor(opt, device): processor = Wav2Vec2FeatureExtractor.from_pretrained(path_ckpt_wav2vec) extractor = Wav2Vec2Model.from_pretrained(path_ckpt_wav2vec).to(device) - return processor, extractor - - - + return processor, extractor \ No newline at end of file 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 52617ee..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,7 +148,8 @@ if __name__ == "__main__": 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_lr_scheduler: + # model.update_learning_rate(valid_loss_dict["all"]) ################# testing if opt.TRAIN.apply_testing and (epoch+1) % opt.FREQ.epoch_test == 0: