From 8c4865effb997933411daa4efccc8a505103d3bf Mon Sep 17 00:00:00 2001 From: Sen Liang Date: Mon, 7 Feb 2022 17:28:40 +0800 Subject: [PATCH] Happy new years --- .gitignore | 6 +- common/animation.py | 31 +- common/vis/visualizer.py | 39 +- .../infer_audio2motionV_CN_20220127.yaml | 81 ++++ .../infer_audio2motionW_20220111.yaml | 67 +++ .../infer_audio2motionW_20220118.yaml | 66 +++ .../infer_audio2motionW_20220120.yaml | 69 +++ .../train_audio2motion3_obama.yaml | 85 ++++ .../train_audio2motionCL_20220119.yaml | 77 ++++ .../train_audio2motionC_20220119.yaml | 77 ++++ .../train_audio2motionFH_CN_20220125.yaml | 78 ++++ .../train_audio2motionFH_CN_20220126.yaml | 78 ++++ .../train_audio2motionF_CN_20220125.yaml | 85 ++++ .../train_audio2motionF_CN_20220126.yaml | 84 ++++ .../train_audio2motionR_20220112.yaml | 86 ++++ .../train_audio2motionV_20220120.yaml | 76 ++++ .../train_audio2motionV_20220120B.yaml | 76 ++++ .../train_audio2motionV_CN_20220123.yaml | 75 ++++ .../train_audio2motionV_CN_20220126.yaml | 83 ++++ .../train_audio2motionV_CN_20220127.yaml | 81 ++++ .../train_audio2motionV_CN_20220207.yaml | 81 ++++ .../train_audio2motionV_CN_20220207_2.yaml | 83 ++++ .../train_audio2motionW_20220111.yaml | 87 ++++ .../train_audio2motionW_20220118.yaml | 87 ++++ .../train_audio2motionW_20220120.yaml | 87 ++++ .../train_audio2motionW_CN_20220123.yaml | 76 ++++ .../train_audio2motionW_CN_20220125.yaml | 76 ++++ .../train_audio2motion_obama.yaml | 84 ++++ infer_one_live.py | 168 +++++++ scripts/LuoXData/run-01-prepare-data.py | 100 +++++ .../run-10-speech-features-mel-align.py | 73 ++++ .../LuoXData/run-20-deca-reconstruction.py | 141 ++++++ scripts/LuoXData/run-30-features-3dmm.py | 101 +++++ .../run-40-3dmm-train-vaild-test-ds.py | 160 +++++++ scripts/LuoXData/run-41-3dmm-ds-split-data.py | 153 +++++++ .../Obama/run-52-3dmm-train-vaild-test-ds.py | 68 +-- scripts/Test/test_transformer.py | 52 +++ scripts/Test/test_transformer2.py | 87 ++++ scripts/Test/test_transformer3.py | 33 ++ scripts/Test/test_transformer4.py | 94 ++++ src/config.py | 23 +- src/datasets/motion_live.py | 115 +++++ src/models/base.py | 13 +- src/models/model_audio2motion.py | 10 +- src/models/model_audio2motion_live.py | 375 ++++++++++++++++ src/models/model_audio2motion_live2.py | 411 ++++++++++++++++++ src/nn/audio2motion.py | 10 +- src/nn/audio2motion2.py | 84 ++++ src/nn/audio2motion_head.py | 40 ++ src/nn/audio2motion_voca3.py | 78 ++++ src/nn/audio2motion_voca33.py | 89 ++++ src/nn/audio2motion_voca4.py | 107 +++++ train.py | 19 +- 53 files changed, 4604 insertions(+), 61 deletions(-) create mode 100644 experiments/audio2motion/infer_audio2motionV_CN_20220127.yaml create mode 100644 experiments/audio2motion/infer_audio2motionW_20220111.yaml create mode 100644 experiments/audio2motion/infer_audio2motionW_20220118.yaml create mode 100644 experiments/audio2motion/infer_audio2motionW_20220120.yaml create mode 100644 experiments/audio2motion/train_audio2motion3_obama.yaml create mode 100644 experiments/audio2motion/train_audio2motionCL_20220119.yaml create mode 100644 experiments/audio2motion/train_audio2motionC_20220119.yaml create mode 100644 experiments/audio2motion/train_audio2motionFH_CN_20220125.yaml create mode 100644 experiments/audio2motion/train_audio2motionFH_CN_20220126.yaml create mode 100644 experiments/audio2motion/train_audio2motionF_CN_20220125.yaml create mode 100644 experiments/audio2motion/train_audio2motionF_CN_20220126.yaml create mode 100644 experiments/audio2motion/train_audio2motionR_20220112.yaml create mode 100644 experiments/audio2motion/train_audio2motionV_20220120.yaml create mode 100644 experiments/audio2motion/train_audio2motionV_20220120B.yaml create mode 100644 experiments/audio2motion/train_audio2motionV_CN_20220123.yaml create mode 100644 experiments/audio2motion/train_audio2motionV_CN_20220126.yaml create mode 100644 experiments/audio2motion/train_audio2motionV_CN_20220127.yaml create mode 100644 experiments/audio2motion/train_audio2motionV_CN_20220207.yaml create mode 100644 experiments/audio2motion/train_audio2motionV_CN_20220207_2.yaml create mode 100644 experiments/audio2motion/train_audio2motionW_20220111.yaml create mode 100644 experiments/audio2motion/train_audio2motionW_20220118.yaml create mode 100644 experiments/audio2motion/train_audio2motionW_20220120.yaml create mode 100644 experiments/audio2motion/train_audio2motionW_CN_20220123.yaml create mode 100644 experiments/audio2motion/train_audio2motionW_CN_20220125.yaml create mode 100644 experiments/audio2motion/train_audio2motion_obama.yaml create mode 100644 infer_one_live.py create mode 100755 scripts/LuoXData/run-01-prepare-data.py create mode 100644 scripts/LuoXData/run-10-speech-features-mel-align.py create mode 100644 scripts/LuoXData/run-20-deca-reconstruction.py create mode 100644 scripts/LuoXData/run-30-features-3dmm.py create mode 100644 scripts/LuoXData/run-40-3dmm-train-vaild-test-ds.py create mode 100644 scripts/LuoXData/run-41-3dmm-ds-split-data.py create mode 100644 scripts/Test/test_transformer.py create mode 100644 scripts/Test/test_transformer2.py create mode 100644 scripts/Test/test_transformer3.py create mode 100644 scripts/Test/test_transformer4.py create mode 100644 src/datasets/motion_live.py create mode 100644 src/models/model_audio2motion_live.py create mode 100644 src/models/model_audio2motion_live2.py create mode 100644 src/nn/audio2motion2.py create mode 100644 src/nn/audio2motion_head.py create mode 100644 src/nn/audio2motion_voca3.py create mode 100644 src/nn/audio2motion_voca33.py create mode 100644 src/nn/audio2motion_voca4.py diff --git a/.gitignore b/.gitignore index 8b76a86..0361ac3 100644 --- a/.gitignore +++ b/.gitignore @@ -1,4 +1,8 @@ -experiments +# experiments **/__pycache__ **/*.pyc + + +*.mp3 +*.pt \ No newline at end of file diff --git a/common/animation.py b/common/animation.py index 76d0fff..def2c13 100644 --- a/common/animation.py +++ b/common/animation.py @@ -145,7 +145,15 @@ def save_images_with_audio(images, path_audio, path_save): N = len(images) # load audio + # if isinstance(path_audio, str): + # print(f"load audio form str") audioclip = mpy.AudioFileClip(str(path_audio)) + + # elif isinstance(path_audio, np.ndarray): + # print(f"load audio form np.ndarray") + # audioclip = mpy.AudioFileClip(path_audio, fps=16000) + + duration = audioclip.duration # add video @@ -182,14 +190,15 @@ def save_animation_with_gt5(images_pt, images_gt, images_A, images_B, images_C, animation.write_videofile(str(path_save), fps=fps, logger=None) -def save_animation_with_gt2(images_pt, images_gt, path_save): +def save_animation_with_gt2(images_pt, images_gt, path_save, fps=None, path_audio=None, start_time=None, end_time=None): """ convert images_pt to .mp4 animation images_pt, shape len= N list [224, 224, 3] images_gt, shape len= N list [224, 224, 3] """ # print(f"images_pt shape = {len(images_pt)}, shape[0]={images_pt[0].shape}") - fps = 30 + fps = fps if fps else 30 + N = len(images_pt) duration = N / fps # print(f"fps = {fps}, N ={N}, duration={duration}") @@ -200,6 +209,24 @@ def save_animation_with_gt2(images_pt, images_gt, path_save): # mixture & save animation = mpy.clips_array([[animation_pt, animation_gt]]) + + + if path_audio is not None: + audioclip = mpy.AudioFileClip(str(path_audio)) + + # cut-off + if (start_time is not None) and (end_time is not None): + print(f"subclip clips {start_time}:{end_time}") + audioclip = audioclip.subclip(start_time, end_time) + + # alignment to video + audioclip = audioclip.set_duration(duration) + + # add audio to animation + animation = animation.set_audio(audioclip) + animation = animation.set_duration(duration) + + animation.write_videofile(str(path_save), fps=fps) diff --git a/common/vis/visualizer.py b/common/vis/visualizer.py index a94b6c0..3efe648 100644 --- a/common/vis/visualizer.py +++ b/common/vis/visualizer.py @@ -167,6 +167,43 @@ class Visualizer(): webpage.add_images(ims, txts, links, width=self.opt.VISUAL.vsdm_wsize) webpage.save() + + def plot_current_losses_valid(self, epoch, counter_ratio, losses): + """display the current losses on visdom display: dictionary of error labels and values + + Parameters: + epoch (int) -- current epoch + counter_ratio (float) -- progress (percentage) in the current epoch, between 0 to 1 + losses (OrderedDict) -- training losses stored in the format of (name, float) pairs + """ + if not self.opt.VISUAL.use_visdom: return + + if not hasattr(self, 'plot_data_valid'): + self.plot_data_valid = {'X': [], 'Y': [], 'legend': list(losses.keys())} + + self.plot_data_valid['X'].append(epoch + counter_ratio) + self.plot_data_valid['Y'].append([losses[k] for k in self.plot_data_valid['legend']]) + + try: + # print("np.array(self.plot_data_valid['X'])=", np.array(self.plot_data_valid['X'])) + # print("np.array(self.plot_data_valid['Y'])=", np.array(self.plot_data_valid['Y'])) + # print("self.plot_data_valid['legend']", self.plot_data_valid['legend']) + + self.vis.line( + X=np.stack([np.array(self.plot_data_valid['X'])] * len(self.plot_data_valid['legend']), 1), + Y=np.array(self.plot_data_valid['Y']), + opts={ + 'title': self.name + ' loss over time (valid)', + 'legend': self.plot_data_valid['legend'], + 'xlabel': 'epoch', + 'ylabel': 'loss'}, + win=self.opt.VISUAL.vsdm_id + 1000) + + except Exception: + raise("CANNOT vis line") + self.create_visdom_connections() + + def plot_current_losses(self, epoch, counter_ratio, losses): """display the current losses on visdom display: dictionary of error labels and values @@ -188,7 +225,6 @@ class Visualizer(): # print("np.array(self.plot_data['Y'])=", np.array(self.plot_data['Y'])) # print("self.plot_data['legend']", self.plot_data['legend']) - self.vis.line( X=np.stack([np.array(self.plot_data['X'])] * len(self.plot_data['legend']), 1), Y=np.array(self.plot_data['Y']), @@ -198,6 +234,7 @@ class Visualizer(): 'xlabel': 'epoch', 'ylabel': 'loss'}, win=self.opt.VISUAL.vsdm_id) + except Exception: raise("CANNOT vis line") self.create_visdom_connections() diff --git a/experiments/audio2motion/infer_audio2motionV_CN_20220127.yaml b/experiments/audio2motion/infer_audio2motionV_CN_20220127.yaml new file mode 100644 index 0000000..86fee60 --- /dev/null +++ b/experiments/audio2motion/infer_audio2motionV_CN_20220127.yaml @@ -0,0 +1,81 @@ +GPUS: '4' +WORKERS: 8 +OUTPUT_DIR: 'experiments/audio2motion' + +DEBUG: False +verbose: False + + +VISUAL: + use_HTML: False + use_visdom: True + vsdm_port: 9000 + vsdm_ncol: 4 + vsdm_env: "audio2motion-VOCA-big-sgd" + +FREQ: + epoch_save: 5 + epoch_valid: 1 + batch_print: 20 + + epoch_test: 5 + + +MODEL: + name: 'audio2motion_live2' + name_netG: "audio2motion_voca3" + + dim_motion: 53 # 68*2 + dim_speech: 1024 + dim_hidden: 256 + + pretrain: True + path_checkpoint: "experiments/audio2motion/train_audio2motionV_CN_20220127/20220127-20H48M25S" + load_epoch: 125 + + +DATASET: + fps: 50 + sr: 16000 + name: "motion_live" + root: './data/LuoXData-raw-deca-6h' # obama-deca-3-5-08-mini + filter: 'savgol' + speech_extractor: 'wav2vec' + + nwind_second_train: 3 + nwind_second_valid: 3 + nwind_second_test: 10 + +TEST: + batch_size: 2 + +TRAIN: + lr: 0.001 + batch_size: 32 + shuffle: True + + apply_testing: True + apply_validation: True + + optimizer: 'SGD' + momentum: 0.9 + beta1: 0.5 + beta2: 0.999 + weight_decay: 0.0001 + nesterov: False + grad_clip_norm: False + lr_policy: 'multistep' + lr_milestones: [10, 100, 500] + # lr_policy: 'plateau' + + resume: False + reset_lr: False + resume_suffix: "20220120-11H42M19S" + epoch_begin: 0 # 5000 # 2300 # 2600 + epoch_end: 1000 + + +LOSS: + names: ["all", "rec_exp", "rec_pos", "vol_exp", "vol_pos"] + lambda_rec: 1 + lambda_rec_smooth: 1 \ No newline at end of file diff --git a/experiments/audio2motion/infer_audio2motionW_20220111.yaml b/experiments/audio2motion/infer_audio2motionW_20220111.yaml new file mode 100644 index 0000000..aee1bb4 --- /dev/null +++ b/experiments/audio2motion/infer_audio2motionW_20220111.yaml @@ -0,0 +1,67 @@ +GPUS: '0' +WORKERS: 8 +OUTPUT_DIR: 'experiments/audio2motion' +DEBUG: False +verbose: False + +isTrain: False + + +MODEL: + name: 'audio2motion' + name_netG: "audio2motion" + + dim_motion: 53 # 68*2 + dim_speech: 27 + dim_hidden: 256 + + n_lookprevs_motion: 0 + n_lookprevs_speech: 5 + n_lookahead_speech: 5 + + n_layer_lstm: 3 + + pretrain: True + path_checkpoint: "experiments/audio2motion/train_audio2motionW_20220111/20220118-13H20M22S" + load_epoch: 400 + + +DATASET: + name: "motion_window" + root: './data/obama-deca-5-10-08' # obama-deca-3-5-08-mini + filter: 'savgol' + +TEST: + batch_size: 3 + +TRAIN: + lr: 0.0005 + 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: False + grad_clip_norm: False + # lr_policy: 'multistep' + # lr_milestones: [10, 100, 200] + lr_policy: 'plateau' + + + resume: False + reset_lr: False + resume_suffix: "20220118-13H20M22S" + epoch_begin: 80 # 5000 # 2300 # 2600 + epoch_end: 500 + + +LOSS: + names: ["all", "rec", "rec_l1", "rec_smooth", "rec_smooth_l1"] + lambda_rec: 1 + lambda_rec_smooth: 1 \ No newline at end of file diff --git a/experiments/audio2motion/infer_audio2motionW_20220118.yaml b/experiments/audio2motion/infer_audio2motionW_20220118.yaml new file mode 100644 index 0000000..a68b8d6 --- /dev/null +++ b/experiments/audio2motion/infer_audio2motionW_20220118.yaml @@ -0,0 +1,66 @@ +GPUS: '1' +WORKERS: 8 +OUTPUT_DIR: 'experiments/audio2motion' +DEBUG: False +verbose: False + +isTrain: False + +MODEL: + name: 'audio2motion' + name_netG: "audio2motion" + + dim_motion: 53 # 68*2 + dim_speech: 27 + dim_hidden: 256 + + n_lookprevs_motion: 0 + n_lookprevs_speech: 9 + n_lookahead_speech: 9 + + n_layer_lstm: 3 + + pretrain: True + path_checkpoint: "experiments/audio2motion/train_audio2motionW_20220118/20220118-17H18M27S" + load_epoch: 50 + + +DATASET: + name: "motion_window" + root: './data/obama-deca-5-10-08' # obama-deca-3-5-08-mini + filter: 'savgol' + +TEST: + batch_size: 3 + + +TRAIN: + lr: 0.0005 + batch_size: 128 + shuffle: True + + apply_testing: False + apply_validation: False + + optimizer: 'Adam' + momentum: 0.9 + beta1: 0.5 + beta2: 0.999 + weight_decay: 0.0001 + nesterov: False + grad_clip_norm: False + lr_policy: 'multistep' + lr_milestones: [10, 100, 200] + # lr_policy: 'plateau' + + + resume: False + reset_lr: True + resume_suffix: "20220118-17H18M27S" + epoch_begin: 120 # 5000 # 2300 # 2600 + epoch_end: 500 + +LOSS: + names: ["all", "rec", "rec_l1", "rec_smooth", "rec_smooth_l1"] + lambda_rec: 1 + lambda_rec_smooth: 1 \ No newline at end of file diff --git a/experiments/audio2motion/infer_audio2motionW_20220120.yaml b/experiments/audio2motion/infer_audio2motionW_20220120.yaml new file mode 100644 index 0000000..2947679 --- /dev/null +++ b/experiments/audio2motion/infer_audio2motionW_20220120.yaml @@ -0,0 +1,69 @@ +GPUS: '0' +WORKERS: 8 +OUTPUT_DIR: 'experiments/audio2motion' +DEBUG: False +verbose: False + +isTrain: False + +MODEL: + name: 'audio2motion' + name_netG: "audio2motion" + + dim_motion: 53 # 68*2 + dim_speech: 29 + dim_hidden: 256 + + n_lookprevs_motion: 0 + n_lookprevs_speech: 5 + n_lookahead_speech: 5 + + n_layer_lstm: 3 + + + pretrain: True + path_checkpoint: "experiments/audio2motion/train_audio2motionW_20220120/20220120-12H07M01S" + load_epoch: 300 + + + + +DATASET: + name: "motion_window" + root: './data/obama-dsv1-deca-5-10-08-mini8k' # obama-deca-3-5-08-mini + filter: 'savgol' + +TEST: + batch_size: 2 + +TRAIN: + lr: 0.0005 + batch_size: 16 + shuffle: True + + apply_testing: True + apply_validation: True + + optimizer: 'Adam' + momentum: 0.9 + beta1: 0.5 + beta2: 0.999 + weight_decay: 0.0001 + nesterov: False + grad_clip_norm: False + lr_policy: 'multistep' + lr_milestones: [10, 100, 200] + # lr_policy: 'plateau' + + + resume: False + reset_lr: True + resume_suffix: "20220120-12H07M01S" + epoch_begin: 0 # 5000 # 2300 # 2600 + epoch_end: 500 + + +LOSS: + names: ["all", "rec", "rec_l1", "rec_smooth", "rec_smooth_l1"] + lambda_rec: 1 + lambda_rec_smooth: 0.1 \ No newline at end of file diff --git a/experiments/audio2motion/train_audio2motion3_obama.yaml b/experiments/audio2motion/train_audio2motion3_obama.yaml new file mode 100644 index 0000000..30ca4ba --- /dev/null +++ b/experiments/audio2motion/train_audio2motion3_obama.yaml @@ -0,0 +1,85 @@ +GPUS: '0' +WORKERS: 8 +OUTPUT_DIR: 'experiments/audio2motion' +DEBUG: False +verbose: False + + +VISUAL: + use_HTML: False + use_visdom: True + vsdm_port: 9000 + vsdm_ncol: 4 + vsdm_env: "audio2motion-obama" + +FREQ: + batch_save: 0 + epoch_save: 100 + batch_display: 40 + epoch_display: 1 + batch_print: 40 + epoch_print: 1 + update_html: 100 + batch_test: 10000 + epoch_test: 10 + epoch_valid: 10 + + +MODEL: + name: 'audio2motion' + name_netG: "audio2motion2" + dropout: 0 + + dim_motion: 53 # 68*2 + dim_speech: 27 + dim_hidden: 256 + + n_lookprevs: 3 + n_lookahead: 3 + + n_layer_lstm: 3 + + pretrain: False + path_checkpoint: "experiments/MotionVAE/train-MoCVAE3-Obama/20210726-19H09M17S" + load_epoch: 10 + + +DATASET: + name: "motion" + root: './data/obama-deca-3-5-08' # obama-deca-3-5-08-mini + +TEST: + batch_size: 3 + +TRAIN: + lr: 0.001 + batch_size: 64 + shuffle: True + + apply_testing: True + apply_validation: True + + optimizer: 'Adam' + momentum: 0.9 + beta1: 0.5 + beta2: 0.999 + weight_decay: 0.0001 + nesterov: False + grad_clip_norm: False + # lr_policy: 'multistep' + # lr_milestones: [10, 100, 1000] + lr_policy: 'plateau' + + + + resume: False + reset_lr: 0.0001 + resume_suffix: "20220107-15H53M03S" + epoch_begin: 0 # 5000 # 2300 # 2600 + epoch_end: 2000 + + +LOSS: + names: ["all", "rec", "rec_l1", "rec_smooth", "rec_smooth_l1"] + lambda_rec: 1 + lambda_rec_smooth: 0.1 \ No newline at end of file diff --git a/experiments/audio2motion/train_audio2motionCL_20220119.yaml b/experiments/audio2motion/train_audio2motionCL_20220119.yaml new file mode 100644 index 0000000..25b1bd6 --- /dev/null +++ b/experiments/audio2motion/train_audio2motionCL_20220119.yaml @@ -0,0 +1,77 @@ +GPUS: '1' +WORKERS: 8 +OUTPUT_DIR: 'experiments/audio2motion' + +DEBUG: False +verbose: False + + +VISUAL: + use_HTML: False + use_visdom: True + vsdm_port: 9000 + vsdm_ncol: 4 + vsdm_env: "audio2motion-obama" + +FREQ: + epoch_save: 5 + + batch_print: 5 + epoch_print: 1 + + epoch_test: 5 + epoch_valid: 5 + + +MODEL: + name: 'audio2motion' + name_netG: "audio2motion_conv_lstm" + + dim_motion: 53 # 68*2 + dim_speech: 29 + dim_hidden: 256 + + pretrain: False + path_checkpoint: "experiments/MotionVAE/train-MoCVAE3-Obama/20210726-19H09M17S" + load_epoch: 0 + + +DATASET: + name: "motion" + root: './data/obama-ds-deca-5-10-08-mini' # obama-deca-3-5-08-mini + filter: 'savgol' + +TEST: + batch_size: 3 + +TRAIN: + lr: 0.0005 + batch_size: 16 + shuffle: True + + apply_testing: True + apply_validation: True + + optimizer: 'Adam' + momentum: 0.9 + beta1: 0.5 + beta2: 0.999 + weight_decay: 0.0001 + nesterov: False + grad_clip_norm: False + # lr_policy: 'multistep' + # lr_milestones: [10, 100, 200] + lr_policy: 'plateau' + + + resume: False + reset_lr: False + resume_suffix: "20220119-20H26M39S" + epoch_begin: 0 # 5000 # 2300 # 2600 + epoch_end: 500 + + +LOSS: + names: ["all", "rec", "rec_l1", "rec_smooth", "rec_smooth_l1"] + lambda_rec: 1 + lambda_rec_smooth: 0.1 \ No newline at end of file diff --git a/experiments/audio2motion/train_audio2motionC_20220119.yaml b/experiments/audio2motion/train_audio2motionC_20220119.yaml new file mode 100644 index 0000000..d4d5f1f --- /dev/null +++ b/experiments/audio2motion/train_audio2motionC_20220119.yaml @@ -0,0 +1,77 @@ +GPUS: '0' +WORKERS: 8 +OUTPUT_DIR: 'experiments/audio2motion' + +DEBUG: False +verbose: False + + +VISUAL: + use_HTML: False + use_visdom: True + vsdm_port: 9000 + vsdm_ncol: 4 + vsdm_env: "audio2motion-obama" + +FREQ: + epoch_save: 5 + + batch_print: 5 + epoch_print: 1 + + epoch_test: 5 + epoch_valid: 5 + + +MODEL: + name: 'audio2motion' + name_netG: "audio2motion_conv" + + dim_motion: 53 # 68*2 + dim_speech: 29 + dim_hidden: 256 + + pretrain: False + path_checkpoint: "experiments/MotionVAE/train-MoCVAE3-Obama/20210726-19H09M17S" + load_epoch: 0 + + +DATASET: + name: "motion" + root: './data/obama-ds-deca-5-10-08' # obama-deca-3-5-08-mini + filter: 'savgol' + +TEST: + batch_size: 3 + +TRAIN: + lr: 0.0005 + batch_size: 16 + shuffle: True + + apply_testing: True + apply_validation: True + + optimizer: 'Adam' + momentum: 0.9 + beta1: 0.5 + beta2: 0.999 + weight_decay: 0.0001 + nesterov: False + grad_clip_norm: False + # lr_policy: 'multistep' + # lr_milestones: [10, 100, 200] + lr_policy: 'plateau' + + + resume: True + reset_lr: True + resume_suffix: "20220119-20H26M39S" + epoch_begin: 100 # 5000 # 2300 # 2600 + epoch_end: 500 + + +LOSS: + names: ["all", "rec", "rec_l1", "rec_smooth", "rec_smooth_l1"] + lambda_rec: 1 + lambda_rec_smooth: 1 \ No newline at end of file diff --git a/experiments/audio2motion/train_audio2motionFH_CN_20220125.yaml b/experiments/audio2motion/train_audio2motionFH_CN_20220125.yaml new file mode 100644 index 0000000..2fbf3c2 --- /dev/null +++ b/experiments/audio2motion/train_audio2motionFH_CN_20220125.yaml @@ -0,0 +1,78 @@ +GPUS: '4' +WORKERS: 1 +OUTPUT_DIR: 'experiments/audio2motion' +DEBUG: False +verbose: False + +VISUAL: + use_HTML: False + use_visdom: True + vsdm_port: 9000 + vsdm_ncol: 4 + vsdm_env: "audio2motion-obama" + +FREQ: + epoch_save: 5 + epoch_valid: 5 + batch_print: 20 + epoch_test: 10 + +MODEL: + name: 'audio2motion_live' + name_netG: "audio2motion_head" + + dim_motion: 53 # 68*2 + dim_speech: 1024 + dim_hidden: 256 + + pretrain: False + path_checkpoint: "experiments/MotionVAE/train-MoCVAE3-Obama/20210726-19H09M17S" + load_epoch: 0 + + +DATASET: + fps: 50 + sr: 16000 + name: "motion_live" + root: './data/LuoXData-raw-deca-4h' # obama-deca-3-5-08-mini + filter: 'savgol' + speech_extractor: 'wav2vec' + + nwind_second_train: 5 + nwind_second_valid: 5 + nwind_second_test: 10 + + +TEST: + batch_size: 1 + +TRAIN: + lr: 0.0001 + batch_size: 32 + shuffle: True + + apply_testing: True + apply_validation: True + + optimizer: 'Adam' + momentum: 0.9 + beta1: 0.5 + beta2: 0.999 + weight_decay: 0.0001 + nesterov: False + grad_clip_norm: False + lr_policy: 'multistep' + lr_milestones: [10, 100, 200] + # lr_policy: 'plateau' + + resume: False + reset_lr: False + resume_suffix: "20220125-16H49M44S" + epoch_begin: 0 # 5000 # 2300 # 2600 + epoch_end: 500 + + +LOSS: + names: ["all", "rec", "rec_l1", "rec_smooth", "rec_smooth_l1"] + lambda_rec: 1 + lambda_rec_smooth: 0.1 \ No newline at end of file diff --git a/experiments/audio2motion/train_audio2motionFH_CN_20220126.yaml b/experiments/audio2motion/train_audio2motionFH_CN_20220126.yaml new file mode 100644 index 0000000..ea4b721 --- /dev/null +++ b/experiments/audio2motion/train_audio2motionFH_CN_20220126.yaml @@ -0,0 +1,78 @@ +GPUS: '2' +WORKERS: 1 +OUTPUT_DIR: 'experiments/audio2motion' +DEBUG: False +verbose: False + +VISUAL: + use_HTML: False + use_visdom: True + vsdm_port: 9000 + vsdm_ncol: 4 + vsdm_env: "audio2motion-obama" + +FREQ: + epoch_save: 5 + epoch_valid: 5 + batch_print: 20 + epoch_test: 10 + +MODEL: + name: 'audio2motion_live' + name_netG: "audio2motion_head" + + dim_motion: 53 # 68*2 + dim_speech: 512 + dim_hidden: 256 + + pretrain: False + path_checkpoint: "experiments/MotionVAE/train-MoCVAE3-Obama/20210726-19H09M17S" + load_epoch: 0 + + +DATASET: + fps: 50 + sr: 16000 + name: "motion_live" + root: './data/LuoXData-raw-deca-4h' # obama-deca-3-5-08-mini + filter: 'savgol' + speech_extractor: 'wav2vec' + + nwind_second_train: 5 + nwind_second_valid: 5 + nwind_second_test: 10 + + +TEST: + batch_size: 1 + +TRAIN: + lr: 0.0001 + batch_size: 32 + shuffle: True + + apply_testing: True + apply_validation: True + + optimizer: 'Adam' + momentum: 0.9 + beta1: 0.5 + beta2: 0.999 + weight_decay: 0.0001 + nesterov: False + grad_clip_norm: False + lr_policy: 'multistep' + lr_milestones: [10, 100, 200] + # lr_policy: 'plateau' + + resume: False + reset_lr: False + resume_suffix: "20220125-16H49M44S" + epoch_begin: 0 # 5000 # 2300 # 2600 + epoch_end: 500 + + +LOSS: + names: ["all", "rec", "rec_l1", "rec_smooth", "rec_smooth_l1"] + lambda_rec: 1 + lambda_rec_smooth: 0.1 \ No newline at end of file diff --git a/experiments/audio2motion/train_audio2motionF_CN_20220125.yaml b/experiments/audio2motion/train_audio2motionF_CN_20220125.yaml new file mode 100644 index 0000000..f7ab2ab --- /dev/null +++ b/experiments/audio2motion/train_audio2motionF_CN_20220125.yaml @@ -0,0 +1,85 @@ +GPUS: '0' +WORKERS: 8 +OUTPUT_DIR: 'experiments/audio2motion' +DEBUG: False +verbose: False + +VISUAL: + use_HTML: False + use_visdom: True + vsdm_port: 9000 + vsdm_ncol: 4 + vsdm_env: "audio2motion_live" + +FREQ: + epoch_save: 5 + epoch_valid: 1 + batch_print: 20 + + epoch_test: 5 + + +MODEL: + name: 'audio2motion_live' + name_netG: "audio2motion" + + dim_motion: 53 # 68*2 + dim_speech: 1024 + dim_hidden: 256 + + n_lookprevs_speech: 0 + n_lookahead_speech: 0 + + n_layer_lstm: 1 + + pretrain: False + path_checkpoint: "experiments/audio2motion/train_audio2motionF_CN_20220125/20220125-16H35M55S" + load_epoch: 300 + + +DATASET: + fps: 50 + sr: 16000 + name: "motion_live" + root: './data/LuoXData-raw-deca-4h' # obama-deca-3-5-08-mini + filter: 'savgol' + speech_extractor: 'wav2vec' + + nwind_second_train: 3 + nwind_second_valid: 3 + nwind_second_test: 10 + + +TEST: + batch_size: 2 + +TRAIN: + lr: 0.0001 + batch_size: 32 + shuffle: True + + apply_testing: True + apply_validation: True + + optimizer: 'Adam' + momentum: 0.9 + beta1: 0.5 + beta2: 0.999 + weight_decay: 0.0001 + nesterov: False + grad_clip_norm: False + lr_policy: 'multistep' + lr_milestones: [10, 100, 200, 500] + # lr_policy: 'plateau' + + resume: False + reset_lr: False + resume_suffix: "20220125-16H35M55S" + epoch_begin: 0 # 5000 # 2300 # 2600 + epoch_end: 1000 + + +LOSS: + names: ["all", "rec_exp", "rec_pos", "vol_exp", "vol_pos"] + lambda_rec: 1 + lambda_rec_smooth: 1 \ No newline at end of file diff --git a/experiments/audio2motion/train_audio2motionF_CN_20220126.yaml b/experiments/audio2motion/train_audio2motionF_CN_20220126.yaml new file mode 100644 index 0000000..80d900b --- /dev/null +++ b/experiments/audio2motion/train_audio2motionF_CN_20220126.yaml @@ -0,0 +1,84 @@ +GPUS: '5' +WORKERS: 8 +OUTPUT_DIR: 'experiments/audio2motion' +DEBUG: False +verbose: False + +VISUAL: + use_HTML: False + use_visdom: True + vsdm_port: 9000 + vsdm_ncol: 4 + vsdm_env: "audio2motion-obama" + +FREQ: + epoch_save: 5 + epoch_valid: 5 + batch_print: 20 + epoch_test: 5 + + +MODEL: + name: 'audio2motion_live' + name_netG: "audio2motion" + + dim_motion: 53 # 68*2 + dim_speech: 512 + dim_hidden: 256 + + n_lookprevs_speech: 0 + n_lookahead_speech: 0 + + n_layer_lstm: 3 + + pretrain: False + path_checkpoint: "experiments/MotionVAE/train-MoCVAE3-Obama/20210726-19H09M17S" + load_epoch: 0 + + +DATASET: + fps: 50 + sr: 16000 + name: "motion_live" + root: './data/LuoXData-raw-deca-4h' # obama-deca-3-5-08-mini + filter: 'savgol' + speech_extractor: 'wav2vec' + + nwind_second_train: 3 + nwind_second_valid: 3 + nwind_second_test: 10 + + +TEST: + batch_size: 2 + +TRAIN: + lr: 0.0001 + batch_size: 32 + shuffle: True + + apply_testing: True + apply_validation: True + + optimizer: 'Adam' + momentum: 0.9 + beta1: 0.5 + beta2: 0.999 + weight_decay: 0.0001 + nesterov: False + grad_clip_norm: False + lr_policy: 'multistep' + lr_milestones: [10, 100, 200] + # lr_policy: 'plateau' + + resume: False + reset_lr: True + resume_suffix: "20220125-16H35M55S" + epoch_begin: 65 # 5000 # 2300 # 2600 + epoch_end: 500 + + +LOSS: + names: ["all", "rec", "rec_l1", "rec_smooth", "rec_smooth_l1"] + lambda_rec: 1 + lambda_rec_smooth: 1 \ No newline at end of file diff --git a/experiments/audio2motion/train_audio2motionR_20220112.yaml b/experiments/audio2motion/train_audio2motionR_20220112.yaml new file mode 100644 index 0000000..f92d206 --- /dev/null +++ b/experiments/audio2motion/train_audio2motionR_20220112.yaml @@ -0,0 +1,86 @@ +GPUS: '2' +WORKERS: 8 +OUTPUT_DIR: 'experiments/audio2motion' +DEBUG: False +verbose: False + + +VISUAL: + use_HTML: False + use_visdom: True + vsdm_port: 9000 + vsdm_ncol: 4 + vsdm_env: "audio2motion-obama" + +FREQ: + batch_save: 0 + epoch_save: 5 + batch_display: 40 + epoch_display: 1 + + batch_print: 40 + epoch_print: 1 + update_html: 100 + batch_test: 10000 + + epoch_test: 5 + epoch_valid: 5 + + +MODEL: + name: 'audio2motionR' + name_netG: "audio2motion" + + dim_motion: 53 # 68*2 + dim_speech: 27 + dim_hidden: 256 + + n_lookprevs_motion: 2 + n_lookprevs_speech: 3 + n_lookahead_speech: 3 + + n_layer_lstm: 3 + + pretrain: False + path_checkpoint: "experiments/audio2motion/train_audio2motionR_20220112/20220112-16H45M29S" + load_epoch: 22 + + +DATASET: + name: "motion" + root: './data/obama-deca-5-10-08' # obama-deca-3-5-08-mini + filter: 'savgol' + +TEST: + batch_size: 3 + +TRAIN: + lr: 0.001 + batch_size: 64 + shuffle: True + + apply_testing: True + apply_validation: True + + optimizer: 'Adam' + momentum: 0.9 + beta1: 0.5 + beta2: 0.999 + weight_decay: 0.0001 + nesterov: False + grad_clip_norm: False + lr_policy: 'multistep' + lr_milestones: [10, 100, 200] + # lr_policy: 'plateau' + + resume: False + reset_lr: 0 + resume_suffix: "20220107-15H53M03S" + epoch_begin: 0 # 5000 # 2300 # 2600 + epoch_end: 500 + + +LOSS: + names: ["all", "rec", "rec_l1", "rec_smooth", "rec_smooth_l1"] + lambda_rec: 1 + lambda_rec_smooth: 0.1 \ No newline at end of file diff --git a/experiments/audio2motion/train_audio2motionV_20220120.yaml b/experiments/audio2motion/train_audio2motionV_20220120.yaml new file mode 100644 index 0000000..f06492d --- /dev/null +++ b/experiments/audio2motion/train_audio2motionV_20220120.yaml @@ -0,0 +1,76 @@ +GPUS: '0' +WORKERS: 8 +OUTPUT_DIR: 'experiments/audio2motion' + +DEBUG: False +verbose: False + + +VISUAL: + use_HTML: False + use_visdom: True + vsdm_port: 9000 + vsdm_ncol: 4 + vsdm_env: "audio2motion-obama" + +FREQ: + epoch_save: 5 + epoch_valid: 5 + batch_print: 10 + + epoch_test: 10 + + + +MODEL: + name: 'audio2motion' + name_netG: "audio2motion_voca" + + dim_motion: 53 # 68*2 + dim_speech: 29 + dim_hidden: 256 + + pretrain: False + path_checkpoint: "experiments/MotionVAE/train-MoCVAE3-Obama/20210726-19H09M17S" + load_epoch: 0 + + +DATASET: + name: "motion" + root: './data/obama-ds-deca-5-10-08-mini20' # obama-deca-3-5-08-mini + filter: 'savgol' + +TEST: + batch_size: 2 + +TRAIN: + lr: 0.0005 + batch_size: 16 + shuffle: True + + apply_testing: True + apply_validation: True + + optimizer: 'Adam' + momentum: 0.9 + beta1: 0.5 + beta2: 0.999 + weight_decay: 0.0001 + nesterov: False + grad_clip_norm: False + # lr_policy: 'multistep' + # lr_milestones: [10, 100, 200] + lr_policy: 'plateau' + + + resume: True + reset_lr: True + resume_suffix: "20220120-11H42M19S" + epoch_begin: 270 # 5000 # 2300 # 2600 + epoch_end: 500 + + +LOSS: + names: ["all", "rec", "rec_l1", "rec_smooth", "rec_smooth_l1"] + lambda_rec: 1 + lambda_rec_smooth: 1 \ No newline at end of file diff --git a/experiments/audio2motion/train_audio2motionV_20220120B.yaml b/experiments/audio2motion/train_audio2motionV_20220120B.yaml new file mode 100644 index 0000000..db43864 --- /dev/null +++ b/experiments/audio2motion/train_audio2motionV_20220120B.yaml @@ -0,0 +1,76 @@ +GPUS: '4' +WORKERS: 8 +OUTPUT_DIR: 'experiments/audio2motion' + +DEBUG: False +verbose: False + + +VISUAL: + use_HTML: False + use_visdom: True + vsdm_port: 9000 + vsdm_ncol: 4 + vsdm_env: "audio2motion-obama" + +FREQ: + epoch_save: 5 + epoch_valid: 5 + batch_print: 10 + + epoch_test: 10 + + + +MODEL: + name: 'audio2motion' + name_netG: "audio2motion_voca2" + + dim_motion: 53 # 68*2 + dim_speech: 29 + dim_hidden: 256 + + pretrain: False + path_checkpoint: "experiments/MotionVAE/train-MoCVAE3-Obama/20210726-19H09M17S" + load_epoch: 0 + + +DATASET: + name: "motion" + root: './data/obama-ds-deca-5-10-08-mini20' # obama-deca-3-5-08-mini + filter: 'savgol' + +TEST: + batch_size: 2 + +TRAIN: + lr: 0.0005 + batch_size: 32 + shuffle: True + + apply_testing: True + apply_validation: True + + optimizer: 'Adam' + momentum: 0.9 + beta1: 0.5 + beta2: 0.999 + weight_decay: 0.0001 + nesterov: False + grad_clip_norm: False + lr_policy: 'multistep' + lr_milestones: [10, 100, 200] + # lr_policy: 'plateau' + + + resume: False + reset_lr: False + resume_suffix: "20220120-11H42M19S" + epoch_begin: 0 # 5000 # 2300 # 2600 + epoch_end: 500 + + +LOSS: + names: ["all", "rec", "rec_l1", "rec_smooth", "rec_smooth_l1"] + lambda_rec: 1 + lambda_rec_smooth: 0.1 \ No newline at end of file diff --git a/experiments/audio2motion/train_audio2motionV_CN_20220123.yaml b/experiments/audio2motion/train_audio2motionV_CN_20220123.yaml new file mode 100644 index 0000000..e4b2df5 --- /dev/null +++ b/experiments/audio2motion/train_audio2motionV_CN_20220123.yaml @@ -0,0 +1,75 @@ +GPUS: '8' +WORKERS: 8 +OUTPUT_DIR: 'experiments/audio2motion' + +DEBUG: True +verbose: False + + +VISUAL: + use_HTML: False + use_visdom: True + vsdm_port: 9000 + vsdm_ncol: 4 + vsdm_env: "audio2motion-obama" + +FREQ: + epoch_save: 5 + epoch_valid: 5 + batch_print: 10 + epoch_test: 10 + + + +MODEL: + name: 'audio2motion' + name_netG: "audio2motion_voca2" + + dim_motion: 53 # 68*2 + dim_speech: 256 + dim_hidden: 256 + + pretrain: False + path_checkpoint: "experiments/MotionVAE/train-MoCVAE3-Obama/20210726-19H09M17S" + load_epoch: 0 + + +DATASET: + name: "motion" + root: './data/LuoXData-ds093-deca-3-10-07-mini10' # obama-deca-3-5-08-mini + filter: 'savgol' + +TEST: + batch_size: 2 + +TRAIN: + lr: 0.0005 + batch_size: 32 + shuffle: True + + apply_testing: True + apply_validation: True + + optimizer: 'Adam' + momentum: 0.9 + beta1: 0.5 + beta2: 0.999 + weight_decay: 0.0001 + nesterov: False + grad_clip_norm: False + lr_policy: 'multistep' + lr_milestones: [10, 100, 200] + # lr_policy: 'plateau' + + + resume: True + reset_lr: True + resume_suffix: "20220124-12H17M28S" + epoch_begin: 35 # 5000 # 2300 # 2600 + epoch_end: 500 + + +LOSS: + names: ["all", "rec", "rec_l1", "rec_smooth", "rec_smooth_l1"] + lambda_rec: 1 + lambda_rec_smooth: 0.1 \ No newline at end of file diff --git a/experiments/audio2motion/train_audio2motionV_CN_20220126.yaml b/experiments/audio2motion/train_audio2motionV_CN_20220126.yaml new file mode 100644 index 0000000..7cf2473 --- /dev/null +++ b/experiments/audio2motion/train_audio2motionV_CN_20220126.yaml @@ -0,0 +1,83 @@ +GPUS: '0' +WORKERS: 8 +OUTPUT_DIR: 'experiments/audio2motion' + +DEBUG: False +verbose: False + + +VISUAL: + use_HTML: False + use_visdom: True + vsdm_port: 9000 + vsdm_ncol: 4 + vsdm_env: "audio2motion-VOCA" + +FREQ: + epoch_save: 5 + epoch_valid: 1 + batch_print: 20 + + epoch_test: 5 + + + + +MODEL: + name: 'audio2motion_live2' + name_netG: "audio2motion_voca" + + dim_motion: 53 # 68*2 + dim_speech: 1024 + dim_hidden: 256 + + pretrain: False + path_checkpoint: "experiments/audio2motion/train_audio2motionV_CN_20220126/20220127-19H05M15S" + load_epoch: 20 + + +DATASET: + fps: 50 + sr: 16000 + name: "motion_live" + root: './data/LuoXData-raw-deca-6h' # obama-deca-3-5-08-mini + filter: 'savgol' + speech_extractor: 'wav2vec' + + nwind_second_train: 3 + nwind_second_valid: 3 + nwind_second_test: 10 + +TEST: + batch_size: 2 + +TRAIN: + lr: 0.0001 + batch_size: 32 + shuffle: True + + apply_testing: True + apply_validation: True + + optimizer: 'SGD' + momentum: 0.9 + beta1: 0.5 + beta2: 0.999 + weight_decay: 0.0001 + nesterov: False + grad_clip_norm: False + lr_policy: 'multistep' + lr_milestones: [10, 100, 200, 500] + # lr_policy: 'plateau' + + resume: False + reset_lr: False + resume_suffix: "20220127-19H05M15S" + epoch_begin: 0 # 5000 # 2300 # 2600 + epoch_end: 1000 + + +LOSS: + names: ["all", "rec_exp", "rec_pos", "vol_exp", "vol_pos"] + lambda_rec: 1 + lambda_rec_smooth: 1 \ No newline at end of file diff --git a/experiments/audio2motion/train_audio2motionV_CN_20220127.yaml b/experiments/audio2motion/train_audio2motionV_CN_20220127.yaml new file mode 100644 index 0000000..1bdb144 --- /dev/null +++ b/experiments/audio2motion/train_audio2motionV_CN_20220127.yaml @@ -0,0 +1,81 @@ +GPUS: '4' +WORKERS: 8 +OUTPUT_DIR: 'experiments/audio2motion' + +DEBUG: False +verbose: False + + +VISUAL: + use_HTML: False + use_visdom: True + vsdm_port: 9000 + vsdm_ncol: 4 + vsdm_env: "audio2motion-VOCA-big-sgd-pretrain" + +FREQ: + epoch_save: 5 + epoch_valid: 1 + batch_print: 20 + + epoch_test: 5 + + +MODEL: + name: 'audio2motion_live2' + name_netG: "audio2motion_voca3" + + dim_motion: 53 # 68*2 + dim_speech: 1024 + dim_hidden: 256 + + pretrain: False + path_checkpoint: "experiments/audio2motion/train_audio2motionV_CN_20220127/20220127-20H48M25S" + load_epoch: 0 + + +DATASET: + fps: 50 + sr: 16000 + name: "motion_live" + root: './data/LuoXData-raw-deca-6h' # obama-deca-3-5-08-mini + filter: 'savgol' + speech_extractor: 'wav2vec' + + nwind_second_train: 3 + nwind_second_valid: 3 + nwind_second_test: 10 + +TEST: + batch_size: 2 + +TRAIN: + lr: 0.0005 + batch_size: 32 + shuffle: True + + apply_testing: True + apply_validation: True + + optimizer: 'SGD' + momentum: 0.9 + beta1: 0.5 + beta2: 0.999 + weight_decay: 0.0001 + nesterov: True + grad_clip_norm: False + # lr_policy: 'multistep' + # lr_milestones: [10, 50, 500] + lr_policy: 'plateau' + + resume: True + reset_lr: False + resume_suffix: "20220128-10H10M10S" + epoch_begin: 50 # 5000 # 2300 # 2600 + epoch_end: 1000 + + +LOSS: + names: ["all", "rec_exp", "rec_pos", "vol_exp", "vol_pos"] + lambda_rec: 1 + lambda_rec_smooth: 1 \ No newline at end of file diff --git a/experiments/audio2motion/train_audio2motionV_CN_20220207.yaml b/experiments/audio2motion/train_audio2motionV_CN_20220207.yaml new file mode 100644 index 0000000..53cb457 --- /dev/null +++ b/experiments/audio2motion/train_audio2motionV_CN_20220207.yaml @@ -0,0 +1,81 @@ +GPUS: '7' +WORKERS: 8 +OUTPUT_DIR: 'experiments/audio2motion' + +DEBUG: False +verbose: False + + +VISUAL: + use_HTML: False + use_visdom: True + vsdm_port: 9000 + vsdm_ncol: 4 + vsdm_env: "audio2motion-VOCA-bigger" + +FREQ: + epoch_save: 5 + epoch_valid: 1 + batch_print: 20 + + epoch_test: 5 + + +MODEL: + name: 'audio2motion_live2' + name_netG: "audio2motion_voca4" + + dim_motion: 53 # 68*2 + dim_speech: 1024 + dim_hidden: 256 + + pretrain: False + path_checkpoint: "experiments/audio2motion/train_audio2motionV_CN_20220127/20220127-20H48M25S" + load_epoch: 0 + + +DATASET: + fps: 50 + sr: 16000 + name: "motion_live" + root: './data/LuoXData-raw-deca-8h' # obama-deca-3-5-08-mini + filter: 'savgol' + speech_extractor: 'wav2vec' + + nwind_second_train: 3 + nwind_second_valid: 3 + nwind_second_test: 10 + +TEST: + batch_size: 2 + +TRAIN: + lr: 0.0005 + batch_size: 32 + 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 + grad_clip_norm: False + # lr_policy: 'multistep' + # lr_milestones: [10, 50, 500] + lr_policy: 'plateau' + + resume: False + reset_lr: False + resume_suffix: "20220128-10H10M10S" + epoch_begin: 0 # 5000 # 2300 # 2600 + epoch_end: 1000 + + +LOSS: + names: ["all", "rec_exp", "rec_pos", "vol_exp", "vol_pos"] + lambda_rec: 1 + lambda_rec_smooth: 1 \ No newline at end of file diff --git a/experiments/audio2motion/train_audio2motionV_CN_20220207_2.yaml b/experiments/audio2motion/train_audio2motionV_CN_20220207_2.yaml new file mode 100644 index 0000000..e6db8c7 --- /dev/null +++ b/experiments/audio2motion/train_audio2motionV_CN_20220207_2.yaml @@ -0,0 +1,83 @@ +GPUS: '8' +WORKERS: 8 +OUTPUT_DIR: 'experiments/audio2motion' + +DEBUG: False +verbose: False + + +VISUAL: + use_HTML: False + use_visdom: True + vsdm_port: 9000 + vsdm_ncol: 4 + vsdm_env: "audio2motion-VOCA-bigger-test" + +FREQ: + epoch_save: 5 + epoch_valid: 1 + batch_print: 20 + + epoch_test: 5 + + +MODEL: + name: 'audio2motion_live2' + name_netG: "audio2motion_voca33" + + dim_motion: 53 # 68*2 + dim_speech: 1024 + dim_hidden: 256 + + pretrain: True + path_checkpoint: "experiments/audio2motion/train_audio2motionV_CN_20220207_2/20220207-12H47M47S" + load_epoch: 45 + + +DATASET: + fps: 50 + sr: 16000 + name: "motion_live" + root: './data/LuoXData-raw-deca-8h' # obama-deca-3-5-08-mini + filter: 'savgol' + speech_extractor: 'wav2vec' + + nwind_second_train: 3 + nwind_second_valid: 3 + nwind_second_test: 10 + +TEST: + batch_size: 2 + +TRAIN: + lr: 0.00005 + batch_size: 32 + 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 + grad_clip_norm: False + # lr_policy: 'multistep' + # lr_milestones: [10, 50, 500] + lr_policy: 'plateau' + + resume: False + reset_lr: False + resume_suffix: "20220128-10H10M10S" + epoch_begin: 0 # 5000 # 2300 # 2600 + epoch_end: 1000 + + +LOSS: + names: ["all", "rec_exp", "rec_pos", "vol_exp", "vol_pos"] + lambda_rec_exp: 10 + lambda_rec_pos: 1 + lambda_vol_exp: 1 + lambda_vol_pos: 10 \ No newline at end of file diff --git a/experiments/audio2motion/train_audio2motionW_20220111.yaml b/experiments/audio2motion/train_audio2motionW_20220111.yaml new file mode 100644 index 0000000..d903817 --- /dev/null +++ b/experiments/audio2motion/train_audio2motionW_20220111.yaml @@ -0,0 +1,87 @@ +GPUS: '0' +WORKERS: 8 +OUTPUT_DIR: 'experiments/audio2motion' +DEBUG: False +verbose: False + + +VISUAL: + use_HTML: False + use_visdom: True + vsdm_port: 9000 + vsdm_ncol: 4 + vsdm_env: "audio2motion-obama" + +FREQ: + batch_save: 0 + epoch_save: 5 + + batch_display: 40 + epoch_display: 1 + batch_print: 40 + epoch_print: 1 + update_html: 100 + batch_test: 10000 + + epoch_test: 5 + epoch_valid: 5 + + +MODEL: + name: 'audio2motion' + name_netG: "audio2motion" + + dim_motion: 53 # 68*2 + dim_speech: 27 + dim_hidden: 256 + + n_lookprevs_motion: 0 + n_lookprevs_speech: 5 + n_lookahead_speech: 5 + + n_layer_lstm: 3 + + pretrain: False + path_checkpoint: "experiments/MotionVAE/train-MoCVAE3-Obama/20210726-19H09M17S" + load_epoch: 0 + + +DATASET: + name: "motion_window" + root: './data/obama-deca-5-10-08' # obama-deca-3-5-08-mini + filter: 'savgol' + +TEST: + batch_size: 3 + +TRAIN: + lr: 0.0005 + 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: False + grad_clip_norm: False + # lr_policy: 'multistep' + # lr_milestones: [10, 100, 200] + lr_policy: 'plateau' + + + resume: True + reset_lr: True + resume_suffix: "20220118-13H20M22S" + epoch_begin: 80 # 5000 # 2300 # 2600 + epoch_end: 500 + + +LOSS: + names: ["all", "rec", "rec_l1", "rec_smooth", "rec_smooth_l1"] + lambda_rec: 1 + lambda_rec_smooth: 1 \ No newline at end of file diff --git a/experiments/audio2motion/train_audio2motionW_20220118.yaml b/experiments/audio2motion/train_audio2motionW_20220118.yaml new file mode 100644 index 0000000..8b73803 --- /dev/null +++ b/experiments/audio2motion/train_audio2motionW_20220118.yaml @@ -0,0 +1,87 @@ +GPUS: '1' +WORKERS: 8 +OUTPUT_DIR: 'experiments/audio2motion' +DEBUG: False +verbose: False + + +VISUAL: + use_HTML: False + use_visdom: True + vsdm_port: 9000 + vsdm_ncol: 4 + vsdm_env: "audio2motion-obama" + +FREQ: + batch_save: 0 + epoch_save: 5 + + batch_display: 40 + epoch_display: 1 + batch_print: 40 + epoch_print: 1 + update_html: 100 + batch_test: 10000 + + epoch_test: 5 + epoch_valid: 5 + + +MODEL: + name: 'audio2motion' + name_netG: "audio2motion" + + dim_motion: 53 # 68*2 + dim_speech: 27 + dim_hidden: 256 + + n_lookprevs_motion: 0 + n_lookprevs_speech: 9 + n_lookahead_speech: 9 + + n_layer_lstm: 3 + + pretrain: False + path_checkpoint: "experiments/MotionVAE/train-MoCVAE3-Obama/20210726-19H09M17S" + load_epoch: 0 + + +DATASET: + name: "motion_window" + root: './data/obama-deca-5-10-08' # obama-deca-3-5-08-mini + filter: 'savgol' + +TEST: + batch_size: 3 + +TRAIN: + lr: 0.0005 + 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: False + grad_clip_norm: False + lr_policy: 'multistep' + lr_milestones: [10, 100, 200] + # lr_policy: 'plateau' + + + resume: True + reset_lr: True + resume_suffix: "20220118-17H18M27S" + epoch_begin: 120 # 5000 # 2300 # 2600 + epoch_end: 500 + + +LOSS: + names: ["all", "rec", "rec_l1", "rec_smooth", "rec_smooth_l1"] + lambda_rec: 1 + lambda_rec_smooth: 1 \ No newline at end of file diff --git a/experiments/audio2motion/train_audio2motionW_20220120.yaml b/experiments/audio2motion/train_audio2motionW_20220120.yaml new file mode 100644 index 0000000..294e816 --- /dev/null +++ b/experiments/audio2motion/train_audio2motionW_20220120.yaml @@ -0,0 +1,87 @@ +GPUS: '0' +WORKERS: 8 +OUTPUT_DIR: 'experiments/audio2motion' +DEBUG: False +verbose: False + + +VISUAL: + use_HTML: False + use_visdom: True + vsdm_port: 9000 + vsdm_ncol: 4 + vsdm_env: "audio2motion-obama" + +FREQ: + batch_save: 0 + epoch_save: 5 + + batch_display: 40 + epoch_display: 1 + batch_print: 40 + epoch_print: 1 + update_html: 100 + batch_test: 10000 + + epoch_test: 5 + epoch_valid: 5 + + +MODEL: + name: 'audio2motion' + name_netG: "audio2motion" + + dim_motion: 53 # 68*2 + dim_speech: 29 + dim_hidden: 256 + + n_lookprevs_motion: 0 + n_lookprevs_speech: 5 + n_lookahead_speech: 5 + + n_layer_lstm: 3 + + pretrain: False + path_checkpoint: "experiments/MotionVAE/train-MoCVAE3-Obama/20210726-19H09M17S" + load_epoch: 0 + + +DATASET: + name: "motion_window" + root: './data/obama-dsv1-deca-5-10-08-mini8k' # obama-deca-3-5-08-mini + filter: 'savgol' + +TEST: + batch_size: 2 + +TRAIN: + lr: 0.0005 + batch_size: 16 + shuffle: True + + apply_testing: True + apply_validation: True + + optimizer: 'Adam' + momentum: 0.9 + beta1: 0.5 + beta2: 0.999 + weight_decay: 0.0001 + nesterov: False + grad_clip_norm: False + lr_policy: 'multistep' + lr_milestones: [10, 100, 200] + # lr_policy: 'plateau' + + + resume: True + reset_lr: True + resume_suffix: "20220120-12H07M01S" + epoch_begin: 200 # 5000 # 2300 # 2600 + epoch_end: 500 + + +LOSS: + names: ["all", "rec", "rec_l1", "rec_smooth", "rec_smooth_l1"] + lambda_rec: 1 + lambda_rec_smooth: 0.1 \ No newline at end of file diff --git a/experiments/audio2motion/train_audio2motionW_CN_20220123.yaml b/experiments/audio2motion/train_audio2motionW_CN_20220123.yaml new file mode 100644 index 0000000..46853b6 --- /dev/null +++ b/experiments/audio2motion/train_audio2motionW_CN_20220123.yaml @@ -0,0 +1,76 @@ +GPUS: '0' +WORKERS: 8 +OUTPUT_DIR: 'experiments/audio2motion' +DEBUG: False +verbose: False + +VISUAL: + use_HTML: False + use_visdom: True + vsdm_port: 9000 + vsdm_ncol: 4 + vsdm_env: "audio2motion-obama" + +FREQ: + epoch_save: 5 + epoch_valid: 5 + batch_print: 20 + epoch_test: 10 + +MODEL: + name: 'audio2motion' + name_netG: "audio2motion" + + dim_motion: 53 # 68*2 + dim_speech: 256 + dim_hidden: 256 + + n_lookprevs_speech: 3 + n_lookahead_speech: 3 + + n_layer_lstm: 2 + + pretrain: False + path_checkpoint: "experiments/MotionVAE/train-MoCVAE3-Obama/20210726-19H09M17S" + load_epoch: 0 + + +DATASET: + fps: 50 + name: "motion_window" + root: './data/LuoXData-ds093-deca-3-10-07-mini10' # obama-deca-3-5-08-mini + filter: 'savgol' + +TEST: + batch_size: 1 + +TRAIN: + lr: 0.0001 + batch_size: 64 + shuffle: True + + apply_testing: True + apply_validation: True + + optimizer: 'Adam' + momentum: 0.9 + beta1: 0.5 + beta2: 0.999 + weight_decay: 0.0001 + nesterov: False + grad_clip_norm: False + lr_policy: 'multistep' + lr_milestones: [10, 100, 200] + # lr_policy: 'plateau' + + resume: False + reset_lr: False + resume_suffix: "20220124-12H17M28S" + epoch_begin: 0 # 5000 # 2300 # 2600 + epoch_end: 500 + + +LOSS: + names: ["all", "rec", "rec_l1", "rec_smooth", "rec_smooth_l1"] + lambda_rec: 1 + lambda_rec_smooth: 0.1 \ No newline at end of file diff --git a/experiments/audio2motion/train_audio2motionW_CN_20220125.yaml b/experiments/audio2motion/train_audio2motionW_CN_20220125.yaml new file mode 100644 index 0000000..7caa304 --- /dev/null +++ b/experiments/audio2motion/train_audio2motionW_CN_20220125.yaml @@ -0,0 +1,76 @@ +GPUS: '0' +WORKERS: 8 +OUTPUT_DIR: 'experiments/audio2motion' +DEBUG: False +verbose: False + +VISUAL: + use_HTML: False + use_visdom: True + vsdm_port: 9000 + vsdm_ncol: 4 + vsdm_env: "audio2motion-obama" + +FREQ: + epoch_save: 5 + epoch_valid: 5 + batch_print: 20 + epoch_test: 10 + +MODEL: + name: 'audio2motion' + name_netG: "audio2motion" + + dim_motion: 53 # 68*2 + dim_speech: 27 + dim_hidden: 256 + + n_lookprevs_speech: 7 + n_lookahead_speech: 7 + + n_layer_lstm: 3 + + pretrain: False + path_checkpoint: "experiments/MotionVAE/train-MoCVAE3-Obama/20210726-19H09M17S" + load_epoch: 0 + + +DATASET: + fps: 50 + name: "motion_window" + root: './data/LuoXData-deca-5-10-07-mini' # obama-deca-3-5-08-mini + filter: 'savgol' + +TEST: + batch_size: 2 + +TRAIN: + lr: 0.0001 + batch_size: 64 + shuffle: True + + apply_testing: True + apply_validation: True + + optimizer: 'Adam' + momentum: 0.9 + beta1: 0.5 + beta2: 0.999 + weight_decay: 0.0001 + nesterov: False + grad_clip_norm: False + lr_policy: 'multistep' + lr_milestones: [10, 100, 200] + # lr_policy: 'plateau' + + resume: True + reset_lr: True + resume_suffix: "20220125-12H02M01S" + epoch_begin: 160 # 5000 # 2300 # 2600 + epoch_end: 500 + + +LOSS: + names: ["all", "rec", "rec_l1", "rec_smooth", "rec_smooth_l1"] + lambda_rec: 1 + lambda_rec_smooth: 0.1 \ No newline at end of file diff --git a/experiments/audio2motion/train_audio2motion_obama.yaml b/experiments/audio2motion/train_audio2motion_obama.yaml new file mode 100644 index 0000000..7079969 --- /dev/null +++ b/experiments/audio2motion/train_audio2motion_obama.yaml @@ -0,0 +1,84 @@ +GPUS: '4' +WORKERS: 8 +OUTPUT_DIR: 'experiments/audio2motion' +DEBUG: False +verbose: False + + +VISUAL: + use_HTML: False + use_visdom: True + vsdm_port: 9000 + vsdm_ncol: 4 + vsdm_env: "audio2motion-obama" + +FREQ: + batch_save: 0 + epoch_save: 100 + batch_display: 40 + epoch_display: 1 + batch_print: 40 + epoch_print: 1 + update_html: 100 + batch_test: 10000 + epoch_test: 10 + epoch_valid: 10 + + +MODEL: + name: 'audio2motion' + name_netG: "audio2motion" + dropout: 0 + + dim_motion: 53 # 68*2 + dim_speech: 27 + dim_hidden: 256 + + n_lookprevs: 0 + n_lookahead: 0 + n_layer_lstm: 3 + + pretrain: False + path_checkpoint: "experiments/MotionVAE/train-MoCVAE3-Obama/20210726-19H09M17S" + load_epoch: 10 + + +DATASET: + name: "obama_motion" + root: './data/obama-deca-3-5-08' # obama-deca-3-5-08-mini + +TEST: + batch_size: 3 + +TRAIN: + lr: 0.001 + batch_size: 64 + shuffle: True + + apply_testing: True + apply_validation: True + + optimizer: 'Adam' + momentum: 0.9 + beta1: 0.5 + beta2: 0.999 + weight_decay: 0.0001 + nesterov: False + grad_clip_norm: False + # lr_policy: 'multistep' + # lr_milestones: [10, 100, 1000] + lr_policy: 'plateau' + + + + resume: True + reset_lr: 0.0001 + resume_suffix: "20220107-15H53M03S" + epoch_begin: 300 # 5000 # 2300 # 2600 + epoch_end: 2000 + + +LOSS: + names: ["all", "rec", "rec_l1", "rec_smooth", "rec_smooth_l1"] + lambda_rec: 1 + lambda_rec_smooth: 0.1 \ No newline at end of file diff --git a/infer_one_live.py b/infer_one_live.py new file mode 100644 index 0000000..5d5251c --- /dev/null +++ b/infer_one_live.py @@ -0,0 +1,168 @@ +import sys +import pprint +import argparse +import numpy as np +from pathlib import Path +import torch.nn.functional as F + +import torch +import torchaudio +import librosa + +from src.models import create_model, calculate_model_params +from src.config import config as opt +from src.config import update_config + +from common.vis.visualizer import Visualizer +from common.logger import Logger +from common.animation import save_images_with_audio + +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("/ssdata1/lsen/CODE/Audio2Motion/data/test/test_pangzi_zh_cut15.wav") + # 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(path_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) + audio_raw = resampler(audio_raw).squeeze().numpy() + print(f"audio_raw shape = {audio_raw.shape}, sr = {16000}, duration = {(len(audio_raw)/16000)}") + + # clip 15s + # if len(audio_raw) > 16000 * 5: + # audio_raw = audio_raw[:16000*5] + + # audio_raw_numpy = audio_raw.numpy() + + # load wav2Vec model + print("load Wav2Vec2Model ...") + MODEL_ID = "jonatasgrosman/wav2vec2-large-xlsr-53-chinese-zh-cn" + processor = Wav2Vec2FeatureExtractor.from_pretrained(MODEL_ID) + extractor = Wav2Vec2Model.from_pretrained(MODEL_ID).to(device) + + # padding half frame length for bed and end + npad = int(0.5 * 16000* ( 1 / 50) + 0.5) + audio_raw = np.pad(audio_raw, pad_width=((npad, npad)), mode="edge") + print(f"after padding audio_raw = {audio_raw.shape}, dtype={audio_raw.dtype}") + + inputs = processor(audio_raw, 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 + # model.remove_weightnorm() + + model.infer(cond, path_audio, \ + f"{path_audio.stem}_infer_{Path(opt.MODEL.path_checkpoint).stem}_epoch_{opt.MODEL.load_epoch:03d}") + + # # # Add for WaveFlow + # # # model.netG.module = model.netG.module.remove_weightnorm(model.netG.module) + # # # for i, batch_input in enumerate(test_loader): + + # # motion = batch_input['data'].float().to(device) # (nbatch, nsteps=60, dim_motion=136) + # # speech = batch_input['cond'].float().to(device) # (nbatch, nsteps=173, dim_condit=80) + # # motion = motion.permute(0, 2, 1) # (nbatch, 136, 60) + # # speech = speech.permute(0, 2, 1) # (nbatch, 80, 173) + # # B = motion.size(0) + # # motion_gt = motion.permute(0,2,1)[0:1, :, :] + + # # # generate k samples + # # motion_pt = [] + # # for j in range(3): + # # data_pt = model.testing(batch_input, cur_epoch=opt.MODEL.load_epoch, save_animation=False) # B x nsteps x 136 + # # data_pt = data_pt[0:1, :, :] + # # motion_pt.append(data_pt) + + # # # save + # # print("data_pt shape = ", data_pt.shape) + # # np.save(f"data/ldmk_pdt_align30_{j}.npy", data_pt.cpu().numpy()[0]) + + + # # motion_pt = torch.cat(motion_pt, dim=0) # 8 x nsteps x 136 + # # nsteps = min(motion_gt.size(1), motion_pt.size(1)) + # # total_motion = torch.cat([motion_gt[:, :nsteps, :], motion_pt[:, :nsteps, :]], dim=0) + # # print(f"total motion shape = {total_motion.shape}") + + + + + # # path_save=Path(opt.OUTPUT_DIR).joinpath(f'sampled_{opt.MODEL.load_epoch:05d}.mp4') + # # save_animation_grid(total_motion, path_save=path_save, path_audio=path_audio, ncol=2, w=256, h=256, dpi=100) + # # # animation_with_audio(path_save, path_audio) + + + + # # print(f"SVAE -> {opt.OUTPUT_DIR}") + # # # break + + + # # # # infer + # # # epoch_beg = 400 + # # # epoch_end = 580 + # # # for epoch in range(epoch_end, epoch_beg, -50): + # # # print(f"Testing the epoch{epoch}/{epoch_end}") + + # # # opt.MODEL.load_epoch = epoch # set load epoch + # # # model.setup(opt) # load model + + # # # for i, ibatch_data in enumerate(test_loader): + # # # model.testing(ibatch_data, cur_epoch=epoch, cur_batch=i) + # # # model.testing(ibatch_data, cur_epoch=epoch, cur_batch=(i*100+1)) + # # # model.testing(ibatch_data, cur_epoch=epoch, cur_batch=(i*1000+1)) + # # # break + + + diff --git a/scripts/LuoXData/run-01-prepare-data.py b/scripts/LuoXData/run-01-prepare-data.py new file mode 100755 index 0000000..d5bfb5e --- /dev/null +++ b/scripts/LuoXData/run-01-prepare-data.py @@ -0,0 +1,100 @@ +from pathlib import Path +import json +import moviepy +from moviepy.editor import VideoFileClip, AudioFileClip + + +if __name__ == '__main__': + + path_root = Path("/yrfs/lsen/DATA/LuoXData") + + vpath_videos = sorted(path_root.glob("raw/*.mp4"), reverse=False) + print(f"Have {len(vpath_videos)} dir files") + + # for each video + for i, ipath_item in enumerate(vpath_videos): + iname = ipath_item.stem + print(f"processing {i}/{len(vpath_videos)} -> {ipath_item} ... ") + + # if i < 40: continue + # if iname not in IDs: continue + + # data path + ipath_data = path_root.joinpath("processing2", ipath_item.stem) + + ipath_frame = ipath_data.joinpath("frames") + ipath_video = ipath_data.joinpath("video") + ipath_audio = ipath_data.joinpath("audio") + ipath_infor = ipath_data.joinpath("video/info.json") + + ipath_frame.mkdir(parents=True, exist_ok=True) + ipath_video.mkdir(parents=True, exist_ok=True) + ipath_audio.mkdir(parents=True, exist_ok=True) + + # # load video info + # if ipath_infor.exists(): + + # with open(str(ipath_infor), "r") as f: + # info = json.load(f) + + # nframe_info = info['nframes'] + + + + # 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)}") + + if video.audio is None: + print("\nERROR: audio info is None") + continue + + # Trim + video_sub = video.subclip(t_start=20.0, t_end=int(video.duration)-20.0) + print(f"after cut video duration = {video_sub.duration}, fps = {video_sub.fps}, (start, end)=({video_sub.start},{video_sub.end}), nframes={int(video_sub.duration * video_sub.fps)}") + nframes = int(video_sub.duration * video_sub.fps) + + # check frames + nframe_real = len(list(ipath_frame.glob("*.jpg"))) + if nframe_real == nframes: + print(f"\n Skip: have already done!") + continue + + # check fps + if int(video_sub.fps) != 50: + print(f"\n Skip: fps != 50 realy fps={video_sub.fps}") + continue + + # save video feature + info = {"nframes": nframes, + "fps":video_sub.fps, + "width": video_sub.w, + "height": video_sub.h} + + with open(str(ipath_infor), 'w+') as f: + json.dump(info, f) + print(info) + print(f"save video info in -> {ipath_infor}\n") + + + # # save sub video + # ipath_video_sub = ipath_video.joinpath("video_trim.mp4") + # video_sub.write_videofile(str(ipath_video_sub), fps=50, audio=True) + # print(f"save video > {ipath_video_sub}") + + # get audio + audio_sub = video_sub.audio + if audio_sub is None: + print("\nERROR: audio info is None") + + print(f"audio_sub duration = {audio_sub.duration}, fps = {audio_sub.fps}, (start, end)=({audio_sub.start},{audio_sub.end}), nframes={int(audio_sub.duration * audio_sub.fps)}") + + # save audio_sub + ipath_audio_sub = ipath_audio.joinpath("audio_trim.wav") + audio_sub.write_audiofile(str(ipath_audio_sub), fps=audio_sub.fps) + print(f"save audio > {ipath_audio_sub}") + + # save trim video + print(f"write_images_sequence...") + ipath_format = str(ipath_frame) + "/frame-%06d.jpg" + video_sub.write_images_sequence(ipath_format, fps=50) diff --git a/scripts/LuoXData/run-10-speech-features-mel-align.py b/scripts/LuoXData/run-10-speech-features-mel-align.py new file mode 100644 index 0000000..2714ced --- /dev/null +++ b/scripts/LuoXData/run-10-speech-features-mel-align.py @@ -0,0 +1,73 @@ +import os +import sys +import json +import librosa +import numpy as np +from pathlib2 import Path + +if __name__ == "__main__": + + path_data = Path('/yrfs/lsen/DATA/LuoXData/processing2') # '../data/trinity/source' + + v_dir_videos = sorted(path_data.glob("*"), reverse=False) + print(f"Have {len(v_dir_videos)} dir files, \n {v_dir_videos[:3]}") + + # for each speaker + for i, ipath_data in enumerate(v_dir_videos): + vid = ipath_data.stem + + # if i >= 50: continue + print(f"\n processing the {i}-th video {vid} ... ") + + ipath_info = ipath_data.joinpath("video/info.json") + ipath_audio = ipath_data.joinpath("audio/audio_trim.wav") + ipath_save_feat = ipath_data.joinpath("audio/feat_mel_trim.npy") + + # check + if not ipath_audio.exists(): + print(f"NOT existing {ipath_audio}") + continue + + if ipath_save_feat.exists(): + print(f"have existing {ipath_save_feat}") + continue + + # load video info + with open(str(ipath_info), "r") as f: + info = json.load(f) + fps = info["fps"] + nframes = info["nframes"] + print(f"info={info}") + assert fps == 50, "fps should be 50" + + + # load trim audio + data, sr = librosa.load(str(ipath_audio), sr= int(0.5 + fps * ( 16000 / fps ))) # 16000 = fps * 640 让这个sr是fps的整数, + hop_len = int(sr / fps) + n_fft = int(sr * 0.13) # default 2048 + print(f"data={data.shape}, sr={sr}, fps={fps}, hop_len={sr/fps}, frames = {(len(data) / sr) * fps}, minmax = {np.min(data)},{np.max(data)}") + + # melspectrogram + mel = librosa.feature.melspectrogram(y=data, sr=sr, + n_fft=n_fft, # FFT窗口的长度 + hop_length=hop_len, # 帧移 + win_length=n_fft, # 窗口长度,默认=n_fft + window="hann", # 加hanming窗 + n_mels=27, # 滤波器组 + fmin=0.0, fmax=8000) + mel = np.log(mel+1).T + print(f"mel = {mel.shape}, frames = {(len(data) / sr) * fps}, (min,max)=({np.min(mel), np.max(mel)}") + + # align to video + if mel.shape[0] < nframes: + print(f"\n skip, mel shape ={mel.shape}, frames={(len(data) / sr) * fps}") + else: + mel_align = mel[:nframes, :] + + # save + np.save(ipath_save_feat, mel_align) + + + + + diff --git a/scripts/LuoXData/run-20-deca-reconstruction.py b/scripts/LuoXData/run-20-deca-reconstruction.py new file mode 100644 index 0000000..8d4422c --- /dev/null +++ b/scripts/LuoXData/run-20-deca-reconstruction.py @@ -0,0 +1,141 @@ +import os, sys +import numpy as np +import cv2 +from time import time +import argparse +import json +from pathlib import Path +from torch.utils.data import DataLoader + +sys.path.insert(0, '/ssdata1/lsen/CODE/DECA_old') +from decalib.deca import DECA +from decalib.datasets.datasets2 import ObamaData +from decalib.utils import util +from decalib.utils.config import cfg as deca_cfg + + +def main(args): + device = args.device + + # run DECA + deca_cfg.model.use_tex = args.useTex + deca = DECA(config = deca_cfg, device=device) + + path_data = Path("/yrfs/lsen/DATA/LuoXData/processing2") + v_dir_videos = sorted(path_data.glob("*"), reverse=False) + print(f"Have {len(v_dir_videos)} dir files") + + # for each video + for ipath_data in v_dir_videos[17:]: + ivideo_name = ipath_data.stem + print("\nprocessing ...", ivideo_name) + + ipath_infor = ipath_data.joinpath("video/info.json") + ipath_frame = ipath_data.joinpath("frames") + + ipath_kpt2d = ipath_data.joinpath("DECA_kpt2d") + ipath_kpt3d = ipath_data.joinpath("DECA_kpt3d") + ipath_coeff = ipath_data.joinpath("DECA_coeff") + # ipath_vis = ipath_data.joinpath("DECA_vis2") + + ipath_kpt2d.mkdir(parents=True, exist_ok=True) + ipath_kpt3d.mkdir(parents=True, exist_ok=True) + ipath_coeff.mkdir(parents=True, exist_ok=True) + # ipath_vis.mkdir(parents=True, exist_ok=True) + + # load video info + if not ipath_infor.exists(): + print(f"\n ERROR: info.json not existing {ipath_infor}") + continue + + with open(str(ipath_infor), "r") as f: + info = json.load(f) + nframes = info['nframes'] + + nframe_real = len(list(ipath_frame.glob("*.jpg"))) + + if nframe_real != nframes: + print(f"\n ERROR: nframe_real ={nframe_real} / nframe_info ={nframes}") + continue + + + # check if finish + nkpt2d = len(list(ipath_kpt2d.glob("*.txt"))) + if nkpt2d + 10 > nframes: + print(f"Have finised before, nkpt2d={nkpt2d} nframes = {nframes}") + continue + + datatest = ObamaData(ipath_frame, iscrop=args.iscrop, face_detector=args.detector) + dataloader = DataLoader(datatest, batch_size=48, shuffle=False, drop_last=False) + + + for i, ibatch_data in enumerate(dataloader): + batch_names = ibatch_data["names"] + batch_image = ibatch_data["image"].to(device) + + if i%50 == 0: + print(f"batch {i:04}/{len(dataloader)}... name = ", batch_names[:5]) + + codedict = deca.encode(batch_image) # encoder + + opdict, visdict = deca.decode(codedict, batch_image) # decoder + + for j, jname in enumerate(batch_names): + jpath_kpt2d = ipath_kpt2d.joinpath(f"{jname}.txt") + jpath_kpt3d = ipath_kpt3d.joinpath(f"{jname}.txt") + jpath_coeff = ipath_coeff.joinpath(f"{jname}.json") + + np.savetxt(jpath_kpt2d, opdict['landmarks2d'][j].cpu().numpy(), fmt="%.6f") + np.savetxt(jpath_kpt3d, opdict['landmarks3d'][j].cpu().numpy(), fmt="%.6f") + + # save coeff + jcodedict = {} + for key, value in codedict.items(): + jcodedict[key] = value[j].cpu().numpy() + + # print("json = ", jcodedict) + np.save(jpath_coeff, jcodedict) + + # # save render + # for vis_name in ['inputs', 'rendered_images', 'albedo_images', 'shape_images', 'shape_detail_images']: + # if vis_name not in visdict.keys(): + # continue + # img = util.tensor2image(visdict[vis_name][j]) + # cv2.imwrite(str(ipath_vis.joinpath(f"{jname}_{vis_name}.jpg")), img) + + # break + +if __name__ == '__main__': + parser = argparse.ArgumentParser(description='DECA: Detailed Expression Capture and Animation') + + parser.add_argument('-i', '--inputpath', default='TestSamples/examples', type=str, + help='path to the test data, can be image folder, image path, image list, video') + parser.add_argument('-d', '--device', default='cuda:0', type=str, + help='set device, cpu for using cpu' ) + # process test images + parser.add_argument('--iscrop', default=True, type=lambda x: x.lower() in ['true', '1'], + help='whether to crop input image, set false only when the test image are well cropped' ) + parser.add_argument('--detector', default='fan', type=str, + help='detector for cropping face, check decalib/detectors.py for details' ) + # save + parser.add_argument('--useTex', default=True, type=lambda x: x.lower() in ['true', '1'], + help='whether to use FLAME texture model to generate uv texture map, \ + set it to True only if you downloaded texture model' ) + parser.add_argument('--saveVis', default=True, type=lambda x: x.lower() in ['true', '1'], + help='whether to save visualization of output' ) + parser.add_argument('--saveKpt', default=False, type=lambda x: x.lower() in ['true', '1'], + help='whether to save 2D and 3D keypoints' ) + parser.add_argument('--saveDepth', default=False, type=lambda x: x.lower() in ['true', '1'], + help='whether to save depth image' ) + parser.add_argument('--saveObj', default=False, type=lambda x: x.lower() in ['true', '1'], + help='whether to save outputs as .obj, detail mesh will end with _detail.obj. \ + Note that saving objs could be slow' ) + parser.add_argument('--saveMat', default=False, type=lambda x: x.lower() in ['true', '1'], + help='whether to save outputs as .mat' ) + parser.add_argument('--saveImages', default=False, type=lambda x: x.lower() in ['true', '1'], + help='whether to save visualization output as seperate images' ) + + main(parser.parse_args()) + + + diff --git a/scripts/LuoXData/run-30-features-3dmm.py b/scripts/LuoXData/run-30-features-3dmm.py new file mode 100644 index 0000000..73b490f --- /dev/null +++ b/scripts/LuoXData/run-30-features-3dmm.py @@ -0,0 +1,101 @@ +import os +import sys +import json +import librosa +import numpy as np +from pathlib import Path + +if __name__ == "__main__": + + path_data = Path('/yrfs/lsen/DATA/LuoXData/processing2') # '../data/trinity/source' + + v_dir_videos = sorted(path_data.glob("*")) + print(f"Have {len(v_dir_videos)} dir files") + + # for each video + duration_frame, duration_coeff = 0, 0 + for ipath_data in v_dir_videos: + ivideo_name = ipath_data.stem + + print(f"\n processing {ivideo_name} ... ") + ipath_infors = ipath_data.joinpath("video/info.json") + ipath_coeff = ipath_data.joinpath("DECA_coeff") + ipath_frame = ipath_data.joinpath("frames") + ipath_save_exp = ipath_data.joinpath("audio/feat_DECA_exp_trim.npy") + ipath_save_pos = ipath_data.joinpath("audio/feat_DECA_pos_trim.npy") + ipath_save_idn = ipath_data.joinpath("audio/feat_DECA_idn_trim.npy") + + if ipath_save_exp.exists() and ipath_save_pos.exists(): + print(f"ipath_save_exp have already save > {ipath_save_exp}") + continue + + if not ipath_infors.exists(): + continue + + + # load video info + with open(str(ipath_infors), "r") as f: + info = json.load(f) + fps = info["fps"] + nframes = info["nframes"] + + print(f"info = {info}, duration ={nframes / fps // 60}") + + # check + vframe_frame = list(ipath_frame.glob("*.jpg")) + vframe_coeff = list(ipath_coeff.glob("*.npy")) + print(f"vframe_frame len = {len(vframe_frame)}, vframe_coeff={len(vframe_coeff)}") + + duration_frame += len(vframe_frame) / 50 / 60 + duration_coeff += len(vframe_coeff) / 50 / 60 + print(f"add duration_frame = {duration_frame} min, duration_coeff={duration_coeff} min") + + if len(vframe_frame) != nframes: + print(f"\n ERROR: nframe_real ={len(vframe_frame)} / nframe_info ={nframes}") + continue + + if len(vframe_coeff)+1 < nframes: + print(f"\n ERROR: nframe_coeff ={len(vframe_coeff)} / nframe_info ={nframes}") + continue + + if ipath_save_exp.exists() and ipath_save_pos.exists(): + print(f"ipath_save_exp have already save > {ipath_save_exp}") + continue + + feat_exp = [] + feat_pos = [] + feat_idn = [] + for j in range(len(vframe_frame) - 1): + + jpath_coeff = ipath_coeff.joinpath(f"frame-{j:06d}.json.npy") + + if not jpath_coeff.exists(): + print(f"\n ERROR: Path NOT FOUND! -> {jpath_coeff}") + break + + data_coeff = np.load(jpath_coeff, allow_pickle=True).item() + feat_exp.append(data_coeff["exp"]) + feat_pos.append(data_coeff["pose"]) + feat_idn.append(data_coeff["shape"]) + + # save + feat_exp = np.array(feat_exp) # (nframe_trim, 50) + feat_pos = np.array(feat_pos) # (nframe_trim, 6) + feat_idn = np.array(feat_idn) # (nframe_trim, 100) + + # pad one + feat_exp = np.pad(feat_exp, ((0,1),(0,0)), mode="edge") + feat_pos = np.pad(feat_pos, ((0,1),(0,0)), mode="edge") + feat_idn = np.pad(feat_idn, ((0,1),(0,0)), mode="edge") + + if nframes == feat_idn.shape[0]: + np.save(ipath_save_exp, feat_exp) + np.save(ipath_save_pos, feat_pos) + np.save(ipath_save_idn, feat_idn) + print(f"SAVE OK! exp shape = {feat_exp.shape},pos = {feat_pos.shape}, idn={feat_idn.shape} nframe={nframes}\n save to -> {ipath_save_exp}") # (nframe, 68, 2) + + else: + print("ERROR, skip! ") + + + diff --git a/scripts/LuoXData/run-40-3dmm-train-vaild-test-ds.py b/scripts/LuoXData/run-40-3dmm-train-vaild-test-ds.py new file mode 100644 index 0000000..2c88966 --- /dev/null +++ b/scripts/LuoXData/run-40-3dmm-train-vaild-test-ds.py @@ -0,0 +1,160 @@ +import json +import numpy as np +from pathlib2 import Path + +def interpolate_features(features, input_rate, output_rate, output_len=None): + num_features = features.shape[1] + input_len = features.shape[0] + seq_len = input_len / float(input_rate) + + if output_len is None: + output_len = int(seq_len * output_rate) + + input_timestamps = np.arange(input_len) / float(input_rate) + output_timestamps = np.arange(output_len) / float(output_rate) + output_features = np.zeros((output_len, num_features)) + for feat in range(num_features): + output_features[:, feat] = np.interp(output_timestamps, + input_timestamps, + features[:, feat]) + return output_features + + +def slice_data(data, window_size, overlap): + + nframes = data.shape[0] + overlap_frames = (int)(overlap*window_size) + + n_sequences = (nframes-overlap_frames)//(window_size-overlap_frames) + + if data.ndim == 2: + sliced = np.zeros((n_sequences, window_size, data.shape[1])).astype(np.float32) + else: + sliced = np.zeros((n_sequences, window_size, data.shape[1], data.shape[2])).astype(np.float32) + + if n_sequences>0: + # extract sequences from the data + for i in range(0, n_sequences): + frameIdx = (window_size-overlap_frames) * i + sliced[i] = data[frameIdx:frameIdx+window_size].copy() + else: + print("WARNING: data too small for window") + + return sliced + + +if __name__ == "__main__": + + path_data = Path('/yrfs/lsen/DATA/LuoXData/processing2') # '../data/trinity/source' + + # path_save = Path('data/LuoXData-ds093raw-deca-3-10-08-mini5') # processing + path_save = Path('data/LuoXData-deca-5-10-07-mini') # processing + path_save.mkdir(parents=True, exist_ok=True) + + v_dir_videos = sorted(path_data.glob("*/audio/feat_DECA_exp_trim.npy")) + print(f"Have {len(v_dir_videos)} dir files") + + v_dir_videos = [ipath.parent.parent for ipath in v_dir_videos] + vids = set([ipath.stem for ipath in v_dir_videos]) + print(f"vids total= {vids}") + + + vid_test = set(["2021-P14"]) + vid_valid = set(["2021-P14"]) #set(["2021-P14"]) + # vid_train = set(['2021-P01', '2021-P02', '2021-P']) + vid_train = vids - vid_test - vid_test + + print(f"vid test= {vid_test} \nvalid= {vid_valid}") + print(f"vid train= {vid_train}") + + # set windows + nwin_train_secs = 5 # 6 + nwin_test_secs = 10 # 20 + window_overlap = 0.7 + fps = 50 + + nwin_train = nwin_train_secs * fps # 5 * 50 = 250 + nwin_test = nwin_test_secs * fps # 10 * 50 = 500 + + # for each video + motion_train, motion_valid, motion_test = [], [], [] + speech_train, speech_valid, speech_test = [], [], [] + for i, ipath_data in enumerate(v_dir_videos): + vid = ipath_data.stem + + # if i >= 50: continue + print(f"\n processing the {i}-th video {vid} ... ") + + ipath_info = ipath_data.joinpath("video/info.json") + ipath_feat_exp = ipath_data.joinpath("audio/feat_DECA_exp_trim.npy") + ipath_feat_pos = ipath_data.joinpath("audio/feat_DECA_pos_trim.npy") + + ipath_feat_speech = ipath_data.joinpath("audio/feat_mel_trim.npy") + # ipath_feat_speech = ipath_data.joinpath("audio/audio_trim_ds093.npy") + # ipath_feat_speech = ipath_data.joinpath("audio/audio_trim_ds093_raw.npy") + + if not ipath_feat_speech.exists(): + print(f"NOT existing {ipath_feat_speech}") + continue + + # load video info + with open(str(ipath_info), "r") as f: + info = json.load(f) + fps = info["fps"] + print(f"info={info}") + assert fps == 50, "fps should be 50" + + + # laod motion & speech data + data_exp = np.load(ipath_feat_exp) # (nframe, 50) + data_pos = np.load(ipath_feat_pos) # (nframe, 6) + pos_head = data_pos[:, :3] # (nframe, 3) + pos_lips = data_pos[:, 3:] # (nframe, 3) + + data_motion = np.concatenate([data_exp, pos_lips], axis=1) # (nframe, 53) --> fps=30 + data_speech = np.load(ipath_feat_speech) # (nframe, 256) --> fps=60 + print(f"motion = {data_motion.shape}, speech = {data_speech.shape}") + + # filter data_speech + # data_speech[data_speech < 0] = 0 + + + if vid in vid_train: + motion_sliced = slice_data(data_motion, window_size=nwin_train, overlap=window_overlap) + speech_sliced = slice_data(data_speech, window_size=nwin_train, overlap=window_overlap) + motion_train.append(motion_sliced) + speech_train.append(speech_sliced) + + if vid in vid_valid: + motion_sliced = slice_data(data_motion, window_size=nwin_train, overlap=0) + speech_sliced = slice_data(data_speech, window_size=nwin_train, overlap=0) + motion_valid.append(motion_sliced) + speech_valid.append(speech_sliced) + + if vid in vid_test: + motion_sliced = slice_data(data_motion, window_size=nwin_test, overlap=0) + speech_sliced = slice_data(data_speech, window_size=nwin_test, overlap=0) + motion_test.append(motion_sliced) + speech_test.append(speech_sliced) + + print(f"sliced motion = {motion_sliced.shape}, speech = {speech_sliced.shape}, minmax=({np.min(data_speech)},{np.max(data_speech)}) \n") + + # save + motion_train = np.concatenate(motion_train, axis=0) # (nframe, 250, 53) + speech_train = np.concatenate(speech_train, axis=0) # (nframe, 250, 256) + np.savez(path_save.joinpath("motion_train.npz"), data=motion_train) + np.savez(path_save.joinpath("speech_train.npz"), data=speech_train) + print(f"save train data motion({motion_train.shape}), speech({speech_train.shape}) -> {path_save}") + + motion_valid = np.concatenate(motion_valid, axis=0) # (350, 180, 136) + speech_valid = np.concatenate(speech_valid, axis=0) # (350, 180, 27) + np.savez(path_save.joinpath("motion_valid.npz"), data=motion_valid) + np.savez(path_save.joinpath("speech_valid.npz"), data=speech_valid) + print(f"save valid data motion({motion_valid.shape}), speech({speech_valid.shape}) -> {path_save}") + + motion_test = np.concatenate(motion_test, axis=0) # (41, 600, 136) + speech_test = np.concatenate(speech_test, axis=0) # (41, 600, 27) + np.savez(path_save.joinpath("motion_test.npz"), data=motion_test) + np.savez(path_save.joinpath("speech_test.npz"), data=speech_test) + print(f"save test data motion({motion_test.shape}), speech({speech_test.shape}) -> {path_save}\n") + diff --git a/scripts/LuoXData/run-41-3dmm-ds-split-data.py b/scripts/LuoXData/run-41-3dmm-ds-split-data.py new file mode 100644 index 0000000..332f6a6 --- /dev/null +++ b/scripts/LuoXData/run-41-3dmm-ds-split-data.py @@ -0,0 +1,153 @@ +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('/yrfs/lsen/DATA/LuoXData/processing2') # '../data/trinity/source' + + path_save = Path('data/LuoXData-raw-deca-8h') # processing + path_save.mkdir(parents=True, exist_ok=True) + + v_dir_videos = sorted(path_data.glob("*"), reverse=False) + print(f"Have {len(v_dir_videos)} dir files, \n {v_dir_videos[:3]}") + + v_dir_videos = sorted(path_data.glob("*/audio/feat_DECA_exp_trim.npy")) + print(f"Have {len(v_dir_videos)} dir files") + + v_dir_videos = [ipath.parent.parent for ipath in v_dir_videos] + vids = set([ipath.stem for ipath in v_dir_videos]) + print(f"vids total= {vids}") + + vid_test = set(["2021-P09"]) + vid_valid = set(["2021-P14"]) #set(["2021-P14"]) + # vid_train = set(['2021-P01', '2021-P02', '2021-P']) + vid_train = vids - vid_test - vid_test + print(f"vid test= {vid_test} \nvalid= {vid_valid}") + print(f"vid train= {vid_train}") + + # for each video + data_train, data_valid, data_test = {}, {}, {} + durations_train, durations_valid, durations_test = 0, 0, 0 + for i, ipath_data in enumerate(v_dir_videos): + vid = ipath_data.stem + + print(f"\n processing the {i}-th video {vid} ... ") + + ipath_info = ipath_data.joinpath("video/info.json") + ipath_feat_exp = ipath_data.joinpath("audio/feat_DECA_exp_trim.npy") + ipath_feat_pos = ipath_data.joinpath("audio/feat_DECA_pos_trim.npy") + ipath_speech = ipath_data.joinpath("audio/audio_trim.wav") + + # check existing + if not ipath_speech.exists(): + print(f"NOT existing {ipath_speech}") + continue + + if not ipath_feat_exp.exists(): + print(f"NOT existing {ipath_feat_exp}") + continue + + # load video info + with open(str(ipath_info), "r") as f: + info = json.load(f) + fps = info["fps"] + nframes = info['nframes'] + 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) + pos_head = data_pos[:, :3] # (nframe, 3) + pos_lips = data_pos[:, 3:] # (nframe, 3) + + data_motion = np.concatenate([data_exp, pos_lips], axis=1) # (nframe, 53) --> fps=30 + print(f"motion = {data_motion.shape}") + + + # load raw audio + audio_raw, sample_rate = torchaudio.load(ipath_speech) + 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) + audio_raw = resampler(audio_raw).squeeze().numpy() + print(f"audio_raw shape = {audio_raw.shape}, sr = {16000}, duration = {(len(audio_raw)/16000)}") + + + if vid in vid_train: + durations_train += nframes/fps + + data_train[vid] = { + "fps": info["fps"], + "sr": 16000, + "nframe": nframes, + "data_motion": data_motion, + "data_speech": audio_raw + } + + + if vid in vid_valid: + durations_valid += nframes/fps + + data_valid[vid] = { + "fps": info["fps"], + "sr": 16000, + "nframe": nframes, + "data_motion": data_motion, + "data_speech": audio_raw + } + + + if vid in vid_test: + durations_test += nframes/fps + + data_test[vid] = { + "fps": info["fps"], + "sr": 16000, + "nframe": nframes, + "data_motion": data_motion, + "data_speech": audio_raw + } + + + np.savez(path_save.joinpath("data_train.npz"), data=data_train) + np.savez(path_save.joinpath("data_valid.npz"), data=data_valid) + np.savez(path_save.joinpath("data_test.npz"), data=data_test) + + print(f"Total ids: data_train ({len(data_train)}), data_test ({len(data_test)}) data_valid({len(data_valid)})") + print(f"Total frames: data_train ({durations_train / 3600} h), data_test ({durations_test / 60 } min) data_valid({durations_valid / 60} min)") + + + print(f"--> {path_save}") \ No newline at end of file diff --git a/scripts/Obama/run-52-3dmm-train-vaild-test-ds.py b/scripts/Obama/run-52-3dmm-train-vaild-test-ds.py index ffedeb2..2b95f69 100644 --- a/scripts/Obama/run-52-3dmm-train-vaild-test-ds.py +++ b/scripts/Obama/run-52-3dmm-train-vaild-test-ds.py @@ -112,6 +112,10 @@ if __name__ == "__main__": data_speech = np.load(ipath_feat_speech) # (nframe*2, 16, 29) --> fps=60 print(f"motion = {data_motion.shape}, speech = {data_speech.shape}") + print(f"speech minmax=({np.min(data_speech)},{np.max(data_speech)}) \n") + + + # # downsampling data_speech, 60fps --> fps # (nseq, nwind, nfeat) = data_speech.shape # (nframe*2, 16, 29) # data_speech = data_speech.reshape(nseq, -1) # (nframe*2, 16x29) @@ -119,42 +123,42 @@ if __name__ == "__main__": # data_speech = data_speech.reshape(-1, nwind, nfeat) # print(f"after motion = {data_motion.shape}, speech = {data_speech.shape}") - if vid in vid_train: - motion_sliced = slice_data(data_motion, window_size=nwin_train, overlap=window_overlap) - speech_sliced = slice_data(data_speech, window_size=nwin_train, overlap=window_overlap) - motion_train.append(motion_sliced) - speech_train.append(speech_sliced) + # if vid in vid_train: + # motion_sliced = slice_data(data_motion, window_size=nwin_train, overlap=window_overlap) + # speech_sliced = slice_data(data_speech, window_size=nwin_train, overlap=window_overlap) + # motion_train.append(motion_sliced) + # speech_train.append(speech_sliced) - if vid in vid_valid: - motion_sliced = slice_data(data_motion, window_size=nwin_train, overlap=window_overlap) - speech_sliced = slice_data(data_speech, window_size=nwin_train, overlap=window_overlap) - motion_valid.append(motion_sliced) - speech_valid.append(speech_sliced) + # if vid in vid_valid: + # motion_sliced = slice_data(data_motion, window_size=nwin_train, overlap=window_overlap) + # speech_sliced = slice_data(data_speech, window_size=nwin_train, overlap=window_overlap) + # motion_valid.append(motion_sliced) + # speech_valid.append(speech_sliced) - if vid in vid_test: - motion_sliced = slice_data(data_motion, window_size=nwin_test, overlap=0) - speech_sliced = slice_data(data_speech, window_size=nwin_test, overlap=0) - motion_test.append(motion_sliced) - speech_test.append(speech_sliced) + # if vid in vid_test: + # motion_sliced = slice_data(data_motion, window_size=nwin_test, overlap=0) + # speech_sliced = slice_data(data_speech, window_size=nwin_test, overlap=0) + # motion_test.append(motion_sliced) + # speech_test.append(speech_sliced) - print(f"sliced motion = {motion_sliced.shape}, speech = {speech_sliced.shape}, minmax=({np.min(data_speech)},{np.max(data_speech)}) \n") + # print(f"sliced motion = {motion_sliced.shape}, speech = {speech_sliced.shape}, minmax=({np.min(data_speech)},{np.max(data_speech)}) \n") - # save - motion_train = np.concatenate(motion_train, axis=0) # (nframe, 180, 136) - speech_train = np.concatenate(speech_train, axis=0) # (nframe, 180, 27) - np.savez(path_save.joinpath("motion_train.npz"), data=motion_train) - np.savez(path_save.joinpath("speech_train.npz"), data=speech_train) - print(f"save train data motion({motion_train.shape}), speech({speech_train.shape}) -> {path_save}") + # # save + # motion_train = np.concatenate(motion_train, axis=0) # (nframe, 180, 136) + # speech_train = np.concatenate(speech_train, axis=0) # (nframe, 180, 27) + # np.savez(path_save.joinpath("motion_train.npz"), data=motion_train) + # np.savez(path_save.joinpath("speech_train.npz"), data=speech_train) + # print(f"save train data motion({motion_train.shape}), speech({speech_train.shape}) -> {path_save}") - motion_valid = np.concatenate(motion_valid, axis=0) # (350, 180, 136) - speech_valid = np.concatenate(speech_valid, axis=0) # (350, 180, 27) - np.savez(path_save.joinpath("motion_valid.npz"), data=motion_valid) - np.savez(path_save.joinpath("speech_valid.npz"), data=speech_valid) - print(f"save valid data motion({motion_valid.shape}), speech({speech_valid.shape}) -> {path_save}") + # motion_valid = np.concatenate(motion_valid, axis=0) # (350, 180, 136) + # speech_valid = np.concatenate(speech_valid, axis=0) # (350, 180, 27) + # np.savez(path_save.joinpath("motion_valid.npz"), data=motion_valid) + # np.savez(path_save.joinpath("speech_valid.npz"), data=speech_valid) + # print(f"save valid data motion({motion_valid.shape}), speech({speech_valid.shape}) -> {path_save}") - motion_test = np.concatenate(motion_test, axis=0) # (41, 600, 136) - speech_test = np.concatenate(speech_test, axis=0) # (41, 600, 27) - np.savez(path_save.joinpath("motion_test.npz"), data=motion_test) - np.savez(path_save.joinpath("speech_test.npz"), data=speech_test) - print(f"save test data motion({motion_test.shape}), speech({speech_test.shape}) -> {path_save}\n") + # motion_test = np.concatenate(motion_test, axis=0) # (41, 600, 136) + # speech_test = np.concatenate(speech_test, axis=0) # (41, 600, 27) + # np.savez(path_save.joinpath("motion_test.npz"), data=motion_test) + # np.savez(path_save.joinpath("speech_test.npz"), data=speech_test) + # print(f"save test data motion({motion_test.shape}), speech({speech_test.shape}) -> {path_save}\n") diff --git a/scripts/Test/test_transformer.py b/scripts/Test/test_transformer.py new file mode 100644 index 0000000..ba926cf --- /dev/null +++ b/scripts/Test/test_transformer.py @@ -0,0 +1,52 @@ +# !pip install transformers +# !pip install datasets +import soundfile as sf +import torch +from datasets import load_dataset +from transformers import Wav2Vec2ForCTC, Wav2Vec2Processor + +# load pretrained model +processor = Wav2Vec2Processor.from_pretrained("facebook/wav2vec2-base-960h") +model = Wav2Vec2ForCTC.from_pretrained("facebook/wav2vec2-base-960h") + + +librispeech_samples_ds = load_dataset("patrickvonplaten/librispeech_asr_dummy", "clean", split="validation") +path_file = librispeech_samples_ds[1]["file"] + +print("file = ", path_file) + + +# load audio +audio_input, sample_rate = sf.read(path_file) + +print(f"audio_input shape = {audio_input.shape}, sr = {sample_rate}, duration = {(len(audio_input)/sample_rate)}") + +# pad input values and return pt tensor +input_values = processor(audio_input, sampling_rate=sample_rate, return_tensors="pt").input_values + +# INFERENCE + +# retrieve logits & take argmax +logits = model(input_values).logits + +print(f"logit shape = {logits.shape}") + +# predicted_ids = torch.argmax(logits, dim=-1) + +# # transcribe +# transcription = processor.decode(predicted_ids[0]) + +# # FINE-TUNE + +# target_transcription = "A MAN SAID TO THE UNIVERSE I EXIST" + +# # encode labels +# with processor.as_target_processor(): +# labels = processor(target_transcription, return_tensors="pt").input_ids + +# # compute loss by passing labels +# loss = model(input_values, labels=labels).loss +# print("loss", loss) + +# # loss.backward() + diff --git a/scripts/Test/test_transformer2.py b/scripts/Test/test_transformer2.py new file mode 100644 index 0000000..572b1f5 --- /dev/null +++ b/scripts/Test/test_transformer2.py @@ -0,0 +1,87 @@ +import torch +import torchaudio +import torch.nn.functional as F +import soundfile as sf +import librosa +from datasets import load_dataset +from transformers import Wav2Vec2ForCTC, Wav2Vec2Processor,Wav2Vec2Model +from pathlib import Path +import numpy as np + + +LANG_ID = "zh-CN" +MODEL_ID = "jonatasgrosman/wav2vec2-large-xlsr-53-chinese-zh-cn" +SAMPLES = 2 + +print("load model ...") +processor = Wav2Vec2Processor.from_pretrained(MODEL_ID) +# model = Wav2Vec2ForCTC.from_pretrained(MODEL_ID) +model = Wav2Vec2Model.from_pretrained(MODEL_ID) + +# processor = Wav2Vec2Processor.from_pretrained("ydshieh/wav2vec2-large-xlsr-53-chinese-zh-cn-gpt") +# model = Wav2Vec2ForCTC.from_pretrained("ydshieh/wav2vec2-large-xlsr-53-chinese-zh-cn-gpt") + +# # Preprocessing the datasets. +# # We need to read the audio files as arrays +# def speech_file_to_array_fn(batch): +# speech_array, sampling_rate = librosa.load(batch["path"], sr=16_000) +# batch["speech"] = speech_array +# batch["sentence"] = batch["sentence"].upper() + +# return batch + +# print("load dataest ...") +# test_dataset = load_dataset("common_voice", LANG_ID, split=f"test[:{SAMPLES}]") +# test_dataset = test_dataset.map(speech_file_to_array_fn) +# inputs = processor(test_dataset["speech"], sampling_rate=16_000, return_tensors="pt", padding=True) + + +librispeech_samples_ds = load_dataset("patrickvonplaten/librispeech_asr_dummy", "clean", split="validation") +path_file = librispeech_samples_ds[0]["file"] +# path_file = '/yrfs/lsen/DATA/LuoXData/processing2/2021-P01/audio/audio_trim.wav' +# print("file = ", path_file) + + +# load audio +# audio_input, sample_rate = sf.read(path_file) +audio_input, sample_rate = torchaudio.load(path_file) +if len(audio_input.shape) == 2: + audio_input = audio_input[0] + +print(f"audio_input shape = {audio_input.shape}, sr = {sample_rate}, duration = {(len(audio_input)/sample_rate)}") + +if sample_rate != 16000: + resampler = torchaudio.transforms.Resample(sample_rate, 16_000) + audio_input = resampler(audio_input).squeeze().numpy() + print(f"audio_input shape = {audio_input.shape}, sr = {16000}, duration = {(len(audio_input)/16000)}") + + +# Preprocessing the datasets. +# We need to read the aduio files as arrays + +# pad input values and return pt tensor +inputs = processor(audio_input, sampling_rate=16000, return_tensors="pt") + + +print("predict ...") +with torch.no_grad(): + logits = model(inputs.input_values, attention_mask=inputs.attention_mask) + + + print(f"logits shape = {logits.shape}") + + logits = F.softmax(logits, dim=-1) + print(f"logits reshape = {logits.shape}") + + # padding last vector by last (0,0), model (0,1) + logits = F.pad(logits, (0,0,0,1), mode='replicate') + logits = torch.squeeze(logits) + print(f"pad reshape = {logits.shape}") + + # convert to numpy + logits = logits.cpu().numpy() + path_save = Path(path_file).parent.joinpath(f"{Path(path_file).stem}_wav2vec2.npy") + np.save(path_save, logits) + + + diff --git a/scripts/Test/test_transformer3.py b/scripts/Test/test_transformer3.py new file mode 100644 index 0000000..ef96eab --- /dev/null +++ b/scripts/Test/test_transformer3.py @@ -0,0 +1,33 @@ +import torch +import torchaudio +from datasets import load_dataset +from transformers import Wav2Vec2ForCTC, Wav2Vec2Processor + +test_dataset = load_dataset("common_voice", "zh-CN", split="test") + +processor = Wav2Vec2Processor.from_pretrained("ydshieh/wav2vec2-large-xlsr-53-chinese-zh-cn-gpt") +model = Wav2Vec2ForCTC.from_pretrained("ydshieh/wav2vec2-large-xlsr-53-chinese-zh-cn-gpt") + +resampler = torchaudio.transforms.Resample(48_000, 16_000) + +# Preprocessing the datasets. +# We need to read the aduio files as arrays +def speech_file_to_array_fn(batch): + ipath = batch["path"] + print(f"ipath speech = {ipath}") + speech_array, sampling_rate = torchaudio.load(ipath) + + batch["speech"] = resampler(speech_array).squeeze().numpy() + return batch + +test_dataset = test_dataset.map(speech_file_to_array_fn) +inputs = processor(test_dataset[:2]["speech"], sampling_rate=16_000, return_tensors="pt", padding=True) + +with torch.no_grad(): + logits = model(inputs.input_values, attention_mask=inputs.attention_mask).logits + print(f"logits shape = {logits.shape}") + +predicted_ids = torch.argmax(logits, dim=-1) + +print("Prediction:", processor.batch_decode(predicted_ids)) +print("Reference:", test_dataset[:2]["sentence"]) \ No newline at end of file diff --git a/scripts/Test/test_transformer4.py b/scripts/Test/test_transformer4.py new file mode 100644 index 0000000..de6e22c --- /dev/null +++ b/scripts/Test/test_transformer4.py @@ -0,0 +1,94 @@ +import torch +import torchaudio +import torch.nn.functional as F +import soundfile as sf +import librosa +from datasets import load_dataset +from transformers import Wav2Vec2FeatureExtractor, Wav2Vec2Model +from pathlib import Path +import numpy as np + + +LANG_ID = "zh-CN" +MODEL_ID = "jonatasgrosman/wav2vec2-large-xlsr-53-chinese-zh-cn" +SAMPLES = 2 + +print("load model ...") +processor = Wav2Vec2FeatureExtractor.from_pretrained(MODEL_ID) +# model = Wav2Vec2ForCTC.from_pretrained(MODEL_ID) +model = Wav2Vec2Model.from_pretrained(MODEL_ID) + + +# processor = Wav2Vec2Processor.from_pretrained("ydshieh/wav2vec2-large-xlsr-53-chinese-zh-cn-gpt") +# model = Wav2Vec2ForCTC.from_pretrained("ydshieh/wav2vec2-large-xlsr-53-chinese-zh-cn-gpt") + +# # Preprocessing the datasets. +# # We need to read the audio files as arrays +# def speech_file_to_array_fn(batch): +# speech_array, sampling_rate = librosa.load(batch["path"], sr=16_000) +# batch["speech"] = speech_array +# batch["sentence"] = batch["sentence"].upper() + +# return batch + +# print("load dataest ...") +# test_dataset = load_dataset("common_voice", LANG_ID, split=f"test[:{SAMPLES}]") +# test_dataset = test_dataset.map(speech_file_to_array_fn) +# inputs = processor(test_dataset["speech"], sampling_rate=16_000, return_tensors="pt", padding=True) + + +librispeech_samples_ds = load_dataset("patrickvonplaten/librispeech_asr_dummy", "clean", split="validation") +path_file = librispeech_samples_ds[0]["file"] +# path_file = '/yrfs/lsen/DATA/LuoXData/processing2/2021-P01/audio/audio_trim.wav' +# print("file = ", path_file) + + +# load audio +# audio_input, sample_rate = sf.read(path_file) +audio_input, sample_rate = torchaudio.load(path_file) +if len(audio_input.shape) == 2: + audio_input = audio_input[0] + +print(f"audio_input shape = {audio_input.shape}, sr = {sample_rate}, duration = {(len(audio_input)/sample_rate)}") + +if sample_rate != 16000: + resampler = torchaudio.transforms.Resample(sample_rate, 16_000) + audio_input = resampler(audio_input).squeeze().numpy() + print(f"audio_input shape = {audio_input.shape}, sr = {16000}, duration = {(len(audio_input)/16000)}") + + +# Preprocessing the datasets. +# We need to read the aduio files as arrays +print(f"audio_input shap={audio_input.shape}, dtype={audio_input.dtype}") +# pad input values and return pt tensor +inputs = processor(audio_input, sampling_rate=16000, return_tensors="pt") + + +print("predict ...") +with torch.no_grad(): + output = model(**inputs) + + + # print(f"hidden_states = {output.hidden_states}") + print(f"extract_features = {output.extract_features.shape}") + print(f"last_hidden_state = {output.last_hidden_state.shape}") + # print(f"attentions = {output.attentions.shape}") + + + # print(f"logits shape = {logits.shape}") + + # logits = F.softmax(logits, dim=-1) + # print(f"logits reshape = {logits.shape}") + + # # padding last vector by last (0,0), model (0,1) + # logits = F.pad(logits, (0,0,0,1), mode='replicate') + # logits = torch.squeeze(logits) + # print(f"pad reshape = {logits.shape}") + + # # convert to numpy + # logits = logits.cpu().numpy() + # path_save = Path(path_file).parent.joinpath(f"{Path(path_file).stem}_wav2vec2.npy") + # np.save(path_save, logits) + + + diff --git a/src/config.py b/src/config.py index 194e9c7..4504c6e 100644 --- a/src/config.py +++ b/src/config.py @@ -71,13 +71,13 @@ config.MODEL.dim_motion = 0 config.MODEL.dim_speech = 0 config.MODEL.dim_hidden = 0 -config.MODEL.n_lookprevs_motion = 3 -config.MODEL.n_lookprevs_speech = 3 +config.MODEL.n_lookprevs_motion = 0 +config.MODEL.n_lookprevs_speech = 0 -config.MODEL.n_lookahead_motion = 7 -config.MODEL.n_lookahead_speech = 7 +config.MODEL.n_lookahead_motion = 0 +config.MODEL.n_lookahead_speech = 0 -config.MODEL.n_layer_lstm = 2 +config.MODEL.n_layer_lstm = 0 # # for wavenet @@ -120,6 +120,8 @@ config.MODEL.n_layer_lstm = 2 ########################## # dataset related params config.DATASET = edict() +config.DATASET.fps = 30 +config.DATASET.sr = 16000 config.DATASET.name = 'ravdess' config.DATASET.type = '' # "clips" | "frame" | "none" config.DATASET.root = "../data/" @@ -128,7 +130,7 @@ config.DATASET.root = "../data/" config.DATASET.nwind_second_train = 0 config.DATASET.nwind_second_valid = 0 config.DATASET.nwind_second_test = 0 - +config.DATASET.speech_extractor = '' # for data smooth config.DATASET.filter = '' # "gaussian" | "savgol" @@ -189,11 +191,12 @@ config.TRAIN.gamma2 = 0.0 # loss related params config.LOSS = edict() config.LOSS.names = ["all", "L1"] + config.LOSS.lambda_rec = 1 -config.LOSS.lambda_kld = 0 -config.LOSS.lambda_dif = 0 -config.LOSS.lambda_cyc = 0 -config.LOSS.lambda_trp = 0 +config.LOSS.lambda_rec_exp = 0 +config.LOSS.lambda_rec_pos = 0 +config.LOSS.lambda_vol_exp = 0 +config.LOSS.lambda_vol_pos = 0 config.LOSS.lambda_geo = 0 config.LOSS.lambda_rec_smooth = 0 config.LOSS.lambda_geo_smooth = 0 diff --git a/src/datasets/motion_live.py b/src/datasets/motion_live.py new file mode 100644 index 0000000..96e35ec --- /dev/null +++ b/src/datasets/motion_live.py @@ -0,0 +1,115 @@ +import numpy as np +import torch +import time +from torch.utils.data import Dataset +from pathlib import Path +from scipy.signal import savgol_filter + +from common.debug import debug + +class MotionLiveDataset(Dataset): + """ + Motion dataset. + Prepares conditioning information (previous poses + control signal) and the corresponding next poses""" + + def __init__(self, opt, phase="train"): + """ + phase = "train | valid | test " + """ + super(MotionLiveDataset, 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}") + # 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()) + + 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} ''') + + + # 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 20000 + elif self.phase == "valid": + return 1000 + else: + return 100 + + 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 + """ + np.random.seed(int(idx + time.time())) + vid = self.pids[idx % self.num_pid] + + # random select idx + 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 = np.random.randint(nframe - self.nsteps_frame - 10) + 5 # select from (5:-5) + 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})\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, ) + + # 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] + } + + return result \ No newline at end of file diff --git a/src/models/base.py b/src/models/base.py index 8dc8f49..7e67a48 100644 --- a/src/models/base.py +++ b/src/models/base.py @@ -178,7 +178,7 @@ class Base(): return visual_ret - def get_current_losses(self): + def get_current_losses(self, phase=None): """Return traning losses / errors. train.py will print out these errors on console, and save them to a file""" @@ -186,8 +186,13 @@ class Base(): for name in self.names_loss: # print(f"name = ",name) # errors_ret[name] = self.loss_dict["loss_" + name ].detach().float().cpu() # float(...) works for both scalar tensor and float number - errors_ret[name] = self.loss_dict["loss_" + name ].float().cpu() # float(...) works for both scalar tensor and float number - + # errors_ret[name] = self.loss_dict["loss_" + name ].float().cpu() # float(...) works for both scalar tensor and float number + if phase == "valid": + errors_ret[name+"_val"] = self.loss_dict["loss_" + name ].float().cpu() # float(...) works for both scalar tensor and float number + else: + errors_ret[name] = self.loss_dict["loss_" + name ].float().cpu() + + return errors_ret def save_networks(self, epoch): @@ -278,7 +283,7 @@ class Base(): if load_info: # load training state path_state = load_path.joinpath("checkpoints", f'{load_suffix}_net_train_state.pth') - load_state = torch.load(str(path_state)) + load_state = torch.load(str(path_state), map_location=str(self.device)) for name in self.names_model: optimizer_ = getattr(self, 'optimizer_' + name) diff --git a/src/models/model_audio2motion.py b/src/models/model_audio2motion.py index 2dd9b4d..ac2c6fd 100644 --- a/src/models/model_audio2motion.py +++ b/src/models/model_audio2motion.py @@ -53,11 +53,10 @@ class Audio2motionModel(Base): self.mean_dict = np.load(path_deca_mean, allow_pickle=True).item() print(self.mean_dict.keys()) - def set_input(self, batch_input): - self.data = batch_input["data"].float().to(self.device) # (nsteps, dim_data) - self.cond = batch_input["cond"].float().to(self.device) # (nsteps, dim_cond) + self.data = batch_input["data"].float().to(self.device) # (B, nsteps, dim_data) + self.cond = batch_input["cond"].float().to(self.device) # (B, nsteps, dim_cond) self.B = self.data.size(0) debug(self.opt, f"data = {self.data.shape}, cond = {self.cond.shape}, dtype={self.data.dtype}", verbose=False) @@ -254,7 +253,7 @@ class Audio2motionModel(Base): # 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, jpath_save) + save_animation_with_gt2(v_render_pt, v_render_gt, jpath_save, fps=self.opt.DATASET.fps) @@ -290,6 +289,9 @@ def define_netG(opt): from src.nn.audio2motion import Audio2Motion netG = Audio2Motion(opt) + elif opt.MODEL.name_netG == "audio2motion2": + from src.nn.audio2motion2 import Audio2Motion2 + netG = Audio2Motion2(opt) else: raise NameError(f"The model of opt.MODEL.name_netAE(={opt.MODEL.name_netG}) not existing!") diff --git a/src/models/model_audio2motion_live.py b/src/models/model_audio2motion_live.py new file mode 100644 index 0000000..339ccfe --- /dev/null +++ b/src/models/model_audio2motion_live.py @@ -0,0 +1,375 @@ +import sys +import numpy as np + +import torch +import torch.nn as nn +import torch.nn.functional as F +from pathlib import Path + +from src.models import init_net +from src.models.base import Base +from src.optims import get_optimizer, get_scheduler + +# common +from common.animation import save_animation_with_gt2, save_images_with_audio +from common.debug import debug +from common.losses import WingLoss + +# disentangle model +class Audio2motionLiveModel(Base): + + def __init__(self, opt, logger): + Base.__init__(self, opt, logger) + + self.opt = opt + self.logger = logger + self.names_model = ["G"] # G + + + # define networks + self.netG = define_netG(opt) + self.netG.to() + self.netG = torch.nn.DataParallel(self.netG, opt.GPUS) # multi-GPUs + init_net(self.netG, init_type='kaiming', gpu_ids=opt.GPUS) + + self.loss_func_l1 = nn.L1Loss(reduction="mean") + self.loss_func_wing = WingLoss(reduction="mean") + + if self.isTrain: + self.names_loss = opt.LOSS.names + + # define optimizers + self.optimizer_G = get_optimizer(self.netG, opt) + self.optimizers.append(self.optimizer_G) + + self.scheduler_G = get_scheduler(self.optimizer_G, opt) + self.schedulers.append(self.scheduler_G) + + if self.opt.TRAIN.apply_testing or not self.isTrain: + # load mean lighting & shape + self.netR = define_netR(device=self.device) + # self.netG.init_reconstruct_model(self.netR) + + path_deca_mean = Path("./data/DECA_obama_mean.npy") + self.mean_dict = np.load(path_deca_mean, allow_pickle=True).item() + print(self.mean_dict.keys()) + + 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) + + + + def set_input(self, batch_input): + + # motion data + self.data = batch_input["data"].float().to(self.device) # (B, nsteps, nc_motion) + self.B, self.nsteps = self.data.size(0), self.data.size(1) + debug(self.opt, f"data = {self.data.shape}, dtype={self.data.dtype}", verbose=False) + + # speech data + 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) + 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) + self.cond = output.last_hidden_state + # self.cond = output.extract_features + + + debug(self.opt, f"data = {self.data.shape}, dtype={self.data.dtype}, device={self.data.device}", verbose=False) + debug(self.opt, f"cond = {self.cond.shape}, dtype={self.cond.dtype}, device={self.cond.device}", verbose=False) + + + def training(self, batch_input): + self.train() # set train model + self.set_input(batch_input) + + # forward + self.pred = self.netG(self.cond) + + # loss + loss, self.loss_dict = self.eval_losses(self.pred, self.data) + + # backward + self.optimizer_G.zero_grad() + loss.backward() + + if self.opt.TRAIN.grad_clip_norm: # operate grad + torch.nn.utils.clip_grad_value_(self.netG.parameters(), self.opt.TRAIN.max_grad_clip) + torch.nn.utils.clip_grad_norm_(self.netG.parameters(), self.opt.TRAIN.max_grad_norm) + + self.optimizer_G.step() + + return loss + + + def validation(self, batch_input): + self.eval() # set eval model + self.set_input(batch_input) + + with torch.no_grad(): + self.pred = self.netG(self.cond) + loss, self.loss_dict = self.eval_losses(self.pred, self.data) + + return loss + + def infer(self, batch_cond, path_audio, suffix=""): + self.eval() + self.cond = batch_cond.float().to(self.device) # (nsteps, dim_cond) + + with torch.no_grad(): + samples_pt = self.netG(self.cond).cpu().numpy() # B x N x dim_motion + print(f"testing pt shape = {samples_pt.shape}") + + self.save_reconstruct(samples_pt, path_audio, + path_save=Path(self.opt.OUTPUT_DIR), + suffix=suffix) + + + def testing(self, batch_input, cur_epoch=0, cur_batch=0): + self.eval() # set eval model + self.set_input(batch_input) + + with torch.no_grad(): + samples_pt = self.netG(self.cond).cpu().numpy() # B x N x dim_motion + samples_gt = self.data.cpu().numpy() # B x N x dim_motion + + print(f"testing pt shape = {samples_pt.shape}, gt shape = {samples_gt.shape}") + + self.save_reconstruct_with_gt(samples_pt, samples_gt, + path_save=Path(self.opt.OUTPUT_DIR), + suffix=f'sampled_{cur_epoch:05d}_{cur_batch:03d}') + + + def eval_losses(self, batch_pdt, batch_tgt): + """ Computes the VAE loss function. + pramas: + batch_pred, (nbatch, seqlen, dim_motion) + batch_targt, (nbatch, seqlen, dim_motion) + """ + loss = 0 + loss_dict = {} + + batch_pdt_exp = batch_pdt[..., :50] + batch_pdt_pos = batch_pdt[..., 50:] + + batch_tgt_exp = batch_tgt[..., :50] + batch_tgt_pos = batch_tgt[..., 50:] + + + # rec loss + loss = 0 + + loss_rec_exp = self.loss_func_wing(batch_pdt_exp, batch_tgt_exp) / 50 + loss_dict["loss_rec_exp"] = loss_rec_exp.detach() + + loss_rec_pos = self.loss_func_wing(batch_pdt_pos, batch_tgt_pos) / 3 + loss_dict["loss_rec_pos"] = loss_rec_pos.detach() + + loss += loss_rec_exp * self.opt.LOSS.lambda_rec + loss += loss_rec_pos * self.opt.LOSS.lambda_rec * 10 + + + # rec smooth + diff_pdt_exp = batch_pdt_exp[:, 1:, :] - batch_pdt_exp[:, :-1, :] + diff_tgt_exp = batch_tgt_exp[:, 1:, :] - batch_tgt_exp[:, :-1, :] + loss_vol_exp = self.loss_func_wing(diff_pdt_exp, diff_tgt_exp) / 50 + loss_dict["loss_vol_exp"] = loss_vol_exp.detach() + + diff_pdt_pos = batch_pdt_pos[:, 1:, :] - batch_pdt_pos[:, :-1, :] + diff_tgt_pos = batch_tgt_pos[:, 1:, :] - batch_tgt_pos[:, :-1, :] + loss_vol_pos = self.loss_func_wing(diff_pdt_pos, diff_tgt_pos) / 3 + loss_dict["loss_vol_pos"] = loss_vol_pos.detach() + + loss += loss_vol_exp * self.opt.LOSS.lambda_rec_smooth + loss += loss_vol_pos * self.opt.LOSS.lambda_rec_smooth * 10 + + # total loss + loss_dict['loss_all'] = loss.detach() + + return loss, loss_dict + + + def save_reconstruct(self, samples_pt, path_audio, path_save, suffix=""): + # samples_pt, [B x N x dim_motion] + + B, N, _ = samples_pt.shape + nbatch_render = 10 + + # for each batch + for j in range(B): + jcoeff_pt = samples_pt[j, :, :] + jpath_save = path_save.joinpath(f"{suffix}_{j:02d}.mp4") + + v_render_pt = [] + for k in range(0, N, nbatch_render): + jcodedict_pt = {} + + jcodedict_pt["exp"] = jcoeff_pt[k:k+nbatch_render, :50] # (nbatch_render, 50) + nbatch_real = jcodedict_pt["exp"].shape[0] + + # pose + jcodedict_pt["pose"] = np.repeat([self.mean_dict["pose"]], nbatch_real, axis=0) # (nbatch_render, 6) + jcodedict_pt["pose"][:, 3:6] = jcoeff_pt[k:k+nbatch_render, 50:53] + + # others ==> to mean + mean_cam = [[5,0,0]] # or [self.mean_dict["cam"]] + jcodedict_pt["cam"] = np.repeat(mean_cam, nbatch_real, axis=0) # (nbatch_render, 3) + jcodedict_pt["light"] = np.repeat([self.mean_dict["light"]], nbatch_real, axis=0) # (nbatch_render, 9, 3) + jcodedict_pt["shape"] = np.repeat([self.mean_dict["shape"]], nbatch_real, axis=0) # (nbatch_render, 100) + jcodedict_pt["detail"] = np.repeat([self.mean_dict["detail"]], nbatch_real, axis=0) # (nbatch_render, 128) + + _, visdict_pt = self.netR.decode_one(jcodedict_pt, nbatch_real, self.device) + + render_pt = visdict_pt["shape_images"] # (nbatch_render, 3, 224, 224) + # print(f"render pt shape = {render_pt.shape}") + + for m in range(nbatch_real): + # cv2.imwrite(str(kpath_image), util.tensor2image(render_image[m, ...])) + v_render_pt.append(tensor2image(render_pt[m, ...])) + + # save animation + # print(f"testing v_render_pt = {len(v_render_pt)}") + save_images_with_audio(v_render_pt, path_audio, jpath_save) + + + + def save_reconstruct_with_gt(self, samples_pt, samples_gt, path_save, suffix=""): + # samples_pt, [B x N x dim_motion] + # samples_gt, [B x N x dim_motion] + B, N, _ = samples_pt.shape + nbatch_render = 10 + + # for each batch + for j in range(B): + jcoeff_pt = samples_pt[j, :, :] + jcoeff_gt = samples_gt[j, :, :] + jpath_save = path_save.joinpath(f"{suffix}_{j:02d}.mp4") + + v_render_pt = [] + v_render_gt = [] + + for k in range(0, N, nbatch_render): + jcodedict_pt = {} + jcodedict_gt = {} + + # exp + jcodedict_pt["exp"] = jcoeff_pt[k:k+nbatch_render, :50] # (nbatch_render, 50) + jcodedict_gt["exp"] = jcoeff_gt[k:k+nbatch_render, :50] # (nbatch_render, 50) + nbatch_real = jcodedict_pt["exp"].shape[0] + + # pose + jcodedict_pt["pose"] = np.repeat([self.mean_dict["pose"]], nbatch_real, axis=0) # (nbatch_render, 6) + jcodedict_gt["pose"] = np.repeat([self.mean_dict["pose"]], nbatch_real, axis=0) # (nbatch_render, 6) + jcodedict_pt["pose"][:, 3:6] = jcoeff_pt[k:k+nbatch_render, 50:53] + jcodedict_gt["pose"][:, 3:6] = jcoeff_gt[k:k+nbatch_render, 50:53] + + # others ==> to mean + mean_cam = [[5,0,0]] # or [self.mean_dict["cam"]] + jcodedict_pt["cam"] = np.repeat(mean_cam, nbatch_real, axis=0) # (nbatch_render, 3) + jcodedict_pt["light"] = np.repeat([self.mean_dict["light"]], nbatch_real, axis=0) # (nbatch_render, 9, 3) + jcodedict_pt["shape"] = np.repeat([self.mean_dict["shape"]], nbatch_real, axis=0) # (nbatch_render, 100) + jcodedict_pt["detail"] = np.repeat([self.mean_dict["detail"]], nbatch_real, axis=0) # (nbatch_render, 128) + + jcodedict_gt["cam"] = np.repeat(mean_cam, nbatch_real, axis=0) # (nbatch_render, 3) + jcodedict_gt["light"] = np.repeat([self.mean_dict["light"]], nbatch_real, axis=0) # (nbatch_render, 9, 3) + jcodedict_gt["shape"] = np.repeat([self.mean_dict["shape"]], nbatch_real, axis=0) # (nbatch_render, 100) + jcodedict_gt["detail"] = np.repeat([self.mean_dict["detail"]], nbatch_real, axis=0) # (nbatch_render, 128) + + _, visdict_pt = self.netR.decode_one(jcodedict_pt, nbatch_real, self.device) + _, visdict_gt = self.netR.decode_one(jcodedict_gt, nbatch_real, self.device) + + render_pt = visdict_pt["shape_images"] # (nbatch_render, 3, 224, 224) + render_gt = visdict_gt["shape_images"] # (nbatch_render, 3, 224, 224) + # print(f"render pt shape = {render_pt.shape}, gt {render_gt.shape}") + + for m in range(nbatch_real): + # cv2.imwrite(str(kpath_image), util.tensor2image(render_image[m, ...])) + v_render_pt.append(tensor2image(render_pt[m, ...])) + v_render_gt.append(tensor2image(render_gt[m, ...])) + + # 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, jpath_save, fps=self.opt.DATASET.fps) + + + +######################################### +def tensor2image(tensor): + image = tensor.detach().cpu().numpy() + image = image*255. + image = np.maximum(np.minimum(image, 255), 0) + image = image.transpose(1,2,0)[:,:,[2,1,0]] + return image.astype(np.uint8).copy() + + +def define_netG(opt): + netG = None + + if opt.MODEL.name_netG == "audio2motion_head": + from src.nn.audio2motion_head import Audio2MotionHead + netG = Audio2MotionHead(opt) + + elif opt.MODEL.name_netG == "audio2motion_voca": + from src.nn.audio2motion_voca import Audio2MotionVOCA + netG = Audio2MotionVOCA(opt) + + elif opt.MODEL.name_netG == "audio2motion_voca2": + from src.nn.audio2motion_voca3 import Audio2MotionVOCA3 + netG = Audio2MotionVOCA3(opt) + + elif opt.MODEL.name_netG == "audio2motion_conv": + from src.nn.audio2motion_conv import Audio2MotionConv + netG = Audio2MotionConv(opt) + + elif opt.MODEL.name_netG == "audio2motion": + from src.nn.audio2motion import Audio2Motion + netG = Audio2Motion(opt) + + elif opt.MODEL.name_netG == "audio2motion2": + from src.nn.audio2motion2 import Audio2Motion2 + netG = Audio2Motion2(opt) + else: + raise NameError(f"The model of opt.MODEL.name_netAE(={opt.MODEL.name_netG}) not existing!") + + + return netG + + +def define_netR(device): + # import + sys.path.insert(0, "/ssdata1/lsen/CODE/DECA_old") + from decalib.deca import DECA + from decalib.utils import util + from decalib.utils.config import cfg as deca_cfg + + # use device + # device = "cuda:2" + # whether to use FLAME texture model to generate uv texture map + deca_cfg.model.use_tex = False + deca_cfg.dataset.image_size = 512 + + # reconstruction model + netR = DECA(config = deca_cfg, device=device) + + return netR + + + diff --git a/src/models/model_audio2motion_live2.py b/src/models/model_audio2motion_live2.py new file mode 100644 index 0000000..9f2dfd1 --- /dev/null +++ b/src/models/model_audio2motion_live2.py @@ -0,0 +1,411 @@ +import sys +import numpy as np + +import torch +import torch.nn as nn +import torch.nn.functional as F +from pathlib import Path + +from src.models import init_net +from src.models.base import Base +from src.optims import get_optimizer, get_scheduler + +# common +from common.animation import save_animation_with_gt2, save_images_with_audio +from common.debug import debug +from common.losses import WingLoss + +# disentangle model +class Audio2motionLive2Model(Base): + + def __init__(self, opt, logger): + Base.__init__(self, opt, logger) + + self.opt = opt + self.logger = logger + self.names_model = ["G"] # G + + + # define networks + self.netG = define_netG(opt) + self.netG.to() + self.netG = torch.nn.DataParallel(self.netG, opt.GPUS) # multi-GPUs + init_net(self.netG, init_type='kaiming', gpu_ids=opt.GPUS) + + self.loss_func_l1 = nn.L1Loss(reduction="mean") + self.loss_func_wing = WingLoss(reduction="mean") + + if self.isTrain: + self.names_loss = opt.LOSS.names + + # define optimizers + self.optimizer_G = get_optimizer(self.netG, opt) + self.optimizers.append(self.optimizer_G) + + self.scheduler_G = get_scheduler(self.optimizer_G, opt) + self.schedulers.append(self.scheduler_G) + + if self.opt.TRAIN.apply_testing or not self.isTrain: + # load mean lighting & shape + self.netR = define_netR(device=self.device) + # self.netG.init_reconstruct_model(self.netR) + + path_deca_mean = Path("./data/DECA_obama_mean.npy") + self.mean_dict = np.load(path_deca_mean, allow_pickle=True).item() + print(self.mean_dict.keys()) + + 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) + + + + def set_input(self, batch_input): + + # motion data + self.data = batch_input["data"].float().to(self.device) # (B, nsteps, nc_motion) + + self.batch_vid = batch_input['vid'] + self.batch_nframe = batch_input['nframe'] + self.batch_interv = batch_input['frame_interval'] + + debug(self.opt, f"data = {self.data.shape}, dtype={self.data.dtype}", verbose=False) + debug(self.opt, f"batch_vid = {self.batch_vid[:2]}", verbose=False) + debug(self.opt, f"batch_nframe = {self.batch_nframe[:2]}", verbose=False) + debug(self.opt, f"batch_interv len={len(self.batch_interv)} len([0])={len(self.batch_interv[0])}, \ + beg={self.batch_interv[0][:4]}, end={self.batch_interv[1][:4]}", verbose=False) + + self.B, self.nsteps = self.data.size(0), self.data.size(1) + + # speech data + 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) + 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) + self.cond = output.last_hidden_state + # self.cond = output.extract_features + + # B x nsteps x nc_feat + debug(self.opt, f"data = {self.data.shape}, dtype={self.data.dtype}, device={self.data.device}", verbose=False) + debug(self.opt, f"cond = {self.cond.shape}, dtype={self.cond.dtype}, device={self.cond.device}", verbose=False) + + # unfold + # self.data = self.data.unfold(dimension=1, size=16, step=1) # (B, nseqs, nc_motion, 16) + # self.data = self.data.permute(0, 1, 3, 2) # (B, nseqs, 16, 53) + + self.cond = self.cond.unfold(dimension=1, size=16, step=1) # (nseqs, nc_motion, 16) + self.cond = self.cond.permute(0, 1, 3, 2) # (nseqs, 16, 53) + + self.nseq = self.cond.size(1) + self.data = self.data[:, 7:7+self.nseq, :] + + debug(self.opt, f"\n a data = {self.data.shape}, dtype={self.data.dtype}, device={self.data.device}", verbose=False) + debug(self.opt, f"a cond = {self.cond.shape}, dtype={self.cond.dtype}, device={self.cond.device}", verbose=False) + + def training(self, batch_input): + self.train() # set train model + self.set_input(batch_input) + + # forward + self.pred = self.netG(self.cond) + + # loss + loss, self.loss_dict = self.eval_losses(self.pred, self.data) + + # backward + self.optimizer_G.zero_grad() + loss.backward() + + if self.opt.TRAIN.grad_clip_norm: # operate grad + torch.nn.utils.clip_grad_value_(self.netG.parameters(), self.opt.TRAIN.max_grad_clip) + torch.nn.utils.clip_grad_norm_(self.netG.parameters(), self.opt.TRAIN.max_grad_norm) + + self.optimizer_G.step() + + return loss + + + def validation(self, batch_input): + self.eval() # set eval model + self.set_input(batch_input) + + with torch.no_grad(): + self.pred = self.netG(self.cond) + loss, self.loss_dict = self.eval_losses(self.pred, self.data) + + return loss + + + def infer(self, batch_cond, path_audio, suffix=""): + self.eval() + self.cond = batch_cond.float().to(self.device) # (nsteps, dim_cond) + + with torch.no_grad(): + samples_pt = self.netG(self.cond).cpu().numpy() # B x N x dim_motion + print(f"testing pt shape = {samples_pt.shape}") + + self.save_reconstruct(samples_pt, path_audio, + path_save=Path(self.opt.OUTPUT_DIR), + suffix=suffix) + + + def testing(self, batch_input, cur_epoch=0, cur_batch=0): + self.eval() # set eval model + self.set_input(batch_input) + + with torch.no_grad(): + samples_pt = self.netG(self.cond).cpu().numpy() # B x N x dim_motion + samples_gt = self.data.cpu().numpy() # B x N x dim_motion + + print(f"testing pt shape = {samples_pt.shape}, gt shape = {samples_gt.shape}") + + self.save_reconstruct_with_gt(samples_pt, samples_gt, + path_save=Path(self.opt.OUTPUT_DIR), + suffix=f'sampled_{cur_epoch:05d}_{cur_batch:03d}') + + + def eval_losses(self, batch_pdt, batch_tgt): + """ Computes the VAE loss function. + pramas: + batch_pred, (nbatch, seqlen, dim_motion) + batch_targt, (nbatch, seqlen, dim_motion) + """ + loss = 0 + loss_dict = {} + + batch_pdt_exp = batch_pdt[..., :50] + batch_pdt_pos = batch_pdt[..., 50:] + + batch_tgt_exp = batch_tgt[..., :50] + batch_tgt_pos = batch_tgt[..., 50:] + + + # rec loss + loss = 0 + loss_rec_exp = self.loss_func_wing(batch_pdt_exp, batch_tgt_exp) / 50 + loss_dict["loss_rec_exp"] = loss_rec_exp.detach() + + loss_rec_pos = self.loss_func_wing(batch_pdt_pos, batch_tgt_pos) / 3 + loss_dict["loss_rec_pos"] = loss_rec_pos.detach() + + loss += loss_rec_exp * self.opt.LOSS.lambda_rec_exp + loss += loss_rec_pos * self.opt.LOSS.lambda_rec_pos + + + # rec smooth + diff_pdt_exp = batch_pdt_exp[:, 1:, :] - batch_pdt_exp[:, :-1, :] + diff_tgt_exp = batch_tgt_exp[:, 1:, :] - batch_tgt_exp[:, :-1, :] + loss_vol_exp = self.loss_func_wing(diff_pdt_exp, diff_tgt_exp) / 50 + loss_dict["loss_vol_exp"] = loss_vol_exp.detach() + + diff_pdt_pos = batch_pdt_pos[:, 1:, :] - batch_pdt_pos[:, :-1, :] + diff_tgt_pos = batch_tgt_pos[:, 1:, :] - batch_tgt_pos[:, :-1, :] + loss_vol_pos = self.loss_func_wing(diff_pdt_pos, diff_tgt_pos) / 3 + loss_dict["loss_vol_pos"] = loss_vol_pos.detach() + + loss += loss_vol_exp * self.opt.LOSS.lambda_vol_exp + loss += loss_vol_pos * self.opt.LOSS.lambda_vol_pos + + # total loss + loss_dict['loss_all'] = loss.detach() + + return loss, loss_dict + + + def save_reconstruct(self, samples_pt, path_audio, path_save, suffix=""): + # samples_pt, [B x N x dim_motion] + + B, N, _ = samples_pt.shape + nbatch_render = 10 + + # for each batch + for j in range(B): + jcoeff_pt = samples_pt[j, :, :] + jpath_save = path_save.joinpath(f"{suffix}_{j:02d}.mp4") + + v_render_pt = [] + for k in range(0, N, nbatch_render): + jcodedict_pt = {} + + jcodedict_pt["exp"] = jcoeff_pt[k:k+nbatch_render, :50] # (nbatch_render, 50) + nbatch_real = jcodedict_pt["exp"].shape[0] + + # pose + jcodedict_pt["pose"] = np.repeat([self.mean_dict["pose"]], nbatch_real, axis=0) # (nbatch_render, 6) + jcodedict_pt["pose"][:, 3:6] = jcoeff_pt[k:k+nbatch_render, 50:53] + + # others ==> to mean + mean_cam = [[5,0,0]] # or [self.mean_dict["cam"]] + jcodedict_pt["cam"] = np.repeat(mean_cam, nbatch_real, axis=0) # (nbatch_render, 3) + jcodedict_pt["light"] = np.repeat([self.mean_dict["light"]], nbatch_real, axis=0) # (nbatch_render, 9, 3) + jcodedict_pt["shape"] = np.repeat([self.mean_dict["shape"]], nbatch_real, axis=0) # (nbatch_render, 100) + jcodedict_pt["detail"] = np.repeat([self.mean_dict["detail"]], nbatch_real, axis=0) # (nbatch_render, 128) + + _, visdict_pt = self.netR.decode_one(jcodedict_pt, nbatch_real, self.device) + + render_pt = visdict_pt["shape_images"] # (nbatch_render, 3, 224, 224) + # print(f"render pt shape = {render_pt.shape}") + + for m in range(nbatch_real): + # cv2.imwrite(str(kpath_image), util.tensor2image(render_image[m, ...])) + v_render_pt.append(tensor2image(render_pt[m, ...])) + + # save animation + # print(f"testing v_render_pt = {len(v_render_pt)}") + save_images_with_audio(v_render_pt, path_audio, jpath_save) + + + def save_reconstruct_with_gt(self, samples_pt, samples_gt, path_save, suffix=""): + # samples_pt, [B x N x dim_motion] + # samples_gt, [B x N x dim_motion] + B, N, _ = samples_pt.shape + nbatch_render = 10 + + # for each batch + for j in range(B): + jcoeff_pt = samples_pt[j, :, :] + jcoeff_gt = samples_gt[j, :, :] + jpath_save = path_save.joinpath(f"{suffix}_{j:02d}.mp4") + + v_render_pt = [] + v_render_gt = [] + + for k in range(0, N, nbatch_render): + jcodedict_pt = {} + jcodedict_gt = {} + + # exp + jcodedict_pt["exp"] = jcoeff_pt[k:k+nbatch_render, :50] # (nbatch_render, 50) + jcodedict_gt["exp"] = jcoeff_gt[k:k+nbatch_render, :50] # (nbatch_render, 50) + nbatch_real = jcodedict_pt["exp"].shape[0] + + # pose + jcodedict_pt["pose"] = np.repeat([self.mean_dict["pose"]], nbatch_real, axis=0) # (nbatch_render, 6) + jcodedict_gt["pose"] = np.repeat([self.mean_dict["pose"]], nbatch_real, axis=0) # (nbatch_render, 6) + jcodedict_pt["pose"][:, 3:6] = jcoeff_pt[k:k+nbatch_render, 50:53] + jcodedict_gt["pose"][:, 3:6] = jcoeff_gt[k:k+nbatch_render, 50:53] + + # others ==> to mean + mean_cam = [[5,0,0]] # or [self.mean_dict["cam"]] + jcodedict_pt["cam"] = np.repeat(mean_cam, nbatch_real, axis=0) # (nbatch_render, 3) + jcodedict_pt["light"] = np.repeat([self.mean_dict["light"]], nbatch_real, axis=0) # (nbatch_render, 9, 3) + jcodedict_pt["shape"] = np.repeat([self.mean_dict["shape"]], nbatch_real, axis=0) # (nbatch_render, 100) + jcodedict_pt["detail"] = np.repeat([self.mean_dict["detail"]], nbatch_real, axis=0) # (nbatch_render, 128) + + jcodedict_gt["cam"] = np.repeat(mean_cam, nbatch_real, axis=0) # (nbatch_render, 3) + jcodedict_gt["light"] = np.repeat([self.mean_dict["light"]], nbatch_real, axis=0) # (nbatch_render, 9, 3) + jcodedict_gt["shape"] = np.repeat([self.mean_dict["shape"]], nbatch_real, axis=0) # (nbatch_render, 100) + jcodedict_gt["detail"] = np.repeat([self.mean_dict["detail"]], nbatch_real, axis=0) # (nbatch_render, 128) + + _, visdict_pt = self.netR.decode_one(jcodedict_pt, nbatch_real, self.device) + _, visdict_gt = self.netR.decode_one(jcodedict_gt, nbatch_real, self.device) + + render_pt = visdict_pt["shape_images"] # (nbatch_render, 3, 224, 224) + render_gt = visdict_gt["shape_images"] # (nbatch_render, 3, 224, 224) + # print(f"render pt shape = {render_pt.shape}, gt {render_gt.shape}") + + for m in range(nbatch_real): + # cv2.imwrite(str(kpath_image), util.tensor2image(render_image[m, ...])) + v_render_pt.append(tensor2image(render_pt[m, ...])) + v_render_gt.append(tensor2image(render_gt[m, ...])) + + # get audio + jvid = self.batch_vid[j] + jnframe = self.batch_nframe[j].numpy() + jstart_frame = self.batch_interv[0][j].numpy() + + jpath_audio = f"/yrfs/lsen/DATA/LuoXData/processing2/{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, jpath_save, fps=self.opt.DATASET.fps,\ + path_audio=jpath_audio, start_time=jstart_time, end_time=jend_time) + + +######################################### +def tensor2image(tensor): + image = tensor.detach().cpu().numpy() + image = image*255. + image = np.maximum(np.minimum(image, 255), 0) + image = image.transpose(1,2,0)[:,:,[2,1,0]] + return image.astype(np.uint8).copy() + + +def define_netG(opt): + netG = None + + if opt.MODEL.name_netG == "audio2motion_voca4": + from src.nn.audio2motion_voca4 import Audio2MotionVOCA + netG = Audio2MotionVOCA(opt) + + elif opt.MODEL.name_netG == "audio2motion_voca": + from src.nn.audio2motion_voca import Audio2MotionVOCA + netG = Audio2MotionVOCA(opt) + + elif opt.MODEL.name_netG == "audio2motion_voca3": + from src.nn.audio2motion_voca3 import Audio2MotionVOCA3 + netG = Audio2MotionVOCA3(opt) + + elif opt.MODEL.name_netG == "audio2motion_voca33": + from src.nn.audio2motion_voca33 import Audio2MotionVOCA + netG = Audio2MotionVOCA(opt) + + elif opt.MODEL.name_netG == "audio2motion": + from src.nn.audio2motion import Audio2Motion + netG = Audio2Motion(opt) + + elif opt.MODEL.name_netG == "audio2motion2": + from src.nn.audio2motion2 import Audio2Motion2 + netG = Audio2Motion2(opt) + else: + raise NameError(f"The model of opt.MODEL.name_netAE(={opt.MODEL.name_netG}) not existing!") + + + return netG + + +def define_netR(device): + # import + sys.path.insert(0, "/ssdata1/lsen/CODE/DECA_old") + from decalib.deca import DECA + from decalib.utils import util + from decalib.utils.config import cfg as deca_cfg + + # use device + # device = "cuda:2" + # whether to use FLAME texture model to generate uv texture map + deca_cfg.model.use_tex = False + deca_cfg.dataset.image_size = 512 + + # reconstruction model + netR = DECA(config = deca_cfg, device=device) + + return netR + + + diff --git a/src/nn/audio2motion.py b/src/nn/audio2motion.py index b23ccf3..9022b7a 100644 --- a/src/nn/audio2motion.py +++ b/src/nn/audio2motion.py @@ -25,12 +25,14 @@ class Audio2Motion(nn.Module): nn.Linear(in_features=self.dim_condit, out_features=self.dim_hidden), nn.LayerNorm(self.dim_hidden), nn.LeakyReLU(0.2), + nn.Dropout(0.5), nn.Linear(in_features=self.dim_hidden, out_features=4*self.dim_hidden), nn.LayerNorm(4*self.dim_hidden), nn.LeakyReLU(0.2), nn.Dropout(0.1), - + nn.Dropout(0.5), + nn.Linear(in_features=4*self.dim_hidden, out_features=self.dim_hidden), ) @@ -49,17 +51,17 @@ class Audio2Motion(nn.Module): nn.Linear(in_features=self.dim_hidden, out_features=4*self.dim_hidden), nn.LayerNorm(4*self.dim_hidden), nn.LeakyReLU(0.2), - nn.Dropout(0.1), + nn.Dropout(0.5), nn.Linear(in_features=4*self.dim_hidden, out_features=4*self.dim_hidden), nn.LayerNorm(4*self.dim_hidden), nn.LeakyReLU(0.2), - nn.Dropout(0.1), + nn.Dropout(0.5), nn.Linear(in_features=4*self.dim_hidden, out_features=self.dim_hidden), nn.LayerNorm(self.dim_hidden), nn.LeakyReLU(0.2), - nn.Dropout(0.1), + nn.Dropout(0.5), nn.Linear(in_features=self.dim_hidden, out_features=self.dim_motion), nn.Tanh() diff --git a/src/nn/audio2motion2.py b/src/nn/audio2motion2.py new file mode 100644 index 0000000..81ae220 --- /dev/null +++ b/src/nn/audio2motion2.py @@ -0,0 +1,84 @@ +import torch +import torch.nn as nn +from common.debug import debug + +class Audio2Motion2(nn.Module): + + def __init__(self, opt): + super(Audio2Motion2, self).__init__() + + self.opt = opt + nseqR_m = opt.MODEL.n_lookprevs_motion # 3 + nseqR_s = opt.MODEL.n_lookprevs_speech # 3 + nseqL_s = opt.MODEL.n_lookahead_speech # 1 + + nLSTM = opt.MODEL.n_layer_lstm # 3 + + self.dim_motion = opt.MODEL.dim_motion # 53 + self.dim_speech = opt.MODEL.dim_speech # 27 + self.dim_hidden = opt.MODEL.dim_hidden # 256 + self.dim_condit = self.dim_motion * nseqR_m + self.dim_speech * (nseqR_s + 1 + nseqL_s) + print(f"dim_condit={self.dim_condit}") + + # encoder + self.encoder = nn.Sequential( # nbatch x nseqlen x 27 + nn.Linear(in_features=self.dim_condit, out_features=self.dim_hidden), + nn.LeakyReLU(0.2), + + nn.Linear(in_features=self.dim_hidden, out_features=4*self.dim_hidden), + nn.LeakyReLU(0.2), + + nn.Linear(in_features=4*self.dim_hidden, out_features=self.dim_hidden), + ) + + # lstm + self.LSTM = nn.LSTM( + input_size = self.dim_hidden, + hidden_size = self.dim_hidden, + num_layers= nLSTM, + dropout = 0, + bidirectional=False, + batch_first = True + ) + + # output + self.decoder = nn.Sequential( + nn.Linear(in_features=self.dim_hidden, out_features=4*self.dim_hidden), + nn.LeakyReLU(0.2), + + nn.Linear(in_features=4*self.dim_hidden, out_features=4*self.dim_hidden), + nn.LeakyReLU(0.2), + + nn.Linear(in_features=4*self.dim_hidden, out_features=self.dim_hidden), + nn.LeakyReLU(0.2), + + nn.Linear(in_features=self.dim_hidden, out_features=self.dim_motion), + nn.Tanh() + ) + + def forward(self, x): + """ forward function + Args: + x: torch.Tensor, [nbatch x seqlen x dim_condit] + target: torch.Tensor, [nbatch x seqlen x dim_motion] + return: + pred: torch.Tensor, [nbatch x seqlen x dim_motion] + """ + + (nbatch, nseqlen, nfeat) = x.shape + debug(self.opt, f"[forward] input x shape = {x.shape}", verbose=False) + + feat = self.encoder(x) # [nbatch x nseqlen x dim_hidden] + debug(self.opt, f"[forward] encoder shape = {feat.shape}", verbose=False) + + + feat, _ = self.LSTM(feat) # [nbatch x nseqlen x dim_hidden] + debug(self.opt, f"[forward] lstm shape = {feat.shape}", verbose=False) + + + pred = self.decoder(feat) # [nbatch x nseqlen x dim_motion] + debug(self.opt, f"[forward] decoder shape = {pred.shape}", verbose=False) + + return pred + + diff --git a/src/nn/audio2motion_head.py b/src/nn/audio2motion_head.py new file mode 100644 index 0000000..19c775d --- /dev/null +++ b/src/nn/audio2motion_head.py @@ -0,0 +1,40 @@ +import torch +import torch.nn as nn +from common.debug import debug + +class Audio2MotionHead(nn.Module): + + def __init__(self, opt): + super(Audio2MotionHead, self).__init__() + + self.opt = opt + self.dim_motion = opt.MODEL.dim_motion # 53 + self.dim_speech = opt.MODEL.dim_speech # 27 + print(f"dim_speech={self.dim_speech}") + + # encoder + self.head = nn.Sequential( # nbatch x nseqlen x 27 + nn.Linear(in_features=self.dim_speech, out_features=256), + nn.LeakyReLU(0.2), + + nn.Linear(in_features=256, out_features=self.dim_motion), + nn.Tanh() + ) + + + def forward(self, x): + """ forward function + Args: + x: torch.Tensor, [nbatch x seqlen x dim_condit] + return: + pred: torch.Tensor, [nbatch x seqlen x dim_motion] + """ + debug(self.opt, f"[forward] input x shape = {x.shape}", verbose=False) + + pred = self.head(x) # [nbatch x nseqlen x dim_hidden] + + debug(self.opt, f"[forward] decoder shape = {pred.shape}", verbose=False) + + return pred + + diff --git a/src/nn/audio2motion_voca3.py b/src/nn/audio2motion_voca3.py new file mode 100644 index 0000000..dee64e6 --- /dev/null +++ b/src/nn/audio2motion_voca3.py @@ -0,0 +1,78 @@ +import torch +import torch.nn as nn +from common.debug import debug + +class Audio2MotionVOCA3(nn.Module): + + def __init__(self, opt): + super(Audio2MotionVOCA3, self).__init__() + + self.opt = opt + self.dim_motion = opt.MODEL.dim_motion # 53 + self.dim_speech = opt.MODEL.dim_speech # 29 + self.dim_hidden = opt.MODEL.dim_hidden # 256 + + # encoder + self.encoder = nn.Sequential( # (nbatch, nchannel=29, H=16, W=1) + nn.BatchNorm2d(self.dim_speech), + + # block 1 + nn.Conv2d(self.dim_speech, 512, kernel_size=(3,1), stride=(2,1), padding=(1,0), bias=True), # 32 x 8 x 1 + nn.LeakyReLU(0.02, True), + + nn.Conv2d(512, 512, kernel_size=(3,1), stride=(2,1), padding=(1,0), bias=True), # 32 x 4 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=(2,1), padding=(1,0), bias=True), # 64 x 1 x 1 + nn.LeakyReLU(0.02, True), + + nn.Conv2d(256, 128, kernel_size=(3,1), stride=(2,1), padding=(1,0), bias=True), # 64 x 1 x 1 + nn.LeakyReLU(0.02, True), + + nn.Flatten(), # 64, + + nn.Linear(in_features=128, out_features=1024), # 128, + nn.Tanh(), + + nn.Linear(in_features=1024, out_features=128) # 50, + ) + + + # output + self.decoder = nn.Sequential( + nn.Linear(in_features=128, out_features=self.dim_motion), + ) + + + def forward(self, x): + """ forward function + Args: + x: torch.Tensor, [nbatch x seqlen x nwind x dim_condit] + return: + pred: torch.Tensor, [nbatch x seqlen x dim_motion] + """ + (nbatch, nseqlen, nwind, nfeat) = x.shape # (B, nseq, 16, 29) + debug(self.opt, f"[forward] input x shape = {x.shape}", verbose=False) + + # preprocessing data + x = x.reshape(nbatch * nseqlen, 1, nwind, nfeat) # (B * nseq, 1, 16, 29) + x = torch.transpose(x, 1, 3) # (B * nseq, 29, 16, 1) + debug(self.opt, f"[forward] transpose x shape = {x.shape}", verbose=False) + + + feat = self.encoder(x) # (B * nseq, 50) + debug(self.opt, f"[forward] encoder shape = {feat.shape}", verbose=False) + + + pred = self.decoder(feat) # (B * nseq, dim_motion) + debug(self.opt, f"[forward] decoder shape = {pred.shape}", verbose=False) + + pred = pred.reshape(nbatch, nseqlen, -1) # (B, nseq, dim_motion) + debug(self.opt, f"[forward] reshape shape = {pred.shape}", verbose=False) + + return pred + + diff --git a/src/nn/audio2motion_voca33.py b/src/nn/audio2motion_voca33.py new file mode 100644 index 0000000..dd452dc --- /dev/null +++ b/src/nn/audio2motion_voca33.py @@ -0,0 +1,89 @@ +import torch +import torch.nn as nn +from common.debug import debug + +class Audio2MotionVOCA(nn.Module): + + def __init__(self, opt): + super(Audio2MotionVOCA, self).__init__() + + self.opt = opt + self.dim_motion = opt.MODEL.dim_motion # 53 + self.dim_speech = opt.MODEL.dim_speech # 29 + self.dim_hidden = opt.MODEL.dim_hidden # 256 + + # encoder + self.encoder = nn.Sequential( # (nbatch, nchannel=29, H=16, W=1) + nn.BatchNorm2d(self.dim_speech), + + # block 1 + nn.Conv2d(self.dim_speech, 512, kernel_size=(3,1), stride=(2,1), padding=(1,0), bias=True), # 32 x 8 x 1 + nn.LeakyReLU(0.02, True), + 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, 512, kernel_size=(3,1), stride=(2,1), padding=(1,0), bias=True), # 32 x 4 x 1 + nn.LeakyReLU(0.02, True), + 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 + nn.LeakyReLU(0.02, True), + + nn.Conv2d(256, 128, kernel_size=(3,1), stride=(2,1), padding=(1,0), bias=True), # 64 x 1 x 1 + nn.LeakyReLU(0.02, True), + + nn.Flatten(), # 64, + + nn.Linear(in_features=128, out_features=2048), # 128, + nn.Tanh(), + + nn.Linear(in_features=2048, out_features=128) # 50, + ) + + + # output + self.decoder = nn.Sequential( + nn.Linear(in_features=128, out_features=self.dim_motion), + ) + + + def forward(self, x): + """ forward function + Args: + x: torch.Tensor, [nbatch x seqlen x nwind x dim_condit] + return: + pred: torch.Tensor, [nbatch x seqlen x dim_motion] + """ + (nbatch, nseqlen, nwind, nfeat) = x.shape # (B, nseq, 16, 29) + debug(self.opt, f"[forward] input x shape = {x.shape}", verbose=False) + + # preprocessing data + x = x.reshape(nbatch * nseqlen, 1, nwind, nfeat) # (B * nseq, 1, 16, 29) + x = torch.transpose(x, 1, 3) # (B * nseq, 29, 16, 1) + debug(self.opt, f"[forward] transpose x shape = {x.shape}", verbose=False) + + + feat = self.encoder(x) # (B * nseq, 50) + debug(self.opt, f"[forward] encoder shape = {feat.shape}", verbose=False) + + + pred = self.decoder(feat) # (B * nseq, dim_motion) + debug(self.opt, f"[forward] decoder shape = {pred.shape}", verbose=False) + + pred = pred.reshape(nbatch, nseqlen, -1) # (B, nseq, dim_motion) + debug(self.opt, f"[forward] reshape shape = {pred.shape}", verbose=False) + + return pred + + diff --git a/src/nn/audio2motion_voca4.py b/src/nn/audio2motion_voca4.py new file mode 100644 index 0000000..f092ca7 --- /dev/null +++ b/src/nn/audio2motion_voca4.py @@ -0,0 +1,107 @@ +import torch +import torch.nn as nn +from common.debug import debug + +class Audio2MotionVOCA(nn.Module): + + def __init__(self, opt): + super(Audio2MotionVOCA, self).__init__() + + self.opt = opt + self.dim_motion = opt.MODEL.dim_motion # 53 + self.dim_speech = opt.MODEL.dim_speech # 29 + self.dim_hidden = opt.MODEL.dim_hidden # 256 + + # encoder + self.encoder = nn.Sequential( # (nbatch, nchannel=29, H=16, W=1) + nn.BatchNorm2d(self.dim_speech), + + + # block 1 + nn.Conv2d(self.dim_speech, 128, kernel_size=(3,1), stride=(1,1), padding=(1,0), bias=True), # 128 x 16 x 1 + nn.BatchNorm2d(128), + nn.LeakyReLU(0.02, True), + nn.Conv2d(128, 128, kernel_size=(3,1), stride=(1,1), padding=(1,0), bias=True), # 128 x 16 x 1 + nn.BatchNorm2d(128), + nn.LeakyReLU(0.02, True), + nn.Conv2d(128, 128, kernel_size=(3,1), stride=(1,1), padding=(1,0), bias=True), # 128 x 16 x 1 + nn.BatchNorm2d(128), + nn.LeakyReLU(0.02, True), + + # block 2 + nn.Conv2d(128, 256, kernel_size=(3,1), stride=(2,1), padding=(1,0), bias=True), # 256 x 8 x 1 + nn.BatchNorm2d(256), + nn.LeakyReLU(0.02, True), + nn.Conv2d(256, 256, kernel_size=(3,1), stride=(1,1), padding=(1,0), bias=True), # 256 x 8 x 1 + nn.BatchNorm2d(256), + nn.LeakyReLU(0.02, True), + nn.Conv2d(256, 256, kernel_size=(3,1), stride=(1,1), padding=(1,0), bias=True), # 256 x 8 x 1 + nn.BatchNorm2d(256), + nn.LeakyReLU(0.02, True), + nn.Conv2d(256, 512, kernel_size=(3,1), stride=(1,1), padding=(1,0), bias=True), # 512 x 8 x 1 + nn.BatchNorm2d(512), + nn.LeakyReLU(0.02, True), + + + # block 3 + nn.Conv2d(512, 512, kernel_size=(3,1), stride=(2,1), padding=(1,0), bias=True), # 512 x 4 x 1 + nn.BatchNorm2d(512), + nn.LeakyReLU(0.02, True), + nn.Conv2d(512, 512, kernel_size=(3,1), stride=(1,1), padding=(1,0), bias=True), # 512 x 4 x 1 + nn.BatchNorm2d(512), + nn.LeakyReLU(0.02, True), + nn.Conv2d(512, 512, kernel_size=(3,1), stride=(2,1), padding=(1,0), bias=True), # 512 x 2 x 1 + nn.BatchNorm2d(512), + nn.LeakyReLU(0.02, True), + nn.Conv2d(512, 512, kernel_size=(3,1), stride=(2,1), padding=(1,0), bias=True), # 512 x 1 x 1 + nn.BatchNorm2d(512), + nn.LeakyReLU(0.02, True), + + + nn.Flatten(), # 256, + + nn.Linear(in_features=512, out_features=128), # 2014, + nn.Tanh(), + + nn.Linear(in_features=128, out_features=2048), # 2014, + nn.Tanh(), + + nn.Linear(in_features=2048, out_features=128) # 128, + ) + + + # output + self.decoder = nn.Sequential( + nn.Linear(in_features=128, out_features=self.dim_motion), + ) + + + def forward(self, x): + """ forward function + Args: + x: torch.Tensor, [nbatch x seqlen x nwind x dim_condit] + return: + pred: torch.Tensor, [nbatch x seqlen x dim_motion] + """ + (nbatch, nseqlen, nwind, nfeat) = x.shape # (B, nseq, 16, 29) + debug(self.opt, f"[forward] input x shape = {x.shape}", verbose=False) + + # preprocessing data + x = x.reshape(nbatch * nseqlen, 1, nwind, nfeat) # (B * nseq, 1, 16, 29) + x = torch.transpose(x, 1, 3) # (B * nseq, 29, 16, 1) + debug(self.opt, f"[forward] transpose x shape = {x.shape}", verbose=False) + + + feat = self.encoder(x) # (B * nseq, 50) + debug(self.opt, f"[forward] encoder shape = {feat.shape}", verbose=False) + + + pred = self.decoder(feat) # (B * nseq, dim_motion) + debug(self.opt, f"[forward] decoder shape = {pred.shape}", verbose=False) + + pred = pred.reshape(nbatch, nseqlen, -1) # (B, nseq, dim_motion) + debug(self.opt, f"[forward] reshape shape = {pred.shape}", verbose=False) + + return pred + + diff --git a/train.py b/train.py index 4c13d35..1b393b1 100644 --- a/train.py +++ b/train.py @@ -5,6 +5,12 @@ import shutil import argparse from pathlib import Path +import torch +import numpy as np +# from torch.utils.tensorboard import SummaryWriter + +# writer = SummaryWriter(log_dir='tb', flush_secs=30) + import torch from torch.utils.data import DataLoader @@ -62,7 +68,7 @@ if __name__ == "__main__": valid_dataset = create_dataset(opt, phase='valid') valid_loader = DataLoader(valid_dataset, batch_size=opt.TRAIN.batch_size * len(opt.GPUS), - shuffle=False, + shuffle=True, num_workers=opt.WORKERS, pin_memory=False) logger.info(f"validation dataset size = {len(valid_dataset)}, batch = {len(valid_loader)}") @@ -128,8 +134,15 @@ if __name__ == "__main__": loss_valid = 0 for iv, ibatch_valid in enumerate(valid_loader): # if iv > 100: break - loss_valid += model.validation(ibatch_valid) # forward and backward - + loss_valid += model.validation(ibatch_valid) # forward and backward + + # print logger + if (iv+1) % opt.FREQ.batch_print == 0 and epoch % opt.FREQ.epoch_print == 0: + losses = model.get_current_losses() # pach to loss dict + visor.print_current_losses(epoch, iv, losses) + visor.plot_current_losses_valid(epoch, float(iv)/len(valid_loader), losses) + + logger.info(f"validation loss = {loss_valid /(iv+1) }") # len(valid_loader)