diff --git a/common/animation.py b/common/animation.py index def2c13..6d9ba6e 100644 --- a/common/animation.py +++ b/common/animation.py @@ -2,7 +2,7 @@ import moviepy.editor as mpy import numpy as np import sys -sys.path.insert(0, "/mnt/data/CODE/Audio2Expression") +# sys.path.insert(0, "/ssdata1/lsen/CODE/Audio2Motion") from common.landmark import landmark_to_images @@ -136,6 +136,9 @@ def save_animation_with_gts(images_list, path_save): animation = mpy.clips_array([animations]) animation.write_videofile(str(path_save), fps=fps, logger=None) + # close + animation.close() + def save_images_with_audio(images, path_audio, path_save): """ convert images_pt to .mp4 animation images_pt, shape len=N list [224, 224, 3] @@ -153,7 +156,6 @@ def save_images_with_audio(images, path_audio, path_save): # print(f"load audio form np.ndarray") # audioclip = mpy.AudioFileClip(path_audio, fps=16000) - duration = audioclip.duration # add video @@ -165,30 +167,11 @@ def save_images_with_audio(images, path_audio, path_save): animation.write_videofile(str(path_save), fps=fps) print(f"fps = {fps}, N ={N}, duration={duration} -> save to = {path_save}") + # close + audioclip.close() + animation.close() -def save_animation_with_gt5(images_pt, images_gt, images_A, images_B, images_C, path_save): - """ 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 - N = len(images_pt) - duration = N / fps - # print(f"fps = {fps}, N ={N}, duration={duration}") - - # assert len(images_pt) == len(images_gt), f"pt and gt imamge size not the same ({len(images_pt)}, {len(images_pt)})" - animation_pt = mpy.VideoClip(lambda t: images_pt[int(fps * t + 0.5) -1], duration= duration) - animation_gt = mpy.VideoClip(lambda t: images_gt[int(fps * t + 0.5) -1], duration= duration) - animation_A = mpy.VideoClip(lambda t: images_A[int(fps * t + 0.5) -1], duration= duration) - animation_B = mpy.VideoClip(lambda t: images_B[int(fps * t + 0.5) -1], duration= duration) - animation_C = mpy.VideoClip(lambda t: images_C[int(fps * t + 0.5) -1], duration= duration) - - # mixture & save - animation = mpy.clips_array([[animation_pt, animation_gt, animation_A, animation_B, animation_C]]) - animation.write_videofile(str(path_save), fps=fps, logger=None) - 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 @@ -228,14 +211,20 @@ def save_animation_with_gt2(images_pt, images_gt, path_save, fps=None, path_audi animation.write_videofile(str(path_save), fps=fps) + + # close + animation_pt.close() + animation_gt.close() + animation.close() + -def save_animation_with_gt(data_motion, data_motion_gt, path_save, suffix, w=128*5, h=72*5, dpi=80, maxsave=3): +def save_animation_with_gt(data_motion, data_motion_gt, path_save, suffix, w=128*5, h=72*5, dpi=80, maxsave=3, fps=30): """ convert data_motion to .mp4 animation data_motion, shape [B, N, 68, 2] data_motion_gt, shape [B, N, 68, 2] """ - fps = 30 + B, *_ = data_motion.shape B = min(B, maxsave) @@ -258,4 +247,9 @@ def save_animation_with_gt(data_motion, data_motion_gt, path_save, suffix, w=128 ipath_save = path_save.joinpath(f"{suffix}_{i:02d}.mp4") animation.write_videofile(str(ipath_save), fps=fps, logger=None) + # close + animation_pt.close() + animation_gt.close() + animation.close() + diff --git a/common/debug.py b/common/debug.py index 86045ef..13c72cb 100644 --- a/common/debug.py +++ b/common/debug.py @@ -1,5 +1,9 @@ -def debug(opt, msg, verbose=False): +def debug(opt=None, msg="", verbose=False): + + if opt is None or verbose: + print(msg) + if opt.DEBUG or verbose: print(msg) diff --git a/experiments/audio2mesh/infer_audio2mesh_CN_20220208.yaml b/experiments/audio2mesh/infer_audio2mesh_CN_20220208.yaml new file mode 100644 index 0000000..39b0692 --- /dev/null +++ b/experiments/audio2mesh/infer_audio2mesh_CN_20220208.yaml @@ -0,0 +1,57 @@ +GPUS: '2' +WORKERS: 8 +OUTPUT_DIR: 'experiments/audio2mesh' + +DEBUG: False +verbose: False +isTrain: False + + +MODEL: + name: 'audio2mesh_specific' + name_netG: "audio2mesh" + + dim_motion: 53 # 68*2 + dim_speech: 1024 + num_vertices: 5023 + + + pretrain: True + path_checkpoint: "experiments/audio2mesh/train_audio2mesh_CN_20220220/20220222-10H37M51S" + load_epoch: 235 + +DATASET: + fps: 50 + sr: 16000 + name: "motion_live" + root: './data/LuoXData-raw-deca-16h' # obama-deca-3-5-08-mini + root_raw: '/yrfs/lsen/DATA/LuoXData/processing2' + path_mean_dict: './data/DECA_LuoXData_mean.npy' + filter: 'savgol' + speech_extractor: 'wav2vec' + + nwind_second_train: 3 + nwind_second_valid: 3 + nwind_second_test: 15 + +TEST: + batch_size: 2 + +TRAIN: + lr: 0.00001 + 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: True + grad_clip_norm: False + lr_policy: 'multistep' + lr_milestones: [50, 100] + # lr_policy: 'plateau' diff --git a/experiments/audio2mesh/infer_audio2mesh_EN_20220208.yaml b/experiments/audio2mesh/infer_audio2mesh_EN_20220208.yaml new file mode 100644 index 0000000..f549e24 --- /dev/null +++ b/experiments/audio2mesh/infer_audio2mesh_EN_20220208.yaml @@ -0,0 +1,52 @@ +GPUS: '2' +WORKERS: 8 +OUTPUT_DIR: 'experiments/audio2mesh' + +DEBUG: False +verbose: False +isTrain: False + +MODEL: + name: 'audio2mesh' + # name: 'audio2mesh_specific' + name_netG: "audio2mesh" + + dim_motion: 53 # 68*2 + dim_speech: 1024 + num_vertices: 5023 + + pretrain: True + path_checkpoint: "experiments/audio2mesh/train_audio2mesh_EN_20220208/20220217-17H36M22S" + load_epoch: 115 + + +DATASET: + fps: 50 + sr: 16000 + name: "motion_live" + root: './data/obama-raw-deca-9h-50fps' # obama-deca-3-5-08-mini + root_raw: '/yrfs/lsen/DATA/Obama/processing' + path_mean_dict: './data/DECA_obama_mean.npy' + filter: 'savgol' + speech_extractor: 'wav2vec' + + +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: True + grad_clip_norm: False + # lr_policy: 'multistep' + # lr_milestones: [50, 100, 200] + lr_policy: 'plateau' + diff --git a/experiments/audio2mesh/train_audio2meshF_CN_20220218.yaml b/experiments/audio2mesh/train_audio2meshF_CN_20220218.yaml new file mode 100644 index 0000000..8608db9 --- /dev/null +++ b/experiments/audio2mesh/train_audio2meshF_CN_20220218.yaml @@ -0,0 +1,94 @@ +GPUS: '9' +WORKERS: 8 +OUTPUT_DIR: 'experiments/audio2mesh' + +DEBUG: False +verbose: False + + +VISUAL: + use_HTML: False + use_visdom: True + vsdm_port: 9900 + vsdm_ncol: 4 + vsdm_env: "audio2meshF-cn" + +FREQ: + epoch_save: 1 + epoch_valid: 1 + batch_print: 20 + epoch_test: 5 + + +MODEL: + name: 'audio2meshF' + name_netG: "MotionWaveFlow" + + dim_motion: 5023*3 # 68*2 + dim_speech: 1024 + num_vertices: 5023 + + dim_hidden: 128 + n_flowstep: 12 # 12 # 24 + n_early_every: 3 # 3 # 6 + n_layer_wave: 4 + kernel_size: 3 + lambda_std: [1, 1, 1, 1] #[1, 0.75, 0.5, 0.25] # [1, 1, 1, 1] + fix_dims: [0, 0, -1, -1] + + pretrain: False + path_checkpoint: "experiments/audio2mesh/train_audio2mesh_EN_20220208/20220216-19H57M17S" + load_epoch: 155 + + +DATASET: + fps: 50 + sr: 16000 + name: "motion_live" + root: './data/LuoXData-raw-deca-10h' # obama-deca-3-5-08-mini + root_raw: '/yrfs/lsen/DATA/LuoXData/processing2' + filter: 'savgol' + speech_extractor: 'wav2vec' + + nwind_second_train: 3 + nwind_second_valid: 3 + nwind_second_test: 15 + +TEST: + batch_size: 2 + +TRAIN: + lr: 0.0001 + batch_size: 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: True + max_grad_clip: 5 + max_grad_norm: 100 + lr_policy: 'plateau' # multistep, plateau, consine + # lr_milestones: [20, 80] + + resume: False + reset_lr: False + resume_suffix: "20220211-16H54M11S" + epoch_begin: 0 # 5000 # 2300 # 2600 + epoch_end: 200 + + +LOSS: + names: ["all", "logp", "logdet"] + lambda_logp: 1 + lambda_logdet: 1 + + # names: ["all", "rec_geo", "rec_geo_w", "vol_geo", "vol_geo_w"] + # lambda_rec_geo: 1 + # lambda_vol_geo: 10 diff --git a/experiments/audio2mesh/train_audio2meshF_EN_20220218.yaml b/experiments/audio2mesh/train_audio2meshF_EN_20220218.yaml new file mode 100644 index 0000000..bf04c1e --- /dev/null +++ b/experiments/audio2mesh/train_audio2meshF_EN_20220218.yaml @@ -0,0 +1,94 @@ +GPUS: '6' +WORKERS: 8 +OUTPUT_DIR: 'experiments/audio2mesh' + +DEBUG: False +verbose: False + + +VISUAL: + use_HTML: False + use_visdom: True + vsdm_port: 9900 + vsdm_ncol: 4 + vsdm_env: "audio2meshF-en" + +FREQ: + epoch_save: 1 + epoch_valid: 1 + batch_print: 20 + epoch_test: 5 + + +MODEL: + name: 'audio2meshF' + name_netG: "MotionWaveFlow" + + dim_motion: 5023*3 # 68*2 + dim_speech: 1024 + num_vertices: 5023 + + dim_hidden: 128 + n_flowstep: 12 # 12 # 24 + n_early_every: 3 # 3 # 6 + n_layer_wave: 4 + kernel_size: 3 + lambda_std: [1, 1, 1, 1.0] #[1, 0.75, 0.5, 0.25] # [1, 1, 1, 1] + fix_dims: [0, 0, -1, -1] + + pretrain: False + path_checkpoint: "experiments/audio2mesh/train_audio2mesh_EN_20220208/20220216-19H57M17S" + load_epoch: 155 + + +DATASET: + fps: 50 + sr: 16000 + name: "motion_live" + root: './data/obama-raw-deca-9h-50fps' # obama-deca-3-5-08-mini + root_raw: '/yrfs/lsen/DATA/Obama/processing' + filter: 'savgol' + speech_extractor: 'wav2vec' + + nwind_second_train: 3 + nwind_second_valid: 3 + nwind_second_test: 15 + +TEST: + batch_size: 2 + +TRAIN: + lr: 0.0001 + batch_size: 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: True + max_grad_clip: 5 + max_grad_norm: 100 + lr_policy: 'plateau' # multistep, plateau, consine + # lr_milestones: [20, 80] + + resume: False + reset_lr: False + resume_suffix: "20220211-16H54M11S" + epoch_begin: 0 # 5000 # 2300 # 2600 + epoch_end: 200 + + +LOSS: + names: ["all", "logp", "logdet"] + lambda_logp: 1 + lambda_logdet: 1 + + # names: ["all", "rec_geo", "rec_geo_w", "vol_geo", "vol_geo_w"] + # lambda_rec_geo: 1 + # lambda_vol_geo: 10 diff --git a/experiments/audio2mesh/train_audio2mesh_CN_20220208.yaml b/experiments/audio2mesh/train_audio2mesh_CN_20220208.yaml new file mode 100644 index 0000000..7e77edf --- /dev/null +++ b/experiments/audio2mesh/train_audio2mesh_CN_20220208.yaml @@ -0,0 +1,84 @@ +GPUS: '3' +WORKERS: 8 +OUTPUT_DIR: 'experiments/audio2mesh' + +DEBUG: False +verbose: False + + +VISUAL: + use_HTML: False + use_visdom: True + vsdm_port: 9900 + vsdm_ncol: 4 + vsdm_env: "audio2mesh-resnet-cn-weight-50-2" + +FREQ: + epoch_save: 5 + epoch_valid: 1 + batch_print: 20 + epoch_test: 5 + + +MODEL: + name: 'audio2mesh' + name_netG: "audio2mesh_resnet" + name_header: "resnet50" # "resnet50", "resnet34", + dim_motion: 53 # 68*2 + dim_speech: 1024 + num_vertices: 5023 + + + pretrain: False + path_checkpoint: "experiments/audio2mesh/train_audio2mesh_EN_20220208/20220216-19H57M17S" + load_epoch: 0 + + +DATASET: + fps: 50 + sr: 16000 + name: "motion_live" + # root: './data/LuoXData-raw-deca-toy' # obama-deca-3-5-08-mini + # root: './data/LuoXData-raw-deca-4min' # obama-deca-3-5-08-mini + root: './data/LuoXData-raw-deca-16h' # obama-deca-3-5-08-mini + root_raw: '/yrfs/lsen/DATA/LuoXData/processing2' + filter: 'savgol' + speech_extractor: 'wav2vec' + + nwind_second_train: 3 + nwind_second_valid: 3 + nwind_second_test: 15 + +TEST: + batch_size: 2 + +TRAIN: + lr: 0.00001 + 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: True + grad_clip_norm: False + # lr_policy: 'multistep' + # lr_milestones: [50, 100] + lr_policy: 'plateau' + + resume: False + reset_lr: False + resume_suffix: "20220211-16H54M11S" + epoch_begin: 0 # 5000 # 2300 # 2600 + epoch_end: 300 + + +LOSS: + names: ["all", "rec_geo", "rec_geo_w", "vol_geo", "vol_geo_w"] + lambda_rec_geo: 1 + lambda_vol_geo: 10 \ No newline at end of file diff --git a/experiments/audio2motion/train_audio2motionF_CN_20220125.yaml b/experiments/audio2mesh/train_audio2mesh_CN_20220210.yaml similarity index 56% rename from experiments/audio2motion/train_audio2motionF_CN_20220125.yaml rename to experiments/audio2mesh/train_audio2mesh_CN_20220210.yaml index f7ab2ab..ac404b2 100644 --- a/experiments/audio2motion/train_audio2motionF_CN_20220125.yaml +++ b/experiments/audio2mesh/train_audio2mesh_CN_20220210.yaml @@ -1,15 +1,17 @@ -GPUS: '0' +GPUS: '6' WORKERS: 8 -OUTPUT_DIR: 'experiments/audio2motion' +OUTPUT_DIR: 'experiments/audio2mesh' + DEBUG: False verbose: False + VISUAL: use_HTML: False use_visdom: True vsdm_port: 9000 vsdm_ncol: 4 - vsdm_env: "audio2motion_live" + vsdm_env: "audio2mesh-voca" FREQ: epoch_save: 5 @@ -20,28 +22,24 @@ FREQ: MODEL: - name: 'audio2motion_live' - name_netG: "audio2motion" + name: 'audio2mesh' + name_netG: "audio2mesh_voca" dim_motion: 53 # 68*2 dim_speech: 1024 - dim_hidden: 256 + num_vertices: 5023 - 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 + path_checkpoint: "experiments/audio2motion/train_audio2motionV_CN_20220207_2/20220207-12H47M47S" + load_epoch: 0 DATASET: fps: 50 sr: 16000 name: "motion_live" - root: './data/LuoXData-raw-deca-4h' # obama-deca-3-5-08-mini + root: './data/LuoXData-raw-deca-10h' # obama-deca-3-5-08-mini filter: 'savgol' speech_extractor: 'wav2vec' @@ -49,13 +47,12 @@ DATASET: nwind_second_valid: 3 nwind_second_test: 10 - TEST: batch_size: 2 TRAIN: - lr: 0.0001 - batch_size: 32 + lr: 0.00001 + batch_size: 64 shuffle: True apply_testing: True @@ -66,20 +63,20 @@ TRAIN: beta1: 0.5 beta2: 0.999 weight_decay: 0.0001 - nesterov: False + nesterov: True grad_clip_norm: False lr_policy: 'multistep' - lr_milestones: [10, 100, 200, 500] + lr_milestones: [50, 100] # lr_policy: 'plateau' resume: False reset_lr: False - resume_suffix: "20220125-16H35M55S" + 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 + names: ["all", "rec_geo", "vol_geo"] + lambda_rec_geo: 1 + lambda_vol_geo: 10 \ No newline at end of file diff --git a/experiments/audio2mesh/train_audio2mesh_CN_20220220.yaml b/experiments/audio2mesh/train_audio2mesh_CN_20220220.yaml new file mode 100644 index 0000000..39baa2c --- /dev/null +++ b/experiments/audio2mesh/train_audio2mesh_CN_20220220.yaml @@ -0,0 +1,83 @@ +GPUS: '8' +WORKERS: 4 +OUTPUT_DIR: 'experiments/audio2mesh' + +DEBUG: False +verbose: False + + +VISUAL: + use_HTML: False + use_visdom: True + vsdm_port: 9900 + vsdm_ncol: 4 + vsdm_env: "audio2mesh-specific-resnet-50" + +FREQ: + epoch_save: 5 + epoch_valid: 1 + batch_print: 20 + + epoch_test: 5 + + +MODEL: + name: 'audio2mesh_specific' + name_netG: "audio2mesh_resnet" + name_header: "resnet50" # "resnet50", "resnet34", + dim_motion: 53 # 68*2 + dim_speech: 1024 + num_vertices: 5023 + + + pretrain: True + path_checkpoint: "experiments/audio2mesh/train_audio2mesh_CN_20220220/20220225-19H08M53S" + load_epoch: 295 + +DATASET: + fps: 50 + sr: 16000 + name: "motion_live2" + root: './data/LuoXData-raw-deca-16h' # obama-deca-3-5-08-mini + root_raw: '/yrfs/lsen/DATA/LuoXData/processing2' + path_mean_dict: './data/DECA_LuoXData_mean.npy' + filter: 'savgol' + speech_extractor: 'wav2vec' + + nwind_second_train: 3 + nwind_second_valid: 3 + nwind_second_test: 15 + +TEST: + batch_size: 2 + +TRAIN: + lr: 0.00001 + batch_size: 48 + 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: [50, 100] + lr_policy: 'plateau' + + resume: False + reset_lr: False + resume_suffix: "20220128-10H10M10S" + epoch_begin: 0 # 5000 # 2300 # 2600 + epoch_end: 300 + + +LOSS: + names: ["all", "rec_geo", "rec_geo_w", "vol_geo", "vol_geo_w"] + lambda_rec_geo: 1 + lambda_vol_geo: 10 \ No newline at end of file diff --git a/experiments/audio2mesh/train_audio2mesh_EN_20220208.yaml b/experiments/audio2mesh/train_audio2mesh_EN_20220208.yaml new file mode 100644 index 0000000..bda3809 --- /dev/null +++ b/experiments/audio2mesh/train_audio2mesh_EN_20220208.yaml @@ -0,0 +1,81 @@ +GPUS: '6' +WORKERS: 8 +OUTPUT_DIR: 'experiments/audio2mesh' + +DEBUG: False +verbose: False + + +VISUAL: + use_HTML: False + use_visdom: True + vsdm_port: 9900 + vsdm_ncol: 4 + vsdm_env: "audio2mesh-resnet-en-weight-101" + +FREQ: + epoch_save: 5 + epoch_valid: 1 + batch_print: 20 + epoch_test: 5 + + +MODEL: + name: 'audio2mesh' + name_netG: "audio2mesh_resnet" + name_header: "resnet101" # "resnet50", "resnet34", + dim_motion: 53 # 68*2 + dim_speech: 1024 + num_vertices: 5023 + + pretrain: False + path_checkpoint: "experiments/audio2mesh/train_audio2mesh_EN_20220208/20220216-19H57M17S" + load_epoch: 155 + + +DATASET: + fps: 50 + sr: 16000 + name: "motion_live" + root: './data/obama-raw-deca-9h-50fps' # obama-deca-3-5-08-mini + root_raw: '/yrfs/lsen/DATA/Obama/processing' + filter: 'savgol' + speech_extractor: 'wav2vec' + + nwind_second_train: 3 + nwind_second_valid: 3 + nwind_second_test: 15 + +TEST: + batch_size: 2 + +TRAIN: + lr: 0.00001 + 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: True + grad_clip_norm: False + lr_policy: 'multistep' + lr_milestones: [50, 100] + # lr_policy: 'plateau' + + resume: False + reset_lr: False + resume_suffix: "20220211-16H54M11S" + epoch_begin: 0 # 5000 # 2300 # 2600 + epoch_end: 300 + + +LOSS: + names: ["all", "rec_geo", "rec_geo_w", "vol_geo", "vol_geo_w"] + lambda_rec_geo: 1 + lambda_vol_geo: 10 diff --git a/experiments/audio2mesh/train_audio2mesh_EN_20220220.yaml b/experiments/audio2mesh/train_audio2mesh_EN_20220220.yaml new file mode 100644 index 0000000..ed50990 --- /dev/null +++ b/experiments/audio2mesh/train_audio2mesh_EN_20220220.yaml @@ -0,0 +1,82 @@ +GPUS: '9' +WORKERS: 4 +OUTPUT_DIR: 'experiments/audio2mesh' + +DEBUG: False +verbose: False + +VISUAL: + use_HTML: False + use_visdom: True + vsdm_port: 9900 + vsdm_ncol: 4 + vsdm_env: "audio2mesh-specific-en-resnet-50" + +FREQ: + epoch_save: 5 + epoch_valid: 1 + batch_print: 20 + epoch_test: 5 + + +MODEL: + name: 'audio2mesh_specific' + name_netG: "audio2mesh_resnet" + name_header: "resnet50" # "resnet50", "resnet34", + dim_motion: 53 # 68*2 + dim_speech: 1024 + num_vertices: 5023 + + + pretrain: False + path_checkpoint: "experiments/audio2mesh/train_audio2mesh_CN_20220220/20220221-18H39M50S" + load_epoch: 0 + + +DATASET: + fps: 50 + sr: 16000 + name: "motion_live2" + root: './data/obama-raw-deca-9h-50fps' # obama-deca-3-5-08-mini + root_raw: '/yrfs/lsen/DATA/Obama/processing' + path_mean_dict: './data/DECA_obama_mean.npy' + filter: 'savgol' + speech_extractor: 'wav2vec' + + nwind_second_train: 3 + nwind_second_valid: 3 + nwind_second_test: 15 + +TEST: + batch_size: 2 + +TRAIN: + lr: 0.00005 + batch_size: 48 + 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: [50, 100] + lr_policy: 'plateau' + + resume: False + reset_lr: False + resume_suffix: "20220128-10H10M10S" + epoch_begin: 0 # 5000 # 2300 # 2600 + epoch_end: 300 + + +LOSS: + names: ["all", "rec_geo", "rec_geo_w", "vol_geo", "vol_geo_w"] + lambda_rec_geo: 1 + lambda_vol_geo: 10 \ No newline at end of file diff --git a/experiments/audio2mesh/train_waveflow_EN_20220218.yaml b/experiments/audio2mesh/train_waveflow_EN_20220218.yaml new file mode 100644 index 0000000..4569ff8 --- /dev/null +++ b/experiments/audio2mesh/train_waveflow_EN_20220218.yaml @@ -0,0 +1,94 @@ +GPUS: '5' +WORKERS: 8 +OUTPUT_DIR: 'experiments/audio2mesh' + +DEBUG: False +verbose: False + + +VISUAL: + use_HTML: False + use_visdom: True + vsdm_port: 9000 + vsdm_ncol: 4 + vsdm_env: "waveflow-en" + +FREQ: + epoch_save: 5 + epoch_valid: 1 + batch_print: 20 + epoch_test: 1 + + +MODEL: + name: 'MotionWave' + name_netG: "MotionWaveFlow" + + dim_motion: 53 # 68*2 + dim_speech: 1024 + num_vertices: 5023 + + dim_hidden: 256 + n_flowstep: 12 # 12 # 24 + n_early_every: 3 # 3 # 6 + n_layer_wave: 4 + kernel_size: 3 + lambda_std: [0.25, 0.5, 0.75, 1.0] #[1, 0.75, 0.5, 0.25] # [1, 1, 1, 1] + fix_dims: [0, 0, -1, -1] + + pretrain: False + path_checkpoint: "experiments/audio2mesh/train_audio2mesh_EN_20220208/20220216-19H57M17S" + load_epoch: 155 + + +DATASET: + fps: 50 + sr: 16000 + name: "motion_live" + root: './data/obama-raw-deca-9h-50fps' # obama-deca-3-5-08-mini + root_raw: '/yrfs/lsen/DATA/Obama/processing' + filter: 'savgol' + speech_extractor: 'wav2vec' + + nwind_second_train: 3 + nwind_second_valid: 3 + nwind_second_test: 15 + +TEST: + batch_size: 2 + +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: True + max_grad_clip: 5 + max_grad_norm: 100 + lr_policy: 'plateau' # multistep, plateau, consine + # lr_milestones: [20, 80] + + resume: False + reset_lr: False + resume_suffix: "20220211-16H54M11S" + epoch_begin: 0 # 5000 # 2300 # 2600 + epoch_end: 200 + + +LOSS: + names: ["all", "logp", "logdet"] + lambda_logp: 1 + lambda_logdet: 1 + + # names: ["all", "rec_geo", "rec_geo_w", "vol_geo", "vol_geo_w"] + # lambda_rec_geo: 1 + # lambda_vol_geo: 10 diff --git a/experiments/audio2motion/infer_audio2motionV_CN_20220208.yaml b/experiments/audio2motion/infer_audio2motionV_CN_20220208.yaml new file mode 100644 index 0000000..08d90e3 --- /dev/null +++ b/experiments/audio2motion/infer_audio2motionV_CN_20220208.yaml @@ -0,0 +1,85 @@ +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-VOCA-bigger-geo" + +FREQ: + epoch_save: 5 + epoch_valid: 1 + batch_print: 20 + + epoch_test: 5 + + +MODEL: + name: 'audio2motion_live3' + name_netG: "audio2motion_voca33" + + dim_motion: 53 # 68*2 + dim_speech: 1024 + dim_hidden: 256 + + pretrain: True + path_checkpoint: "experiments/audio2motion/train_audio2motionV_CN_20220208/20220208-16H16M24S" + load_epoch: 120 + + +DATASET: + fps: 50 + sr: 16000 + name: "motion_live" + root: './data/LuoXData-raw-deca-10h' # 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: 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: 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", "rec_geo", "vol_exp", "vol_pos", "vol_geo"] + lambda_rec_exp: 10 + lambda_rec_pos: 1 + lambda_rec_geo: 10 + lambda_vol_exp: 1 + lambda_vol_pos: 10 + lambda_vol_geo: 10 \ No newline at end of file diff --git a/experiments/audio2motion/infer_audio2motionV_CN_overfitting.yaml b/experiments/audio2motion/infer_audio2motionV_CN_overfitting.yaml new file mode 100644 index 0000000..ed229b3 --- /dev/null +++ b/experiments/audio2motion/infer_audio2motionV_CN_overfitting.yaml @@ -0,0 +1,84 @@ +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-toy" + +FREQ: + epoch_save: 5 + epoch_valid: 1 + batch_print: 20 + epoch_test: 10 + + +MODEL: + name: 'audio2motion_live2' + name_netG: "audio2motion_voca" + + dim_motion: 53 # 68*2 + dim_speech: 1024 + dim_hidden: 256 + + pretrain: True + path_checkpoint: "experiments/audio2motion/train_audio2motionV_CN_20220215/20220216-11H42M55S" + load_epoch: 70 + + +DATASET: + fps: 50 + sr: 16000 + name: "motion_live" + # root: './data/LuoXData-raw-deca-10h' # obama-deca-3-5-08-mini + root: './data/LuoXData-raw-deca-toy' # obama-deca-3-5-08-mini + root_raw: '/yrfs/lsen/DATA/LuoXData/processing2' + 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: 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: 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/infer_audio2motionW_20220111.yaml b/experiments/audio2motion/infer_audio2motionW_20220111.yaml deleted file mode 100644 index aee1bb4..0000000 --- a/experiments/audio2motion/infer_audio2motionW_20220111.yaml +++ /dev/null @@ -1,67 +0,0 @@ -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 deleted file mode 100644 index a68b8d6..0000000 --- a/experiments/audio2motion/infer_audio2motionW_20220118.yaml +++ /dev/null @@ -1,66 +0,0 @@ -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 deleted file mode 100644 index 2947679..0000000 --- a/experiments/audio2motion/infer_audio2motionW_20220120.yaml +++ /dev/null @@ -1,69 +0,0 @@ -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 deleted file mode 100644 index 30ca4ba..0000000 --- a/experiments/audio2motion/train_audio2motion3_obama.yaml +++ /dev/null @@ -1,85 +0,0 @@ -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_audio2motionFH_CN_20220125.yaml b/experiments/audio2motion/train_audio2motionFH_CN_20220125.yaml deleted file mode 100644 index 2fbf3c2..0000000 --- a/experiments/audio2motion/train_audio2motionFH_CN_20220125.yaml +++ /dev/null @@ -1,78 +0,0 @@ -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 deleted file mode 100644 index ea4b721..0000000 --- a/experiments/audio2motion/train_audio2motionFH_CN_20220126.yaml +++ /dev/null @@ -1,78 +0,0 @@ -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_20220126.yaml b/experiments/audio2motion/train_audio2motionF_CN_20220126.yaml deleted file mode 100644 index 80d900b..0000000 --- a/experiments/audio2motion/train_audio2motionF_CN_20220126.yaml +++ /dev/null @@ -1,84 +0,0 @@ -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_audio2motionF_CN_20220218.yaml b/experiments/audio2motion/train_audio2motionF_CN_20220218.yaml new file mode 100644 index 0000000..ccb1e4b --- /dev/null +++ b/experiments/audio2motion/train_audio2motionF_CN_20220218.yaml @@ -0,0 +1,94 @@ +GPUS: '4' +WORKERS: 8 +OUTPUT_DIR: 'experiments/audio2motion' + +DEBUG: False +verbose: False + + +VISUAL: + use_HTML: False + use_visdom: True + vsdm_port: 9900 + vsdm_ncol: 4 + vsdm_env: "audio2motionF-cn" + +FREQ: + epoch_save: 5 + epoch_valid: 1 + batch_print: 20 + epoch_test: 5 + + +MODEL: + name: 'audio2motionF' + name_netG: "MotionWaveFlow" + + dim_motion: 53 # 68*2 + dim_speech: 1024 + num_vertices: 5023 + + dim_hidden: 256 + n_flowstep: 12 # 12 # 24 + n_early_every: 3 # 3 # 6 + n_layer_wave: 4 + kernel_size: 3 + lambda_std: [0.25, 0.5, 0.75, 1.0] #[1, 0.75, 0.5, 0.25] # [1, 1, 1, 1] + fix_dims: [0, 0, -1, -1] + + pretrain: False + path_checkpoint: "experiments/audio2mesh/train_audio2mesh_EN_20220208/20220216-19H57M17S" + load_epoch: 155 + + +DATASET: + fps: 50 + sr: 16000 + name: "motion_live" + root: './data/LuoXData-raw-deca-10h' + root_raw: '/yrfs/lsen/DATA/LuoXData/processing2' + filter: 'savgol' + speech_extractor: 'wav2vec' + + nwind_second_train: 3 + nwind_second_valid: 3 + nwind_second_test: 15 + +TEST: + batch_size: 2 + +TRAIN: + lr: 0.0001 + batch_size: 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: True + max_grad_clip: 5 + max_grad_norm: 100 + lr_policy: 'plateau' # multistep, plateau, consine + # lr_milestones: [20, 80] + + resume: False + reset_lr: False + resume_suffix: "20220211-16H54M11S" + epoch_begin: 0 # 5000 # 2300 # 2600 + epoch_end: 200 + + +LOSS: + names: ["all", "logp", "logdet"] + lambda_logp: 1 + lambda_logdet: 1 + + # names: ["all", "rec_geo", "rec_geo_w", "vol_geo", "vol_geo_w"] + # lambda_rec_geo: 1 + # lambda_vol_geo: 10 diff --git a/experiments/audio2motion/train_audio2motionF_CN_20220220.yaml b/experiments/audio2motion/train_audio2motionF_CN_20220220.yaml new file mode 100644 index 0000000..951539b --- /dev/null +++ b/experiments/audio2motion/train_audio2motionF_CN_20220220.yaml @@ -0,0 +1,94 @@ +GPUS: '4' +WORKERS: 8 +OUTPUT_DIR: 'experiments/audio2motion' + +DEBUG: False +verbose: False + + +VISUAL: + use_HTML: False + use_visdom: True + vsdm_port: 9900 + vsdm_ncol: 4 + vsdm_env: "audio2motionF-en-w" + +FREQ: + epoch_save: 5 + epoch_valid: 1 + batch_print: 20 + epoch_test: 1 + + +MODEL: + name: 'audio2motionFW' + name_netG: "MotionWaveFlow2" + + dim_motion: 53 # 68*2 + dim_speech: 1024 + num_vertices: 5023 + + dim_hidden: 256 + n_flowstep: 12 # 12 # 24 + n_early_every: 3 # 3 # 6 + n_layer_wave: 4 + kernel_size: 3 + lambda_std: [1.0, 1.0, 1.0, 1.0] #[1, 0.75, 0.5, 0.25] # [1, 1, 1, 1] + fix_dims: [0, 0, -1, -1] + + pretrain: False + path_checkpoint: "experiments/audio2mesh/train_audio2mesh_EN_20220208/20220216-19H57M17S" + load_epoch: 155 + + +DATASET: + fps: 50 + sr: 16000 + name: "motion_live" + root: './data/obama-raw-deca-9h-50fps' # obama-deca-3-5-08-mini + root_raw: '/yrfs/lsen/DATA/Obama/processing' + filter: 'savgol' + speech_extractor: 'wav2vec' + + nwind_second_train: 15 + nwind_second_valid: 15 + nwind_second_test: 15 + +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: True + max_grad_clip: 5 + max_grad_norm: 100 + lr_policy: 'plateau' # multistep, plateau, consine + # lr_milestones: [20, 80] + + resume: False + reset_lr: False + resume_suffix: "20220211-16H54M11S" + epoch_begin: 0 # 5000 # 2300 # 2600 + epoch_end: 300 + + +LOSS: + names: ["all", "logp", "logdet"] + lambda_logp: 1 + lambda_logdet: 1 + + # names: ["all", "rec_geo", "rec_geo_w", "vol_geo", "vol_geo_w"] + # lambda_rec_geo: 1 + # lambda_vol_geo: 10 diff --git a/experiments/audio2motion/train_audio2motionF_EN_20220218.yaml b/experiments/audio2motion/train_audio2motionF_EN_20220218.yaml new file mode 100644 index 0000000..2880ca7 --- /dev/null +++ b/experiments/audio2motion/train_audio2motionF_EN_20220218.yaml @@ -0,0 +1,94 @@ +GPUS: '5' +WORKERS: 8 +OUTPUT_DIR: 'experiments/audio2motion' + +DEBUG: False +verbose: False + + +VISUAL: + use_HTML: False + use_visdom: True + vsdm_port: 9900 + vsdm_ncol: 4 + vsdm_env: "audio2motionF-en-w" + +FREQ: + epoch_save: 5 + epoch_valid: 1 + batch_print: 20 + epoch_test: 1 + + +MODEL: + name: 'audio2motionFW' + name_netG: "MotionWaveFlow22" + + dim_motion: 53 # 68*2 + dim_speech: 1024 + num_vertices: 5023 + + dim_hidden: 256 + n_flowstep: 12 # 12 # 24 + n_early_every: 3 # 3 # 6 + n_layer_wave: 4 + kernel_size: 3 + lambda_std: [1.0, 1.0, 1.0, 1.0] #[1, 0.75, 0.5, 0.25] # [1, 1, 1, 1] + fix_dims: [0, 0, -1, -1] + + pretrain: False + path_checkpoint: "experiments/audio2motion/train_audio2motionF_EN_20220218/20220221-11H40M55S" + load_epoch: 0 + + +DATASET: + fps: 50 + sr: 16000 + name: "motion_live" + root: './data/obama-raw-deca-9h-50fps' # obama-deca-3-5-08-mini + root_raw: '/yrfs/lsen/DATA/Obama/processing' + filter: 'savgol' + speech_extractor: 'wav2vec' + + nwind_second_train: 3 + nwind_second_valid: 3 + nwind_second_test: 15 + +TEST: + batch_size: 2 + +TRAIN: + lr: 0.0001 + batch_size: 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: True + max_grad_clip: 5 + max_grad_norm: 100 + lr_policy: 'multistep' # multistep, plateau, consine + lr_milestones: [20, 100] + + resume: False + reset_lr: False + resume_suffix: "20220221-11H40M55S" + epoch_begin: 0 # 5000 # 2300 # 2600 + epoch_end: 200 + + +LOSS: + names: ["all", "logp", "logdet"] + lambda_logp: 1 + lambda_logdet: 1 + + # names: ["all", "rec_geo", "rec_geo_w", "vol_geo", "vol_geo_w"] + # lambda_rec_geo: 1 + # lambda_vol_geo: 10 diff --git a/experiments/audio2motion/train_audio2motionF_EN_20220220.yaml b/experiments/audio2motion/train_audio2motionF_EN_20220220.yaml new file mode 100644 index 0000000..bf75c40 --- /dev/null +++ b/experiments/audio2motion/train_audio2motionF_EN_20220220.yaml @@ -0,0 +1,93 @@ +GPUS: '0' +WORKERS: 8 +OUTPUT_DIR: 'experiments/audio2motion' + +DEBUG: False +verbose: False + + +VISUAL: + use_HTML: False + use_visdom: True + vsdm_port: 9900 + vsdm_ncol: 4 + +FREQ: + epoch_save: 5 + epoch_valid: 1 + batch_print: 20 + epoch_test: 5 + + +MODEL: + name: 'audio2motionFW' + name_netG: "MotionWaveFlow2" + + dim_motion: 53 # 68*2 + dim_speech: 1024 + num_vertices: 5023 + + dim_hidden: 256 + n_flowstep: 12 # 12 # 24 + n_early_every: 3 # 3 # 6 + n_layer_wave: 4 + kernel_size: 3 + lambda_std: [1.0, 1.0, 1.0, 1.0] #[1, 0.75, 0.5, 0.25] # [1, 1, 1, 1] + fix_dims: [0, 0, -1, -1] + + pretrain: False + path_checkpoint: "experiments/audio2mesh/train_audio2mesh_EN_20220208/20220216-19H57M17S" + load_epoch: 155 + + +DATASET: + fps: 50 + sr: 16000 + name: "motion_live" + root: './data/obama-raw-deca-9h-50fps' # obama-deca-3-5-08-mini + root_raw: '/yrfs/lsen/DATA/Obama/processing' + filter: 'savgol' + speech_extractor: 'wav2vec' + + nwind_second_train: 3 + nwind_second_valid: 3 + nwind_second_test: 15 + +TEST: + batch_size: 2 + +TRAIN: + lr: 0.0001 + batch_size: 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: True + max_grad_clip: 5 + max_grad_norm: 100 + lr_policy: 'plateau' # multistep, plateau, consine + # lr_milestones: [20, 80] + + resume: False + reset_lr: False + resume_suffix: "20220211-16H54M11S" + epoch_begin: 0 # 5000 # 2300 # 2600 + epoch_end: 300 + + +LOSS: + names: ["all", "logp", "logdet"] + lambda_logp: 1 + lambda_logdet: 1 + + # names: ["all", "rec_geo", "rec_geo_w", "vol_geo", "vol_geo_w"] + # lambda_rec_geo: 1 + # lambda_vol_geo: 10 diff --git a/experiments/audio2motion/train_audio2motionR_20220112.yaml b/experiments/audio2motion/train_audio2motionR_20220112.yaml deleted file mode 100644 index f92d206..0000000 --- a/experiments/audio2motion/train_audio2motionR_20220112.yaml +++ /dev/null @@ -1,86 +0,0 @@ -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 deleted file mode 100644 index f06492d..0000000 --- a/experiments/audio2motion/train_audio2motionV_20220120.yaml +++ /dev/null @@ -1,76 +0,0 @@ -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 deleted file mode 100644 index db43864..0000000 --- a/experiments/audio2motion/train_audio2motionV_20220120B.yaml +++ /dev/null @@ -1,76 +0,0 @@ -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_20220207.yaml b/experiments/audio2motion/train_audio2motionV_CN_20220207.yaml index 53cb457..ffb8863 100644 --- a/experiments/audio2motion/train_audio2motionV_CN_20220207.yaml +++ b/experiments/audio2motion/train_audio2motionV_CN_20220207.yaml @@ -1,4 +1,4 @@ -GPUS: '7' +GPUS: '2' WORKERS: 8 OUTPUT_DIR: 'experiments/audio2motion' @@ -50,7 +50,7 @@ TEST: batch_size: 2 TRAIN: - lr: 0.0005 + lr: 0.001 batch_size: 32 shuffle: True @@ -68,14 +68,16 @@ TRAIN: # lr_milestones: [10, 50, 500] lr_policy: 'plateau' - resume: False + resume: True reset_lr: False - resume_suffix: "20220128-10H10M10S" - epoch_begin: 0 # 5000 # 2300 # 2600 + resume_suffix: "20220207-18H14M59S" + epoch_begin: 15 # 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 + 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_audio2motionV_CN_20220207_2.yaml b/experiments/audio2motion/train_audio2motionV_CN_20220207_2.yaml index e6db8c7..6aa0a1d 100644 --- a/experiments/audio2motion/train_audio2motionV_CN_20220207_2.yaml +++ b/experiments/audio2motion/train_audio2motionV_CN_20220207_2.yaml @@ -1,4 +1,4 @@ -GPUS: '8' +GPUS: '1' WORKERS: 8 OUTPUT_DIR: 'experiments/audio2motion' @@ -9,15 +9,14 @@ verbose: False VISUAL: use_HTML: False use_visdom: True - vsdm_port: 9000 + vsdm_port: 9900 vsdm_ncol: 4 - vsdm_env: "audio2motion-VOCA-bigger-test" + vsdm_env: "audio2motion-bigger-toy" FREQ: epoch_save: 5 epoch_valid: 1 batch_print: 20 - epoch_test: 5 @@ -29,29 +28,31 @@ MODEL: dim_speech: 1024 dim_hidden: 256 - pretrain: True + pretrain: False path_checkpoint: "experiments/audio2motion/train_audio2motionV_CN_20220207_2/20220207-12H47M47S" - load_epoch: 45 + load_epoch: 50 DATASET: fps: 50 sr: 16000 name: "motion_live" - root: './data/LuoXData-raw-deca-8h' # obama-deca-3-5-08-mini + # root: './data/LuoXData-raw-deca-10h' # obama-deca-3-5-08-mini + root: './data/LuoXData-raw-deca-toy' # obama-deca-3-5-08-mini + root_raw: '/yrfs/lsen/DATA/LuoXData/processing2' filter: 'savgol' speech_extractor: 'wav2vec' nwind_second_train: 3 nwind_second_valid: 3 - nwind_second_test: 10 + nwind_second_test: 15 TEST: batch_size: 2 TRAIN: - lr: 0.00005 - batch_size: 32 + lr: 0.0001 + batch_size: 64 shuffle: True apply_testing: True @@ -65,19 +66,19 @@ TRAIN: nesterov: True grad_clip_norm: False # lr_policy: 'multistep' - # lr_milestones: [10, 50, 500] + # lr_milestones: [50, 100] lr_policy: 'plateau' resume: False reset_lr: False - resume_suffix: "20220128-10H10M10S" + resume_suffix: "20220216-09H59M26S" epoch_begin: 0 # 5000 # 2300 # 2600 - epoch_end: 1000 + epoch_end: 300 LOSS: names: ["all", "rec_exp", "rec_pos", "vol_exp", "vol_pos"] - lambda_rec_exp: 10 + lambda_rec_exp: 1 lambda_rec_pos: 1 lambda_vol_exp: 1 - lambda_vol_pos: 10 \ No newline at end of file + lambda_vol_pos: 1 \ No newline at end of file diff --git a/experiments/audio2motion/train_audio2motionV_CN_20220208.yaml b/experiments/audio2motion/train_audio2motionV_CN_20220208.yaml new file mode 100644 index 0000000..111eb65 --- /dev/null +++ b/experiments/audio2motion/train_audio2motionV_CN_20220208.yaml @@ -0,0 +1,86 @@ +GPUS: '2' +WORKERS: 8 +OUTPUT_DIR: 'experiments/audio2motion' + +DEBUG: False +verbose: False +isTrain: True + + +VISUAL: + use_HTML: False + use_visdom: True + vsdm_port: 9000 + vsdm_ncol: 4 + vsdm_env: "audio2motion-VOCA-bigger-geo-test" + +FREQ: + epoch_save: 5 + epoch_valid: 1 + batch_print: 20 + + epoch_test: 5 + + +MODEL: + name: 'audio2motion_live3' + name_netG: "audio2motion_voca33" + + dim_motion: 53 # 68*2 + dim_speech: 1024 + dim_hidden: 256 + + pretrain: True + path_checkpoint: "experiments/audio2motion/train_audio2motionV_CN_20220208/20220208-16H16M24S" + load_epoch: 120 + + +DATASET: + fps: 50 + sr: 16000 + name: "motion_live" + root: './data/LuoXData-raw-deca-10h' # 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: 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: 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", "rec_geo", "vol_exp", "vol_pos", "vol_geo"] + lambda_rec_exp: 10 + lambda_rec_pos: 1 + lambda_rec_geo: 10 + lambda_vol_exp: 1 + lambda_vol_pos: 10 + lambda_vol_geo: 10 \ No newline at end of file diff --git a/experiments/audio2motion/train_audio2motionV_CN_20220215.yaml b/experiments/audio2motion/train_audio2motionV_CN_20220215.yaml new file mode 100644 index 0000000..f9db658 --- /dev/null +++ b/experiments/audio2motion/train_audio2motionV_CN_20220215.yaml @@ -0,0 +1,84 @@ +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-VOCA-biggest-toy" + +FREQ: + epoch_save: 5 + epoch_valid: 1 + batch_print: 20 + epoch_test: 10 + + +MODEL: + name: 'audio2motion_live2' + name_netG: "audio2motion_voca34" + + dim_motion: 53 # 68*2 + dim_speech: 1024 + dim_hidden: 256 + + pretrain: False + path_checkpoint: "experiments/audio2motion/train_audio2motionV_CN_20220207_2/20220207-12H47M47S" + load_epoch: 0 + + +DATASET: + fps: 50 + sr: 16000 + name: "motion_live" + root: './data/LuoXData-raw-deca-10h' # obama-deca-3-5-08-mini + # root: './data/LuoXData-raw-deca-toy' # obama-deca-3-5-08-mini + root_raw: '/yrfs/lsen/DATA/LuoXData/processing2' + filter: 'savgol' + speech_extractor: 'wav2vec' + + nwind_second_train: 3 + nwind_second_valid: 3 + nwind_second_test: 10 + +TEST: + batch_size: 2 + +TRAIN: + lr: 0.00001 + 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: True + grad_clip_norm: False + # lr_policy: 'multistep' + # lr_milestones: [10, 50, 500] + lr_policy: 'plateau' + + resume: True + reset_lr: True + resume_suffix: "20220216-10H20M38S" + epoch_begin: 75 # 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_audio2motionV_EN_20220208.yaml b/experiments/audio2motion/train_audio2motionV_EN_20220208.yaml new file mode 100644 index 0000000..ce3485f --- /dev/null +++ b/experiments/audio2motion/train_audio2motionV_EN_20220208.yaml @@ -0,0 +1,87 @@ +GPUS: '3' +WORKERS: 8 +OUTPUT_DIR: 'experiments/audio2motion' + +DEBUG: False +verbose: False +isTrain: Train + + +VISUAL: + use_HTML: False + use_visdom: True + vsdm_port: 9000 + vsdm_ncol: 4 + vsdm_env: "audio2motion-VOCA-bigger-geo-en" + +FREQ: + epoch_save: 5 + epoch_valid: 1 + batch_print: 20 + + epoch_test: 1 + + +MODEL: + name: 'audio2motion_live3' + name_netG: "audio2motion_voca33" + + dim_motion: 53 # 68*2 + dim_speech: 1024 + dim_hidden: 256 + + pretrain: False + path_checkpoint: "experiments/audio2motion/train_audio2motionV_CN_20220208/20220208-16H16M24S" + load_epoch: 0 + + +DATASET: + fps: 50 + sr: 16000 + name: "motion_live" + root: './data/obama-raw-deca-9h-50fps' # obama-deca-3-5-08-mini + root_raw: '/yrfs/lsen/DATA/Obama/processing' # + filter: 'savgol' + speech_extractor: 'wav2vec' + + nwind_second_train: 3 + nwind_second_valid: 3 + nwind_second_test: 15 + +TEST: + batch_size: 2 + +TRAIN: + lr: 0.00001 + 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: True + grad_clip_norm: False + # lr_policy: 'multistep' + # lr_milestones: [50, 100, 200] + lr_policy: 'plateau' + + resume: True + reset_lr: True + resume_suffix: "20220215-14H30M16S" + epoch_begin: 40 # 5000 # 2300 # 2600 + epoch_end: 500 + + +LOSS: + names: ["all", "rec_exp", "rec_pos", "rec_geo", "vol_exp", "vol_pos", "vol_geo"] + lambda_rec_exp: 1 + lambda_rec_pos: 1 + lambda_rec_geo: 10 + lambda_vol_exp: 10 + lambda_vol_pos: 10 + lambda_vol_geo: 10 \ No newline at end of file diff --git a/experiments/audio2motion/train_audio2motionW_20220111.yaml b/experiments/audio2motion/train_audio2motionW_20220111.yaml deleted file mode 100644 index d903817..0000000 --- a/experiments/audio2motion/train_audio2motionW_20220111.yaml +++ /dev/null @@ -1,87 +0,0 @@ -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 deleted file mode 100644 index 8b73803..0000000 --- a/experiments/audio2motion/train_audio2motionW_20220118.yaml +++ /dev/null @@ -1,87 +0,0 @@ -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 deleted file mode 100644 index 294e816..0000000 --- a/experiments/audio2motion/train_audio2motionW_20220120.yaml +++ /dev/null @@ -1,87 +0,0 @@ -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_audio2motion_obama.yaml b/experiments/audio2motion/train_audio2motion_obama.yaml deleted file mode 100644 index 7079969..0000000 --- a/experiments/audio2motion/train_audio2motion_obama.yaml +++ /dev/null @@ -1,84 +0,0 @@ -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 index 22fbb04..2bf2b27 100644 --- a/infer_one_live.py +++ b/infer_one_live.py @@ -42,10 +42,20 @@ if __name__ == "__main__": 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("/yrfs/lsen/DATA/LuoXData/processing2/2021-P09/audio/audio_trim_60_120s.wav") + + # path_audio = Path("/yrfs/lsen/DATA/Obama/processing/Bringing-Our-Workplace-Policies-into-the-21st-Century/audio/audio_trim_120s.wav") + path_audio = Path("/yrfs/lsen/DATA/Obama/processing/Celebrating-Independence-Day/audio/audio_trim_60_120s.wav") + # path_audio = Path("/yrfs/lsen/DATA/LuoXData/processing2/2021-P09/audio/audio_trim_120s.wav") + # path_audio = Path("/yrfs/lsen/DATA/LuoXData/processing2/2021-P22/audio/audio_trim.wav") + + # path_audio = Path("/ssdata1/lsen/CODE/Audio2Motion/data/test/test_pangzi_zh_cut15.wav") + # path_audio = Path("/ssdata1/lsen/CODE/Audio2Motion/data/test/P74_lite.mp3") + # path_audio = Path("/ssdata1/lsen/CODE/voca/data/audio/test_video_15.wav") # path_audio = Path("/ssdata1/lsen/CODE/voca/data/audio/cut_lsz.wav") # path_audio = Path("/ssdata1/lsen/CODE/voca/data/audio/obama.wav") + # data extract audio # Load data_audio and extract features @@ -61,9 +71,10 @@ if __name__ == "__main__": 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] + + # clip + # if len(audio_raw) > 16000 * 120: + # audio_raw = audio_raw[:16000*120] # audio_raw_numpy = audio_raw.numpy() diff --git a/scripts/LuoXData/run-00-mean-coeff.py b/scripts/LuoXData/run-00-mean-coeff.py new file mode 100644 index 0000000..5949aea --- /dev/null +++ b/scripts/LuoXData/run-00-mean-coeff.py @@ -0,0 +1,166 @@ +import numpy as np +from pathlib import Path + + +if __name__ == "__main__": + + # fid = "Bringing-Our-Workplace-Policies-into-the-21st-Century" + fid = "2021-P09" + path_root = Path("/yrfs/lsen/DATA/LuoXData/processing2/") + path_data = path_root.joinpath(fid) + + path_coeff = path_data.joinpath("DECA_coeff") + vpath_coeff = sorted(path_coeff.glob("*.npy"), reverse=False) + print(f"Have {len(vpath_coeff)} frames") + + + feat_shape = [] + feat_tex = [] + feat_cam = [] + feat_exp = [] + feat_pos = [] + feat_light = [] + feat_detail = [] + + for ipath_coeff in vpath_coeff: + + data_coeff = np.load(ipath_coeff, allow_pickle=True).item() + + # print(data_coeff.keys()) + + feat_exp.append(data_coeff["exp"]) + feat_pos.append(data_coeff["pose"]) + feat_tex.append(data_coeff["tex"]) + feat_cam.append(data_coeff["cam"]) + feat_light.append(data_coeff["light"]) + feat_detail.append(data_coeff["detail"]) + feat_shape.append(data_coeff["shape"]) + + # save + feat_exp = np.array(feat_exp) # (nframe_trim, 50) + feat_pos = np.array(feat_pos) # (nframe_trim, 6) + feat_tex = np.array(feat_tex) # (nframe_trim, 50) + feat_cam = np.array(feat_cam) # (nframe_trim, 6) + feat_light = np.array(feat_light) # (nframe_trim, 50) + feat_detail = np.array(feat_detail) # (nframe_trim, 6) + feat_shape = np.array(feat_shape) # (nframe_trim, 50) + + mean_exp = feat_exp.mean(axis=0) + mean_pos = feat_pos.mean(axis=0) + mean_tex = feat_tex.mean(axis=0) + mean_cam = feat_cam.mean(axis=0) + mean_light = feat_light.mean(axis=0) + mean_detail = feat_detail.mean(axis=0) + mean_shape = feat_shape.mean(axis=0) + + print(f"feat_exp shape = {feat_exp.shape}, mean = {mean_exp.shape}, \n{mean_exp}") + print(f"mean_pos shape = {feat_pos.shape}, mean = {mean_pos.shape}, \n{mean_pos}") + print(f"mean_tex shape = {feat_tex.shape}, mean = {mean_tex.shape}, \n{mean_tex}") + print(f"mean_cam shape = {feat_cam.shape}, mean = {mean_cam.shape}, \n{mean_cam}") + print(f"mean_light shape = {feat_light.shape}, mean = {mean_light.shape}, \n{mean_light}") + print(f"mean_detail shape = {feat_detail.shape}, mean = {mean_detail.shape}, \n{mean_detail}") + print(f"mean_shape shape = {feat_shape.shape}, mean = {mean_shape.shape}, \n{mean_shape}") + + # save + mean_DECA = { + "exp": mean_exp, # (50, ) + "pose": mean_pos, # (6, ) + "tex": mean_tex, # (50, ) + "cam": mean_cam, # (3, ) + "light": mean_light, # (9, 3) + "detail": mean_detail,# (128, ) + "shape": mean_shape, # (100, ) + } + + path_save = "./data/DECA_LuoXData_mean.npy" + np.save(path_save, mean_DECA) + print("save to --> ", path_save) + +# Have 21499 frames +# feat_exp shape = (21499, 50), mean = (50,), +# [ 0.44338268 0.4472932 0.3063721 0.7504411 -0.4381568 -0.17690322 +# -0.05219001 -0.57315934 0.18184426 0.9165148 -0.59275323 0.56516534 +# -0.07709685 0.329883 0.3242076 -0.3435903 -0.6763506 -0.4351912 +# -0.04082069 0.8187175 0.03223863 -0.5716034 0.54998404 0.0491897 +# -0.1993383 0.09097239 -0.00910581 0.22115254 -0.16818044 -0.29952174 +# 0.09535432 -0.33055896 0.28673303 -0.25529468 0.19485517 -0.00993109 +# 0.07266268 -0.13707523 0.1642315 -0.05313531 -0.22445893 -0.09244996 +# -0.01606068 -0.01136032 -0.18826558 0.17590263 -0.04148029 0.15630233 +# -0.04461758 0.03858361] +# mean_pos shape = (21499, 6), mean = (6,), +# [ 0.25185004 0.06190158 -0.04912106 0.0478017 0.00894242 0.03168569] +# mean_tex shape = (21499, 50), mean = (50,), +# [-0.3978834 -0.42889112 -0.16672912 -0.0809032 -0.0311112 0.10049947 +# 0.33035028 -0.41055256 -0.11721741 -0.07116426 -0.04352681 0.308682 +# 0.25109372 -0.21540923 -0.03529367 0.1724729 0.23672035 0.24651733 +# 0.09847663 0.00665621 0.0794858 -0.06461164 0.01242481 0.052638 +# -0.03111307 -0.00460155 0.14652304 0.01369311 -0.1782642 0.10161535 +# -0.00404513 -0.08375361 0.12226686 0.08011193 -0.14495994 0.05208473 +# -0.13073783 0.14158903 -0.00310591 -0.13385871 -0.12640713 0.04086212 +# 0.12389808 -0.00319803 0.08630313 0.02669481 -0.04975258 0.06850675 +# 0.0145871 -0.03593108] +# mean_cam shape = (21499, 3), mean = (3,), +# [ 9.70313 -0.00973762 0.05297631] +# mean_light shape = (21499, 9, 3), mean = (9, 3), +# [[ 3.668586 3.6666408 3.6884367 ] +# [-0.02417332 -0.01953881 -0.02340931] +# [ 0.13705754 0.14098997 0.1339419 ] +# [-0.3177393 -0.33407646 -0.27969545] +# [ 0.03982113 0.03903044 0.03949506] +# [ 0.00550121 0.0090305 0.00659682] +# [-0.0473443 -0.0428174 -0.04730038] +# [ 0.2589516 0.25872716 0.2667857 ] +# [ 0.3665497 0.3590046 0.37101206]] +# mean_detail shape = (21499, 128), mean = (128,), +# [ 3.61521721e-01 6.14889897e-02 -9.27711353e-02 -4.99111451e-02 +# 9.35071558e-02 -4.14181035e-03 8.36418290e-03 1.42222671e-02 +# -6.43310547e-02 6.34927675e-02 -4.77789193e-02 -6.49932697e-02 +# -1.25051411e-02 -1.42840430e-01 -2.68053383e-01 -4.33399342e-02 +# 5.79991080e-02 -6.73886761e-02 -1.68433964e-01 3.68494689e-02 +# -1.16020657e-01 1.02660023e-01 5.25341071e-02 -8.19350109e-02 +# -1.01520777e-01 1.95464730e-01 -3.04076709e-02 -4.90539931e-02 +# -3.66580971e-02 -6.70471564e-02 3.78390849e-01 -5.20394333e-02 +# -4.54101205e-01 4.37255716e-03 5.44623472e-02 8.57212916e-02 +# 1.58119053e-01 -1.92813739e-01 9.49373189e-03 1.81852393e-02 +# 5.11284471e-02 1.03188865e-02 -7.73664191e-02 -2.01583542e-02 +# 5.95133752e-02 -7.51507431e-02 -9.99203101e-02 7.36503676e-02 +# 1.58722445e-01 6.02622665e-02 -3.20148505e-02 -4.51608598e-02 +# -8.57862309e-02 -7.13788047e-02 1.60456672e-02 1.00568458e-01 +# -2.49848496e-02 -9.89784896e-02 -3.26840989e-02 -3.01793907e-02 +# -6.15731366e-02 4.05075662e-02 6.88920915e-02 -1.12864830e-01 +# 2.88244411e-02 -9.44222510e-02 1.49918213e-01 -5.53867444e-02 +# -4.31086451e-01 3.11203804e-02 4.79492359e-02 -5.20009361e-02 +# 3.43780033e-02 2.66235732e-02 3.38539705e-02 -3.00715804e-01 +# -1.81968529e-02 -3.17425169e-02 1.62658636e-02 1.21782655e-02 +# -2.83036269e-02 1.15976281e-01 7.14496151e-02 4.37062651e-01 +# 4.90688123e-02 2.40370128e-02 -5.72391078e-02 -6.25709668e-02 +# 7.10044131e-02 -1.65119901e-01 -2.34024543e-02 -2.69950107e-02 +# 6.52964264e-02 2.17279568e-01 -8.76158103e-02 -9.41120610e-02 +# 2.69935168e-02 -7.41094574e-02 1.83443710e-01 -7.56433010e-02 +# 1.50024280e-01 3.49961817e-01 1.26819417e-01 2.67323870e-02 +# -2.79632300e-01 -4.44744639e-02 1.91484280e-02 -2.59159375e-02 +# 5.70407100e-02 -2.09884532e-02 -2.51313988e-02 -3.76658551e-02 +# 1.85259376e-02 -9.42206103e-03 7.46866986e-02 2.46279147e-02 +# -9.56854001e-02 6.84051365e-02 4.84354645e-01 4.01193229e-03 +# -2.31952056e-01 4.11941558e-02 -4.09149914e-04 5.58872700e-01 +# 3.48035753e-01 2.20942989e-01 -1.54582923e-02 5.18014990e-02] +# mean_shape shape = (21499, 100), mean = (100,), +# [-0.32458988 0.17692271 -0.59014773 -0.0735845 0.16357006 -0.35708523 +# 0.06076029 0.07674006 -0.21280588 -0.28636473 0.05864865 0.04630899 +# -0.00805237 -0.07572373 -0.01006004 -0.02728044 -0.03204667 0.05797856 +# -0.0428825 -0.3848283 0.39713535 0.0483583 0.19617037 0.14579436 +# 0.09192853 -0.09590823 -0.05430005 -0.15612626 0.13853826 -0.09018957 +# 0.03631187 0.05067807 -0.05036244 -0.00284541 -0.1159773 -0.08631504 +# -0.1413492 -0.01819041 -0.08816721 0.03550155 -0.11542681 0.15759806 +# 0.00542928 0.01032758 0.11571501 -0.1593183 0.05542826 -0.05267807 +# -0.35371011 -0.0929389 0.17742656 -0.38268778 0.0423925 -0.22057873 +# 0.05460614 -0.08430341 0.08110942 0.00884286 0.12435686 -0.00792618 +# -0.02667568 -0.18690723 -0.06518848 0.06365784 -0.03344199 -0.07648047 +# 0.01697154 -0.13141611 -0.01001224 0.00656717 -0.04314337 -0.181731 +# 0.0684299 -0.08775398 -0.06183273 -0.04920578 -0.10702839 0.01475282 +# 0.1069483 -0.01643799 0.00402089 -0.01572194 0.16098669 0.07922536 +# -0.01868843 0.02041192 -0.09030195 -0.03367294 0.01796311 -0.02930326 +# 0.10064717 -0.01723173 0.01651016 0.01912417 -0.00323546 -0.00704829 +# 0.0334241 -0.02697726 0.01572118 0.04431901] +# save to --> ./data/DECA_LuoXData_mean.npy + diff --git a/scripts/LuoXData/run-01-prepare-data.py b/scripts/LuoXData/run-01-prepare-data.py index d5bfb5e..08fb37f 100755 --- a/scripts/LuoXData/run-01-prepare-data.py +++ b/scripts/LuoXData/run-01-prepare-data.py @@ -11,13 +11,14 @@ if __name__ == '__main__': vpath_videos = sorted(path_root.glob("raw/*.mp4"), reverse=False) print(f"Have {len(vpath_videos)} dir files") + IDs = ["2021-P29"] # 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 + if iname not in IDs: continue # data path ipath_data = path_root.joinpath("processing2", ipath_item.stem) @@ -55,10 +56,10 @@ if __name__ == '__main__': 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 + # 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: @@ -94,7 +95,7 @@ if __name__ == '__main__': 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) + # # 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-20-deca-reconstruction.py b/scripts/LuoXData/run-20-deca-reconstruction.py index 8d4422c..d85d5fa 100644 --- a/scripts/LuoXData/run-20-deca-reconstruction.py +++ b/scripts/LuoXData/run-20-deca-reconstruction.py @@ -26,7 +26,7 @@ def main(args): print(f"Have {len(v_dir_videos)} dir files") # for each video - for ipath_data in v_dir_videos[17:]: + for ipath_data in v_dir_videos[18:]: ivideo_name = ipath_data.stem print("\nprocessing ...", ivideo_name) @@ -58,7 +58,6 @@ def main(args): 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: diff --git a/scripts/LuoXData/run-21-deca-render-video.py b/scripts/LuoXData/run-21-deca-render-video.py new file mode 100644 index 0000000..b3b5e13 --- /dev/null +++ b/scripts/LuoXData/run-21-deca-render-video.py @@ -0,0 +1,97 @@ +import sys +import numpy as np + +import torch +from pathlib import Path + +# common +sys.path.insert(0, "/ssdata1/lsen/CODE/Audio2Motion") +from common.animation import save_images_with_audio + +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 + +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() + + + +if __name__ == "__main__": + + # load data + pid = "2021-P09" # "2021-P22" + path_root = Path("/yrfs/lsen/DATA/LuoXData/processing2/") + path_data = path_root.joinpath(pid) + + path_pos = path_data.joinpath("audio/feat_DECA_pos_trim.npy") + path_idn = path_data.joinpath("audio/feat_DECA_idn_trim.npy") + path_exp = path_data.joinpath("audio/feat_DECA_exp_trim.npy") + # path_audio = path_data.joinpath("audio/audio_trim.wav") + path_audio = path_data.joinpath("audio/audio_trim_60_120s.wav") + + data_pos = np.load(path_pos)[3000:6000] # N x 6 + data_idn = np.load(path_idn)[3000:6000] # N x 100 + data_exp = np.load(path_exp)[3000:6000] # N x 50 + N = data_exp.shape[0] + + + # load mean + path_deca_mean = Path("./data/DECA_LuoXData_mean.npy") + mean_dict = np.load(path_deca_mean, allow_pickle=True).item() + print(mean_dict.keys()) + + # load deca model + device = torch.device("cuda:0") + deca_cfg.model.use_tex = False + deca_cfg.dataset.image_size = 512 + netR = DECA(config = deca_cfg, device=device) + + # render + path_save = path_data.joinpath("video/deca_render_no_pos_60_120s.mp4") + v_render_pt = [] + nbatch_render = 10 + for k in range(0, N, nbatch_render): + codedict = {} + + codedict["exp"] = data_exp[k:k+nbatch_render, :50] # (nbatch_render, 50) + + nbatch_real = codedict["exp"].shape[0] + + codedict["pose"] = np.zeros((nbatch_real, 6)) # (nbatch_render, 6) + codedict["pose"][:, 3:6] = data_pos[k:k+nbatch_render, 3:6] + # codedict["pose"] = data_pos[k:k+nbatch_render, :] # (nbatch_render, 6) + + # codedict["shape"] = np.zeros((nbatch_real, 100)) # (nabtch_render, 100) + codedict["shape"] = data_idn[k:k+nbatch_render, :] # (nabatch_render, 100) + + # others ==> to mean + mean_cam = [[5,0,0]] # or [self.mean_dict["cam"]] + codedict["cam"] = np.repeat(mean_cam, nbatch_real, axis=0) # (nbatch_render, 3) + codedict["light"] = np.repeat([mean_dict["light"]], nbatch_real, axis=0) # (nbatch_render, 9, 3) + # codedict["shape"] = np.repeat([mean_dict["shape"]], nbatch_real, axis=0) # (nbatch_render, 100) + codedict["detail"] = np.repeat([mean_dict["detail"]], nbatch_real, axis=0) # (nbatch_render, 128) + + + _, visdict_pt = netR.decode_one(codedict, nbatch_real, 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_images_with_audio(v_render_pt, path_audio, path_save) + + + + + + diff --git a/scripts/LuoXData/run-41-3dmm-ds-split-data.py b/scripts/LuoXData/run-41-train-dict-data-raw-deca.py similarity index 66% rename from scripts/LuoXData/run-41-3dmm-ds-split-data.py rename to scripts/LuoXData/run-41-train-dict-data-raw-deca.py index 332f6a6..f7e012e 100644 --- a/scripts/LuoXData/run-41-3dmm-ds-split-data.py +++ b/scripts/LuoXData/run-41-train-dict-data-raw-deca.py @@ -9,7 +9,7 @@ from scipy import interpolate import torchaudio def landmark_resample_fps(y, source_fps = 30, target_fps=25): - """y, N x 136, with 30fps + """ y, N x 136, with 30fps """ nsteps = y.shape[0] @@ -27,12 +27,11 @@ def landmark_resample_fps(y, source_fps = 30, target_fps=25): 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 = Path('data/LuoXData-raw-deca-3min') # processing path_save.mkdir(parents=True, exist_ok=True) v_dir_videos = sorted(path_data.glob("*"), reverse=False) @@ -43,26 +42,33 @@ if __name__ == "__main__": 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}") + # print(f"vids total= {vids}") + + # vid_test = set(["2021-P09", "2021-P22"]) + # vid_valid = set(["2021-P14", "2021-P20"]) + # vid_train = vids - vid_test - vid_test + + vids = set(["2021-P09", "2021-P14", "2021-P22"]) + vid_test = set(["2021-P09" ]) + vid_valid = set(["2021-P14" ]) + vid_train = set(["2021-P22" ]) - 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 + if vid not in vids: 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_idn = ipath_data.joinpath("audio/feat_DECA_idn_trim.npy") ipath_speech = ipath_data.joinpath("audio/audio_trim.wav") # check existing @@ -84,12 +90,16 @@ if __name__ == "__main__": # 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_exp = np.load(ipath_feat_exp) # (nframe, 50) + data_pos = np.load(ipath_feat_pos) # (nframe, 6) + data_idn = np.load(ipath_feat_idn) # (nframe, 100) - data_motion = np.concatenate([data_exp, pos_lips], axis=1) # (nframe, 53) --> fps=30 + assert data_exp.shape[0] == data_pos.shape[0], f"data_exp shape={data_exp.shape}, data_pos shape={data_pos.shape}" + assert data_exp.shape[0] == data_idn.shape[0], f"data_exp shape={data_exp.shape}, data_idn shape={data_idn.shape}" + + data_pos_head = data_pos[:, :3] # (nframe, 3) + data_pos_lips = data_pos[:, 3:] # (nframe, 3) + data_motion = np.concatenate([data_exp, data_pos_lips], axis=1) # (nframe, 53) --> fps=30 print(f"motion = {data_motion.shape}") @@ -105,6 +115,16 @@ if __name__ == "__main__": audio_raw = resampler(audio_raw).squeeze().numpy() print(f"audio_raw shape = {audio_raw.shape}, sr = {16000}, duration = {(len(audio_raw)/16000)}") + #################################### + # clips 4min + nclip = 4 + nframes = nclip * 60 * 50 # min * 60s * fps + nsegmts = nclip * 60 * 16000 # min * 60s * sr + data_motion = data_motion[:nframes] + audio_raw = audio_raw[:nsegmts] + data_idn = data_idn[:nframes] + #################################### + if vid in vid_train: durations_train += nframes/fps @@ -114,7 +134,8 @@ if __name__ == "__main__": "sr": 16000, "nframe": nframes, "data_motion": data_motion, - "data_speech": audio_raw + "data_speech": audio_raw, + "data_shape": data_idn, } @@ -126,7 +147,8 @@ if __name__ == "__main__": "sr": 16000, "nframe": nframes, "data_motion": data_motion, - "data_speech": audio_raw + "data_speech": audio_raw, + "data_shape": data_idn, } @@ -138,7 +160,8 @@ if __name__ == "__main__": "sr": 16000, "nframe": nframes, "data_motion": data_motion, - "data_speech": audio_raw + "data_speech": audio_raw, + "data_shape": data_idn, } @@ -147,7 +170,6 @@ if __name__ == "__main__": 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"Total frames: data_train ({durations_train / 60 } min) ({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-00-deca-render-video.py b/scripts/Obama/run-00-deca-render-video.py new file mode 100644 index 0000000..7540275 --- /dev/null +++ b/scripts/Obama/run-00-deca-render-video.py @@ -0,0 +1,104 @@ +import sys +import numpy as np + +import torch +from pathlib import Path + +# common +sys.path.insert(0, "/ssdata1/lsen/CODE/Audio2Motion") +from common.animation import save_images_with_audio + +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 + +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() + + + +if __name__ == "__main__": + + # load data + # pid = "Bringing-Our-Workplace-Policies-into-the-21st-Century" # "2021-P22" + pid = "Celebrating-Independence-Day" + path_root = Path("/yrfs/lsen/DATA/Obama/processing/") + path_data = path_root.joinpath(pid) + + path_pos = path_data.joinpath("audio/feat_DECA_pos_trim.npy") + path_idn = path_data.joinpath("audio/feat_DECA_idn_trim.npy") + path_exp = path_data.joinpath("audio/feat_DECA_exp_trim.npy") + # path_audio = path_data.joinpath("audio/audio_trim.wav") + path_audio = path_data.joinpath("audio/audio_trim_60_120s.wav") + + + fps = 29.97002997002997 + nframe_beg = int(60 * fps + 0.5) + nframe = int(120 * fps + 0.5) + print(f"fps = {fps}, beg = {nframe_beg}, len= 120s * fps = frame = {nframe}") + + data_pos = np.load(path_pos)[nframe_beg:nframe_beg+nframe] # N x 6 + data_idn = np.load(path_idn)[nframe_beg:nframe_beg+nframe] # N x 100 + data_exp = np.load(path_exp)[nframe_beg:nframe_beg+nframe] # N x 50 + N = data_exp.shape[0] + + + # load mean + path_deca_mean = Path("./data/DECA_obama_mean.npy") + mean_dict = np.load(path_deca_mean, allow_pickle=True).item() + print(mean_dict.keys()) + + # load deca model + device = torch.device("cuda:3") + deca_cfg.model.use_tex = False + deca_cfg.dataset.image_size = 512 + netR = DECA(config = deca_cfg, device=device) + + # render + path_save = path_data.joinpath("video/deca_render_no_pose_60_120s.mp4") + v_render_pt = [] + nbatch_render = 10 + for k in range(0, N, nbatch_render): + codedict = {} + + codedict["exp"] = data_exp[k:k+nbatch_render, :50] # (nbatch_render, 50) + + nbatch_real = codedict["exp"].shape[0] + + codedict["pose"] = np.zeros((nbatch_real, 6)) # (nbatch_render, 6) + codedict["pose"][:, 3:6] = data_pos[k:k+nbatch_render, 3:6] + # codedict["pose"] = data_pos[k:k+nbatch_render, :] # (nbatch_render, 6) + + # codedict["shape"] = np.zeros((nbatch_real, 100)) # (nabtch_render, 100) + codedict["shape"] = data_idn[k:k+nbatch_render, :] # (nabatch_render, 100) + + # others ==> to mean + mean_cam = [[5,0,0]] # or [self.mean_dict["cam"]] + codedict["cam"] = np.repeat(mean_cam, nbatch_real, axis=0) # (nbatch_render, 3) + codedict["light"] = np.repeat([mean_dict["light"]], nbatch_real, axis=0) # (nbatch_render, 9, 3) + # codedict["shape"] = np.repeat([mean_dict["shape"]], nbatch_real, axis=0) # (nbatch_render, 100) + codedict["detail"] = np.repeat([mean_dict["detail"]], nbatch_real, axis=0) # (nbatch_render, 128) + + + _, visdict_pt = netR.decode_one(codedict, nbatch_real, 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_images_with_audio(v_render_pt, path_audio, path_save) + + + + + + diff --git a/scripts/Obama/run-00-mean-coeff.py b/scripts/Obama/run-00-mean-coeff.py new file mode 100644 index 0000000..4d59bb8 --- /dev/null +++ b/scripts/Obama/run-00-mean-coeff.py @@ -0,0 +1,80 @@ +import numpy as np +from pathlib import Path + + +if __name__ == "__main__": + + # fid = "Bringing-Our-Workplace-Policies-into-the-21st-Century" + fid = "Equipping-Workers-with-Skills-Employers-Need-Now-and-for-the-Future" + path_root = Path("/yrfs/lsen/DATA/Obama/processing/") + path_data = path_root.joinpath(fid) + + path_coeff = path_data.joinpath("DECA_coeff") + vpath_coeff = sorted(path_coeff.glob("*.npy"), reverse=False) + print(f"Have {len(vpath_coeff)} frames") + + + feat_shape = [] + feat_tex = [] + feat_cam = [] + feat_exp = [] + feat_pos = [] + feat_light = [] + feat_detail = [] + + for ipath_coeff in vpath_coeff: + + data_coeff = np.load(ipath_coeff, allow_pickle=True).item() + + # print(data_coeff.keys()) + + feat_exp.append(data_coeff["exp"]) + feat_pos.append(data_coeff["pose"]) + feat_tex.append(data_coeff["tex"]) + feat_cam.append(data_coeff["cam"]) + feat_light.append(data_coeff["light"]) + feat_detail.append(data_coeff["detail"]) + feat_shape.append(data_coeff["shape"]) + + # save + feat_exp = np.array(feat_exp) # (nframe_trim, 50) + feat_pos = np.array(feat_pos) # (nframe_trim, 6) + feat_tex = np.array(feat_tex) # (nframe_trim, 50) + feat_cam = np.array(feat_cam) # (nframe_trim, 6) + feat_light = np.array(feat_light) # (nframe_trim, 50) + feat_detail = np.array(feat_detail) # (nframe_trim, 6) + feat_shape = np.array(feat_shape) # (nframe_trim, 50) + + mean_exp = feat_exp.mean(axis=0) + mean_pos = feat_pos.mean(axis=0) + mean_tex = feat_tex.mean(axis=0) + mean_cam = feat_cam.mean(axis=0) + mean_light = feat_light.mean(axis=0) + mean_detail = feat_detail.mean(axis=0) + mean_shape = feat_shape.mean(axis=0) + + print(f"feat_exp shape = {feat_exp.shape}, mean = {mean_exp.shape}, \n{mean_exp}") + print(f"mean_pos shape = {feat_pos.shape}, mean = {mean_pos.shape}, \n{mean_pos}") + print(f"mean_tex shape = {feat_tex.shape}, mean = {mean_tex.shape}, \n{mean_tex}") + print(f"mean_cam shape = {feat_cam.shape}, mean = {mean_cam.shape}, \n{mean_cam}") + print(f"mean_light shape = {feat_light.shape}, mean = {mean_light.shape}, \n{mean_light}") + print(f"mean_detail shape = {feat_detail.shape}, mean = {mean_detail.shape}, \n{mean_detail}") + print(f"mean_shape shape = {feat_shape.shape}, mean = {mean_shape.shape}, \n{mean_shape}") + + # save + mean_DECA = { + "exp": mean_exp, # (50, ) + "pose": mean_pos, # (6, ) + "tex": mean_tex, # (50, ) + "cam": mean_cam, # (3, ) + "light": mean_light, # (9, 3) + "detail": mean_detail,# (128, ) + "shape": mean_shape, # (100, ) + } + + path_save = "./data/DECA_obama_mean.npy" + # np.save(path_save, mean_DECA) + print("save to --> ", path_save) + + + diff --git a/scripts/Obama/run-53-3dmm-train-valid-test-dict.py b/scripts/Obama/run-53-train-dict-data-mel-deca.py similarity index 75% rename from scripts/Obama/run-53-3dmm-train-valid-test-dict.py rename to scripts/Obama/run-53-train-dict-data-mel-deca.py index 5b24679..524c451 100644 --- a/scripts/Obama/run-53-3dmm-train-valid-test-dict.py +++ b/scripts/Obama/run-53-train-dict-data-mel-deca.py @@ -9,41 +9,37 @@ from pathlib2 import Path if __name__ == "__main__": path_data = Path('/yrfs/lsen/DATA/Obama/processing') # '../data/trinity/source' - path_save = Path('data/obama-deca-mel') # processing + path_save = Path('data/obama-ds-daca-5h') # 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 = [ipath.stem for ipath in v_dir_videos] + print(f"Have {len(v_dir_videos)} video id[:3] > {vids[:3]}") - nv_total = len(v_dir_videos) - nv_valid, nv_test = 1, 1 - nv_train = nv_total - (nv_valid + nv_test) - vid_test = vids[:nv_test] - vid_valid = vids[nv_test:nv_test+nv_valid] - vid_train = vids[nv_test+nv_valid:] + vid_test = set(vids[:1]) + vid_valid = set(vids[1:2]) + vid_train = set(vids) - vid_test - vid_valid print("vid_test = ", vid_test) + print("vid_valid = ", vid_valid) # 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 - if i % 50 == 0: - print(f"\n processing the {i}-th video {vid} ... ") + print(f"\n processing the {i}-th video {vid} ... ") ipath_info = ipath_data.joinpath("video/info.json") ipath_exp = ipath_data.joinpath("audio/feat_DECA_exp_trim.npy") ipath_pos = ipath_data.joinpath("audio/feat_DECA_pos_trim.npy") + # ipath_speech = ipath_data.joinpath("audio/audio_trim.wav") ipath_speech = ipath_data.joinpath("audio/feat_mel_no_align_trim.npy") - - if not ipath_speech.exists(): print(f"ERROR: NOT Exist {ipath_speech}" ) continue @@ -53,19 +49,14 @@ if __name__ == "__main__": continue # check existing - if not ipath_speech.exists() or not ipath_info.exists(): - msg = "ERROR: NOT exsiting " - if not ipath_info.exists(): - msg += f"\n\t {ipath_info} " - if not ipath_speech.exists(): - msg += f"\n\t {ipath_speech} " - - print(msg) + if not ipath_info.exists(): + print(f"ERROR: NOT Exist {ipath_info}") continue # load video info with open(str(ipath_info), "r") as f: info = json.load(f) + fps = info["info"] # 29.89990, NOT fixed width = info["width"][0] # 1280 or 1920 height = info["height"][0] # 720 or 1080 print("\nwidth=",width, "height=",height, "fps=",info["fps"], "-->", ipath_data) @@ -81,12 +72,16 @@ if __name__ == "__main__": continue # load data - # feat_idn = np.load(ipath_idn) # (nframe_trim, 100) - feat_exp = np.load(ipath_exp) # (nframe_trim, 50) - feat_pos = np.load(ipath_pos) # (nframe_trim, 6) # (N, 6) - data_motion = np.concatenate([feat_exp, feat_pos[:, 3:6]], axis=1) # (N, 53) - data_speech = np.load(ipath_speech) # (M, 80) please note that M != N + feat_exp = np.load(ipath_exp) # (nframe_trim, 50) + feat_pos = np.load(ipath_pos) # (nframe_trim, 6) + feat_pos_head = feat_pos[:, :3] # (nframe_trim, 3) + feat_pos_lips = feat_pos[:, 3:] # (nframe_trim, 3) + data_motion = np.concatenate([feat_exp, feat_pos_lips], axis=1) # (N, 53) + print(f"motion = {data_motion.shape}") + + # load raw audio + data_speech = np.load(ipath_speech) # (M, 80) please note that M != N print(f"motion data = {data_motion.shape}, speech data = {data_speech.shape}") # assert data_motion.shape[0] == data_speech.shape[0] diff --git a/scripts/Obama/run-53-train-dict-data-raw-deca.py b/scripts/Obama/run-53-train-dict-data-raw-deca.py new file mode 100644 index 0000000..b17b91b --- /dev/null +++ b/scripts/Obama/run-53-train-dict-data-raw-deca.py @@ -0,0 +1,168 @@ +import json +import torchaudio +import numpy as np +from pathlib2 import Path +from scipy import interpolate + +def convert_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/Obama/processing') # '../data/trinity/source' + path_save = Path('data/obama-raw-deca-9h-50fps') # processing + path_save.mkdir(parents=True, exist_ok=True) + + v_dir_videos = sorted(path_data.glob("*/audio/feat_DECA_exp_trim.npy")) + v_dir_videos = [ipath.parent.parent for ipath in v_dir_videos] + vids = [ipath.stem for ipath in v_dir_videos] + print(f"Have {len(v_dir_videos)} video id[:3] > {vids[:3]}") + + vid_test = set(vids[:2]) + vid_valid = set(vids[2:4]) + vid_train = set(vids) - vid_test - vid_valid + print("vid_test = ", vid_test) + print("vid_valid = ", vid_valid) + + # 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_exp = ipath_data.joinpath("audio/feat_DECA_exp_trim.npy") + ipath_pos = ipath_data.joinpath("audio/feat_DECA_pos_trim.npy") + ipath_idn = ipath_data.joinpath("audio/feat_DECA_idn_trim.npy") + ipath_speech = ipath_data.joinpath("audio/audio_trim.wav") + + if not ipath_speech.exists(): + print(f"ERROR: NOT Exist {ipath_speech}" ) + continue + + if not ipath_exp.exists() or not ipath_pos.exists(): + print(f"ERROR: NOT Exist {ipath_pos} or {ipath_exp}" ) + continue + + # check existing + if not ipath_info.exists(): + print(f"ERROR: NOT Exist {ipath_info}") + continue + + # load video info + with open(str(ipath_info), "r") as f: + info = json.load(f) + fps = info["fps"] # 29.89990, NOT fixed + width = info["width"][0] # 1280 or 1920 + height = info["height"][0] # 720 or 1080 + print("\nwidth=",width, "height=",height, "fps=",fps, "-->", ipath_data) + + # fps = info["fps"] + if len(info["active_frames"]) == 2: + ibeg = info["active_frames"][0] + iend = info["active_frames"][1] + nframe_trim = iend - ibeg + # print(f"frame trim = {nframe_trim}, info['active_frames'] = {info['active_frames']}") + else: + print(f"ERROR: info['active_frames'] = {info['active_frames']}") + continue + + # load data + feat_exp = np.load(ipath_exp) # (nframe_trim, 50) + feat_pos = np.load(ipath_pos) # (nframe_trim, 6) + feat_idn = np.load(ipath_idn) # (nframe_trim, 100) + + feat_pos_head = feat_pos[:, :3] # (nframe_trim, 3) + feat_pos_lips = feat_pos[:, 3:] # (nframe_trim, 3) + data_motion = np.concatenate([feat_exp, feat_pos_lips], axis=1) # (N, 53) + print(f"motion = {data_motion.shape}") + + # laod shape + + + # resample to 30fps + fps_convert = 50 + data_motion = convert_fps(data_motion, source_fps=fps, target_fps=fps_convert) + data_shape = convert_fps(feat_idn, source_fps=fps, target_fps=fps_convert) + nframe_convert = data_motion.shape[0] + assert data_motion.shape[0] == data_shape.shape[0], f"motion = {data_motion.shape[0]} shape = {data_shape.shape[0]}" + + print(f"after convert motion = {data_motion.shape}, duration = {nframe_convert / fps_convert} vs. orignal duration = {nframe_trim / fps}") + # print(f"after convert shape = {data_shape.shape}, duration = {nframe_convert / fps_convert} vs. orignal duration = {nframe_trim / fps}") + + # 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)}") + + # add to data dict + if vid in vid_train: + durations_train += nframe_trim / fps + data_train[vid] = { + "W": width, "H": height, + "sr":16000, "FPS": fps_convert, + "nframe": nframe_convert, + "data_motion": data_motion, + "data_speech": audio_raw, + "data_shape": data_shape, + } + + if vid in vid_valid: + durations_valid += nframe_trim / fps + data_valid[vid] = { + "W": width, "H": height, + "sr":16000, "FPS": fps_convert, + "nframe": nframe_convert, + "data_motion": data_motion, + "data_speech": audio_raw, + "data_shape": data_shape, + } + + if vid in vid_test: + durations_test += nframe_trim / fps + data_test[vid] = { + "W": width, "H": height, + "sr":16000, "FPS": fps_convert, + "nframe": nframe_convert, + "data_motion": data_motion, + "data_speech": audio_raw, + "data_shape": data_shape, + } + + + + 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/stack_video.py b/scripts/Obama/stack_video.py new file mode 100644 index 0000000..958d46f --- /dev/null +++ b/scripts/Obama/stack_video.py @@ -0,0 +1,62 @@ +import os +import numpy as np +import moviepy.editor as mpy +from pathlib import Path + + + +if __name__ == "__main__": + + + fps_save = 30 + path_save = "/yrfs/lsen/DATA/Obama/processing/Celebrating-Independence-Day/video/audio2mesh_compare_60_115_GT.mp4" + + path_clipA = "experiments/audio2mesh/infer_audio2mesh_EN_20220208/20220225-17H57M52S/audio_trim_60_120s_infer_20220217-17H36M22S_epoch_115_00.mp4" + path_clipB = "experiments/audio2mesh/infer_audio2mesh_EN_20220208/20220225-17H48M06S/audio_trim_60_120s_infer_20220223-22H17M02S_epoch_060_00.mp4" + path_clipC = "/yrfs/lsen/DATA/Obama/processing/Celebrating-Independence-Day/video/deca_render_no_pose_60_120s.mp4" + + + # path_clipAA = "experiments/audio2mesh/infer_audio2mesh_EN_20220208/20220224-17H27M45S/audio_trim_120s_infer_20220223-22H17M02S_epoch_060_00.mp4" + # path_clipBB = "/yrfs/lsen/DATA/Obama/processing/Bringing-Our-Workplace-Policies-into-the-21st-Century/video/deca_render_no_pose_120s.mp4" + # path_clipCC = "/yrfs/lsen/DATA/LuoXData/processing2/2021-P09/video/deca_render_no_pos_60_120s.mp4" + + path_audio = "/yrfs/lsen/DATA/Obama/processing/Celebrating-Independence-Day/audio/audio_trim_60_120s.wav" + + clip_A = mpy.VideoFileClip(path_clipA) + clip_B = mpy.VideoFileClip(path_clipB) + clip_C = mpy.VideoFileClip(path_clipC) + + # clip_AA = mpy.VideoFileClip(path_clipAA) + # clip_BB = mpy.VideoFileClip(path_clipBB) + # clip_CC = mpy.VideoFileClip(path_clipCC) + + audio = mpy.AudioFileClip(path_audio) + + # txtClip = mpy.TextClip('orignal',color='white', kerning = 5, fontsize=18) + # clip_A = mpy.CompositeVideoClip( [clip_A, txtClip.set_pos('top')], size=(512,512)) + + # txtClip = mpy.TextClip('-pose',color='white', kerning = 5, fontsize=18) + # clip_B = mpy.CompositeVideoClip( [clip_B, txtClip.set_pos('top')], size=(512,512)) + + # txtClip = mpy.TextClip('-pose-idn',color='white', kerning = 5, fontsize=18) + # clip_C = mpy.CompositeVideoClip( [clip_C, txtClip.set_pos('top')], size=(512,512)) + + # align to clipGT + duration = min(min(clip_A.duration, clip_C.duration), audio.duration) + + clip_A = clip_A.set_duration(duration) + clip_B = clip_B.set_duration(duration) + clip_C = clip_C.set_duration(duration) + audio = audio.set_duration(duration) + + # stack + # video = mpy.clips_array([[clip_A, clip_B], [clip_AA, clip_BB]]) # clip_C + video = mpy.clips_array([[clip_A, clip_B, clip_C]]) # clip_C + video = video.set_audio(audio) # audd audio + + # save + video.write_videofile(path_save, fps=fps_save, logger=None) + print(f"save to > {path_save}") + + + diff --git a/scripts/Test/frames-to-video-2.py b/scripts/Test/frames-to-video-2.py new file mode 100644 index 0000000..13b87ae --- /dev/null +++ b/scripts/Test/frames-to-video-2.py @@ -0,0 +1,110 @@ +import moviepy +import numpy as np +from pathlib import Path + +from moviepy.editor import * + +STEP_VIDEO = False +STEP_CONCATE = True + +if __name__ == "__main__": + + video_name = "2021-P09" + path_root = Path(f"/yrfs/lsen/DATA/LuoXData/processing2/{video_name}") + path_frame = path_root.joinpath(f"frames") + path_audio = path_root.joinpath("audio/audio_trim.wav") + + # load audio + clip_audio = AudioFileClip(str(path_audio)) + clip_audio.set_duration(120.0) + + # load video + clip_video = ImageSequenceClip(path_frame, fps=50, load_images=True) + clip_video.set_duration(120.0) + + # add audio + clip_image.write_videofile(str(path_image_save), fps=25) + + concate_clips = concate_clips.set_audio(clip_audio) + + # save + path_concate_save = path_data.joinpath("concate4.mp4") + #concate_clips = concate_clips.resize(width=720) + + concate_clips.write_videofile(str(path_concate_save), fps=25) + + + + + + # # to video + # if STEP_VIDEO: + # path_image = path_data.joinpath("frames_crop") + # path_image_save = path_data.joinpath("images.mp4") + # clip_image = ImageSequenceClip(path_image, fps=25, load_images=True) + # clip_image.write_videofile(str(path_image_save), fps=25) + + # path_frame = path_data.joinpath("render") + # path_frame_save = path_data.joinpath("render.mp4") + # clip_render = ImageSequenceClip(path_frame, fps=25, load_images=True) + # clip_render.write_videofile(str(path_frame_save), fps=25) + + # path_frame = path_data.joinpath("render_pt") + # path_frame_save = path_data.joinpath("render_pt.mp4") + # clip_render_pt = ImageSequenceClip(path_frame, fps=25, load_images=True) + # clip_render_pt.write_videofile(str(path_frame_save), fps=25) + + # path_frame = path_data.joinpath("render_pt_fix_idn") + # path_frame_save = path_data.joinpath("render_pt_fix_idn.mp4") + # clip_render_pt2 = ImageSequenceClip(path_frame, fps=25, load_images=True) + # clip_render_pt2.write_videofile(str(path_frame_save), fps=25) + + + # # concate + # if STEP_CONCATE: + + # # image + # clip_image = VideoFileClip(str(path_data.joinpath("images.mp4"))).margin(10) + # clip_text = TextClip("Crop Image", fontsize = 14, color = 'white', stroke_width=3) + # clip_text = clip_text.set_pos((0.4, 0.9), relative=True).set_duration(clip_image.duration) + # clip_image = CompositeVideoClip([clip_image, clip_text]) + + # # render + # clip_render = VideoFileClip(str(path_data.joinpath("render.mp4"))).margin(10) + # clip_text = TextClip("Render GT", fontsize = 14, color = 'white', stroke_width=3) + # clip_text = clip_text.set_pos((0.4,0.9), relative=True).set_duration(clip_render.duration) + # clip_render = CompositeVideoClip([clip_render, clip_text]) + + # # render with specific identiy + # clip_render2 = VideoFileClip(str(path_data.joinpath("render_pt.mp4"))).margin(10) + # clip_text = TextClip("Render PT fix identity", fontsize = 14, color = 'white', stroke_width=3) + # clip_text = clip_text.set_pos((0.2,0.9), relative=True).set_duration(clip_render2.duration) + # clip_render2 = CompositeVideoClip([clip_render2, clip_text]) + + # # render with specific identiy + # clip_render3 = VideoFileClip(str(path_data.joinpath("render_pt_fix_idn.mp4"))).margin(10) + # # clip_text = TextClip("Render PT with fixed identity", fontsize = 14, color = 'red') + # # clip_text = clip_text.set_pos("center", "top").set_duration(clip_render3.duration) + # # clip_render3 = CompositeVideoClip([clip_render3, clip_text]) + + + # # audio + # path_audio = path_data.joinpath("../audio/test_video.wav") + # clip_audio = AudioFileClip(str(path_audio)) + + # # concate + # # concate_clips = clips_array([[clip_image, clip_render], + # # [clip_render2, clip_render3]]) + # concate_clips = clips_array([[clip_image, clip_render, clip_render2]]) + + # concate_clips = concate_clips.set_audio(clip_audio) + + # # save + # path_concate_save = path_data.joinpath("concate4.mp4") + # #concate_clips = concate_clips.resize(width=720) + + # concate_clips.write_videofile(str(path_concate_save), fps=25) + + + + diff --git a/scripts/Test/stack_video.py b/scripts/Test/stack_video.py new file mode 100644 index 0000000..eb152ca --- /dev/null +++ b/scripts/Test/stack_video.py @@ -0,0 +1,69 @@ +import os +import numpy as np +import moviepy.editor as mpy +from pathlib import Path + + + +if __name__ == "__main__": + + + # path_clipA = "/ssdata1/lsen/CODE/voca/data/animation_obama/video_save.mp4" + # path_clipB = "/ssdata1/lsen/CODE/Audio2Motion/experiments/audio2mesh/infer_audio2mesh_EN_20220208/20220216-12H58M21S/obama_infer_20220215-15H12M28S_epoch_120_00.mp4" + # path_audio = "/ssdata1/lsen/CODE/voca/data/audio/obama.wav" + + # path_clipA = "/ssdata1/lsen/CODE/voca/data/animation_obama2/video_save.mp4" + # path_clipB = "/ssdata1/lsen/CODE/Audio2Motion/experiments/audio2mesh/infer_audio2mesh_EN_20220208/20220216-13H01M33S/audio_trim_infer_20220215-15H12M28S_epoch_120_00.mp4" + # path_audio = "/yrfs/lsen/DATA/Obama/processing/Bringing-Our-Workplace-Policies-into-the-21st-Century/audio/audio_trim.wav" + + path_clipA = "/ssdata1/lsen/CODE/Audio2Motion/experiments/audio2mesh/infer_audio2mesh_CN_20220208/20220214-18H49M33S/audio_trim_60_120s_infer_20220211-15H41M37S_epoch_120_00.mp4" + path_clipB = "/ssdata1/lsen/CODE/Audio2Motion/experiments/audio2mesh/infer_audio2mesh_CN_20220208/20220223-19H47M15S/audio_trim_60_120s_infer_20220217-18H29M20S_epoch_160_00.mp4" + path_clipC = "/yrfs/lsen/DATA/LuoXData/processing2/2021-P09/video/deca_render_no_idn_no_pos_60_120s.mp4" + # path_audio = "/yrfs/lsen/DATA/LuoXData/processing2/2021-P09/audio/audio_trim_60_120s.wav" + + path_clipAA = "experiments/audio2mesh/infer_audio2mesh_EN_20220208/20220223-21H45M05S/audio_trim_60_120s_infer_20220215-15H12M28S_epoch_120_00.mp4" + path_clipBB = "experiments/audio2mesh/infer_audio2mesh_CN_20220208/20220223-20H51M40S/audio_trim_60_120s_infer_20220222-10H37M51S_epoch_235_00.mp4" + path_clipCC = "/yrfs/lsen/DATA/LuoXData/processing2/2021-P09/video/deca_render_no_pos_60_120s.mp4" + + + path_audio = "/yrfs/lsen/DATA/LuoXData/processing2/2021-P09/audio/audio_trim_60_120s.wav" + + clip_A = mpy.VideoFileClip(path_clipA) + clip_B = mpy.VideoFileClip(path_clipB) + clip_C = mpy.VideoFileClip(path_clipC) + + clip_AA = mpy.VideoFileClip(path_clipAA) + clip_BB = mpy.VideoFileClip(path_clipBB) + clip_CC = mpy.VideoFileClip(path_clipCC) + + audio = mpy.AudioFileClip(path_audio) + + # txtClip = mpy.TextClip('orignal',color='white', kerning = 5, fontsize=18) + # clip_A = mpy.CompositeVideoClip( [clip_A, txtClip.set_pos('top')], size=(512,512)) + + # txtClip = mpy.TextClip('-pose',color='white', kerning = 5, fontsize=18) + # clip_B = mpy.CompositeVideoClip( [clip_B, txtClip.set_pos('top')], size=(512,512)) + + # txtClip = mpy.TextClip('-pose-idn',color='white', kerning = 5, fontsize=18) + # clip_C = mpy.CompositeVideoClip( [clip_C, txtClip.set_pos('top')], size=(512,512)) + + # align to clipGT + duration = min(min(clip_A.duration, clip_B.duration), audio.duration) + + clip_A = clip_A.set_duration(duration) + clip_B = clip_B.set_duration(duration) + # clip_C = clip_C.set_duration(duration) + audio = audio.set_duration(duration) + + # stack + video = mpy.clips_array([[clip_A, clip_B, clip_C], [clip_AA, clip_BB, clip_CC]]) # clip_C + video = video.set_audio(audio) # audd audio + + # save + path_save = "/yrfs/lsen/DATA/LuoXData/processing2/2021-P09/video/predict_compare_6.mp4" + # path_save = "/ssdata1/lsen/CODE/Audio2Motion/experiments/audio2mesh/infer_audio2mesh_EN_20220208/20220216-12H58M21S/compare_voca.mp4" + video.write_videofile(path_save, fps=50, logger=None) + print(f"save to > {path_save}") + + + diff --git a/scripts/stack_video_diverse.py b/scripts/Test/stack_video_diverse.py similarity index 100% rename from scripts/stack_video_diverse.py rename to scripts/Test/stack_video_diverse.py diff --git a/scripts/TestData/run-01-prepare-data.py b/scripts/TestData/run-01-prepare-data.py new file mode 100755 index 0000000..1ea9959 --- /dev/null +++ b/scripts/TestData/run-01-prepare-data.py @@ -0,0 +1,123 @@ +from pathlib import Path +import json +import moviepy +from moviepy.editor import VideoFileClip, AudioFileClip + + +if __name__ == '__main__': + + path_root = Path("/yrfs/lsen/DATA/TestData") + + vpath_videos = sorted(path_root.glob("raw/*.mp4"), reverse=False) + print(f"Have {len(vpath_videos)} dir files") + + # IDs = ["2021-P29"] + + # 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("processing", 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 + + + + # save sub video fps=50 + ipath_video_sub = ipath_video.joinpath("video_trim.mp4") + + if ipath_video_sub.exists(): + print("\nERROR: ipath_video_sub.exists()") + continue + else: + video.write_videofile(str(ipath_video_sub), fps=50, audio=True) + print(f"save video > {ipath_video_sub}") + + + # reload video + video.close() + video = VideoFileClip(str(ipath_video_sub)) + print(f"video reload duration = {video.duration}, fps = {video.fps}, (start, end)=({video.start},{video.end}), nframes={int(video.duration * video.fps)}") + + + # Trim + # video = video.subclip(t_start=20.0, t_end=int(video.duration)-20.0) + # print(f"after cut video duration = {video.duration}, fps = {video.fps}, (start, end)=({video.start},{video.end}), nframes={int(video.duration * video.fps)}") + nframes = int(video.duration * video.fps) + + # check frames + nframe_real = len(list(ipath_frame.glob("*.jpg"))) + if nframe_real == nframes: + print(f"\n Skip: have already done!") + continue + + # get audio + audio_sub = video.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}") + + + # # check fps + # if int(video.fps) != 50: + # print(f"\n Skip: fps != 50 realy fps={video.fps}, convert to 50fps") + + # ipath_video_save = ipath_data.joinpath("video", f"video_50fps.mp4") + # video.write_videofile(str(ipath_video_save), fps=50.0) + # print(f"save video to > {ipath_video_save}...") + + # save video feature + info = {"nframes": nframes, + "fps": video.fps, + "width": video.w, + "height": video.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 trim video + print(f"write_images_sequence...") + ipath_format = str(ipath_frame) + "/frame-%06d.jpg" + video.write_images_sequence(ipath_format, fps=50) + + + + + diff --git a/scripts/TestData/run-20-deca-reconstruction.py b/scripts/TestData/run-20-deca-reconstruction.py new file mode 100644 index 0000000..3bb4fd0 --- /dev/null +++ b/scripts/TestData/run-20-deca-reconstruction.py @@ -0,0 +1,145 @@ +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/TestData/processing") + 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[1:]: + 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) + + # save vis + # cv2.imwrite(str(ipath_vis.joinpath(f"{jname}_vis.jpg")), deca.visualize(visdict)) + + # 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:2', 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/TestData/run-21-deca-render-video.py b/scripts/TestData/run-21-deca-render-video.py new file mode 100644 index 0000000..bbaccc0 --- /dev/null +++ b/scripts/TestData/run-21-deca-render-video.py @@ -0,0 +1,95 @@ +import sys +import numpy as np + +import torch +from pathlib import Path + +# common +sys.path.insert(0, "/ssdata1/lsen/CODE/Audio2Motion") +from common.animation import save_images_with_audio + +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 + +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() + + + +if __name__ == "__main__": + + # load data + pid = "1645666605877506" # "2021-P22" + path_root = Path("/yrfs/lsen/DATA/TestData/processing/") + path_data = path_root.joinpath(pid) + + path_pos = path_data.joinpath("audio/feat_DECA_pos_trim.npy") + path_idn = path_data.joinpath("audio/feat_DECA_idn_trim.npy") + path_exp = path_data.joinpath("audio/feat_DECA_exp_trim.npy") + path_audio = path_data.joinpath("audio/audio_trim.wav") + # path_audio = path_data.joinpath("audio/audio_trim_60_120s.wav") + + data_pos = np.load(path_pos) # N x 6 + data_idn = np.load(path_idn) # N x 100 + data_exp = np.load(path_exp) # N x 50 + N = data_exp.shape[0] + + + # load mean + path_deca_mean = Path("./data/DECA_LuoXData_mean.npy") + mean_dict = np.load(path_deca_mean, allow_pickle=True).item() + print(mean_dict.keys()) + + # load deca model + device = torch.device("cuda:0") + deca_cfg.model.use_tex = False + deca_cfg.dataset.image_size = 512 + netR = DECA(config = deca_cfg, device=device) + + # render + path_save = path_data.joinpath("video/deca_render_no_pos_no_idn.mp4") + v_render_pt = [] + nbatch_render = 10 + for k in range(0, N, nbatch_render): + codedict = {} + + codedict["exp"] = data_exp[k:k+nbatch_render, :50] # (nbatch_render, 50) + + nbatch_real = codedict["exp"].shape[0] + + codedict["pose"] = np.zeros((nbatch_real, 6)) # (nbatch_render, 6) + codedict["pose"][:, 3:6] = data_pos[k:k+nbatch_render, 3:6] + # codedict["pose"] = data_pos[k:k+nbatch_render, :] # (nbatch_render, 6) + + codedict["shape"] = np.zeros((nbatch_real, 100)) # (nabtch_render, 100) + # codedict["shape"] = data_idn[k:k+nbatch_render, :] # (nabatch_render, 100) + + # others ==> to mean + mean_cam = [[5,0,0]] # or [self.mean_dict["cam"]] + codedict["cam"] = np.repeat(mean_cam, nbatch_real, axis=0) # (nbatch_render, 3) + codedict["light"] = np.repeat([mean_dict["light"]], nbatch_real, axis=0) # (nbatch_render, 9, 3) + codedict["detail"] = np.repeat([mean_dict["detail"]], nbatch_real, axis=0) # (nbatch_render, 128) + + _, visdict_pt = netR.decode_one(codedict, nbatch_real, 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_images_with_audio(v_render_pt, path_audio, path_save) + + + + + + diff --git a/scripts/TestData/run-30-features-3dmm.py b/scripts/TestData/run-30-features-3dmm.py new file mode 100644 index 0000000..2d986c1 --- /dev/null +++ b/scripts/TestData/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/TestData/processing') # '../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)): + + 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/TestData/stack_video.py b/scripts/TestData/stack_video.py new file mode 100644 index 0000000..aab5c3a --- /dev/null +++ b/scripts/TestData/stack_video.py @@ -0,0 +1,62 @@ +import os +import numpy as np +import moviepy.editor as mpy +from pathlib import Path + + + +if __name__ == "__main__": + + + fps_save = 50 + path_save = "/yrfs/lsen/DATA/TestData/processing/1645666605877506/video/predict_compare_3.mp4" + + path_clipA = "/yrfs/lsen/DATA/TestData/processing/1645666605877506/video/deca_render.mp4" + path_clipB = "/yrfs/lsen/DATA/TestData/processing/1645666605877506/video/deca_render_no_pos.mp4" + path_clipC = "/yrfs/lsen/DATA/TestData/processing/1645666605877506/video/deca_render_no_pos_no_idn.mp4" + + # path_clipAA = "experiments/audio2mesh/infer_audio2mesh_EN_20220208/20220223-21H45M05S/audio_trim_60_120s_infer_20220215-15H12M28S_epoch_120_00.mp4" + # path_clipBB = "experiments/audio2mesh/infer_audio2mesh_CN_20220208/20220223-20H51M40S/audio_trim_60_120s_infer_20220222-10H37M51S_epoch_235_00.mp4" + # path_clipCC = "/yrfs/lsen/DATA/LuoXData/processing2/2021-P09/video/deca_render_no_pos_60_120s.mp4" + + + path_audio = "/yrfs/lsen/DATA/TestData/processing/1645666605877506/audio/audio_trim.wav" + + clip_A = mpy.VideoFileClip(path_clipA) + clip_B = mpy.VideoFileClip(path_clipB) + clip_C = mpy.VideoFileClip(path_clipC) + + # clip_AA = mpy.VideoFileClip(path_clipAA) + # clip_BB = mpy.VideoFileClip(path_clipBB) + # clip_CC = mpy.VideoFileClip(path_clipCC) + + audio = mpy.AudioFileClip(path_audio) + + # txtClip = mpy.TextClip('orignal',color='white', kerning = 5, fontsize=18) + # clip_A = mpy.CompositeVideoClip( [clip_A, txtClip.set_pos('top')], size=(512,512)) + + # txtClip = mpy.TextClip('-pose',color='white', kerning = 5, fontsize=18) + # clip_B = mpy.CompositeVideoClip( [clip_B, txtClip.set_pos('top')], size=(512,512)) + + # txtClip = mpy.TextClip('-pose-idn',color='white', kerning = 5, fontsize=18) + # clip_C = mpy.CompositeVideoClip( [clip_C, txtClip.set_pos('top')], size=(512,512)) + + # align to clipGT + duration = min(min(clip_A.duration, clip_B.duration), audio.duration) + + clip_A = clip_A.set_duration(duration) + clip_B = clip_B.set_duration(duration) + # clip_C = clip_C.set_duration(duration) + audio = audio.set_duration(duration) + + # stack + # video = mpy.clips_array([[clip_A, clip_B, clip_C], [clip_AA, clip_BB, clip_CC]]) # clip_C + video = mpy.clips_array([[clip_A, clip_B, clip_C]]) # clip_C + video = video.set_audio(audio) # audd audio + + # save + video.write_videofile(path_save, fps=fps_save, logger=None) + print(f"save to > {path_save}") + + + diff --git a/src/config.py b/src/config.py index 4504c6e..f362e0a 100644 --- a/src/config.py +++ b/src/config.py @@ -58,6 +58,7 @@ config.CUDNN.enable = True config.MODEL = edict() config.MODEL.name = "LandmarkAE" config.MODEL.name_netG = "MLP" +config.MODEL.name_header = "resnet50" config.MODEL.dropout = 0.1 # load & init model @@ -66,11 +67,12 @@ config.MODEL.path_pretrained = "" config.MODEL.path_checkpoint = "" config.MODEL.load_epoch = 0 -# for MOGLOW config.MODEL.dim_motion = 0 config.MODEL.dim_speech = 0 config.MODEL.dim_hidden = 0 +config.MODEL.num_vertices = 0 # 5023 + config.MODEL.n_lookprevs_motion = 0 config.MODEL.n_lookprevs_speech = 0 @@ -80,11 +82,14 @@ config.MODEL.n_lookahead_speech = 0 config.MODEL.n_layer_lstm = 0 -# # for wavenet -# config.MODEL.n_early_every = 0 -# config.MODEL.n_early_size = 0 -# config.MODEL.n_layer_wave = 0 -# config.MODEL.kernel_size = 0 +# for MOGLOW +config.MODEL.n_flowstep = 0 +config.MODEL.n_early_every = 0 +config.MODEL.n_early_size = 0 +config.MODEL.n_layer_wave = 0 +config.MODEL.kernel_size = 0 +config.MODEL.lambda_std = [] +config.MODEL.fix_dims = [] # # for transformer # config.MODEL.n_src_vocab = 0 @@ -125,6 +130,8 @@ config.DATASET.sr = 16000 config.DATASET.name = 'ravdess' config.DATASET.type = '' # "clips" | "frame" | "none" config.DATASET.root = "../data/" +config.DATASET.root_raw = "/data/lsen/DATA/xxxx/processing" +config.DATASET.path_mean_dict = "./data/xxxx_mean.npy" # from dataset iteratiion config.DATASET.nwind_second_train = 0 @@ -182,7 +189,7 @@ config.TRAIN.beta_stop = 1.0 config.TRAIN.optimizer = 'adam' config.TRAIN.momentum = 0.9 -config.TRAIN.weight_decay = 0.0001 +config.TRAIN.weight_decay = 0 #0.0001 config.TRAIN.nesterov = False config.TRAIN.gamma1 = 0.99 config.TRAIN.gamma2 = 0.0 @@ -193,13 +200,19 @@ config.LOSS = edict() config.LOSS.names = ["all", "L1"] config.LOSS.lambda_rec = 1 +config.LOSS.lambda_rec_smooth = 0 + config.LOSS.lambda_rec_exp = 0 config.LOSS.lambda_rec_pos = 0 +config.LOSS.lambda_rec_geo = 0 +config.LOSS.lambda_rec_syn = 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 +config.LOSS.lambda_vol_geo = 0 +config.LOSS.lambda_vol_syn = 0 + +# for Flow config.LOSS.lambda_logp = 0 config.LOSS.lambda_logdet = 0 diff --git a/src/datasets/motion_live.py b/src/datasets/motion_live.py index 96e35ec..147228c 100644 --- a/src/datasets/motion_live.py +++ b/src/datasets/motion_live.py @@ -18,18 +18,23 @@ class MotionLiveDataset(Dataset): """ super(MotionLiveDataset, self).__init__() + self.opt = opt self.phase = phase path_data= Path(opt.DATASET.root).joinpath(f"data_{phase}.npz") + # for test + # if phase == "valid": + # path_data= Path(opt.DATASET.root).joinpath(f"data_train.npz") + + # if phase == "test": + # path_data= Path(opt.DATASET.root).joinpath(f"data_train.npz") print(f"\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()) @@ -60,9 +65,9 @@ class MotionLiveDataset(Dataset): def __len__(self): if self.phase == "train": - return 20000 + return 20000 #40000 elif self.phase == "valid": - return 1000 + return 2000 #5000 else: return 100 @@ -77,11 +82,20 @@ class MotionLiveDataset(Dataset): """ np.random.seed(int(idx + time.time())) vid = self.pids[idx % self.num_pid] + + # # filter "2021-P29" + # while vid == "2021-P29": + # vid = self.pids[idx % self.num_pid] # random select idx data = self.annodb[vid] - data_motion = data["data_motion"] # (nframes, nc_motion) - data_speech = data["data_speech"] # (nsegemts, ) + data_motion = data["data_motion"] # (nframes, nc_motion) + data_speech = data["data_speech"] # (nsegemts, ) + # data_shape = data["data_shape"] # (nframes, nc_shape) + + data_motion = data["data_motion"] # (nframes, nc_motion) + data_speech = data["data_speech"] # (nsegemts, ) + # data_shape = data["data_shape"] # (nframes, nc_shape) nframe = data_motion.shape[0] nsegmt = data_speech.shape[0] @@ -94,22 +108,27 @@ class MotionLiveDataset(Dataset): 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, ) + # data_shape = data_shape[beg_frame:end_frame, :] # (nsteps, 100) + # 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') + # data_shape = savgol_filter(data_shape, window_length=5, polyorder=3, axis=0, mode='nearest') result = { "data": data_motion, # (nsteps_frame, dim_motion) "cond": data_speech, # (nsteps_frame, dim_speech) + # "shape": data_shape, "vid": vid, "nframe": nframe, "frame_interval": [beg_frame, end_frame], # "duration_interval": [beg_frame/nframe, end_frame/nframe] } + assert data_speech.shape[0] == self.nsteps_segmt, f"data_speech shape={data_speech.shape}, vid={vid}" + return result \ No newline at end of file diff --git a/src/datasets/motion_live2.py b/src/datasets/motion_live2.py new file mode 100644 index 0000000..c8f526e --- /dev/null +++ b/src/datasets/motion_live2.py @@ -0,0 +1,132 @@ +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 MotionLive2Dataset(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(MotionLive2Dataset, self).__init__() + + + self.opt = opt + self.phase = phase + path_data= Path(opt.DATASET.root).joinpath(f"data_{phase}.npz") + + # for test + # if phase == "valid": + # path_data= Path(opt.DATASET.root).joinpath(f"data_train.npz") + + # if phase == "test": + # path_data= Path(opt.DATASET.root).joinpath(f"data_train.npz") + + + print(f"\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 #40000 + elif self.phase == "valid": + return 2000 #5000 + 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] + + # # filter "2021-P29" + # while vid == "2021-P29": + # vid = self.pids[idx % self.num_pid] + + # random select idx + data = self.annodb[vid] + data_motion = data["data_motion"] # (nframes, nc_motion) + data_speech = data["data_speech"] # (nsegemts, ) + data_shape = data["data_shape"] # (nframes, nc_shape) + + 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, ) + data_shape = data_shape[beg_frame:end_frame, :] # (nsteps, 100) + + + + # 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') + data_shape = savgol_filter(data_shape, window_length=5, polyorder=3, axis=0, mode='nearest') + + + result = { + "data": data_motion, # (nsteps_frame, dim_motion) + "cond": data_speech, # (nsteps_frame, dim_speech) + "shape": data_shape, + "vid": vid, + "nframe": nframe, + "frame_interval": [beg_frame, end_frame], + # "duration_interval": [beg_frame/nframe, end_frame/nframe] + } + + assert data_speech.shape[0] == self.nsteps_segmt, f"data_speech shape={data_speech.shape}, vid={vid}" + + return result \ No newline at end of file diff --git a/src/models/info.py b/src/models/info.py new file mode 100644 index 0000000..4060821 --- /dev/null +++ b/src/models/info.py @@ -0,0 +1,37 @@ + +flame_mouth_idx = [ + 1576, 1577, 1578, 1579, 1580, 1581, 1582, 1583, 1584, 1585, + 1586, 1587, 1590, 1596, 1597, 1598, 1599, 1601, 1603, 1657, + 1658, 1662, 1663, 1667, 1668, 1669, 1670, 1671, 1672, 1673, + 1674, 1686, 1687, 1688, 1689, 1690, 1691, 1693, 1694, 1695, + 1696, 1697, 1698, 1699, 1700, 1701, 1702, 1703, 1704, 1705, + 1706, 1707, 1708, 1709, 1710, 1711, 1712, 1713, 1714, 1715, + 1716, 1717, 1718, 1719, 1720, 1721, 1722, 1723, 1724, 1725, + 1728, 1729, 1730, 1731, 1732, 1733, 1734, 1735, 1736, 1737, + 1738, 1740, 1741, 1743, 1748, 1749, 1750, 1751, 1758, 1763, + 1766, 1767, 1768, 1769, 1770, 1771, 1773, 1774, 1775, 1776, + 1777, 1778, 1781, 1782, 1787, 1788, 1789, 1791, 1792, 1793, + 1794, 1795, 1796, 1797, 1798, 1799, 1800, 1801, 1802, 1803, + 1804, 1805, 1826, 1827, 1836, 1848, 1849, 1850, 1863, 1864, + 1865, 1866, 2712, 2713, 2714, 2715, 2716, 2717, 2718, 2719, + 2720, 2721, 2722, 2723, 2726, 2727, 2729, 2732, 2733, 2734, + 2735, 2737, 2738, 2739, 2774, 2775, 2780, 2784, 2786, 2787, + 2788, 2789, 2790, 2791, 2803, 2804, 2805, 2806, 2807, 2808, + 2810, 2811, 2812, 2813, 2814, 2815, 2816, 2817, 2818, 2819, + 2820, 2821, 2822, 2823, 2824, 2825, 2826, 2827, 2828, 2829, + 2830, 2831, 2832, 2833, 2834, 2835, 2836, 2837, 2838, 2839, + 2840, 2841, 2842, 2843, 2844, 2845, 2846, 2847, 2848, 2849, + 2850, 2851, 2852, 2853, 2855, 2858, 2863, 2864, 2865, 2866, + 2869, 2871, 2873, 2874, 2875, 2876, 2877, 2878, 2879, 2880, + 2881, 2882, 2883, 2884, 2885, 2887, 2888, 2889, 2890, 2891, + 2892, 2894, 2895, 2896, 2897, 2898, 2899, 2900, 2901, 2902, + 2903, 2904, 2905, 2906, 2907, 2908, 2928, 2929, 2934, 2937, + 2938, 2939, 2946, 2947, 2948, 2949, 3174, 3429, 3430, 3431, + 3432, 3433, 3434, 3489, 3490, 3491, 3492, 3493, 3499, 3502, + 3503, 3504, 3506, 3507, 3509, 3511, 3513, 3515, 3531, 3537, + 3538, 3541, 3543, 3546, 3659, 3660, 3662, 3663, 3664, 3761, + 3762, 3769, 3771, 3772, 3790, 3791, 3792, 3793, 3794, 3795, + 3796, 3797, 3798, 3799, 3800, 3801, 3802, 3803, 3804, 3805, + 3806, 3914, 3915, 3916, 3917, 3918, 3919, 3920, 3921, 3922, + 3923, 3924, 3925, 3926, 3927, 3928 + ] \ No newline at end of file diff --git a/src/models/model_audio2mesh.py b/src/models/model_audio2mesh.py new file mode 100644 index 0000000..27b7f1c --- /dev/null +++ b/src/models/model_audio2mesh.py @@ -0,0 +1,442 @@ +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.info import flame_mouth_idx +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 Audio2MeshModel(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) + init_net(self.netG, init_type='kaiming', gpu_ids=opt.GPUS) + + # init last layer + init_exp_weight = np.load("/ssdata1/lsen/CODE/voca/training_data/init_expression_basis.npy") + init_exp_weight = torch.from_numpy(init_exp_weight).float().to(self.device) + init_exp_weight = init_exp_weight[:, :50] + self.netG.module.decoder_mesh.weight.data = init_exp_weight + print(f"init_exp_weight shape = {init_exp_weight.shape}") + + # # print network parameters + # for name, param in self.netG.named_parameters(): + # print(name, '\t\t', param.size()) + + # load mean lighting & shape + self.netR, self.flame = define_netR(device=self.device) + # self.netG.init_reconstruct_model(self.netR) + + path_deca_mean = Path("./data/DECA_obama_mean.npy") + self.mean_dict = np.load(path_deca_mean, allow_pickle=True).item() + self.template_verts = self.get_template_vertices() + debug(opt, f"template_verts shape = {self.template_verts.shape}") + debug(opt, f"mean_dict keys = {self.mean_dict.keys()}", verbose=True) + + 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) + + # define loss weight + self.vertices_weight = torch.ones((1, 1, self.opt.MODEL.num_vertices, 3)).to(self.device) + self.vertices_weight[:, :, flame_mouth_idx, :] = 10 + + + 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'] + 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) + 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) + + # speech data + self.cond = None + 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 + else: + assert 0, "opt.DATASET.speech_extractor should be 'wav2vec | deepspeech | mfcc ' " + + # 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 speech data + 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) + self.pred += self.template_verts + debug(self.opt, f"traing pred = {self.pred.shape}", verbose=False) + + # 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) + self.pred += self.template_verts + + 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) # B x N x dim_motion + samples_pt += self.template_verts # B x N x 5023 x 3 + + print(f"testing pt shape = {samples_pt.shape}") + + self.save_reconstruct(samples_pt, path_audio, + path_save=Path(self.opt.OUTPUT_DIR), + suffix=suffix) + + # save result + samples_pt = samples_pt.cpu().numpy() + path_save_npy = Path(self.opt.OUTPUT_DIR).joinpath(f"{suffix}.npy") + np.save(path_save_npy, samples_pt) + print(f"save infer_result shape = {samples_pt.shape} -> {path_save_npy}") + + + 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) # B x N x 5023 x 3 + samples_pt += self.template_verts # B x N x 5023 x 3 + + samples_gt = self.get_vertices(self.data) # B x N x 5023 x 3 + # samples_gt = samples_gt.cpu().numpy() # B x N x 5023 x 3 + + 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 get_template_vertices(self, mean_dict=None): + + if mean_dict is not None: + pass + + else: + batch_shape = torch.zeros(1, 100).to(self.device) + batch_exp = torch.zeros(1, 50).to(self.device) + batch_pos = torch.zeros(1, 6).to(self.device) + + verts, _, _ = self.netR.get_vertices(batch_shape, batch_exp, batch_pos) # 1 x 5023 x 3 + verts = verts.unsqueeze(dim=0) # 1 x 1 x 5023 x 3 + print(f"template verts reshape = {verts.shape}") + + return verts + + + def get_vertices(self, batch_motion): + """ + batch_motion, (nbatch, seqlen, 53) + """ + batch_exp = batch_motion[..., :50] + batch_pos = batch_motion[..., 50:] + nbatch, seqlen = batch_exp.size(0), batch_exp.size(1) + + batch_exp = batch_exp.reshape(nbatch * seqlen, -1) # nbatch * seqlen x 50 + batch_pos = batch_pos.reshape(nbatch * seqlen, -1) # nbatch * seqlen x 3 + + batch_shape= torch.zeros(nbatch * seqlen, 100).to(self.device) # nbatch * seqlen x 50 + batch_pose = torch.zeros(nbatch * seqlen, 6).to(self.device) # nbatch * seqlen x 6 + batch_pose[:, 3:6] = batch_pos + + verts, _, _ = self.netR.get_vertices(batch_shape, batch_exp, batch_pose) # nbatch * seqlen x 5023 x 3 + verts = verts.reshape(nbatch, seqlen, -1, 3) # nbatch x seqlen x 5023 x 3 + # print(f"verts reshape = {verts.shape}") + + return verts + + + def eval_losses(self, batch_pdt_geo, batch_tgt): + """ Computes the VAE loss function. + pramas: + batch_tgt, (nbatch, seqlen, dim_motion) + batch_pdt_geo, (nbatch, seqlen, num_vertices, 3) + """ + loss = 0 + loss_dict = {} + + # get mesh geometry + batch_tgt_geo = self.get_vertices(batch_tgt) # B x nseq x num_vertices x 3 + + # synthesis geo rec + loss = 0 + loss_rec_geo = self.loss_func_wing(batch_pdt_geo, batch_tgt_geo) + loss_dict["loss_rec_geo"] = loss_rec_geo.detach() + + loss_rec_geo2 = self.loss_func_wing(batch_pdt_geo, batch_tgt_geo, weight=self.vertices_weight) + loss_dict["loss_rec_geo_w"] = loss_rec_geo2.detach() + loss += loss_rec_geo2 * self.opt.LOSS.lambda_rec_geo + + # synthesis geo volocity + diff_pdt_geo = batch_pdt_geo[:, 1:, :] - batch_pdt_geo[:, :-1, :] + diff_tgt_geo = batch_tgt_geo[:, 1:, :] - batch_tgt_geo[:, :-1, :] + + loss_vol_geo = self.loss_func_wing(diff_pdt_geo, diff_tgt_geo) + loss_dict["loss_vol_geo"] = loss_vol_geo.detach() + + loss_vol_geo2 = self.loss_func_wing(diff_pdt_geo, diff_tgt_geo, weight=self.vertices_weight) + loss_dict["loss_vol_geo_w"] = loss_vol_geo2.detach() + loss += loss_vol_geo2 * self.opt.LOSS.lambda_vol_geo + + # 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 i in range(B): + igeo_pt = samples_pt[i, ...] + ipath_save = path_save.joinpath(f"{suffix}_{i:02d}.mp4") + + v_render_pt = [] + for k in range(0, N, nbatch_render): + # split + kgeo_pt = igeo_pt[k:k+nbatch_render, ...] # [nbatch_real x 5023 x 3] + nbatch_real = kgeo_pt.size(0) + + # cam + cam = torch.tensor([5, 0, 0], device=self.device) # (1, 3) + cam = cam.repeat(nbatch_real, 1) # (nbatch_real, 3) + # print(f"cam shape = {cam.shape}") + + # render + render_pt = self.netR.render_geometry(kgeo_pt, cam, self.device) # (nbatch_real, 3, 512, 512) + # print(f"render_pt ={render_pt.shape}, render_gt={render_gt.shape}") + + # append each frame + for m in range(nbatch_real): + 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, ipath_save) + + + def save_reconstruct_with_gt(self, samples_pt, samples_gt, path_save, suffix=""): + # samples_pt, [B x N x 5023 x 3] + # samples_gt, [B x N x 5023 x 3] + B, N, *_ = samples_pt.shape + nbatch_render = 10 + + # for each batch + for i in range(B): + igeo_pt = samples_pt[i, ...] # [N x 5023 x 3] + igeo_gt = samples_gt[i, ...] # [N x 5023 x 3] + ipath_save = path_save.joinpath(f"{suffix}_{i:02d}.mp4") + + v_render_pt = [] + v_render_gt = [] + + for k in range(0, N, nbatch_render): + + # split + kgeo_pt = igeo_pt[k:k+nbatch_render, ...] # [nbatch_real x 5023 x 3] + kgeo_gt = igeo_gt[k:k+nbatch_render, ...] # [nbatch_real x 5023 x 3] + nbatch_real = kgeo_pt.size(0) + + # cam + cam = torch.tensor([5, 0, 0], device=self.device) # (1, 3) + cam = cam.repeat(nbatch_real, 1) # (nbatch_real, 3) + # print(f"cam shape = {cam.shape}") + + # render + render_pt = self.netR.render_geometry(kgeo_pt, cam, self.device) # (nbatch_real, 3, 512, 512) + render_gt = self.netR.render_geometry(kgeo_gt, cam, self.device) # (nbatch_real, 3, 512, 512) + # print(f"render_pt ={render_pt.shape}, render_gt={render_gt.shape}") + + # append each frame + for m in range(nbatch_real): + v_render_pt.append(tensor2image(render_pt[m, ...])) + v_render_gt.append(tensor2image(render_gt[m, ...])) + + # get audio + jvid = self.batch_vid[i] + jnframe = self.batch_nframe[i].numpy() + jstart_frame = self.batch_interv[0][i].numpy() + + jpath_audio = f"{self.opt.DATASET.root_raw}/{jvid}/audio/audio_trim.wav" + jstart_time = (jstart_frame + 7) / self.opt.DATASET.fps # xxx.yyy min + jend_time = (jstart_frame + 7 + self.nseq) / self.opt.DATASET.fps # xxx.yyy min + # print(f"jvid={jvid}, jnfram={jnframe}, jstart_frame={jstart_frame}, jpath_audio={jpath_audio}") + # print(f"jstart_time={jstart_time}, jend_time={jend_time}") + + + # save animation + # print(f"testing v_render_pt = {len(v_render_pt)}, gt shape = {len(v_render_gt)}") + save_animation_with_gt2(v_render_pt, v_render_gt, ipath_save, fps=self.opt.DATASET.fps,\ + path_audio=jpath_audio, start_time=jstart_time, end_time=jend_time) + +######################################### +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 == "audio2mesh": + from src.nn.audio2mesh import Audio2Mesh + netG = Audio2Mesh(opt) + + elif opt.MODEL.name_netG == "audio2mesh_voca": + from src.nn.audio2mesh_voca import Audio2Mesh + netG = Audio2Mesh(opt) + + elif opt.MODEL.name_netG == "audio2mesh_resnet": + from src.nn.audio2mesh_resnet import Audio2Mesh + netG = Audio2Mesh(opt) + + else: + raise NameError(f"The model of opt.MODEL.name_netAE(={opt.MODEL.name_netG}) not existing!") + + # to GPU + netG.to(f"cuda:{opt.GPUS[0]}") + netG = torch.nn.DataParallel(netG, opt.GPUS) # multi-GPUs + + return netG + + +def define_netR(device): + # import + + from src.nn.FLAME import FLAME + + 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) + + # flame model + flame = FLAME(deca_cfg.model).to(device) + + + return netR, flame + + + diff --git a/src/models/model_audio2meshF.py b/src/models/model_audio2meshF.py new file mode 100644 index 0000000..8da7b0b --- /dev/null +++ b/src/models/model_audio2meshF.py @@ -0,0 +1,346 @@ + +import sys +import torch +import torch.nn as nn +import numpy as np +from pathlib import Path + +from src.models.base import Base +from src.optims import get_optimizer, get_scheduler + +from common.debug import debug +from common.animation import save_animation_with_gt2, save_images_with_audio + +class Audio2MeshFModel(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) + + # init + if self.opt.MODEL.pretrain or self.opt.TRAIN.resume: + self.netG.module.set_actnorm_init(True) + else: + self.netG.module.set_actnorm_init(False) + + + 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, self.flame = 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() + self.template_verts = self.get_template_vertices() + self.num_vertices = self.opt.MODEL.num_vertices + debug(opt, f"template_verts shape = {self.template_verts.shape}") + debug(opt, f"mean_dict keys = {self.mean_dict.keys()}", verbose=True) + + + 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) + + # speech data + self.cond = None + 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": + + # 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 + else: + assert 0, "opt.DATASET.speech_extractor should be 'wav2vec | deepspeech | mfcc ' " + + + # 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) + + self.cond = self.cond.permute(0, 2, 1) # (B, nc_motion, nseqs) + self.data = self.data.permute(0, 2, 1) # (B, nc_condit, nseqs) + self.nseq = self.cond.size(2) + + 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 remove_weightnorm(self): + def remove(conv_list): + new_conv_list = nn.ModuleList() + for old_conv in conv_list: + old_conv = nn.utils.remove_weight_norm(old_conv) + new_conv_list.append(old_conv) + return new_conv_list + + for model in self.netG.module.FusionNets: + model.layer_head = nn.utils.remove_weight_norm(model.layer_head) + model.layer_cond = nn.utils.remove_weight_norm(model.layer_cond) + model.in_layers = remove(model.in_layers) + model.res_skip_layers = remove(model.res_skip_layers) + + + def training(self, batch_input): + self.train() # set train model + self.set_input(batch_input) + + data_input = self.get_vertices(self.data) # nbatch x 5023*3 x nsteps + + # forward + z, logdet = self.netG(data_input, self.cond) + debug(self.opt, f"[Train] netG z shape = {len(z)}, logs shape = {logdet.shape}", verbose=False) + + # loss + # loss, self.loss_dict = self.netG.module.eval_losses() + loss, self.loss_dict = self.netG.module.loss_function_(z, logdet) + debug(self.opt, f"[Train] loss shape = {loss.shape}", verbose=False) + + # 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) + + # step + 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(): + data_input = self.get_vertices(self.data) # nbatch x 5023*3 x nsteps + + z, logdet = self.netG(data_input, self.cond) + loss, self.loss_dict = self.netG.module.loss_function_(z, logdet) + return loss + + + 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.module.inverse(self.cond) # B x 5023*3 x nsteps + + # add template mesh + B, N = samples_pt.size(0), samples_pt.size(2) + samples_pt = samples_pt.permute(0, 2, 1) # B x nsteps x 5023*3 + samples_pt = samples_pt.reshape(B, N, self.num_vertices, 3) # B x nsteps x 5023 x 3 + samples_pt += self.template_verts # B x nsteps x 5023 x 3 + + # + samples_gt = self.get_vertices(self.data) # B x 5023*3 x nsteps + samples_gt = samples_gt.permute(0, 2, 1) # B x nsteps x 5023*3 + samples_gt = samples_gt.reshape(B, N, self.num_vertices, 3) # B x nsteps x 5023 x 3 + samples_gt += self.template_verts # B x nsteps x 5023 x 3 + + # self.data.permute(0, 2, 1).cpu().numpy() # B x nsteps 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 infer(self, batch_cond, path_audio, suffix=""): + self.eval() + # self.cond = + + + def get_template_vertices(self, ): + + batch_shape = torch.zeros(1, 100).to(self.device) + batch_exp = torch.zeros(1, 50).to(self.device) + batch_pos = torch.zeros(1, 6).to(self.device) + + verts, _, _ = self.netR.get_vertices(batch_shape, batch_exp, batch_pos) # 1 x 5023 x 3 + verts = verts.unsqueeze(dim=0) # 1 x 1 x 5023 x 3 + print(f"template verts reshape = {verts.shape}") + + return verts + + + def get_vertices(self, batch_motion): + """ + batch_motion, (nbatch, nc_motion, nsteps) + """ + + # transpose + batch_motion = batch_motion.permute(0, 2, 1) # nbatch x nsteps x nc_motion + + batch_exp = batch_motion[..., :50] + batch_pos = batch_motion[..., 50:] + nbatch, nsteps = batch_exp.size(0), batch_exp.size(1) + + batch_exp = batch_exp.reshape(nbatch * nsteps, -1) # nbatch * nsteps x 50 + batch_pos = batch_pos.reshape(nbatch * nsteps, -1) # nbatch * nsteps x 3 + + batch_shape= torch.zeros(nbatch * nsteps, 100).to(self.device) # nbatch * nsteps x 50 + batch_pose = torch.zeros(nbatch * nsteps, 6).to(self.device) # nbatch * nsteps x 6 + batch_pose[:, 3:6] = batch_pos + + verts, _, _ = self.netR.get_vertices(batch_shape, batch_exp, batch_pose) # nbatch * nsteps x 5023 x 3 + verts = verts.reshape(nbatch, nsteps, -1) # nbatch x nsteps x 5023*3 + verts = verts.permute(0, 2, 1) # nbatch x 5023*3 x nsteps + # print(f"verts reshape = {verts.shape}") + + return verts + + def save_reconstruct_with_gt(self, samples_pt, samples_gt, path_save, suffix=""): + # samples_pt, [B x N x 5023 x 3] + # samples_gt, [B x N x 5023 x 3] + B, N, *_ = samples_pt.shape + nbatch_render = 10 + + # for each batch + for i in range(B): + igeo_pt = samples_pt[i, ...] # [N x 5023 x 3] + igeo_gt = samples_gt[i, ...] # [N x 5023 x 3] + ipath_save = path_save.joinpath(f"{suffix}_{i:02d}.mp4") + + v_render_pt = [] + v_render_gt = [] + + for k in range(0, N, nbatch_render): + + # split + kgeo_pt = igeo_pt[k:k+nbatch_render, ...] # [nbatch_real x 5023 x 3] + kgeo_gt = igeo_gt[k:k+nbatch_render, ...] # [nbatch_real x 5023 x 3] + nbatch_real = kgeo_pt.size(0) + + # cam + cam = torch.tensor([5, 0, 0], device=self.device) # (1, 3) + cam = cam.repeat(nbatch_real, 1) # (nbatch_real, 3) + # print(f"cam shape = {cam.shape}") + + # render + render_pt = self.netR.render_geometry(kgeo_pt, cam, self.device) # (nbatch_real, 3, 512, 512) + render_gt = self.netR.render_geometry(kgeo_gt, cam, self.device) # (nbatch_real, 3, 512, 512) + # print(f"render_pt ={render_pt.shape}, render_gt={render_gt.shape}") + + # append each frame + for m in range(nbatch_real): + v_render_pt.append(tensor2image(render_pt[m, ...])) + v_render_gt.append(tensor2image(render_gt[m, ...])) + + # get audio + jvid = self.batch_vid[i] + jnframe = self.batch_nframe[i].numpy() + jstart_frame = self.batch_interv[0][i].numpy() + + jpath_audio = f"{self.opt.DATASET.root_raw}/{jvid}/audio/audio_trim.wav" + jstart_time = jstart_frame / self.opt.DATASET.fps # xxx.yyy min + jend_time = (jstart_frame + self.nseq) / self.opt.DATASET.fps # xxx.yyy min + # print(f"jvid={jvid}, jnfram={jnframe}, jstart_frame={jstart_frame}, jpath_audio={jpath_audio}") + # print(f"jstart_time={jstart_time}, jend_time={jend_time}") + + # save animation + # print(f"testing v_render_pt = {len(v_render_pt)}, gt shape = {len(v_render_gt)}") + save_animation_with_gt2(v_render_pt, v_render_gt, ipath_save, fps=self.opt.DATASET.fps,\ + path_audio=jpath_audio, start_time=jstart_time, end_time=jend_time) + +######################################### +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 == "MotionWaveFlow": + from src.nn.MotionWaveFlow import MotionWaveFlow + netG = MotionWaveFlow(opt) + + else: + raise NameError(f"The model of opt.MODEL.name_netG(={opt.MODEL.name_netG}) not existing!") + + # to GPU + netG.to(f"cuda:{opt.GPUS[0]}") + netG = torch.nn.DataParallel(netG, opt.GPUS) # multi-GPUs + + + return netG + + +def define_netR(device): + # import + + from src.nn.FLAME import FLAME + + 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) + + # flame model + flame = FLAME(deca_cfg.model).to(device) + + + return netR, flame diff --git a/src/models/model_audio2mesh_coef.py b/src/models/model_audio2mesh_coef.py new file mode 100644 index 0000000..042cb41 --- /dev/null +++ b/src/models/model_audio2mesh_coef.py @@ -0,0 +1,472 @@ +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 Audio2MeshModel(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, self.flame = 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_coef, self.pred_vert = self.netG(self.cond) + + # loss + loss, self.loss_dict = self.eval_losses(self.pred_coef, self.pred_vert, 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_coef = self.netG(self.cond) + loss, self.loss_dict = self.eval_losses(self.pred_coef, 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 get_vertices(self, batch_exp, batch_pos): + """ + batch_exp, (nbatch, seqlen, 50) + batch_pos, (nbatch, seqlen, 3) + """ + nbatch, seqlen = batch_exp.size(0), batch_exp.size(1) + batch_exp = batch_exp.reshape(nbatch * seqlen, -1) # nbatch * seqlen x 50 + batch_pos = batch_pos.reshape(nbatch * seqlen, -1) # nbatch * seqlen x 3 + + batch_shape = np.repeat([self.mean_dict["shape"]], nbatch * seqlen, axis=0) # (nbatch * seqlen, 100) + batch_shape= torch.from_numpy(batch_shape).to(self.device) + + batch_pose = np.repeat([self.mean_dict["pose"]], nbatch * seqlen, axis=0) # (nbatch * seqlen, 6) + batch_pose = torch.from_numpy(batch_pose).to(self.device) + batch_pose[:, 3:6] = batch_pos + + + verts, _, _ = self.netR.get_vertices(batch_shape, batch_exp, batch_pose) # nbatch * seqlen x 5023 x 3 + verts = verts.reshape(nbatch, seqlen, -1, 3) # nbatch x seqlen x 5023 x 3 + # print(f"verts reshape = {verts.shape}") + + return verts + + def eval_losses(self, batch_pdt_coef, batch_pdt_geo, batch_tgt): + """ Computes the VAE loss function. + pramas: + batch_tgt, (nbatch, seqlen, dim_motion) + batch_pdt_coef, (nbatch, seqlen, dim_motion) + batch_pdt_geo, (nbatch, seqlen, num_vertices, 3) + """ + loss = 0 + loss_dict = {} + + batch_pdt_exp = batch_pdt_coef[..., :50] + batch_pdt_pos = batch_pdt_coef[..., 50:] + + batch_tgt_exp = batch_tgt[..., :50] + batch_tgt_pos = batch_tgt[..., 50:] + + + # get mesh geometry + batch_syn_geo = self.get_vertices(batch_pdt_exp, batch_pdt_pos) # B x nseq x num_vertices x 3 + batch_tgt_geo = self.get_vertices(batch_tgt_exp, batch_tgt_pos) # B x nseq x num_vertices x 3 + + + # 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 + + # synthesis geo rec + loss_rec_geo = self.loss_func_wing(batch_syn_geo, batch_tgt_geo) + loss_dict["loss_rec_syn"] = loss_rec_geo.detach() + loss += loss_rec_geo * self.opt.LOSS.lambda_rec_syn + + + # synthesis geo volocity + diff_syn_geo = batch_syn_geo[:, 1:, :] - batch_syn_geo[:, :-1, :] + diff_tgt_geo = batch_tgt_geo[:, 1:, :] - batch_tgt_geo[:, :-1, :] + loss_vol_geo = self.loss_func_wing(diff_syn_geo, diff_tgt_geo) + loss_dict["loss_vol_syn"] = loss_vol_geo.detach() + loss += loss_vol_geo * self.opt.LOSS.lambda_vol_syn + + # synthesis geo rec + loss_rec_geo = self.loss_func_wing(batch_pdt_geo, batch_tgt_geo) + loss_dict["loss_rec_geo"] = loss_rec_geo.detach() + loss += loss_rec_geo * self.opt.LOSS.lambda_rec_geo + + # synthesis geo volocity + diff_pdt_geo = batch_pdt_geo[:, 1:, :] - batch_pdt_geo[:, :-1, :] + diff_tgt_geo = batch_tgt_geo[:, 1:, :] - batch_tgt_geo[:, :-1, :] + loss_vol_geo = self.loss_func_wing(diff_pdt_geo, diff_tgt_geo) + loss_dict["loss_vol_geo"] = loss_vol_geo.detach() + loss += loss_vol_geo * self.opt.LOSS.lambda_vol_geo + + # 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 + + from src.nn.FLAME import FLAME + + 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) + + # flame model + flame = FLAME(deca_cfg.model).to(device) + + + return netR, flame + + + diff --git a/src/models/model_audio2mesh_specific.py b/src/models/model_audio2mesh_specific.py new file mode 100644 index 0000000..626c05c --- /dev/null +++ b/src/models/model_audio2mesh_specific.py @@ -0,0 +1,448 @@ +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.info import flame_mouth_idx +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 Audio2MeshSpecificModel(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) + init_net(self.netG, init_type='kaiming', gpu_ids=opt.GPUS) + + # init last layer + init_exp_weight = np.load("/ssdata1/lsen/CODE/voca/training_data/init_expression_basis.npy") + init_exp_weight = torch.from_numpy(init_exp_weight).float().to(self.device) + init_exp_weight = init_exp_weight[:, :50] + self.netG.module.decoder_mesh.weight.data = init_exp_weight + print(f"init_exp_weight shape = {init_exp_weight.shape}") + + # # print network parameters + # for name, param in self.netG.named_parameters(): + # print(name, '\t\t', param.size()) + + # load mean lighting & shape + self.netR, self.flame = define_netR(device=self.device) + # self.netG.init_reconstruct_model(self.netR) + + # path_deca_mean = Path("./data/DECA_obama_mean.npy") + path_deca_mean = self.opt.DATASET.path_mean_dict + self.mean_dict = np.load(path_deca_mean, allow_pickle=True).item() + print(f"mean_dict keys = {self.mean_dict.keys()}") + + self.template_verts = self.get_template_vertices(self.mean_dict) + debug(opt, f"template_verts shape = {self.template_verts.shape}") + debug(opt, f"mean_dict keys = {self.mean_dict.keys()}", verbose=True) + + 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) + + # define loss weight + self.vertices_weight = torch.ones((1, 1, self.opt.MODEL.num_vertices, 3)).to(self.device) + self.vertices_weight[:, :, flame_mouth_idx, :] = 50 # 10 + + + 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_shape = batch_input["shape"].float().to(self.device) # (B, nsteps, nc_shape) + + self.batch_vid = batch_input['vid'] + self.batch_nframe = batch_input['nframe'] + self.batch_interv = batch_input['frame_interval'] + 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) + 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) + + # speech data + self.cond = None + 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 + else: + assert 0, "opt.DATASET.speech_extractor should be 'wav2vec | deepspeech | mfcc ' " + + # 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 speech data + 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, :] + self.batch_shape = self.batch_shape[:, 7:7+self.nseq, :] # (B, nsteps, nc_shape) + + 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) + self.pred += self.template_verts + debug(self.opt, f"traing pred = {self.pred.shape}", verbose=False) + + # 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) + self.pred += self.template_verts + + 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) # B x N x dim_motion + samples_pt += self.template_verts # B x N x 5023 x 3 + + print(f"testing pt shape = {samples_pt.shape}") + + self.save_reconstruct(samples_pt, path_audio, + path_save=Path(self.opt.OUTPUT_DIR), + suffix=suffix) + + # save result + samples_pt = samples_pt.cpu().numpy() + path_save_npy = Path(self.opt.OUTPUT_DIR).joinpath(f"{suffix}.npy") + np.save(path_save_npy, samples_pt) + print(f"save infer_result shape = {samples_pt.shape} -> {path_save_npy}") + + + 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) # B x N x 5023 x 3 + samples_pt += self.template_verts # B x N x 5023 x 3 + + samples_gt = self.get_vertices(self.data, self.batch_shape) # B x N x 5023 x 3 + # samples_gt = samples_gt.cpu().numpy() # B x N x 5023 x 3 + + 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 get_template_vertices(self, mean_dict=None): + + batch_exp = torch.zeros(1, 50).to(self.device) + batch_pos = torch.zeros(1, 6).to(self.device) + + if mean_dict is not None: + batch_shape = self.mean_dict["shape"].reshape(1, 100) + batch_shape = torch.from_numpy(batch_shape).float().to(self.device) + else: + batch_shape = torch.zeros(1, 100).to(self.device) + + + verts, _, _ = self.netR.get_vertices(batch_shape, batch_exp, batch_pos) # 1 x 5023 x 3 + verts = verts.unsqueeze(dim=0) # 1 x 1 x 5023 x 3 + print(f"template verts reshape = {verts.shape}") + + return verts + + + def get_vertices(self, batch_motion, batch_shape): + """ + batch_motion, (nbatch, seqlen, 53) + batch_shape, (nbatch, seqlen, 100) + """ + batch_exp = batch_motion[..., :50] + batch_pos = batch_motion[..., 50:] + nbatch, seqlen = batch_exp.size(0), batch_exp.size(1) + + batch_exp = batch_exp.reshape(nbatch * seqlen, 50) # nbatch * seqlen x 50 + batch_pos = batch_pos.reshape(nbatch * seqlen, 3) # nbatch * seqlen x 3 + batch_idn = batch_shape.reshape(nbatch * seqlen, 100) # nbatch * seqlen x 100 + + # pose + batch_pose = torch.zeros(nbatch * seqlen, 6).to(self.device) # nbatch * seqlen x 6 + batch_pose[:, 3:6] = batch_pos + + verts, _, _ = self.netR.get_vertices(batch_idn, batch_exp, batch_pose) # nbatch * seqlen x 5023 x 3 + verts = verts.reshape(nbatch, seqlen, -1, 3) # nbatch x seqlen x 5023 x 3 + # print(f"verts reshape = {verts.shape}") + + return verts + + + def eval_losses(self, batch_pdt_geo, batch_tgt): + """ Computes the VAE loss function. + pramas: + batch_tgt, (nbatch, seqlen, dim_motion) + batch_pdt_geo, (nbatch, seqlen, num_vertices, 3) + """ + loss = 0 + loss_dict = {} + + # get mesh geometry + batch_tgt_geo = self.get_vertices(batch_tgt, self.batch_shape) # B x nseq x num_vertices x 3 + + # synthesis geo rec + loss = 0 + loss_rec_geo = self.loss_func_wing(batch_pdt_geo, batch_tgt_geo) + loss_dict["loss_rec_geo"] = loss_rec_geo.detach() + + loss_rec_geo2 = self.loss_func_wing(batch_pdt_geo, batch_tgt_geo, weight=self.vertices_weight) + loss_dict["loss_rec_geo_w"] = loss_rec_geo2.detach() + loss += loss_rec_geo2 * self.opt.LOSS.lambda_rec_geo + + # synthesis geo volocity + diff_pdt_geo = batch_pdt_geo[:, 1:, :] - batch_pdt_geo[:, :-1, :] + diff_tgt_geo = batch_tgt_geo[:, 1:, :] - batch_tgt_geo[:, :-1, :] + + loss_vol_geo = self.loss_func_wing(diff_pdt_geo, diff_tgt_geo) + loss_dict["loss_vol_geo"] = loss_vol_geo.detach() + + loss_vol_geo2 = self.loss_func_wing(diff_pdt_geo, diff_tgt_geo, weight=self.vertices_weight) + loss_dict["loss_vol_geo_w"] = loss_vol_geo2.detach() + loss += loss_vol_geo2 * self.opt.LOSS.lambda_vol_geo + + # 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 i in range(B): + igeo_pt = samples_pt[i, ...] + ipath_save = path_save.joinpath(f"{suffix}_{i:02d}.mp4") + + v_render_pt = [] + for k in range(0, N, nbatch_render): + # split + kgeo_pt = igeo_pt[k:k+nbatch_render, ...] # [nbatch_real x 5023 x 3] + nbatch_real = kgeo_pt.size(0) + + # cam + cam = torch.tensor([5, 0, 0], device=self.device) # (1, 3) + cam = cam.repeat(nbatch_real, 1) # (nbatch_real, 3) + # print(f"cam shape = {cam.shape}") + + # render + render_pt = self.netR.render_geometry(kgeo_pt, cam, self.device) # (nbatch_real, 3, 512, 512) + # print(f"render_pt ={render_pt.shape}, render_gt={render_gt.shape}") + + # append each frame + for m in range(nbatch_real): + 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, ipath_save) + + + def save_reconstruct_with_gt(self, samples_pt, samples_gt, path_save, suffix=""): + # samples_pt, [B x N x 5023 x 3] + # samples_gt, [B x N x 5023 x 3] + B, N, *_ = samples_pt.shape + nbatch_render = 10 + + # for each batch + for i in range(B): + igeo_pt = samples_pt[i, ...] # [N x 5023 x 3] + igeo_gt = samples_gt[i, ...] # [N x 5023 x 3] + ipath_save = path_save.joinpath(f"{suffix}_{i:02d}.mp4") + + v_render_pt = [] + v_render_gt = [] + + for k in range(0, N, nbatch_render): + + # split + kgeo_pt = igeo_pt[k:k+nbatch_render, ...] # [nbatch_real x 5023 x 3] + kgeo_gt = igeo_gt[k:k+nbatch_render, ...] # [nbatch_real x 5023 x 3] + nbatch_real = kgeo_pt.size(0) + + # cam + cam = torch.tensor([5, 0, 0], device=self.device) # (1, 3) + cam = cam.repeat(nbatch_real, 1) # (nbatch_real, 3) + # print(f"cam shape = {cam.shape}") + + # render + render_pt = self.netR.render_geometry(kgeo_pt, cam, self.device) # (nbatch_real, 3, 512, 512) + render_gt = self.netR.render_geometry(kgeo_gt, cam, self.device) # (nbatch_real, 3, 512, 512) + # print(f"render_pt ={render_pt.shape}, render_gt={render_gt.shape}") + + # append each frame + for m in range(nbatch_real): + v_render_pt.append(tensor2image(render_pt[m, ...])) + v_render_gt.append(tensor2image(render_gt[m, ...])) + + # get audio + jvid = self.batch_vid[i] + jnframe = self.batch_nframe[i].numpy() + jstart_frame = self.batch_interv[0][i].numpy() + + jpath_audio = f"{self.opt.DATASET.root_raw}/{jvid}/audio/audio_trim.wav" + jstart_time = (jstart_frame + 7) / self.opt.DATASET.fps # xxx.yyy min + jend_time = (jstart_frame + 7 + self.nseq) / self.opt.DATASET.fps # xxx.yyy min + # print(f"jvid={jvid}, jnfram={jnframe}, jstart_frame={jstart_frame}, jpath_audio={jpath_audio}") + # print(f"jstart_time={jstart_time}, jend_time={jend_time}") + + + # save animation + # print(f"testing v_render_pt = {len(v_render_pt)}, gt shape = {len(v_render_gt)}") + save_animation_with_gt2(v_render_pt, v_render_gt, ipath_save, fps=self.opt.DATASET.fps,\ + path_audio=jpath_audio, start_time=jstart_time, end_time=jend_time) + +######################################### +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 == "audio2mesh": + from src.nn.audio2mesh import Audio2Mesh + netG = Audio2Mesh(opt) + + elif opt.MODEL.name_netG == "audio2mesh_voca": + from src.nn.audio2mesh_voca import Audio2Mesh + netG = Audio2Mesh(opt) + + elif opt.MODEL.name_netG == "audio2mesh_resnet": + from src.nn.audio2mesh_resnet import Audio2Mesh + netG = Audio2Mesh(opt) + + else: + raise NameError(f"The model of opt.MODEL.name_netAE(={opt.MODEL.name_netG}) not existing!") + + # to GPU + netG.to(f"cuda:{opt.GPUS[0]}") + netG = torch.nn.DataParallel(netG, opt.GPUS) # multi-GPUs + + return netG + + +def define_netR(device): + # import + + from src.nn.FLAME import FLAME + + 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) + + # flame model + flame = FLAME(deca_cfg.model).to(device) + + + return netR, flame + + + diff --git a/src/models/model_audio2motionF.py b/src/models/model_audio2motionF.py new file mode 100644 index 0000000..af99278 --- /dev/null +++ b/src/models/model_audio2motionF.py @@ -0,0 +1,334 @@ + +import sys +import torch +import torch.nn as nn +import numpy as np +from pathlib import Path + +from src.models.base import Base +from src.optims import get_optimizer, get_scheduler + +from common.debug import debug +from common.animation import save_animation_with_gt2 + +class Audio2MotionFModel(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) + + # init + if self.opt.MODEL.pretrain or self.opt.TRAIN.resume: + self.netG.module.set_actnorm_init(True) + else: + self.netG.module.set_actnorm_init(False) + + + 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, self.flame = 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) + + # speech data + self.cond = None + raw_speech = batch_input["cond"].numpy() # (B, nsegments) + + if self.opt.DATASET.speech_extractor == "wav2vec": + + # 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 + else: + assert 0, "opt.DATASET.speech_extractor should be 'wav2vec | deepspeech | mfcc ' " + + + # 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) + + self.cond = self.cond.permute(0, 2, 1) # (B, nc_motion, nseqs) + self.data = self.data.permute(0, 2, 1) # (B, nc_condit, nseqs) + self.nseq = self.cond.size(2) + debug(self.opt, f"permute data = {self.data.shape}, dtype={self.data.dtype}, device={self.data.device}", verbose=False) + debug(self.opt, f"permute cond = {self.cond.shape}, dtype={self.cond.dtype}, device={self.cond.device}", verbose=False) + + def remove_weightnorm(self): + def remove(conv_list): + new_conv_list = nn.ModuleList() + for old_conv in conv_list: + old_conv = nn.utils.remove_weight_norm(old_conv) + new_conv_list.append(old_conv) + return new_conv_list + + for model in self.netG.module.FusionNets: + model.layer_head = nn.utils.remove_weight_norm(model.layer_head) + model.layer_cond = nn.utils.remove_weight_norm(model.layer_cond) + model.in_layers = remove(model.in_layers) + model.res_skip_layers = remove(model.res_skip_layers) + + + def training(self, batch_input): + self.train() # set train model + self.set_input(batch_input) + + # forward + z, logdet = self.netG(self.data, self.cond) + debug(self.opt, f"[Train] netG z shape = {len(z)}, logs shape = {logdet.shape}", verbose=False) + + # loss + # loss, self.loss_dict = self.netG.module.eval_losses() + loss, self.loss_dict = self.netG.module.loss_function_(z, logdet) + debug(self.opt, f"[Train] loss shape = {loss.shape}", verbose=False) + + # 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) + + # step + 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(): + z, logdet = self.netG(self.data, self.cond) + loss, self.loss_dict = self.netG.module.loss_function_(z, logdet) + return loss + + + 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.module.inverse(self.cond) # B x dim_motion x nsteps + + samples_pt = samples_pt.permute(0, 2, 1).cpu().numpy() # B x nsteps x dim_motion + samples_gt = self.data.permute(0, 2, 1).cpu().numpy() # B x nsteps 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 infer(self, batch_cond, path_audio, suffix=""): + self.eval() + # self.cond = + + def get_vertices(self, batch_exp, batch_pos): + """ + batch_exp, (nbatch, seqlen, 50) + batch_pos, (nbatch, seqlen, 3) + """ + nbatch, seqlen = batch_exp.size(0), batch_exp.size(1) + batch_exp = batch_exp.reshape(nbatch * seqlen, -1) # nbatch * seqlen x 50 + batch_pos = batch_pos.reshape(nbatch * seqlen, -1) # nbatch * seqlen x 3 + + batch_shape = np.repeat([self.mean_dict["shape"]], nbatch * seqlen, axis=0) # (nbatch * seqlen, 100) + batch_shape= torch.from_numpy(batch_shape).to(self.device) + + batch_pose = np.repeat([self.mean_dict["pose"]], nbatch * seqlen, axis=0) # (nbatch * seqlen, 6) + batch_pose = torch.from_numpy(batch_pose).to(self.device) + batch_pose[:, 3:6] = batch_pos + + + verts, _, _ = self.netR.get_vertices(batch_shape, batch_exp, batch_pose) # nbatch * seqlen x 5023 x 3 + verts = verts.reshape(nbatch, seqlen, -1, 3) # nbatch x seqlen x 5023 x 3 + # print(f"verts reshape = {verts.shape}") + + return verts + + 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"{self.opt.DATASET.root_raw}/{jvid}/audio/audio_trim.wav" + # jpath_audio = f"/yrfs/lsen/DATA/LuoXData/processing2/{jvid}/audio/audio_trim.wav" + jstart_time = (jstart_frame) / self.opt.DATASET.fps # xxx.yyy min + jend_time = (jstart_frame + 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 == "MotionWaveFlow": + from src.nn.MotionWaveFlow import MotionWaveFlow + netG = MotionWaveFlow(opt) + + elif opt.MODEL.name_netG == "MotionWaveFlow2": + from src.nn.MotionWaveFlow2 import MotionWaveFlow + netG = MotionWaveFlow(opt) + + else: + raise NameError(f"The model of opt.MODEL.name_netG(={opt.MODEL.name_netG}) not existing!") + + # to GPU + netG.to(f"cuda:{opt.GPUS[0]}") + netG = torch.nn.DataParallel(netG, opt.GPUS) # multi-GPUs + + + return netG + + +def define_netR(device): + # import + + from src.nn.FLAME import FLAME + + 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) + + # flame model + flame = FLAME(deca_cfg.model).to(device) + + + return netR, flame diff --git a/src/models/model_audio2motionFW.py b/src/models/model_audio2motionFW.py new file mode 100644 index 0000000..c4304a7 --- /dev/null +++ b/src/models/model_audio2motionFW.py @@ -0,0 +1,354 @@ + +import sys +import torch +import torch.nn as nn +import numpy as np +from pathlib import Path + +from src.models.base import Base +from src.optims import get_optimizer, get_scheduler + +from common.debug import debug +from common.animation import save_animation_with_gt2 + +class Audio2MotionFWModel(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) + + # init + if self.opt.MODEL.pretrain or self.opt.TRAIN.resume: + self.netG.module.set_actnorm_init(True) + else: + self.netG.module.set_actnorm_init(False) + + + 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, self.flame = 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) + + # speech data + self.cond = None + raw_speech = batch_input["cond"].numpy() # (B, nsegments) + + if self.opt.DATASET.speech_extractor == "wav2vec": + + # 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 + else: + assert 0, "opt.DATASET.speech_extractor should be 'wav2vec | deepspeech | mfcc ' " + + + # 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.cond = self.cond.unfold(dimension=1, size=16, step=1) # (B, nsteps2, nc_motion, 16) + self.cond = self.cond.permute(0, 1, 3, 2) # (B, nsteps2, 16, nc_motion) + + + # self.cond = self.cond.permute(0, 2, 1) # (B, nc_motion, nsteps) + + self.nseq = self.cond.size(1) # nsteps2 + self.data = self.data.permute(0, 2, 1) # (B, nc_condit, nsteps) + self.data = self.data[:, :, 7:7+self.nseq] # (B, nc_condit, nsteps2) + + debug(self.opt, f"permute data = {self.data.shape}, dtype={self.data.dtype}, device={self.data.device}", verbose=False) + debug(self.opt, f"permute cond = {self.cond.shape}, dtype={self.cond.dtype}, device={self.cond.device}", verbose=False) + + def remove_weightnorm(self): + def remove(conv_list): + new_conv_list = nn.ModuleList() + for old_conv in conv_list: + old_conv = nn.utils.remove_weight_norm(old_conv) + new_conv_list.append(old_conv) + return new_conv_list + + for model in self.netG.module.FusionNets: + model.layer_head = nn.utils.remove_weight_norm(model.layer_head) + model.layer_cond = nn.utils.remove_weight_norm(model.layer_cond) + model.in_layers = remove(model.in_layers) + model.res_skip_layers = remove(model.res_skip_layers) + + + def training(self, batch_input): + self.train() # set train model + self.set_input(batch_input) + + # forward + z, logdet = self.netG(self.data, self.cond) + debug(self.opt, f"[Train] netG z shape = {len(z)}, logs shape = {logdet.shape}", verbose=False) + + # loss + # loss, self.loss_dict = self.netG.module.eval_losses() + loss, self.loss_dict = self.netG.module.loss_function_(z, logdet) + debug(self.opt, f"[Train] loss shape = {loss.shape}", verbose=False) + + # 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) + + # step + 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(): + z, logdet = self.netG(self.data, self.cond) + loss, self.loss_dict = self.netG.module.loss_function_(z, logdet) + return loss + + + 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.module.inverse(self.cond) # B x dim_motion x nsteps + + samples_pt = samples_pt.permute(0, 2, 1).cpu().numpy() # B x nsteps x dim_motion + samples_gt = self.data.permute(0, 2, 1).cpu().numpy() # B x nsteps 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 infer(self, batch_cond, path_audio, suffix=""): + self.eval() + # self.cond = + + def get_vertices(self, batch_exp, batch_pos): + """ + batch_exp, (nbatch, seqlen, 50) + batch_pos, (nbatch, seqlen, 3) + """ + nbatch, seqlen = batch_exp.size(0), batch_exp.size(1) + batch_exp = batch_exp.reshape(nbatch * seqlen, -1) # nbatch * seqlen x 50 + batch_pos = batch_pos.reshape(nbatch * seqlen, -1) # nbatch * seqlen x 3 + + batch_shape = np.repeat([self.mean_dict["shape"]], nbatch * seqlen, axis=0) # (nbatch * seqlen, 100) + batch_shape= torch.from_numpy(batch_shape).to(self.device) + + batch_pose = np.repeat([self.mean_dict["pose"]], nbatch * seqlen, axis=0) # (nbatch * seqlen, 6) + batch_pose = torch.from_numpy(batch_pose).to(self.device) + batch_pose[:, 3:6] = batch_pos + + + verts, _, _ = self.netR.get_vertices(batch_shape, batch_exp, batch_pose) # nbatch * seqlen x 5023 x 3 + verts = verts.reshape(nbatch, seqlen, -1, 3) # nbatch x seqlen x 5023 x 3 + # print(f"verts reshape = {verts.shape}") + + return verts + + 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() + 7 + + + jpath_audio = f"{self.opt.DATASET.root_raw}/{jvid}/audio/audio_trim.wav" + # jpath_audio = f"/yrfs/lsen/DATA/LuoXData/processing2/{jvid}/audio/audio_trim.wav" + jstart_time = (jstart_frame ) / self.opt.DATASET.fps # xxx.yyy min + jend_time = (jstart_frame + 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 == "MotionWaveFlow": + from src.nn.MotionWaveFlow import MotionWaveFlow + netG = MotionWaveFlow(opt) + + elif opt.MODEL.name_netG == "MotionWaveFlow2": + from src.nn.MotionWaveFlow2 import MotionWaveFlow + netG = MotionWaveFlow(opt) + + elif opt.MODEL.name_netG == "MotionWaveFlow22": + from src.nn.MotionWaveFlow22 import MotionWaveFlow + netG = MotionWaveFlow(opt) + + elif opt.MODEL.name_netG == "MotionWaveFlow3": + from src.nn.MotionWaveFlow3 import MotionWaveFlow + netG = MotionWaveFlow(opt) + + elif opt.MODEL.name_netG == "MotionWaveFlow4": + from src.nn.MotionWaveFlow4 import MotionWaveFlow + netG = MotionWaveFlow(opt) + + else: + raise NameError(f"The model of opt.MODEL.name_netG(={opt.MODEL.name_netG}) not existing!") + + # to GPU + netG.to(f"cuda:{opt.GPUS[0]}") + netG = torch.nn.DataParallel(netG, opt.GPUS) # multi-GPUs + + + return netG + + +def define_netR(device): + # import + + from src.nn.FLAME import FLAME + + 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) + + # flame model + flame = FLAME(deca_cfg.model).to(device) + + + return netR, flame diff --git a/src/models/model_audio2motion_live2.py b/src/models/model_audio2motion_live2.py index 9f2dfd1..ddca78d 100644 --- a/src/models/model_audio2motion_live2.py +++ b/src/models/model_audio2motion_live2.py @@ -331,7 +331,9 @@ class Audio2motionLive2Model(Base): 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" + + jpath_audio = f"{self.opt.DATASET.root_raw}/{jvid}/audio/audio_trim.wav" + # 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 @@ -367,9 +369,9 @@ def define_netG(opt): 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_voca34": + from src.nn.audio2motion_voca34 import Audio2MotionVOCA + netG = Audio2MotionVOCA(opt) elif opt.MODEL.name_netG == "audio2motion_voca33": from src.nn.audio2motion_voca33 import Audio2MotionVOCA diff --git a/src/models/model_audio2motion_live3.py b/src/models/model_audio2motion_live3.py new file mode 100644 index 0000000..6164f2b --- /dev/null +++ b/src/models/model_audio2motion_live3.py @@ -0,0 +1,464 @@ +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 Audio2motionLive3Model(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, self.flame = 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) + + # save result + path_save_npy = Path(self.opt.OUTPUT_DIR).joinpath(f"{suffix}.npy") + np.save(path_save_npy, samples_pt) + print(f"save infer_result shape = {samples_pt.shape} -> {path_save_npy}") + + + 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 get_vertices(self, batch_exp, batch_pos): + """ + batch_exp, (nbatch, seqlen, 50) + batch_pos, (nbatch, seqlen, 3) + """ + nbatch, seqlen = batch_exp.size(0), batch_exp.size(1) + batch_exp = batch_exp.reshape(nbatch * seqlen, -1) # nbatch * seqlen x 50 + batch_pos = batch_pos.reshape(nbatch * seqlen, -1) # nbatch * seqlen x 3 + + batch_shape = np.repeat([self.mean_dict["shape"]], nbatch * seqlen, axis=0) # (nbatch * seqlen, 100) + batch_shape= torch.from_numpy(batch_shape).to(self.device) + + batch_pose = np.repeat([self.mean_dict["pose"]], nbatch * seqlen, axis=0) # (nbatch * seqlen, 6) + batch_pose = torch.from_numpy(batch_pose).to(self.device) + batch_pose[:, 3:6] = batch_pos + + + verts, _, _ = self.netR.get_vertices(batch_shape, batch_exp, batch_pose) # nbatch * seqlen x 5023 x 3 + verts = verts.reshape(nbatch, seqlen, -1, 3) # nbatch x seqlen x 5023 x 3 + # print(f"verts reshape = {verts.shape}") + + return verts + + + 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:] + + # get reconstruction + batch_pdt_geo = self.get_vertices(batch_pdt_exp, batch_pdt_pos) # B x nseq x num_vertices x 3 + batch_tgt_geo = self.get_vertices(batch_tgt_exp, batch_tgt_pos) # B x nseq x num_vertices x 3 + + # 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 + + # geo rec + loss_rec_geo = self.loss_func_wing(batch_pdt_geo, batch_tgt_geo) + loss_dict["loss_rec_geo"] = loss_rec_geo.detach() + loss += loss_rec_geo * self.opt.LOSS.lambda_rec_geo + + + # geo volocity + diff_pdt_geo = batch_pdt_geo[:, 1:, :] - batch_pdt_geo[:, :-1, :] + diff_tgt_geo = batch_tgt_geo[:, 1:, :] - batch_tgt_geo[:, :-1, :] + loss_vol_geo = self.loss_func_wing(diff_pdt_geo, diff_tgt_geo) + loss_dict["loss_vol_geo"] = loss_vol_geo.detach() + loss += loss_vol_geo * self.opt.LOSS.lambda_vol_geo + + + # 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() + 7 + + + jpath_audio = f"{self.opt.DATASET.root_raw}/{jvid}/audio/audio_trim.wav" + # jpath_audio = f"/yrfs/lsen/DATA/LuoXData/processing2/{jvid}/audio/audio_trim.wav" + jstart_time = (jstart_frame) / self.opt.DATASET.fps # xxx.yyy min + jend_time = (jstart_frame + 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_voca34": + from src.nn.audio2motion_voca34 import Audio2MotionVOCA + netG = Audio2MotionVOCA(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 + + from src.nn.FLAME import FLAME + + 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) + + # flame model + flame = FLAME(deca_cfg.model).to(device) + + + return netR, flame + + + diff --git a/src/nn/FLAME.py b/src/nn/FLAME.py new file mode 100644 index 0000000..c2e76b5 --- /dev/null +++ b/src/nn/FLAME.py @@ -0,0 +1,266 @@ +# -*- coding: utf-8 -*- +# +# Max-Planck-Gesellschaft zur Förderung der Wissenschaften e.V. (MPG) is +# holder of all proprietary rights on this computer program. +# Using this computer program means that you agree to the terms +# in the LICENSE file included with this software distribution. +# Any use not explicitly granted by the LICENSE is prohibited. +# +# Copyright©2019 Max-Planck-Gesellschaft zur Förderung +# der Wissenschaften e.V. (MPG). acting on behalf of its Max Planck Institute +# for Intelligent Systems. All rights reserved. +# +# For comments or questions, please email us at deca@tue.mpg.de +# For commercial licensing contact, please contact ps-license@tuebingen.mpg.de + +import torch +import torch.nn as nn +import numpy as np +import pickle +import torch.nn.functional as F + +from .lbs import lbs, batch_rodrigues, vertices2landmarks, rot_mat_to_euler + +def to_tensor(array, dtype=torch.float32): + if 'torch.tensor' not in str(type(array)): + return torch.tensor(array, dtype=dtype) +def to_np(array, dtype=np.float32): + if 'scipy.sparse' in str(type(array)): + array = array.todense() + return np.array(array, dtype=dtype) + +class Struct(object): + def __init__(self, **kwargs): + for key, val in kwargs.items(): + setattr(self, key, val) + +class FLAME(nn.Module): + """ + borrowed from https://github.com/soubhiksanyal/FLAME_PyTorch/blob/master/FLAME.py + Given flame parameters this class generates a differentiable FLAME function + which outputs the a mesh and 2D/3D facial landmarks + """ + def __init__(self, config): + super(FLAME, self).__init__() + print("creating the FLAME Decoder") + with open(config.flame_model_path, 'rb') as f: + ss = pickle.load(f, encoding='latin1') + flame_model = Struct(**ss) + + self.dtype = torch.float32 + self.register_buffer('faces_tensor', to_tensor(to_np(flame_model.f, dtype=np.int64), dtype=torch.long)) + # The vertices of the template model + self.register_buffer('v_template', to_tensor(to_np(flame_model.v_template), dtype=self.dtype)) + # The shape components and expression + shapedirs = to_tensor(to_np(flame_model.shapedirs), dtype=self.dtype) + shapedirs = torch.cat([shapedirs[:,:,:config.n_shape], shapedirs[:,:,300:300+config.n_exp]], 2) + self.register_buffer('shapedirs', shapedirs) + # The pose components + num_pose_basis = flame_model.posedirs.shape[-1] + posedirs = np.reshape(flame_model.posedirs, [-1, num_pose_basis]).T + self.register_buffer('posedirs', to_tensor(to_np(posedirs), dtype=self.dtype)) + # + self.register_buffer('J_regressor', to_tensor(to_np(flame_model.J_regressor), dtype=self.dtype)) + parents = to_tensor(to_np(flame_model.kintree_table[0])).long(); parents[0] = -1 + self.register_buffer('parents', parents) + self.register_buffer('lbs_weights', to_tensor(to_np(flame_model.weights), dtype=self.dtype)) + + # Fixing Eyeball and neck rotation + default_eyball_pose = torch.zeros([1, 6], dtype=self.dtype, requires_grad=False) + self.register_parameter('eye_pose', nn.Parameter(default_eyball_pose, + requires_grad=False)) + default_neck_pose = torch.zeros([1, 3], dtype=self.dtype, requires_grad=False) + self.register_parameter('neck_pose', nn.Parameter(default_neck_pose, + requires_grad=False)) + + # Static and Dynamic Landmark embeddings for FLAME + lmk_embeddings = np.load(config.flame_lmk_embedding_path, allow_pickle=True, encoding='latin1') + lmk_embeddings = lmk_embeddings[()] + self.register_buffer('lmk_faces_idx', torch.from_numpy(lmk_embeddings['static_lmk_faces_idx']).long()) + self.register_buffer('lmk_bary_coords', torch.from_numpy(lmk_embeddings['static_lmk_bary_coords']).to(self.dtype)) + self.register_buffer('dynamic_lmk_faces_idx', lmk_embeddings['dynamic_lmk_faces_idx'].long()) + self.register_buffer('dynamic_lmk_bary_coords', lmk_embeddings['dynamic_lmk_bary_coords'].to(self.dtype)) + self.register_buffer('full_lmk_faces_idx', torch.from_numpy(lmk_embeddings['full_lmk_faces_idx']).long()) + self.register_buffer('full_lmk_bary_coords', torch.from_numpy(lmk_embeddings['full_lmk_bary_coords']).to(self.dtype)) + + neck_kin_chain = []; NECK_IDX=1 + curr_idx = torch.tensor(NECK_IDX, dtype=torch.long) + while curr_idx != -1: + neck_kin_chain.append(curr_idx) + curr_idx = self.parents[curr_idx] + self.register_buffer('neck_kin_chain', torch.stack(neck_kin_chain)) + + def _find_dynamic_lmk_idx_and_bcoords(self, pose, dynamic_lmk_faces_idx, + dynamic_lmk_b_coords, + neck_kin_chain, dtype=torch.float32): + """ + Selects the face contour depending on the reletive position of the head + Input: + vertices: N X num_of_vertices X 3 + pose: N X full pose + dynamic_lmk_faces_idx: The list of contour face indexes + dynamic_lmk_b_coords: The list of contour barycentric weights + neck_kin_chain: The tree to consider for the relative rotation + dtype: Data type + return: + The contour face indexes and the corresponding barycentric weights + """ + + batch_size = pose.shape[0] + + aa_pose = torch.index_select(pose.view(batch_size, -1, 3), 1, + neck_kin_chain) + rot_mats = batch_rodrigues( + aa_pose.view(-1, 3), dtype=dtype).view(batch_size, -1, 3, 3) + + rel_rot_mat = torch.eye(3, device=pose.device, + dtype=dtype).unsqueeze_(dim=0).expand(batch_size, -1, -1) + for idx in range(len(neck_kin_chain)): + rel_rot_mat = torch.bmm(rot_mats[:, idx], rel_rot_mat) + + y_rot_angle = torch.round( + torch.clamp(rot_mat_to_euler(rel_rot_mat) * 180.0 / np.pi, + max=39)).to(dtype=torch.long) + + neg_mask = y_rot_angle.lt(0).to(dtype=torch.long) + mask = y_rot_angle.lt(-39).to(dtype=torch.long) + neg_vals = mask * 78 + (1 - mask) * (39 - y_rot_angle) + y_rot_angle = (neg_mask * neg_vals + + (1 - neg_mask) * y_rot_angle) + + dyn_lmk_faces_idx = torch.index_select(dynamic_lmk_faces_idx, + 0, y_rot_angle) + dyn_lmk_b_coords = torch.index_select(dynamic_lmk_b_coords, + 0, y_rot_angle) + return dyn_lmk_faces_idx, dyn_lmk_b_coords + + def _vertices2landmarks(self, vertices, faces, lmk_faces_idx, lmk_bary_coords): + """ + Calculates landmarks by barycentric interpolation + Input: + vertices: torch.tensor NxVx3, dtype = torch.float32 + The tensor of input vertices + faces: torch.tensor (N*F)x3, dtype = torch.long + The faces of the mesh + lmk_faces_idx: torch.tensor N X L, dtype = torch.long + The tensor with the indices of the faces used to calculate the + landmarks. + lmk_bary_coords: torch.tensor N X L X 3, dtype = torch.float32 + The tensor of barycentric coordinates that are used to interpolate + the landmarks + + Returns: + landmarks: torch.tensor NxLx3, dtype = torch.float32 + The coordinates of the landmarks for each mesh in the batch + """ + # Extract the indices of the vertices for each face + # NxLx3 + batch_size, num_verts = vertices.shape[:dd2] + lmk_faces = torch.index_select(faces, 0, lmk_faces_idx.view(-1)).view( + 1, -1, 3).view(batch_size, lmk_faces_idx.shape[1], -1) + + lmk_faces += torch.arange(batch_size, dtype=torch.long).view(-1, 1, 1).to( + device=vertices.device) * num_verts + + lmk_vertices = vertices.view(-1, 3)[lmk_faces] + landmarks = torch.einsum('blfi,blf->bli', [lmk_vertices, lmk_bary_coords]) + return landmarks + + def seletec_3d68(self, vertices): + landmarks3d = vertices2landmarks(vertices, self.faces_tensor, + self.full_lmk_faces_idx.repeat(vertices.shape[0], 1), + self.full_lmk_bary_coords.repeat(vertices.shape[0], 1, 1)) + return landmarks3d + + def forward(self, shape_params=None, expression_params=None, pose_params=None, eye_pose_params=None): + """ + Input: + shape_params: N X number of shape parameters + expression_params: N X number of expression parameters + pose_params: N X number of pose parameters (6) + return:d + vertices: N X V X 3 + landmarks: N X number of landmarks X 3 + """ + batch_size = shape_params.shape[0] + if eye_pose_params is None: + eye_pose_params = self.eye_pose.expand(batch_size, -1) + betas = torch.cat([shape_params, expression_params], dim=1) + full_pose = torch.cat([pose_params[:, :3], + self.neck_pose.expand(batch_size, -1), + pose_params[:, 3:], + eye_pose_params], dim=1) + template_vertices = self.v_template.unsqueeze(0).expand(batch_size, -1, -1) + + vertices, _ = lbs(betas, full_pose, template_vertices, + self.shapedirs, self.posedirs, + self.J_regressor, self.parents, + self.lbs_weights, dtype=self.dtype) + + lmk_faces_idx = self.lmk_faces_idx.unsqueeze(dim=0).expand(batch_size, -1) + lmk_bary_coords = self.lmk_bary_coords.unsqueeze(dim=0).expand(batch_size, -1, -1) + + dyn_lmk_faces_idx, dyn_lmk_bary_coords = self._find_dynamic_lmk_idx_and_bcoords( + full_pose, self.dynamic_lmk_faces_idx, + self.dynamic_lmk_bary_coords, + self.neck_kin_chain, dtype=self.dtype) + lmk_faces_idx = torch.cat([dyn_lmk_faces_idx, lmk_faces_idx], 1) + lmk_bary_coords = torch.cat([dyn_lmk_bary_coords, lmk_bary_coords], 1) + + landmarks2d = vertices2landmarks(vertices, self.faces_tensor, + lmk_faces_idx, + lmk_bary_coords) + bz = vertices.shape[0] + landmarks3d = vertices2landmarks(vertices, self.faces_tensor, + self.full_lmk_faces_idx.repeat(bz, 1), + self.full_lmk_bary_coords.repeat(bz, 1, 1)) + + return vertices, landmarks2d, landmarks3d + +class FLAMETex(nn.Module): + """ + FLAME texture: + https://github.com/TimoBolkart/TF_FLAME/blob/ade0ab152300ec5f0e8555d6765411555c5ed43d/sample_texture.py#L64 + FLAME texture converted from BFM: + https://github.com/TimoBolkart/BFM_to_FLAME + """ + def __init__(self, config): + super(FLAMETex, self).__init__() + if config.tex_type == 'BFM': + mu_key = 'MU' + pc_key = 'PC' + n_pc = 199 + tex_path = config.tex_path + tex_space = np.load(tex_path) + texture_mean = tex_space[mu_key].reshape(1, -1) + texture_basis = tex_space[pc_key].reshape(-1, n_pc) + + elif config.tex_type == 'FLAME': + mu_key = 'mean' + pc_key = 'tex_dir' + n_pc = 200 + tex_path = config.flame_tex_path + tex_space = np.load(tex_path) + texture_mean = tex_space[mu_key].reshape(1, -1)/255. + texture_basis = tex_space[pc_key].reshape(-1, n_pc)/255. + else: + print('texture type ', config.tex_type, 'not exist!') + raise NotImplementedError + + n_tex = config.n_tex + num_components = texture_basis.shape[1] + texture_mean = torch.from_numpy(texture_mean).float()[None,...] + texture_basis = torch.from_numpy(texture_basis[:,:n_tex]).float()[None,...] + self.register_buffer('texture_mean', texture_mean) + self.register_buffer('texture_basis', texture_basis) + + def forward(self, texcode): + ''' + texcode: [batchsize, n_tex] + texture: [bz, 3, 256, 256], range: 0-1 + ''' + texture = self.texture_mean + (self.texture_basis*texcode[:,None,:]).sum(-1) + texture = texture.reshape(texcode.shape[0], 512, 512, 3).permute(0,3,1,2) + texture = F.interpolate(texture, [256, 256]) + texture = texture[:,[2,1,0], :,:] + return texture \ No newline at end of file diff --git a/src/nn/MotionWaveFlow.py b/src/nn/MotionWaveFlow.py new file mode 100644 index 0000000..d9bb17c --- /dev/null +++ b/src/nn/MotionWaveFlow.py @@ -0,0 +1,304 @@ +import torch +import torch.nn as nn +import torch.nn.functional as F +import numpy as np + +from common.debug import debug +from src.nn.layers import ActNorm1d, Invertible1x1Conv1d as Invertible1x1Conv + +# @torch.jit.script +def fused_add_tanh_sigmoid_multiply(input_a, input_b, n_channels): + n_channels_int = n_channels[0] + in_act = input_a + input_b + t_act = torch.tanh(in_act[:, :n_channels_int, :]) + s_act = torch.sigmoid(in_act[:, n_channels_int:, :]) + acts = t_act * s_act + return acts + + +class MotionWaveFlow(nn.Module): + + def __init__(self, opt): + super(MotionWaveFlow, self).__init__() + + self.opt = opt + self.nc_motion = opt.MODEL.dim_motion # 5023 + self.nc_condit = opt.MODEL.dim_speech # 1024 + + self.n_flows = opt.MODEL.n_flowstep # 12 + self.n_early_every = opt.MODEL.n_early_every # 4 --> 3 + + self.fix_dims = np.array(opt.MODEL.fix_dims) + self.lambda_std = np.array(opt.MODEL.lambda_std) # [1, 0.75, 0.5, 0.25] + self.lambda_std = torch.from_numpy(self.lambda_std).float().cuda(opt.GPUS[0]) + + self.Conv1x1Invs = nn.ModuleList() + self.FusionNets = nn.ModuleList() + self.Actnorms = nn.ModuleList() + nc_motion_rest = self.nc_motion # 8 --> 136 + + for k in range(self.n_flows): + if k % self.n_early_every == 0 and k > 0: # k = 3, 6, 9 + nc_motion_rest = nc_motion_rest - nc_motion_rest // 2 # = 84, 42, 21 + + self.Actnorms.append(ActNorm1d(num_channels=nc_motion_rest)) + self.Conv1x1Invs.append(Invertible1x1Conv(nc_motion_rest)) + self.FusionNets.append(FusionNet(self.opt, nc_motion=nc_motion_rest - nc_motion_rest//2, + nc_condit=self.nc_condit, + nc_output=2*(nc_motion_rest//2))) + + debug(self.opt, f"[Model] k={k} nc_motion_rest={nc_motion_rest}") + + self.nc_motion_rest = nc_motion_rest # Useful during inference, 72 / 8 + + + def set_actnorm_init(self, inited=True): + for name, m in self.named_modules(): + if (m.__class__.__name__.find("ActNorm") >= 0): + m.inited = inited + debug(self.opt, f"[Model] set module {m.__class__.__name__} inited = {inited}") + + + def forward(self, x, c): + """For training, x --> z + x shape = (B, nc_motion, nsteps), + c shape = (B, nc_condit, nsteps), + return: + z shape = (B, dim_motin, nsteps) + """ + + debug(self.opt, f"\n[Forward] start x shape={x.shape}, c={c.shape}", verbose=False) + + predt_z = [] + logdet = torch.zeros(c.size(0), dtype=c.dtype, device=c.device) + + for k in range(self.n_flows): + + x, logdet = self.Actnorms[k](x, logdet) + debug(self.opt, f"[Forward] k={k}, actnorm x shape = {x.shape} logdet={logdet.shape}", verbose=False) + + x, logdet = self.Conv1x1Invs[k](x, logdet) + debug(self.opt, f"[Forward] k={k}, Conv1x1Invs x={x.shape}, logdet={logdet.shape}") + + # coupling layers + nc_motion_half = x.size(1) - x.size(1) // 2 + x1, x2 = x[:, :nc_motion_half, :], x[:, nc_motion_half:, :] + debug(self.opt, f"[Forward] k={k}, coupling split x1={x1.shape}, x2={x2.shape}") + + feat = self.FusionNets[k](x1, c) # (B, nc_motion_half, dim_output) + shift, scale = feat[:, 0::2, :], feat[:, 1::2, :] + scale = torch.sigmoid(scale + 2.) + 1e-6 # to make scale > 1, so that log(s) > 0 + x2 = (x2 + shift) * scale + logdet = torch.sum(torch.log(scale), dim=[1, 2]) + logdet + + # multi-scale split + if k % self.n_early_every == (self.n_early_every -1) and k > 0 and k < self.n_flows -1: + predt_z.append(x2) + x = x1 + debug(self.opt, f"[Forward] k={k}, coupling muli-scale x={x.shape}, x2={x2.shape}, logdet={logdet.shape}", verbose=False) + else: + x = torch.cat([x1, x2], dim=1) + debug(self.opt, f"[Forward] k={k}, coupling concat x={x.shape}, logdet={logdet.shape}", verbose=False) + + + # append the last x + predt_z.append(x) + predt_z = list(reversed(predt_z)) + # predt_z = torch.cat(predt_z, dim=1) + + # [Model] k=0 nc_motion_rest=15069 + # [Model] k=1 nc_motion_rest=15069 + # [Model] k=2 nc_motion_rest=15069 + # [Model] k=3 nc_motion_rest=7535 + # [Model] k=4 nc_motion_rest=7535 + # [Model] k=5 nc_motion_rest=7535 + # [Model] k=6 nc_motion_rest=3768 + # [Model] k=7 nc_motion_rest=3768 + # [Model] k=8 nc_motion_rest=3768 + # [Model] k=9 nc_motion_rest=1884 + # [Model] k=10 nc_motion_rest=1884 + # [Model] k=11 nc_motion_rest=1884 + + return predt_z, logdet + + def inverse(self, c): + """For inference, z --> x + c shape = (B, nc_condit, nsteps_c) + return: + x shape = (B, nc_motion, nsteps_x) + """ + + B, nsteps = c.size(0), c.size(2) + + # add z + mu = torch.zeros(B, self.nc_motion_rest, nsteps, device=c.device) + std = torch.ones(B, self.nc_motion_rest, nsteps, device=c.device) * self.lambda_std[0] + x = torch.normal(mean=mu, std=std) + # x = torch.zeros(B, self.nc_motion_rest, nsteps, device=c.device).normal_() # (B, 40, 60) + + logdet = torch.zeros(c.size(0), dtype=c.dtype, device=c.device) + debug(self.opt, f"[Inverse] c={c.shape}, x={x.shape}, feac_c={c.shape}") + + istd = 1 + for k in reversed(range(self.n_flows)): + # coupling layer + nc_motion_half = x.size(1) - x.size(1) // 2 + x1, x2 = x[:, :nc_motion_half, :], x[:, nc_motion_half:, :] + debug(self.opt, f"[Inverse] k={k}, x1={x1.shape}, x2={x2.shape}", verbose=False) + + feat = self.FusionNets[k](x1, c) # (B, 1, dim_output) + shift, scale = feat[:, 0::2, :], feat[:, 1::2, :] + scale = torch.sigmoid(scale + 2.) + 1e-6 # to make scale > 1, so that log(s) > 0 + debug(self.opt, f"[Inverse] k={k}, coupling feat shape={feat.shape}, shift={shift.shape}, scale={scale.shape}", verbose=False) + + x2 = x2 / scale - shift + x = torch.cat([x1, x2], dim=1) + logdet = - torch.sum(torch.log(scale), dim=[1,2]) + logdet + debug(self.opt, f"[Inverse] k={k}, coupling concat x={x.shape}, logdet={logdet.shape}", verbose=False) + + # 1 x 1 conv inv + x, logdet = self.Conv1x1Invs[k].inverse(x, logdet) + debug(self.opt, f"[Inverse] k={k}, Conv1x1Invs x={x.shape}") + + # actnorm + x, logdet = self.Actnorms[k].inverse(x, logdet) + debug(self.opt, f"[Inverse] k={k}, actnorm x shape = {x.shape}", verbose=False) + + # add noise + if k % self.n_early_every == 0 and k > 0: + # z = torch.zeros(B, x.size(1), nsteps, device=c.device).normal_() # (B, 40, 60) + num_dims = x.size(1) + self.fix_dims[istd] + + mu = torch.zeros(B, num_dims, nsteps, device=c.device) + std = torch.ones(B, num_dims, nsteps, device=c.device) * self.lambda_std[istd] + z = torch.normal(mean=mu, std=std) + istd += 1 + + x = torch.cat((x, z), dim=1) # (B, 8/40/72/104/136, 25) + debug(self.opt, f"[Inverse] k={k}, ADD noise + {x.size(1)} channel, x shape = {x.shape}", verbose=False) + + return x.detach(), logdet # (B, nc_motion, nsteps) + + + def loss_function_(self, z, logdet, sigma=1.0): + """z = list (B, nc_motion, N) + logdet = list (B, ) + """ + + loss = 0 + loss_dict = {} + nsteps = z[0].size(2) + debug(self.opt, f"[Loss] z shape={z[0].shape}, logdet={logdet.shape}") + assert len(z) == len(self.lambda_std) + + logp = 0 + for std, zn in zip(self.lambda_std, z): + ilogp = -torch.log(std) - 0.5*zn*zn / (std * std) - 0.5 * torch.log(2 * torch.tensor(np.pi)) # B x nc x nsteps + logp += torch.sum(ilogp, dim=[1,2]) / (2*sigma * sigma) # (B, ) + + # logp = - 0.5*z*z - 0.5 * torch.log(2 * torch.tensor(np.pi)) # (B, N, nc_motion) + # logp = torch.sum(logp, dim=[1,2]) / (2*sigma * sigma) # (B, ) + + loss_logp = - torch.mean(logp) / (np.log(2.0) * nsteps * len(z)) + loss_logdet = - torch.mean(logdet) / (np.log(2.0) * nsteps) + loss = loss_logp * self.opt.LOSS.lambda_logp + loss_logdet * self.opt.LOSS.lambda_logdet + + loss_dict["loss_logp"] = loss_logp.detach() + loss_dict["loss_logdet"] = loss_logdet.detach() + loss_dict["loss_all"] = loss.detach() + + return loss, loss_dict + + +class FusionNet(nn.Module): + """ + This is the WaveNet like layer for the affine coupling. The primary difference + from WaveNet is the convolutions need not be causal. There is also no dilation + size reset. The dilation only doubles on each layer + """ + + def __init__(self, opt, nc_motion, nc_condit, nc_output): + super(FusionNet, self).__init__() + + self.opt = opt + + self.n_layers = opt.MODEL.n_layer_wave # 4 + self.nc_hidden = opt.MODEL.dim_hidden # 256 + + kernel_size = opt.MODEL.kernel_size # 3 + assert(kernel_size % 2 == 1) + assert(self.nc_hidden % 2 == 0) + + + layer_head = nn.Conv1d(nc_motion, self.nc_hidden, kernel_size=1) + layer_head = nn.utils.weight_norm(layer_head, name='weight') + self.layer_head = layer_head + + # Initializing last layer to 0 makes the affine coupling layers + # do nothing at first. This helps with training stability + layer_tail = nn.Conv1d(self.nc_hidden, nc_output, kernel_size=1) + layer_tail.weight.data.zero_() + layer_tail.bias.data.zero_() + self.layer_tail = layer_tail + + # for + layer_cond = nn.Conv1d(nc_condit, 2*self.nc_hidden*self.n_layers, 1) + self.layer_cond = nn.utils.weight_norm(layer_cond, name='weight') + self.layer_cond = layer_cond + + self.in_layers = nn.ModuleList() + self.res_skip_layers = nn.ModuleList() + + for i in range(self.n_layers): + dilation = 2 ** i # 1, 2, 4, 8 + padding = (kernel_size * dilation - dilation) // 2 # 1, 2, 4, 8 + in_layer = nn.Conv1d(self.nc_hidden, 2*self.nc_hidden, kernel_size, dilation=dilation, padding=padding) + in_layer = nn.utils.weight_norm(in_layer, name='weight') + self.in_layers.append(in_layer) + + # last one is not necessary + nc_skip = 2 * self.nc_hidden if (i < self.n_layers - 1) else self.nc_hidden + layer_skip = nn.Conv1d(self.nc_hidden, nc_skip, kernel_size=1) + layer_skip = nn.utils.weight_norm(layer_skip, name='weight') + self.res_skip_layers.append(layer_skip) + + + def forward(self, x, c): + """ forward function + x shape = (B x nfeat1 x nsteps1) B x nc_motion_half x nstep + c shape = (B x nfeat2 x nsteps2) B x nc_condit*nc_motion x nstep + """ + + feat_x = self.layer_head(x) # B x nc_hidden x nstep + feat_c = self.layer_cond(c) # B x 4*nc_hidden x nstep + feat_o = torch.zeros_like(feat_x) # B x nc_hidden x nstep + debug(self.opt, f"\t[FusionNet] feat_x={feat_x.shape}, feat_c={feat_c.shape}, feat_o={feat_o.shape}") + + nc_hidden_tensor = torch.IntTensor([self.nc_hidden]) + + for i in range(self.n_layers): + c_offset = i * 2 * self.nc_hidden + debug(self.opt, f"\t[FusionNet] layers={i} c_offset={c_offset}") + + + ifeat_x = self.in_layers[i](feat_x) # B x 2*nc_hidden x nstep + ifeat_c = feat_c[:, c_offset:c_offset+2*self.nc_hidden, :] # B x 2*nc_hidden x nstep + debug(self.opt, f"\t[FusionNet] \tifeat_x={ifeat_x.shape} ifeat_c={ifeat_c.shape}") + + ifeat_m = fused_add_tanh_sigmoid_multiply(ifeat_x, ifeat_c, nc_hidden_tensor) # B x nc_hidden x nstep + debug(self.opt, f"\t[FusionNet] \tifeat_m={ifeat_m.shape}") + + ifeat_m = self.res_skip_layers[i](ifeat_m) # B x 2*nc_hidden x nstep if not last layer else B x nc_hidden x 25 + debug(self.opt, f"\t[FusionNet] \t res skip ifeat_m={ifeat_m.shape}") + + if i < self.n_layers - 1: + feat_x = feat_x + ifeat_m[:, :self.nc_hidden, :] # B x nc_hidden x nstep + feat_o = feat_o + ifeat_m[:, self.nc_hidden:, :] # B x nc_hidden x nstep + else: + feat_o = feat_o + ifeat_m # B x nc_hidden x nstep + + feat_o = self.layer_tail(feat_o) # B x nc_motion_half x nstep + debug(self.opt, f"\t[FusionNet] tail feat_o={feat_o.shape}") + + return feat_o + diff --git a/src/nn/MotionWaveFlow2.py b/src/nn/MotionWaveFlow2.py new file mode 100644 index 0000000..b78c12b --- /dev/null +++ b/src/nn/MotionWaveFlow2.py @@ -0,0 +1,371 @@ +import torch +import torch.nn as nn +import torch.nn.functional as F +import numpy as np + +from common.debug import debug +from src.nn.layers import ActNorm1d, Invertible1x1Conv1d as Invertible1x1Conv + +# @torch.jit.script +def fused_add_tanh_sigmoid_multiply(input_a, input_b, n_channels): + n_channels_int = n_channels[0] + in_act = input_a + input_b + t_act = torch.tanh(in_act[:, :n_channels_int, :]) + s_act = torch.sigmoid(in_act[:, n_channels_int:, :]) + acts = t_act * s_act + return acts + + +class MotionWaveFlow(nn.Module): + + def __init__(self, opt): + super(MotionWaveFlow, self).__init__() + + self.opt = opt + self.nc_motion = opt.MODEL.dim_motion # 5023 + self.nc_condit = opt.MODEL.dim_speech # 1024 + self.nc_hidden = opt.MODEL.dim_hidden # 256 + + + self.n_flows = opt.MODEL.n_flowstep # 12 + self.n_early_every = opt.MODEL.n_early_every # 4 --> 3 + + self.fix_dims = np.array(opt.MODEL.fix_dims) + self.lambda_std = np.array(opt.MODEL.lambda_std) # [1, 0.75, 0.5, 0.25] + self.lambda_std = torch.from_numpy(self.lambda_std).float().cuda(opt.GPUS[0]) + + self.speechEncoder = SpeechEncoderNet(opt, self.nc_condit, self.nc_hidden) + self.Conv1x1Invs = nn.ModuleList() + self.FusionNets = nn.ModuleList() + self.Actnorms = nn.ModuleList() + nc_motion_rest = self.nc_motion # 8 --> 136 + + for k in range(self.n_flows): + if k % self.n_early_every == 0 and k > 0: # k = 3, 6, 9 + nc_motion_rest = nc_motion_rest - nc_motion_rest // 2 # = 84, 42, 21 + + self.Actnorms.append(ActNorm1d(num_channels=nc_motion_rest)) + self.Conv1x1Invs.append(Invertible1x1Conv(nc_motion_rest)) + self.FusionNets.append(FusionNet(self.opt, nc_motion=nc_motion_rest - nc_motion_rest//2, + nc_condit=self.nc_hidden, + nc_output=2*(nc_motion_rest//2))) + + debug(self.opt, f"[Model] k={k} nc_motion_rest={nc_motion_rest}") + + self.nc_motion_rest = nc_motion_rest # Useful during inference, 72 / 8 + + + def set_actnorm_init(self, inited=True): + for name, m in self.named_modules(): + if (m.__class__.__name__.find("ActNorm") >= 0): + m.inited = inited + debug(self.opt, f"[Model] set module {m.__class__.__name__} inited = {inited}") + + + def forward(self, x, c): + """For training, x --> z + x shape = (B, nc_motion, nsteps), + c shape = (B, nsteps, nwind, nc_speech), + return: + z shape = (B, dim_motin, nsteps) + """ + + debug(self.opt, f"\n[Forward] start x shape={x.shape}, c={c.shape}", verbose=False) + + predt_z = [] + feat_c = self.speechEncoder(c) # (B, nc_hidden, nsteps) + logdet = torch.zeros(c.size(0), dtype=c.dtype, device=c.device) + debug(self.opt, f"\n[Forward] feat_c shape={feat_c.shape}, logdet={logdet.shape}", verbose=False) + + for k in range(self.n_flows): + + x, logdet = self.Actnorms[k](x, logdet) + debug(self.opt, f"[Forward] k={k}, actnorm x shape = {x.shape} logdet={logdet.shape}", verbose=False) + + x, logdet = self.Conv1x1Invs[k](x, logdet) + debug(self.opt, f"[Forward] k={k}, Conv1x1Invs x={x.shape}, logdet={logdet.shape}") + + # coupling layers + nc_motion_half = x.size(1) - x.size(1) // 2 + x1, x2 = x[:, :nc_motion_half, :], x[:, nc_motion_half:, :] + debug(self.opt, f"[Forward] k={k}, coupling split x1={x1.shape}, x2={x2.shape}") + + feat = self.FusionNets[k](x1, feat_c) # (B, nc_motion_half, nc_output) + shift, scale = feat[:, 0::2, :], feat[:, 1::2, :] + scale = torch.sigmoid(scale + 2.) + 1e-6 # to make scale > 1, so that log(s) > 0 + x2 = (x2 + shift) * scale + logdet = torch.sum(torch.log(scale), dim=[1, 2]) + logdet + + # multi-scale split + if k % self.n_early_every == (self.n_early_every -1) and k > 0 and k < self.n_flows -1: + predt_z.append(x2) + x = x1 + debug(self.opt, f"[Forward] k={k}, coupling muli-scale x={x.shape}, x2={x2.shape}, logdet={logdet.shape}", verbose=False) + else: + x = torch.cat([x1, x2], dim=1) + debug(self.opt, f"[Forward] k={k}, coupling concat x={x.shape}, logdet={logdet.shape}", verbose=False) + + + # append the last x + predt_z.append(x) + predt_z = list(reversed(predt_z)) + # predt_z = torch.cat(predt_z, dim=1) + + return predt_z, logdet + + def inverse(self, c): + """For inference, z --> x + # c shape = (B, nc_condit, nsteps_c) + c shape = (B, nsteps, nwind, nc_speech), + return: + x shape = (B, nc_motion, nsteps_x) + """ + + B, nsteps = c.size(0), c.size(1) + + # add z + mu = torch.zeros(B, self.nc_motion_rest, nsteps, device=c.device) + std = torch.ones(B, self.nc_motion_rest, nsteps, device=c.device) * self.lambda_std[0] + x = torch.normal(mean=mu, std=std) + # x = torch.zeros(B, self.nc_motion_rest, nsteps, device=c.device).normal_() # (B, 40, 60) + + feat_c = self.speechEncoder(c) # (B, nc_hidden, nsteps) + logdet = torch.zeros(B, dtype=c.dtype, device=c.device) + debug(self.opt, f"\n[Inverse] feat_c shape={feat_c.shape}, logdet={logdet.shape}", verbose=False) + + istd = 1 + for k in reversed(range(self.n_flows)): + # coupling layer + nc_motion_half = x.size(1) - x.size(1) // 2 + x1, x2 = x[:, :nc_motion_half, :], x[:, nc_motion_half:, :] + debug(self.opt, f"[Inverse] k={k}, x1={x1.shape}, x2={x2.shape}", verbose=False) + + feat = self.FusionNets[k](x1, feat_c) # (B, 1, nc_output) + shift, scale = feat[:, 0::2, :], feat[:, 1::2, :] + scale = torch.sigmoid(scale + 2.) + 1e-6 # to make scale > 1, so that log(s) > 0 + debug(self.opt, f"[Inverse] k={k}, coupling feat shape={feat.shape}, shift={shift.shape}, scale={scale.shape}", verbose=False) + + x2 = x2 / scale - shift + x = torch.cat([x1, x2], dim=1) + logdet = - torch.sum(torch.log(scale), dim=[1,2]) + logdet + debug(self.opt, f"[Inverse] k={k}, coupling concat x={x.shape}, logdet={logdet.shape}", verbose=False) + + # 1 x 1 conv inv + x, logdet = self.Conv1x1Invs[k].inverse(x, logdet) + debug(self.opt, f"[Inverse] k={k}, Conv1x1Invs x={x.shape}") + + # actnorm + x, logdet = self.Actnorms[k].inverse(x, logdet) + debug(self.opt, f"[Inverse] k={k}, actnorm x shape = {x.shape}", verbose=False) + + # add noise + if k % self.n_early_every == 0 and k > 0: + # z = torch.zeros(B, x.size(1), nsteps, device=c.device).normal_() # (B, 40, 60) + num_dims = x.size(1) + self.fix_dims[istd] + + mu = torch.zeros(B, num_dims, nsteps, device=c.device) + std = torch.ones(B, num_dims, nsteps, device=c.device) * self.lambda_std[istd] + z = torch.normal(mean=mu, std=std) + istd += 1 + + x = torch.cat((x, z), dim=1) # (B, 8/40/72/104/136, 25) + debug(self.opt, f"[Inverse] k={k}, ADD noise + {x.size(1)} channel, x shape = {x.shape}", verbose=False) + + return x.detach(), logdet # (B, nc_motion, nsteps) + + + def loss_function_(self, z, logdet, sigma=1.0): + """z = list (B, nc_motion, N) + logdet = list (B, ) + """ + + loss = 0 + loss_dict = {} + nsteps = z[0].size(2) + debug(self.opt, f"[Loss] z shape={z[0].shape}, logdet={logdet.shape}") + assert len(z) == len(self.lambda_std) + + logp = 0 + for std, zn in zip(self.lambda_std, z): + ilogp = -torch.log(std) - 0.5*zn*zn / (std * std) - 0.5 * torch.log(2 * torch.tensor(np.pi)) # B x nc x nsteps + logp += torch.sum(ilogp, dim=[1,2]) / (2*sigma * sigma) # (B, ) + + # logp = - 0.5*z*z - 0.5 * torch.log(2 * torch.tensor(np.pi)) # (B, N, nc_motion) + # logp = torch.sum(logp, dim=[1,2]) / (2*sigma * sigma) # (B, ) + + loss_logp = - torch.mean(logp) / (np.log(2.0) * nsteps * len(z)) + loss_logdet = - torch.mean(logdet) / (np.log(2.0) * nsteps) + loss = loss_logp * self.opt.LOSS.lambda_logp + loss_logdet * self.opt.LOSS.lambda_logdet + + loss_dict["loss_logp"] = loss_logp.detach() + loss_dict["loss_logdet"] = loss_logdet.detach() + loss_dict["loss_all"] = loss.detach() + + return loss, loss_dict + + +class SpeechEncoderNet(nn.Module): + """ + This is a 2D Conv encoder network for speech data with windows + """ + def __init__(self, opt, nc_speech, nc_output): + super(SpeechEncoderNet, self).__init__() + + self.opt = opt + # encoder + self.encoder = nn.Sequential( # (nbatch, nchannel=1024, H=16, W=1) + nn.BatchNorm2d(nc_speech), + + # block 1 + nn.Conv2d(nc_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=nc_output) # 50, + ) + + def forward(self, x): + """ forward function + Args: + x: [nbatch x nsteps x nwind x dim_condit] + return: + pred: [nbatch x nc_output x nsteps] + """ + + (nbatch, nsteps, nwind, nfeat) = x.shape # (B, nsetps, 16, nc_speech) + debug(self.opt, f"[SpeechEncoderNet] input x shape = {x.shape}", verbose=False) + + # preprocessing data + x = x.reshape(nbatch * nsteps, 1, nwind, nfeat) # (B * nsteps, 1, 16, nc_speech) + x = torch.transpose(x, 1, 3) # (B * nsteps, nc_speech, 16, 1) + debug(self.opt, f"[SpeechEncoderNet] transpose x shape = {x.shape}", verbose=False) + + + feat = self.encoder(x) # (B * nsteps, nc_output) + debug(self.opt, f"[SpeechEncoderNet] encoder shape = {feat.shape}", verbose=False) + + feat = feat.reshape(nbatch, nsteps, -1) # (B, nsteps, nc_output) + feat = torch.transpose(feat, 1, 2) # (B, nc_output, nsteps) + debug(self.opt, f"[SpeechEncoderNet] reshape shape = {feat.shape}", verbose=False) + + return feat + + +class FusionNet(nn.Module): + """ + This is the WaveNet like layer for the affine coupling. The primary difference + from WaveNet is the convolutions need not be causal. There is also no dilation + size reset. The dilation only doubles on each layer + """ + + def __init__(self, opt, nc_motion, nc_condit, nc_output): + super(FusionNet, self).__init__() + + self.opt = opt + + self.n_layers = opt.MODEL.n_layer_wave # 4 + self.nc_hidden = opt.MODEL.dim_hidden # 256 + + kernel_size = opt.MODEL.kernel_size # 3 + assert(kernel_size % 2 == 1) + assert(self.nc_hidden % 2 == 0) + + + layer_head = nn.Conv1d(nc_motion, self.nc_hidden, kernel_size=1) + layer_head = nn.utils.weight_norm(layer_head, name='weight') + self.layer_head = layer_head + + # Initializing last layer to 0 makes the affine coupling layers + # do nothing at first. This helps with training stability + layer_tail = nn.Conv1d(self.nc_hidden, nc_output, kernel_size=1) + layer_tail.weight.data.zero_() + layer_tail.bias.data.zero_() + self.layer_tail = layer_tail + + # for + layer_cond = nn.Conv1d(nc_condit, 2*self.nc_hidden*self.n_layers, 1) + self.layer_cond = nn.utils.weight_norm(layer_cond, name='weight') + self.layer_cond = layer_cond + + self.in_layers = nn.ModuleList() + self.res_skip_layers = nn.ModuleList() + + for i in range(self.n_layers): + dilation = 2 ** i # 1, 2, 4, 8 + padding = (kernel_size * dilation - dilation) // 2 # 1, 2, 4, 8 + in_layer = nn.Conv1d(self.nc_hidden, 2*self.nc_hidden, kernel_size, dilation=dilation, padding=padding) + in_layer = nn.utils.weight_norm(in_layer, name='weight') + self.in_layers.append(in_layer) + + # last one is not necessary + nc_skip = 2 * self.nc_hidden if (i < self.n_layers - 1) else self.nc_hidden + layer_skip = nn.Conv1d(self.nc_hidden, nc_skip, kernel_size=1) + layer_skip = nn.utils.weight_norm(layer_skip, name='weight') + self.res_skip_layers.append(layer_skip) + + + def forward(self, x, c): + """ forward function + x shape = (B x nfeat1 x nsteps1) B x nc_motion_half x nstep + c shape = (B x nfeat2 x nsteps2) B x nc_condit*nc_motion x nstep + """ + + feat_x = self.layer_head(x) # B x nc_hidden x nstep + feat_c = self.layer_cond(c) # B x 4*nc_hidden x nstep + feat_o = torch.zeros_like(feat_x) # B x nc_hidden x nstep + debug(self.opt, f"\t[FusionNet] feat_x={feat_x.shape}, feat_c={feat_c.shape}, feat_o={feat_o.shape}") + + nc_hidden_tensor = torch.IntTensor([self.nc_hidden]) + + for i in range(self.n_layers): + c_offset = i * 2 * self.nc_hidden + debug(self.opt, f"\t[FusionNet] layers={i} c_offset={c_offset}") + + + ifeat_x = self.in_layers[i](feat_x) # B x 2*nc_hidden x nstep + ifeat_c = feat_c[:, c_offset:c_offset+2*self.nc_hidden, :] # B x 2*nc_hidden x nstep + debug(self.opt, f"\t[FusionNet] \tifeat_x={ifeat_x.shape} ifeat_c={ifeat_c.shape}") + + ifeat_m = fused_add_tanh_sigmoid_multiply(ifeat_x, ifeat_c, nc_hidden_tensor) # B x nc_hidden x nstep + debug(self.opt, f"\t[FusionNet] \tifeat_m={ifeat_m.shape}") + + ifeat_m = self.res_skip_layers[i](ifeat_m) # B x 2*nc_hidden x nstep if not last layer else B x nc_hidden x 25 + debug(self.opt, f"\t[FusionNet] \t res skip ifeat_m={ifeat_m.shape}") + + if i < self.n_layers - 1: + feat_x = feat_x + ifeat_m[:, :self.nc_hidden, :] # B x nc_hidden x nstep + feat_o = feat_o + ifeat_m[:, self.nc_hidden:, :] # B x nc_hidden x nstep + else: + feat_o = feat_o + ifeat_m # B x nc_hidden x nstep + + feat_o = self.layer_tail(feat_o) # B x nc_motion_half x nstep + debug(self.opt, f"\t[FusionNet] tail feat_o={feat_o.shape}") + + return feat_o + diff --git a/src/nn/MotionWaveFlow22.py b/src/nn/MotionWaveFlow22.py new file mode 100644 index 0000000..4102e18 --- /dev/null +++ b/src/nn/MotionWaveFlow22.py @@ -0,0 +1,375 @@ +import torch +import torch.nn as nn +import torch.nn.functional as F +import numpy as np + +from common.debug import debug +from src.nn.layers import ActNorm1d, Invertible1x1Conv1d as Invertible1x1Conv + +# @torch.jit.script +def fused_add_tanh_sigmoid_multiply(input_a, input_b, n_channels): + n_channels_int = n_channels[0] + in_act = input_a + input_b + t_act = torch.tanh(in_act[:, :n_channels_int, :]) + s_act = torch.sigmoid(in_act[:, n_channels_int:, :]) + acts = t_act * s_act + return acts + + +class MotionWaveFlow(nn.Module): + + def __init__(self, opt): + super(MotionWaveFlow, self).__init__() + + self.opt = opt + self.nc_motion = opt.MODEL.dim_motion # 5023 + self.nc_condit = opt.MODEL.dim_speech # 1024 + self.nc_hidden = opt.MODEL.dim_hidden # 256 + + + self.n_flows = opt.MODEL.n_flowstep # 12 + self.n_early_every = opt.MODEL.n_early_every # 4 --> 3 + + self.fix_dims = np.array(opt.MODEL.fix_dims) + self.lambda_std = np.array(opt.MODEL.lambda_std) # [1, 0.75, 0.5, 0.25] + self.lambda_std = torch.from_numpy(self.lambda_std).float().cuda(opt.GPUS[0]) + + self.Conv1x1Invs = nn.ModuleList() + self.FusionNets = nn.ModuleList() + self.Actnorms = nn.ModuleList() + nc_motion_rest = self.nc_motion # 8 --> 136 + + for k in range(self.n_flows): + if k % self.n_early_every == 0 and k > 0: # k = 3, 6, 9 + nc_motion_rest = nc_motion_rest - nc_motion_rest // 2 # = 84, 42, 21 + + self.Actnorms.append(ActNorm1d(num_channels=nc_motion_rest)) + self.Conv1x1Invs.append(Invertible1x1Conv(nc_motion_rest)) + self.FusionNets.append(FusionNet(self.opt, nc_motion=nc_motion_rest - nc_motion_rest//2, + nc_condit=self.nc_condit, + nc_output=2*(nc_motion_rest//2))) + + debug(self.opt, f"[Model] k={k} nc_motion_rest={nc_motion_rest}") + + self.nc_motion_rest = nc_motion_rest # Useful during inference, 72 / 8 + + + def set_actnorm_init(self, inited=True): + for name, m in self.named_modules(): + if (m.__class__.__name__.find("ActNorm") >= 0): + m.inited = inited + debug(self.opt, f"[Model] set module {m.__class__.__name__} inited = {inited}") + + + def forward(self, x, c): + """For training, x --> z + x shape = (B, nc_motion, nsteps), + c shape = (B, nsteps, nwind, nc_speech), + return: + z shape = (B, dim_motin, nsteps) + """ + + debug(self.opt, f"\n[Forward] start x shape={x.shape}, c={c.shape}", verbose=False) + + predt_z = [] + # feat_c = self.speechEncoder(c) # (B, nc_hidden, nsteps) + logdet = torch.zeros(c.size(0), dtype=c.dtype, device=c.device) + debug(self.opt, f"\n[Forward] c shape={c.shape}, logdet={logdet.shape}", verbose=False) + + for k in range(self.n_flows): + + x, logdet = self.Actnorms[k](x, logdet) + debug(self.opt, f"[Forward] k={k}, actnorm x shape = {x.shape} logdet={logdet.shape}", verbose=False) + + x, logdet = self.Conv1x1Invs[k](x, logdet) + debug(self.opt, f"[Forward] k={k}, Conv1x1Invs x={x.shape}, logdet={logdet.shape}") + + # coupling layers + nc_motion_half = x.size(1) - x.size(1) // 2 + x1, x2 = x[:, :nc_motion_half, :], x[:, nc_motion_half:, :] + debug(self.opt, f"[Forward] k={k}, coupling split x1={x1.shape}, x2={x2.shape}") + + feat = self.FusionNets[k](x1, c) # (B, nc_motion_half, nc_output) + shift, scale = feat[:, 0::2, :], feat[:, 1::2, :] + scale = torch.sigmoid(scale + 2.) + 1e-6 # to make scale > 1, so that log(s) > 0 + x2 = (x2 + shift) * scale + logdet = torch.sum(torch.log(scale), dim=[1, 2]) + logdet + + # multi-scale split + if k % self.n_early_every == (self.n_early_every -1) and k > 0 and k < self.n_flows -1: + predt_z.append(x2) + x = x1 + debug(self.opt, f"[Forward] k={k}, coupling muli-scale x={x.shape}, x2={x2.shape}, logdet={logdet.shape}", verbose=False) + else: + x = torch.cat([x1, x2], dim=1) + debug(self.opt, f"[Forward] k={k}, coupling concat x={x.shape}, logdet={logdet.shape}", verbose=False) + + + # append the last x + predt_z.append(x) + predt_z = list(reversed(predt_z)) + # predt_z = torch.cat(predt_z, dim=1) + + return predt_z, logdet + + def inverse(self, c): + """For inference, z --> x + # c shape = (B, nc_condit, nsteps_c) + c shape = (B, nsteps, nwind, nc_speech), + return: + x shape = (B, nc_motion, nsteps_x) + """ + + B, nsteps = c.size(0), c.size(1) + + # add z + mu = torch.zeros(B, self.nc_motion_rest, nsteps, device=c.device) + std = torch.ones(B, self.nc_motion_rest, nsteps, device=c.device) * self.lambda_std[0] + x = torch.normal(mean=mu, std=std) + # x = torch.zeros(B, self.nc_motion_rest, nsteps, device=c.device).normal_() # (B, 40, 60) + + # feat_c = self.speechEncoder(c) # (B, nc_hidden, nsteps) + logdet = torch.zeros(B, dtype=c.dtype, device=c.device) + debug(self.opt, f"\n[Inverse] c shape={c.shape}, logdet={logdet.shape}", verbose=False) + + istd = 1 + for k in reversed(range(self.n_flows)): + # coupling layer + nc_motion_half = x.size(1) - x.size(1) // 2 + x1, x2 = x[:, :nc_motion_half, :], x[:, nc_motion_half:, :] + debug(self.opt, f"[Inverse] k={k}, x1={x1.shape}, x2={x2.shape}", verbose=False) + + feat = self.FusionNets[k](x1, c) # (B, 1, nc_output) + shift, scale = feat[:, 0::2, :], feat[:, 1::2, :] + scale = torch.sigmoid(scale + 2.) + 1e-6 # to make scale > 1, so that log(s) > 0 + debug(self.opt, f"[Inverse] k={k}, coupling feat shape={feat.shape}, shift={shift.shape}, scale={scale.shape}", verbose=False) + + x2 = x2 / scale - shift + x = torch.cat([x1, x2], dim=1) + logdet = - torch.sum(torch.log(scale), dim=[1,2]) + logdet + debug(self.opt, f"[Inverse] k={k}, coupling concat x={x.shape}, logdet={logdet.shape}", verbose=False) + + # 1 x 1 conv inv + x, logdet = self.Conv1x1Invs[k].inverse(x, logdet) + debug(self.opt, f"[Inverse] k={k}, Conv1x1Invs x={x.shape}") + + # actnorm + x, logdet = self.Actnorms[k].inverse(x, logdet) + debug(self.opt, f"[Inverse] k={k}, actnorm x shape = {x.shape}", verbose=False) + + # add noise + if k % self.n_early_every == 0 and k > 0: + # z = torch.zeros(B, x.size(1), nsteps, device=c.device).normal_() # (B, 40, 60) + num_dims = x.size(1) + self.fix_dims[istd] + + mu = torch.zeros(B, num_dims, nsteps, device=c.device) + std = torch.ones(B, num_dims, nsteps, device=c.device) * self.lambda_std[istd] + z = torch.normal(mean=mu, std=std) + istd += 1 + + x = torch.cat((x, z), dim=1) # (B, 8/40/72/104/136, 25) + debug(self.opt, f"[Inverse] k={k}, ADD noise + {x.size(1)} channel, x shape = {x.shape}", verbose=False) + + return x.detach(), logdet # (B, nc_motion, nsteps) + + + def loss_function_(self, z, logdet, sigma=1.0): + """z = list (B, nc_motion, N) + logdet = list (B, ) + """ + + loss = 0 + loss_dict = {} + nsteps = z[0].size(2) + debug(self.opt, f"[Loss] z shape={z[0].shape}, logdet={logdet.shape}") + assert len(z) == len(self.lambda_std) + + logp = 0 + for std, zn in zip(self.lambda_std, z): + ilogp = -torch.log(std) - 0.5*zn*zn / (std * std) - 0.5 * torch.log(2 * torch.tensor(np.pi)) # B x nc x nsteps + logp += torch.sum(ilogp, dim=[1,2]) / (2*sigma * sigma) # (B, ) + + # logp = - 0.5*z*z - 0.5 * torch.log(2 * torch.tensor(np.pi)) # (B, N, nc_motion) + # logp = torch.sum(logp, dim=[1,2]) / (2*sigma * sigma) # (B, ) + + loss_logp = - torch.mean(logp) / (np.log(2.0) * nsteps * len(z)) + loss_logdet = - torch.mean(logdet) / (np.log(2.0) * nsteps) + loss = loss_logp * self.opt.LOSS.lambda_logp + loss_logdet * self.opt.LOSS.lambda_logdet + + loss_dict["loss_logp"] = loss_logp.detach() + loss_dict["loss_logdet"] = loss_logdet.detach() + loss_dict["loss_all"] = loss.detach() + + return loss, loss_dict + + +class SpeechEncoderNet(nn.Module): + """ + This is a 2D Conv encoder network for speech data with windows + """ + def __init__(self, opt, nc_speech, nc_output): + super(SpeechEncoderNet, self).__init__() + + self.opt = opt + # encoder + self.encoder = nn.Sequential( # (nbatch, nchannel=1024, H=16, W=1) + nn.BatchNorm2d(nc_speech), + + # block 1 + nn.Conv2d(nc_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=50), # 128, + nn.Tanh(), + + nn.Linear(in_features=50, out_features=nc_output) # 50, + ) + + def forward(self, x): + """ forward function + Args: + x: [nbatch x nsteps x nwind x dim_condit] + return: + pred: [nbatch x nc_output x nsteps] + """ + + (nbatch, nsteps, nwind, nfeat) = x.shape # (B, nsetps, 16, nc_speech) + debug(self.opt, f"[SpeechEncoderNet] input x shape = {x.shape}", verbose=False) + + # preprocessing data + x = x.reshape(nbatch * nsteps, 1, nwind, nfeat) # (B * nsteps, 1, 16, nc_speech) + x = torch.transpose(x, 1, 3) # (B * nsteps, nc_speech, 16, 1) + debug(self.opt, f"[SpeechEncoderNet] transpose x shape = {x.shape}", verbose=False) + + + feat = self.encoder(x) # (B * nsteps, nc_output) + debug(self.opt, f"[SpeechEncoderNet] encoder shape = {feat.shape}", verbose=False) + + feat = feat.reshape(nbatch, nsteps, -1) # (B, nsteps, nc_output) + feat = torch.transpose(feat, 1, 2) # (B, nc_output, nsteps) + debug(self.opt, f"[SpeechEncoderNet] reshape shape = {feat.shape}", verbose=False) + + return feat + + +class FusionNet(nn.Module): + """ + This is the WaveNet like layer for the affine coupling. The primary difference + from WaveNet is the convolutions need not be causal. There is also no dilation + size reset. The dilation only doubles on each layer + """ + + def __init__(self, opt, nc_motion, nc_condit, nc_output): + super(FusionNet, self).__init__() + + self.opt = opt + + self.n_layers = opt.MODEL.n_layer_wave # 4 + self.nc_hidden = opt.MODEL.dim_hidden # 256 + + kernel_size = opt.MODEL.kernel_size # 3 + assert(kernel_size % 2 == 1) + assert(self.nc_hidden % 2 == 0) + + + # audio encoder + self.layer_cond = SpeechEncoderNet(opt, nc_condit, 2* self.nc_hidden * self.n_layers) + + # # for + # layer_cond = nn.Conv1d(self.nc_hidden, 2*self.nc_hidden*self.n_layers, 1) + # self.layer_cond = nn.utils.weight_norm(layer_cond, name='weight') + # self.layer_cond = layer_cond + + + layer_head = nn.Conv1d(nc_motion, self.nc_hidden, kernel_size=1) + layer_head = nn.utils.weight_norm(layer_head, name='weight') + self.layer_head = layer_head + + # Initializing last layer to 0 makes the affine coupling layers + # do nothing at first. This helps with training stability + layer_tail = nn.Conv1d(self.nc_hidden, nc_output, kernel_size=1) + layer_tail.weight.data.zero_() + layer_tail.bias.data.zero_() + self.layer_tail = layer_tail + + + self.in_layers = nn.ModuleList() + self.res_skip_layers = nn.ModuleList() + + for i in range(self.n_layers): + dilation = 2 ** i # 1, 2, 4, 8 + padding = (kernel_size * dilation - dilation) // 2 # 1, 2, 4, 8 + in_layer = nn.Conv1d(self.nc_hidden, 2*self.nc_hidden, kernel_size, dilation=dilation, padding=padding) + in_layer = nn.utils.weight_norm(in_layer, name='weight') + self.in_layers.append(in_layer) + + # last one is not necessary + nc_skip = 2 * self.nc_hidden if (i < self.n_layers - 1) else self.nc_hidden + layer_skip = nn.Conv1d(self.nc_hidden, nc_skip, kernel_size=1) + layer_skip = nn.utils.weight_norm(layer_skip, name='weight') + self.res_skip_layers.append(layer_skip) + + + def forward(self, x, c): + """ forward function + x shape = (B x nfeat1 x nsteps1) B x nc_motion_half x nstep + c shape = (B x nfeat2 x nsteps2) B x nc_condit*nc_motion x nstep + """ + + feat_x = self.layer_head(x) # B x nc_hidden x nstep + feat_c = self.layer_cond(c) # B x 4*nc_hidden x nstep + feat_o = torch.zeros_like(feat_x) # B x nc_hidden x nstep + debug(self.opt, f"\t[FusionNet] feat_x={feat_x.shape}, feat_c={feat_c.shape}, feat_o={feat_o.shape}") + + nc_hidden_tensor = torch.IntTensor([self.nc_hidden]) + + for i in range(self.n_layers): + c_offset = i * 2 * self.nc_hidden + debug(self.opt, f"\t[FusionNet] layers={i} c_offset={c_offset}") + + + ifeat_x = self.in_layers[i](feat_x) # B x 2*nc_hidden x nstep + ifeat_c = feat_c[:, c_offset:c_offset+2*self.nc_hidden, :] # B x 2*nc_hidden x nstep + debug(self.opt, f"\t[FusionNet] \tifeat_x={ifeat_x.shape} ifeat_c={ifeat_c.shape}") + + ifeat_m = fused_add_tanh_sigmoid_multiply(ifeat_x, ifeat_c, nc_hidden_tensor) # B x nc_hidden x nstep + debug(self.opt, f"\t[FusionNet] \tifeat_m={ifeat_m.shape}") + + ifeat_m = self.res_skip_layers[i](ifeat_m) # B x 2*nc_hidden x nstep if not last layer else B x nc_hidden x 25 + debug(self.opt, f"\t[FusionNet] \t res skip ifeat_m={ifeat_m.shape}") + + if i < self.n_layers - 1: + feat_x = feat_x + ifeat_m[:, :self.nc_hidden, :] # B x nc_hidden x nstep + feat_o = feat_o + ifeat_m[:, self.nc_hidden:, :] # B x nc_hidden x nstep + else: + feat_o = feat_o + ifeat_m # B x nc_hidden x nstep + + feat_o = self.layer_tail(feat_o) # B x nc_motion_half x nstep + debug(self.opt, f"\t[FusionNet] tail feat_o={feat_o.shape}") + + return feat_o + diff --git a/src/nn/MotionWaveFlow3.py b/src/nn/MotionWaveFlow3.py new file mode 100644 index 0000000..df9de30 --- /dev/null +++ b/src/nn/MotionWaveFlow3.py @@ -0,0 +1,339 @@ +import torch +import torch.nn as nn +import torch.nn.functional as F +import numpy as np + +from common.debug import debug +from src.nn.layers import ActNorm1d, Invertible1x1Conv1d as Invertible1x1Conv + +# @torch.jit.script +def fused_add_tanh_sigmoid_multiply(input_a, input_b, n_channels): + n_channels_int = n_channels[0] + in_act = input_a + input_b + t_act = torch.tanh(in_act[:, :n_channels_int, :]) + s_act = torch.sigmoid(in_act[:, n_channels_int:, :]) + acts = t_act * s_act + return acts + + +class MotionWaveFlow(nn.Module): + + def __init__(self, opt): + super(MotionWaveFlow, self).__init__() + + self.opt = opt + self.nc_motion = opt.MODEL.dim_motion # 5023 + self.nc_condit = opt.MODEL.dim_speech # 1024 + self.nc_hidden = opt.MODEL.dim_hidden # 256 + + + self.n_flows = opt.MODEL.n_flowstep # 12 + self.n_early_every = opt.MODEL.n_early_every # 4 --> 3 + + self.fix_dims = np.array(opt.MODEL.fix_dims) + self.lambda_std = np.array(opt.MODEL.lambda_std) # [1, 0.75, 0.5, 0.25] + self.lambda_std = torch.from_numpy(self.lambda_std).float().cuda(opt.GPUS[0]) + + self.Conv1x1Invs = nn.ModuleList() + self.FusionNets = nn.ModuleList() + self.Actnorms = nn.ModuleList() + nc_motion_rest = self.nc_motion # 8 --> 136 + + for k in range(self.n_flows): + if k % self.n_early_every == 0 and k > 0: # k = 3, 6, 9 + nc_motion_rest = nc_motion_rest - nc_motion_rest // 2 # = 84, 42, 21 + + self.Actnorms.append(ActNorm1d(num_channels=nc_motion_rest)) + self.Conv1x1Invs.append(Invertible1x1Conv(nc_motion_rest)) + self.FusionNets.append(FusionNet(self.opt, nc_motion=nc_motion_rest - nc_motion_rest//2, + nc_condit=self.nc_condit, + nc_output=2*(nc_motion_rest//2))) + + debug(self.opt, f"[Model] k={k} nc_motion_rest={nc_motion_rest}") + + self.nc_motion_rest = nc_motion_rest # Useful during inference, 72 / 8 + + + def set_actnorm_init(self, inited=True): + for name, m in self.named_modules(): + if (m.__class__.__name__.find("ActNorm") >= 0): + m.inited = inited + debug(self.opt, f"[Model] set module {m.__class__.__name__} inited = {inited}") + + + def forward(self, x, c): + """For training, x --> z + x shape = (B, nc_motion, nsteps), + c shape = (B, nsteps, nwind, nc_speech), + return: + z shape = (B, dim_motin, nsteps) + """ + + debug(self.opt, f"\n[Forward] start x shape={x.shape}, c={c.shape}", verbose=False) + + predt_z = [] + # feat_c = self.speechEncoder(c) # (B, nc_hidden, nsteps) + logdet = torch.zeros(c.size(0), dtype=c.dtype, device=c.device) + debug(self.opt, f"\n[Forward] c shape={c.shape}, logdet={logdet.shape}", verbose=False) + + for k in range(self.n_flows): + + x, logdet = self.Actnorms[k](x, logdet) + debug(self.opt, f"[Forward] k={k}, actnorm x shape = {x.shape} logdet={logdet.shape}", verbose=False) + + x, logdet = self.Conv1x1Invs[k](x, logdet) + debug(self.opt, f"[Forward] k={k}, Conv1x1Invs x={x.shape}, logdet={logdet.shape}") + + # coupling layers + nc_motion_half = x.size(1) - x.size(1) // 2 + x1, x2 = x[:, :nc_motion_half, :], x[:, nc_motion_half:, :] + debug(self.opt, f"[Forward] k={k}, coupling split x1={x1.shape}, x2={x2.shape}") + + feat = self.FusionNets[k](x1, c) # (B, nc_motion_half, nc_output) + shift, scale = feat[:, 0::2, :], feat[:, 1::2, :] + scale = torch.sigmoid(scale + 2.) + 1e-6 # to make scale > 1, so that log(s) > 0 + x2 = (x2 + shift) * scale + logdet = torch.sum(torch.log(scale), dim=[1, 2]) + logdet + + # multi-scale split + if k % self.n_early_every == (self.n_early_every -1) and k > 0 and k < self.n_flows -1: + predt_z.append(x2) + x = x1 + debug(self.opt, f"[Forward] k={k}, coupling muli-scale x={x.shape}, x2={x2.shape}, logdet={logdet.shape}", verbose=False) + else: + x = torch.cat([x1, x2], dim=1) + debug(self.opt, f"[Forward] k={k}, coupling concat x={x.shape}, logdet={logdet.shape}", verbose=False) + + + # append the last x + predt_z.append(x) + predt_z = list(reversed(predt_z)) + # predt_z = torch.cat(predt_z, dim=1) + + return predt_z, logdet + + def inverse(self, c): + """For inference, z --> x + # c shape = (B, nc_condit, nsteps_c) + c shape = (B, nsteps, nwind, nc_speech), + return: + x shape = (B, nc_motion, nsteps_x) + """ + + B, nsteps = c.size(0), c.size(1) + + # add z + mu = torch.zeros(B, self.nc_motion_rest, nsteps, device=c.device) + std = torch.ones(B, self.nc_motion_rest, nsteps, device=c.device) * self.lambda_std[0] + x = torch.normal(mean=mu, std=std) + # x = torch.zeros(B, self.nc_motion_rest, nsteps, device=c.device).normal_() # (B, 40, 60) + + # feat_c = self.speechEncoder(c) # (B, nc_hidden, nsteps) + logdet = torch.zeros(B, dtype=c.dtype, device=c.device) + debug(self.opt, f"\n[Inverse] c shape={c.shape}, logdet={logdet.shape}", verbose=False) + + istd = 1 + for k in reversed(range(self.n_flows)): + # coupling layer + nc_motion_half = x.size(1) - x.size(1) // 2 + x1, x2 = x[:, :nc_motion_half, :], x[:, nc_motion_half:, :] + debug(self.opt, f"[Inverse] k={k}, x1={x1.shape}, x2={x2.shape}", verbose=False) + + feat = self.FusionNets[k](x1, c) # (B, 1, nc_output) + shift, scale = feat[:, 0::2, :], feat[:, 1::2, :] + scale = torch.sigmoid(scale + 2.) + 1e-6 # to make scale > 1, so that log(s) > 0 + debug(self.opt, f"[Inverse] k={k}, coupling feat shape={feat.shape}, shift={shift.shape}, scale={scale.shape}", verbose=False) + + x2 = x2 / scale - shift + x = torch.cat([x1, x2], dim=1) + logdet = - torch.sum(torch.log(scale), dim=[1,2]) + logdet + debug(self.opt, f"[Inverse] k={k}, coupling concat x={x.shape}, logdet={logdet.shape}", verbose=False) + + # 1 x 1 conv inv + x, logdet = self.Conv1x1Invs[k].inverse(x, logdet) + debug(self.opt, f"[Inverse] k={k}, Conv1x1Invs x={x.shape}") + + # actnorm + x, logdet = self.Actnorms[k].inverse(x, logdet) + debug(self.opt, f"[Inverse] k={k}, actnorm x shape = {x.shape}", verbose=False) + + # add noise + if k % self.n_early_every == 0 and k > 0: + # z = torch.zeros(B, x.size(1), nsteps, device=c.device).normal_() # (B, 40, 60) + num_dims = x.size(1) + self.fix_dims[istd] + + mu = torch.zeros(B, num_dims, nsteps, device=c.device) + std = torch.ones(B, num_dims, nsteps, device=c.device) * self.lambda_std[istd] + z = torch.normal(mean=mu, std=std) + istd += 1 + + x = torch.cat((x, z), dim=1) # (B, 8/40/72/104/136, 25) + debug(self.opt, f"[Inverse] k={k}, ADD noise + {x.size(1)} channel, x shape = {x.shape}", verbose=False) + + return x.detach(), logdet # (B, nc_motion, nsteps) + + + def loss_function_(self, z, logdet, sigma=1.0): + """z = list (B, nc_motion, N) + logdet = list (B, ) + """ + + loss = 0 + loss_dict = {} + nsteps = z[0].size(2) + debug(self.opt, f"[Loss] z shape={z[0].shape}, logdet={logdet.shape}") + assert len(z) == len(self.lambda_std) + + logp = 0 + for std, zn in zip(self.lambda_std, z): + ilogp = -torch.log(std) - 0.5*zn*zn / (std * std) - 0.5 * torch.log(2 * torch.tensor(np.pi)) # B x nc x nsteps + logp += torch.sum(ilogp, dim=[1,2]) / (2*sigma * sigma) # (B, ) + + # logp = - 0.5*z*z - 0.5 * torch.log(2 * torch.tensor(np.pi)) # (B, N, nc_motion) + # logp = torch.sum(logp, dim=[1,2]) / (2*sigma * sigma) # (B, ) + + loss_logp = - torch.mean(logp) / (np.log(2.0) * nsteps * len(z)) + loss_logdet = - torch.mean(logdet) / (np.log(2.0) * nsteps) + loss = loss_logp * self.opt.LOSS.lambda_logp + loss_logdet * self.opt.LOSS.lambda_logdet + + loss_dict["loss_logp"] = loss_logp.detach() + loss_dict["loss_logdet"] = loss_logdet.detach() + loss_dict["loss_all"] = loss.detach() + + return loss, loss_dict + + +class SpeechEncoderNet(nn.Module): + """ + This is a 2D Conv encoder network for speech data with windows + """ + def __init__(self, opt, nc_speech, nc_output): + super(SpeechEncoderNet, self).__init__() + + self.opt = opt + # encoder + self.encoder = nn.Sequential( # (nbatch, nchannel=1024, H=16, W=1) + nn.BatchNorm2d(nc_speech), + + # block 1 + nn.Conv2d(nc_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=50), # 128, + nn.Tanh(), + + nn.Linear(in_features=50, out_features=nc_output) # 50, + ) + + def forward(self, x): + """ forward function + Args: + x: [nbatch x nsteps x nwind x dim_condit] + return: + pred: [nbatch x nc_output x nsteps] + """ + + (nbatch, nsteps, nwind, nfeat) = x.shape # (B, nsetps, 16, nc_speech) + debug(self.opt, f"[SpeechEncoderNet] input x shape = {x.shape}", verbose=False) + + # preprocessing data + x = x.reshape(nbatch * nsteps, 1, nwind, nfeat) # (B * nsteps, 1, 16, nc_speech) + x = torch.transpose(x, 1, 3) # (B * nsteps, nc_speech, 16, 1) + debug(self.opt, f"[SpeechEncoderNet] transpose x shape = {x.shape}", verbose=False) + + + feat = self.encoder(x) # (B * nsteps, nc_output) + debug(self.opt, f"[SpeechEncoderNet] encoder shape = {feat.shape}", verbose=False) + + feat = feat.reshape(nbatch, nsteps, -1) # (B, nsteps, nc_output) + feat = torch.transpose(feat, 1, 2) # (B, nc_output, nsteps) + debug(self.opt, f"[SpeechEncoderNet] reshape shape = {feat.shape}", verbose=False) + + return feat + + +class FusionNet(nn.Module): + """ + This is the WaveNet like layer for the affine coupling. The primary difference + from WaveNet is the convolutions need not be causal. There is also no dilation + size reset. The dilation only doubles on each layer + """ + + def __init__(self, opt, nc_motion, nc_condit, nc_output): + super(FusionNet, self).__init__() + + self.opt = opt + + self.n_layers = opt.MODEL.n_layer_wave # 4 + self.nc_hidden = opt.MODEL.dim_hidden # 256 + + kernel_size = opt.MODEL.kernel_size # 3 + assert(kernel_size % 2 == 1) + assert(self.nc_hidden % 2 == 0) + + # audio encoder + self.layer_cond = SpeechEncoderNet(opt, nc_condit, 2 * self.nc_hidden) + + # # for + # layer_cond = nn.Conv1d(self.nc_hidden, 2*self.nc_hidden*self.n_layers, 1) + # self.layer_cond = nn.utils.weight_norm(layer_cond, name='weight') + # self.layer_cond = layer_cond + + + layer_head = nn.Conv1d(nc_motion, 2 * self.nc_hidden, kernel_size=1) + layer_head = nn.utils.weight_norm(layer_head, name='weight') + self.layer_head = layer_head + + # Initializing last layer to 0 makes the affine coupling layers + # do nothing at first. This helps with training stability + layer_tail = nn.Conv1d(self.nc_hidden, nc_output, kernel_size=1) + layer_tail.weight.data.zero_() + layer_tail.bias.data.zero_() + self.layer_tail = layer_tail + + + def forward(self, x, c): + """ forward function + x shape = (B x nfeat1 x nsteps1) B x nc_motion_half x nstep + c shape = (B x nfeat2 x nsteps2) B x nc_condit*nc_motion x nstep + """ + + feat_x = self.layer_head(x) # B x 2*nc_hidden x nstep + feat_c = self.layer_cond(c) # B x 2*nc_hidden x nstep + debug(self.opt, f"\t[FusionNet] feat_x={feat_x.shape}, feat_c={feat_c.shape}") + + nc_hidden_tensor = torch.IntTensor([self.nc_hidden]) + feat_m = fused_add_tanh_sigmoid_multiply(feat_x, feat_c, nc_hidden_tensor) # B x nc_hidden x nstep + debug(self.opt, f"\t[FusionNet] \tfeat_m={feat_m.shape}") + + + feat_o = self.layer_tail(feat_m) # B x nc_motion_half x nstep + debug(self.opt, f"\t[FusionNet] tail feat_o={feat_o.shape}") + + + return feat_o + diff --git a/src/nn/MotionWaveFlow4.py b/src/nn/MotionWaveFlow4.py new file mode 100644 index 0000000..0158300 --- /dev/null +++ b/src/nn/MotionWaveFlow4.py @@ -0,0 +1,351 @@ +import torch +import torch.nn as nn +import torch.nn.functional as F +import numpy as np + +from common.debug import debug +from src.nn.layers import ActNorm1d, Invertible1x1Conv1d as Invertible1x1Conv + +# @torch.jit.script +def fused_add_tanh_sigmoid_multiply(input_a, input_b, n_channels): + n_channels_int = n_channels[0] + in_act = input_a + input_b + t_act = torch.tanh(in_act[:, :n_channels_int, :]) + s_act = torch.sigmoid(in_act[:, n_channels_int:, :]) + acts = t_act * s_act + return acts + + +class MotionWaveFlow(nn.Module): + + def __init__(self, opt): + super(MotionWaveFlow, self).__init__() + + self.opt = opt + self.nc_motion = opt.MODEL.dim_motion # 5023 + self.nc_condit = opt.MODEL.dim_speech # 1024 + self.nc_hidden = opt.MODEL.dim_hidden # 256 + + + self.n_flows = opt.MODEL.n_flowstep # 12 + self.n_early_every = opt.MODEL.n_early_every # 4 --> 3 + + self.fix_dims = np.array(opt.MODEL.fix_dims) + self.lambda_std = np.array(opt.MODEL.lambda_std) # [1, 0.75, 0.5, 0.25] + self.lambda_std = torch.from_numpy(self.lambda_std).float().cuda(opt.GPUS[0]) + + self.Conv1x1Invs = nn.ModuleList() + self.FusionNets = nn.ModuleList() + self.Actnorms = nn.ModuleList() + nc_motion_rest = self.nc_motion # 8 --> 136 + + for k in range(self.n_flows): + if k % self.n_early_every == 0 and k > 0: # k = 3, 6, 9 + nc_motion_rest = nc_motion_rest - nc_motion_rest // 2 # = 84, 42, 21 + + self.Actnorms.append(ActNorm1d(num_channels=nc_motion_rest)) + self.Conv1x1Invs.append(Invertible1x1Conv(nc_motion_rest)) + self.FusionNets.append(FusionNet(self.opt, nc_motion=nc_motion_rest - nc_motion_rest//2, + nc_condit=self.nc_condit, + nc_output=2*(nc_motion_rest//2))) + + debug(self.opt, f"[Model] k={k} nc_motion_rest={nc_motion_rest}") + + self.nc_motion_rest = nc_motion_rest # Useful during inference, 72 / 8 + + + def set_actnorm_init(self, inited=True): + for name, m in self.named_modules(): + if (m.__class__.__name__.find("ActNorm") >= 0): + m.inited = inited + debug(self.opt, f"[Model] set module {m.__class__.__name__} inited = {inited}") + + + def forward(self, x, c): + """For training, x --> z + x shape = (B, nc_motion, nsteps), + c shape = (B, nsteps, nwind, nc_speech), + return: + z shape = (B, dim_motin, nsteps) + """ + + debug(self.opt, f"\n[Forward] start x shape={x.shape}, c={c.shape}", verbose=False) + + predt_z = [] + # feat_c = self.speechEncoder(c) # (B, nc_hidden, nsteps) + logdet = torch.zeros(c.size(0), dtype=c.dtype, device=c.device) + debug(self.opt, f"\n[Forward] c shape={c.shape}, logdet={logdet.shape}", verbose=False) + + for k in range(self.n_flows): + + x, logdet = self.Actnorms[k](x, logdet) + debug(self.opt, f"[Forward] k={k}, actnorm x shape = {x.shape} logdet={logdet.shape}", verbose=False) + + x, logdet = self.Conv1x1Invs[k](x, logdet) + debug(self.opt, f"[Forward] k={k}, Conv1x1Invs x={x.shape}, logdet={logdet.shape}") + + # coupling layers + nc_motion_half = x.size(1) - x.size(1) // 2 + x1, x2 = x[:, :nc_motion_half, :], x[:, nc_motion_half:, :] + debug(self.opt, f"[Forward] k={k}, coupling split x1={x1.shape}, x2={x2.shape}") + + feat = self.FusionNets[k](x1, c) # (B, nc_motion_half, nc_output) + shift, scale = feat[:, 0::2, :], feat[:, 1::2, :] + scale = torch.sigmoid(scale + 2.) + 1e-6 # to make scale > 1, so that log(s) > 0 + x2 = (x2 + shift) * scale + logdet = torch.sum(torch.log(scale), dim=[1, 2]) + logdet + + # multi-scale split + if k % self.n_early_every == (self.n_early_every -1) and k > 0 and k < self.n_flows -1: + predt_z.append(x2) + x = x1 + debug(self.opt, f"[Forward] k={k}, coupling muli-scale x={x.shape}, x2={x2.shape}, logdet={logdet.shape}", verbose=False) + else: + x = torch.cat([x1, x2], dim=1) + debug(self.opt, f"[Forward] k={k}, coupling concat x={x.shape}, logdet={logdet.shape}", verbose=False) + + + # append the last x + predt_z.append(x) + predt_z = list(reversed(predt_z)) + # predt_z = torch.cat(predt_z, dim=1) + + return predt_z, logdet + + def inverse(self, c): + """For inference, z --> x + # c shape = (B, nc_condit, nsteps_c) + c shape = (B, nsteps, nwind, nc_speech), + return: + x shape = (B, nc_motion, nsteps_x) + """ + + B, nsteps = c.size(0), c.size(1) + + # add z + mu = torch.zeros(B, self.nc_motion_rest, nsteps, device=c.device) + std = torch.ones(B, self.nc_motion_rest, nsteps, device=c.device) * self.lambda_std[0] + x = torch.normal(mean=mu, std=std) + # x = torch.zeros(B, self.nc_motion_rest, nsteps, device=c.device).normal_() # (B, 40, 60) + + # feat_c = self.speechEncoder(c) # (B, nc_hidden, nsteps) + logdet = torch.zeros(B, dtype=c.dtype, device=c.device) + debug(self.opt, f"\n[Inverse] c shape={c.shape}, logdet={logdet.shape}", verbose=False) + + istd = 1 + for k in reversed(range(self.n_flows)): + # coupling layer + nc_motion_half = x.size(1) - x.size(1) // 2 + x1, x2 = x[:, :nc_motion_half, :], x[:, nc_motion_half:, :] + debug(self.opt, f"[Inverse] k={k}, x1={x1.shape}, x2={x2.shape}", verbose=False) + + feat = self.FusionNets[k](x1, c) # (B, 1, nc_output) + shift, scale = feat[:, 0::2, :], feat[:, 1::2, :] + scale = torch.sigmoid(scale + 2.) + 1e-6 # to make scale > 1, so that log(s) > 0 + debug(self.opt, f"[Inverse] k={k}, coupling feat shape={feat.shape}, shift={shift.shape}, scale={scale.shape}", verbose=False) + + x2 = x2 / scale - shift + x = torch.cat([x1, x2], dim=1) + logdet = - torch.sum(torch.log(scale), dim=[1,2]) + logdet + debug(self.opt, f"[Inverse] k={k}, coupling concat x={x.shape}, logdet={logdet.shape}", verbose=False) + + # 1 x 1 conv inv + x, logdet = self.Conv1x1Invs[k].inverse(x, logdet) + debug(self.opt, f"[Inverse] k={k}, Conv1x1Invs x={x.shape}") + + # actnorm + x, logdet = self.Actnorms[k].inverse(x, logdet) + debug(self.opt, f"[Inverse] k={k}, actnorm x shape = {x.shape}", verbose=False) + + # add noise + if k % self.n_early_every == 0 and k > 0: + # z = torch.zeros(B, x.size(1), nsteps, device=c.device).normal_() # (B, 40, 60) + num_dims = x.size(1) + self.fix_dims[istd] + + mu = torch.zeros(B, num_dims, nsteps, device=c.device) + std = torch.ones(B, num_dims, nsteps, device=c.device) * self.lambda_std[istd] + z = torch.normal(mean=mu, std=std) + istd += 1 + + x = torch.cat((x, z), dim=1) # (B, 8/40/72/104/136, 25) + debug(self.opt, f"[Inverse] k={k}, ADD noise + {x.size(1)} channel, x shape = {x.shape}", verbose=False) + + return x.detach(), logdet # (B, nc_motion, nsteps) + + + def loss_function_(self, z, logdet, sigma=1.0): + """z = list (B, nc_motion, N) + logdet = list (B, ) + """ + + loss = 0 + loss_dict = {} + nsteps = z[0].size(2) + debug(self.opt, f"[Loss] z shape={z[0].shape}, logdet={logdet.shape}") + assert len(z) == len(self.lambda_std) + + logp = 0 + for std, zn in zip(self.lambda_std, z): + ilogp = -torch.log(std) - 0.5*zn*zn / (std * std) - 0.5 * torch.log(2 * torch.tensor(np.pi)) # B x nc x nsteps + logp += torch.sum(ilogp, dim=[1,2]) / (2*sigma * sigma) # (B, ) + + # logp = - 0.5*z*z - 0.5 * torch.log(2 * torch.tensor(np.pi)) # (B, N, nc_motion) + # logp = torch.sum(logp, dim=[1,2]) / (2*sigma * sigma) # (B, ) + + loss_logp = - torch.mean(logp) / (np.log(2.0) * nsteps * len(z)) + loss_logdet = - torch.mean(logdet) / (np.log(2.0) * nsteps) + loss = loss_logp * self.opt.LOSS.lambda_logp + loss_logdet * self.opt.LOSS.lambda_logdet + + loss_dict["loss_logp"] = loss_logp.detach() + loss_dict["loss_logdet"] = loss_logdet.detach() + loss_dict["loss_all"] = loss.detach() + + return loss, loss_dict + + +class SpeechEncoderNet(nn.Module): + """ + This is a 2D Conv encoder network for speech data with windows + """ + def __init__(self, opt, nc_speech, nc_output): + super(SpeechEncoderNet, self).__init__() + + self.opt = opt + # encoder + self.encoder = nn.Sequential( # (nbatch, nchannel=1024, H=16, W=1) + nn.BatchNorm2d(nc_speech), + + # block 1 + nn.Conv2d(nc_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=50), # 128, + nn.Tanh(), + + nn.Linear(in_features=50, out_features=nc_output) # 50, + ) + + def forward(self, x): + """ forward function + Args: + x: [nbatch x nsteps x nwind x dim_condit] + return: + pred: [nbatch x nc_output x nsteps] + """ + + (nbatch, nsteps, nwind, nfeat) = x.shape # (B, nsetps, 16, nc_speech) + debug(self.opt, f"[SpeechEncoderNet] input x shape = {x.shape}", verbose=False) + + # preprocessing data + x = x.reshape(nbatch * nsteps, 1, nwind, nfeat) # (B * nsteps, 1, 16, nc_speech) + x = torch.transpose(x, 1, 3) # (B * nsteps, nc_speech, 16, 1) + debug(self.opt, f"[SpeechEncoderNet] transpose x shape = {x.shape}", verbose=False) + + + feat = self.encoder(x) # (B * nsteps, nc_output) + debug(self.opt, f"[SpeechEncoderNet] encoder shape = {feat.shape}", verbose=False) + + feat = feat.reshape(nbatch, nsteps, -1) # (B, nsteps, nc_output) + feat = torch.transpose(feat, 1, 2) # (B, nc_output, nsteps) + debug(self.opt, f"[SpeechEncoderNet] reshape shape = {feat.shape}", verbose=False) + + return feat + + +class FusionNet(nn.Module): + """ + This is the WaveNet like layer for the affine coupling. The primary difference + from WaveNet is the convolutions need not be causal. There is also no dilation + size reset. The dilation only doubles on each layer + """ + + def __init__(self, opt, nc_motion, nc_condit, nc_output): + super(FusionNet, self).__init__() + + self.opt = opt + + self.n_layers = opt.MODEL.n_layer_wave # 4 + self.nc_hidden = opt.MODEL.dim_hidden # 256 + + kernel_size = opt.MODEL.kernel_size # 3 + assert(kernel_size % 2 == 1) + assert(self.nc_hidden % 2 == 0) + + # audio encoder + self.layer_cond = SpeechEncoderNet(opt, nc_condit, 2 * self.nc_hidden) + + # # for + # layer_cond = nn.Conv1d(self.nc_hidden, 2*self.nc_hidden*self.n_layers, 1) + # self.layer_cond = nn.utils.weight_norm(layer_cond, name='weight') + # self.layer_cond = layer_cond + + + layer_head = nn.Conv1d(nc_motion, 2 * self.nc_hidden, kernel_size=1) + layer_head = nn.utils.weight_norm(layer_head, name='weight') + self.layer_head = layer_head + + # Initializing last layer to 0 makes the affine coupling layers + # do nothing at first. This helps with training stability + layer_tail = nn.Conv1d(self.nc_hidden, nc_output, kernel_size=1) + layer_tail.weight.data.zero_() + layer_tail.bias.data.zero_() + self.layer_tail = layer_tail + + + self.RNN = nn.LSTM(input_size = self.nc_hidden, + hidden_size = self.nc_hidden, + num_layers = 2, + batch_first=True) + + + def forward(self, x, c): + """ forward function + x shape = (B x nfeat1 x nsteps1) B x nc_motion_half x nstep + c shape = (B x nfeat2 x nsteps2) B x nc_condit*nc_motion x nstep + """ + + feat_x = self.layer_head(x) # B x 2*nc_hidden x nstep + feat_c = self.layer_cond(c) # B x 2*nc_hidden x nstep + debug(self.opt, f"\t[FusionNet] feat_x={feat_x.shape}, feat_c={feat_c.shape}") + + nc_hidden_tensor = torch.IntTensor([self.nc_hidden]) + feat_m = fused_add_tanh_sigmoid_multiply(feat_x, feat_c, nc_hidden_tensor) # B x nc_hidden x nstep + debug(self.opt, f"\t[FusionNet] \tfeat_m={feat_m.shape}") + + + # RNN + feat_m = torch.transpose(feat_m, 1, 2) + feat_m, _ = self.RNN(feat_m) # B x nc_hidden x nstep + feat_m = torch.transpose(feat_m, 1, 2) + + # output + feat_o = self.layer_tail(feat_m) # B x nc_motion_half x nstep + debug(self.opt, f"\t[FusionNet] tail feat_o={feat_o.shape}") + + + return feat_o + diff --git a/src/nn/audio2mesh.py b/src/nn/audio2mesh.py new file mode 100644 index 0000000..52583e4 --- /dev/null +++ b/src/nn/audio2mesh.py @@ -0,0 +1,94 @@ +import torch +import torch.nn as nn +from common.debug import debug + +class Audio2Mesh(nn.Module): + + def __init__(self, opt): + super(Audio2Mesh, self).__init__() + + self.opt = opt + self.num_vertices = opt.MODEL.num_vertices + + self.dim_coef = opt.MODEL.dim_motion # 53 + self.dim_mesh = 3 * self.num_vertices # 3 * 5023 + self.dim_cond = opt.MODEL.dim_speech # 1024 + + # encoder + self.encoder = nn.Sequential( # (nbatch, nchannel=1024, H=16, W=1) + nn.BatchNorm2d(self.dim_cond), + + # block 1 + nn.Conv2d(self.dim_cond, 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=50) # 50, + ) + + # output FLAME mesh + self.decoder_mesh = nn.Linear(in_features=50, out_features=self.dim_mesh) + + + 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_coef] + """ + (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) + + + # # predict FLAME coeff + # pred_coef = self.decoder_coef(feat) # (B * nseq, dim_coef) + # debug(self.opt, f"[forward] decoder coeff shape = {pred_coef.shape}", verbose=False) + + # pred_coef = pred_coef.reshape(nbatch, nseqlen, -1) # (B, nseq, dim_coef) + # debug(self.opt, f"[forward] reshape shape = {pred_coef.shape}", verbose=False) + + # predict FLAME mesh + pred_vert = self.decoder_mesh(feat) # (B * nseq, dim_mesh) + debug(self.opt, f"[forward] decoder mesh shape = {pred_vert.shape}", verbose=False) + + pred_vert = pred_vert.reshape(nbatch, nseqlen, self.num_vertices, 3) # (B, nseq, num_vertices, 3) + debug(self.opt, f"[forward] reshape shape = {pred_vert.shape}", verbose=False) + + return pred_vert + + diff --git a/src/nn/audio2mesh_resnet.py b/src/nn/audio2mesh_resnet.py new file mode 100644 index 0000000..b34dd08 --- /dev/null +++ b/src/nn/audio2mesh_resnet.py @@ -0,0 +1,93 @@ +from termios import NCCS +import torch +import torch.nn as nn +from common.debug import debug + + +class Audio2Mesh(nn.Module): + + def __init__(self, opt): + super(Audio2Mesh, self).__init__() + + self.opt = opt + self.num_vertices = opt.MODEL.num_vertices + + self.dim_coef = opt.MODEL.dim_motion # 53 + self.dim_mesh = 3 * self.num_vertices # 3 * 5023 + self.dim_cond = opt.MODEL.dim_speech # 1024 + + self.layer_bn = nn.BatchNorm2d(self.dim_cond) + + # resnet header + self.header = self.get_resnet(nc=self.dim_cond) + + # encoder + self.encoder = nn.Sequential( + nn.Linear(in_features=2048, out_features=256), # 128, + nn.Tanh(), + + nn.Linear(in_features=256, out_features=50) + ) + + # output FLAME mesh + self.decoder_mesh = nn.Linear(in_features=50, out_features=self.dim_mesh) + + + def get_resnet(self, nc=3): + if self.opt.MODEL.name_header == "resnet34": + from src.nn.resnet import ResNet34 + return ResNet34(num_input=nc) + + elif self.opt.MODEL.name_header == "resnet50": + from src.nn.resnet import ResNet50 + return ResNet50(num_input=nc) + + elif self.opt.MODEL.name_header == "resnet101": + from src.nn.resnet import ResNet101 + return ResNet101(num_input=nc) + + else: + raise("opt.MODEL.name_header should be 'resnet34 | resnet50 | resnet101' ") + + + 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_coef] + """ + (nbatch, nseqlen, nwind, nfeat) = x.shape # (B, nseq, 16, nfeat) + 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, nfeat) + x = torch.transpose(x, 1, 3) # (B * nseq, nfeat, 16, 1) + debug(self.opt, f"[forward] transpose x shape = {x.shape}", verbose=False) + + x = self.layer_bn(x) # (B * nseq, nfeat, 16, 1) + debug(self.opt, f"[forward] bn layer x shape = {x.shape}", verbose=False) + + feat = self.header.get_features(x) # (B * nseq, 2048) + debug(self.opt, f"[forward] header shape = {feat.shape}", verbose=False) + + feat = self.encoder(feat) # (B * nseq, 50) + debug(self.opt, f"[forward] encoder shape = {feat.shape}", verbose=False) + + # # predict FLAME coeff + # pred_coef = self.decoder_coef(feat) # (B * nseq, dim_coef) + # debug(self.opt, f"[forward] decoder coeff shape = {pred_coef.shape}", verbose=False) + + # pred_coef = pred_coef.reshape(nbatch, nseqlen, -1) # (B, nseq, dim_coef) + # debug(self.opt, f"[forward] reshape shape = {pred_coef.shape}", verbose=False) + + # predict FLAME mesh + pred_vert = self.decoder_mesh(feat) # (B * nseq, dim_mesh) + debug(self.opt, f"[forward] decoder mesh shape = {pred_vert.shape}", verbose=False) + + pred_vert = pred_vert.reshape(nbatch, nseqlen, self.num_vertices, 3) # (B, nseq, num_vertices, 3) + debug(self.opt, f"[forward] reshape shape = {pred_vert.shape}", verbose=False) + + return pred_vert + + diff --git a/src/nn/audio2mesh_voca.py b/src/nn/audio2mesh_voca.py new file mode 100644 index 0000000..f1c233c --- /dev/null +++ b/src/nn/audio2mesh_voca.py @@ -0,0 +1,74 @@ +import torch +import torch.nn as nn +from common.debug import debug + +class Audio2Mesh(nn.Module): + + def __init__(self, opt): + super(Audio2Mesh, self).__init__() + + self.opt = opt + self.num_vertices = opt.MODEL.num_vertices + + self.dim_coef = opt.MODEL.dim_motion # 53 + self.dim_mesh = 3 * self.num_vertices # 3 * 5023 + self.dim_cond = opt.MODEL.dim_speech # 1024 + + # encoder + self.encoder = nn.Sequential( # (nbatch, nchannel=1024, H=16, W=1) + nn.BatchNorm2d(self.dim_cond), + + # block 1 + nn.Conv2d(self.dim_cond, 32, kernel_size=(3,1), stride=(2,1), padding=(1,0), bias=True), # 32 x 8 x 1 + nn.LeakyReLU(0.02, True), + + nn.Conv2d(32, 32, kernel_size=(3,1), stride=(2,1), padding=(1,0), bias=True), # 32 x 4 x 1 + nn.LeakyReLU(0.02, True), + + nn.Conv2d(32, 64, kernel_size=(3,1), stride=(2,1), padding=(1,0), bias=True), # 64 x 2 x 1 + nn.LeakyReLU(0.02, True), + + nn.Conv2d(64, 64, 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=64, out_features=128), # 128, + nn.Tanh(), + + nn.Linear(in_features=128, out_features=50) # 50, + ) + + + # output FLAME mesh + self.decoder_mesh = nn.Linear(in_features=50, out_features=self.dim_mesh) + + + 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_coef] + """ + (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) + + # predict FLAME mesh + pred_vert = self.decoder_mesh(feat) # (B * nseq, dim_mesh) + debug(self.opt, f"[forward] decoder mesh shape = {pred_vert.shape}", verbose=False) + + pred_vert = pred_vert.reshape(nbatch, nseqlen, self.num_vertices, 3) # (B, nseq, num_vertices, 3) + debug(self.opt, f"[forward] reshape shape = {pred_vert.shape}", verbose=False) + + return pred_vert + + diff --git a/src/nn/audio2motion_voca3.py b/src/nn/audio2motion_voca3.py index dee64e6..25d950a 100644 --- a/src/nn/audio2motion_voca3.py +++ b/src/nn/audio2motion_voca3.py @@ -57,16 +57,14 @@ class Audio2MotionVOCA3(nn.Module): (nbatch, nseqlen, nwind, nfeat) = x.shape # (B, nseq, 16, 29) debug(self.opt, f"[forward] input x shape = {x.shape}", verbose=False) - # preprocessing data + # 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) diff --git a/src/nn/audio2motion_voca34.py b/src/nn/audio2motion_voca34.py new file mode 100644 index 0000000..005353c --- /dev/null +++ b/src/nn/audio2motion_voca34.py @@ -0,0 +1,116 @@ +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=512), # 128, + nn.LeakyReLU(0.02, True), + + nn.Linear(in_features=512, out_features=512), # 128, + nn.LeakyReLU(0.02, True), + + nn.Linear(in_features=512, out_features=512), # 128, + nn.LeakyReLU(0.02, True), + + nn.Linear(in_features=512, out_features=512), # 128, + nn.LeakyReLU(0.02, True), + + nn.Linear(in_features=512, out_features=1024), # 128, + nn.LeakyReLU(0.02, True), + + nn.Linear(in_features=1024, out_features=1024), # 128, + nn.LeakyReLU(0.02, True), + + nn.Linear(in_features=1024, out_features=1024), # 128, + nn.LeakyReLU(0.02, True), + + nn.Linear(in_features=1024, out_features=1024), # 128, + nn.LeakyReLU(0.02, True), + + nn.Linear(in_features=1024, out_features=2048), # 128, + nn.LeakyReLU(0.02, True), + + nn.Linear(in_features=2048, out_features=256), # 128, + nn.Tanh(), + + nn.Linear(in_features=256, 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 index f092ca7..44612c6 100644 --- a/src/nn/audio2motion_voca4.py +++ b/src/nn/audio2motion_voca4.py @@ -16,57 +16,49 @@ class Audio2MotionVOCA(nn.Module): 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.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(128, 128, kernel_size=(3,1), stride=(1,1), padding=(1,0), bias=True), # 128 x 16 x 1 - nn.BatchNorm2d(128), + 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(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.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.Flatten(), # 256, + 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, 512, kernel_size=(3,1), stride=(1,1), padding=(1,0), bias=True), # 32 x 8 x 1 + nn.LeakyReLU(0.02, True), - nn.Linear(in_features=512, out_features=128), # 2014, + 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=(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, 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=256), # 128, + nn.LeakyReLU(0.02, True), + + nn.Linear(in_features=256, out_features=2048), # 128, nn.Tanh(), - nn.Linear(in_features=128, out_features=2048), # 2014, - nn.Tanh(), - - nn.Linear(in_features=2048, out_features=128) # 128, + nn.Linear(in_features=2048, out_features=128) # 50, ) diff --git a/src/nn/layers.py b/src/nn/layers.py new file mode 100644 index 0000000..2bd3a48 --- /dev/null +++ b/src/nn/layers.py @@ -0,0 +1,190 @@ +import torch +import torch.nn as nn +import torch.nn.functional as F +""" +Follow: +https://github.com/PolinaKirichenko/flows_ood/blob/master/flow_ssl/glow/glow_utils.py +https://github.com/tatsy/normalizing-flows-pytorch/blob/master/flows/modules.py +""" + +class Invertible1x1Conv1d(nn.Module): + """ + The layer outputs both the convolution, and the log determinant + of its weight matrix. If reverse=True it does convolution with + inverse + """ + + def __init__(self, num_channels): + super(Invertible1x1Conv1d, self).__init__() + + self.num_channels = num_channels + weight = torch.qr(torch.randn((num_channels, num_channels)))[0] + self.weight = nn.Parameter(weight) # (num_channels, num_channels) + + def forward(self, input, logdet=None): + """ + log-det = log|abs(|W|)| * nseq + """ + + nbatch, nchannels, nseq = input.size() # (B,C,N) + slogdet = (torch.slogdet(self.weight)[1] * nseq).expand(nbatch) # w * h * log |det w| + + weight = self.weight.view(self.num_channels, self.num_channels, 1) + z = F.conv1d(input, weight) + + logdet = logdet + slogdet if (logdet is not None) else slogdet + + return z, logdet + + def inverse(self, input, logdet=None): + """ + log-det = log|det(W^-1)| * nseq = - log|det(W)| * nseq + """ + nbatch, nchannels, nseq = input.size() # (B,C,N) + slogdet = - (torch.slogdet(self.weight)[1] * nseq).expand(nbatch) # w * h * log |det w| + + weight = torch.inverse(self.weight) + weight = weight.view(self.num_channels, self.num_channels, 1) + z = F.conv1d(input, weight) + + logdet = logdet + slogdet if (logdet is not None) else slogdet + + return z, logdet + + +class Invertible1x1Conv2d(nn.Module): + """ + The layer outputs both the convolution, and the log determinant + of its weight matrix. If reverse=True it does convolution with + inverse + """ + + def __init__(self, num_channels): + super(Invertible1x1Conv2d).__init__() + + self.num_channels = num_channels + weight = torch.qr(torch.randn((num_channels, num_channels)))[0] + self.weight = nn.Parameter(weight) # (num_channels, num_channels) + + def forward(self, input, logdet=None): + """ + log-det = log|abs(|W|)| * h * w + """ + nbatch, nchannels, h, w = input.size() # (B, C, H, W) + slogdet = (torch.slogdet(self.weight)[1] * h * w).expand(nbatch) # w * h * log |det w| + + weight = self.weight.view(self.num_channels, self.num_channels, 1, 1) + z = F.conv2d(input, weight) + logdet = logdet + slogdet if (logdet is not None) else None + + return z, logdet + + def inverse(self, input, logdet=None): + """ + log-det = log|det(W^-1)| * h * w = - log|det(W)| * h * w + """ + nbatch, nchannels, h, w = input.size() # (B,C,N) + slogdet = - (torch.slogdet(self.weight)[1] * h * w).expand(nbatch) # w * h * log |det w| + + weight = torch.inverse(self.weight) + weight = weight.view(self.num_channels, self.num_channels, 1, 1) + z = F.conv2d(input, weight) + logdet = logdet + slogdet if (logdet is not None) else None + + return z, logdet + + +class ActNorm1d(nn.Module): + """ Initializ at the first minibatch with zero mean and unit variance, + After initialization, the bias and logs are treated as a regular trainable parameters that are dependent of data. + """ + def __init__(self, num_channels, eps=1e-6): + super(ActNorm1d, self).__init__() + + self.inited = False + self.eps = eps + self.num_channels = num_channels + + # register bias and scale + self.bias = nn.Parameter(torch.zeros((1, num_channels, 1))) + self.logs = nn.Parameter(torch.zeros((1, num_channels, 1))) # log scale, which easy for det(log|s|) + + def init_parameters(self, input): + if not self.training: + raise ValueError("In Eval mode, but ActNorm not inited") + + with torch.no_grad(): + bias = torch.mean(input, dim=[0,2], keepdim=True) # (1, C, 1) + logs = torch.log(torch.std(input, dim=[0,2], keepdim=True) + self.eps) # (1, C, 1) + self.bias.data.copy_(bias.data) + self.logs.data.copy_(logs.data) + self.inited = True + + + def forward(self, input, logdet=None): + B,C,N = input.size() + + if not self.inited: + self.init_parameters(input) + + z = (input - self.bias) / torch.exp(self.logs) # Normalize by element-wise + dlogdet = - torch.sum(self.logs) * N + logdet = logdet + dlogdet if (logdet is not None) else None + + return z, logdet + + def inverse(self, input, logdet=None): + B,C,N = input.size() + + z = input * torch.exp(self.logs) + self.bias + dlogdet = torch.sum(self.logs) * N + logdet = logdet + dlogdet if (logdet is not None) else None + return z, logdet + + +class ActNorm2d(nn.Module): + """ Initializ at the first minibatch with zero mean and unit variance, + After initialization, the bias and logs are treated as a regular trainable parameters that are dependent of data. + """ + def __init__(self, num_channels, eps=1e-6): + super(ActNorm2d, self).__init__() + + self.inited = False + self.eps = eps + self.num_channels = num_channels + + # register bias and scale + self.bias = nn.Parameter(torch.zeros((1, num_channels, 1, 1))) + self.logs = nn.Parameter(torch.zeros((1, num_channels, 1, 1))) # log scale, which easy for det(log|s|) + + def init_parameters(self, input): + if not self.training: + raise ValueError("In Eval mode, but ActNorm not inited") + + with torch.no_grad(): + bias = torch.mean(input, dim=[0,2,3], keepdim=True) # (1, C, 1, 1) + logs = torch.log(torch.std(input, dim=[0,2,3], keepdim=True) + self.eps) # (1, C, 1, 1) + self.bias.data.copy_(bias.data) + self.logs.data.copy_(logs.data) + self.inited = True + + def forward(self, input, logdet=None): + B,C,H,W = input.size() + + if not self.inited: + self.init_parameters(input) + + z = (input - self.bias) / torch.exp(self.logs) + dlogdet = - torch.sum(self.logs) * H * W + logdet = logdet + dlogdet if (logdet is not None) else None + + return z, logdet + + def inverse(self, input, logdet=None): + B,C,H,W = input.size() + + z = input * torch.exp(self.logs) + self.bias + dlogdet = torch.sum(self.logs) * H * W + logdet = logdet + dlogdet if (logdet is not None) else None + + return z, logdet \ No newline at end of file diff --git a/src/nn/lbs.py b/src/nn/lbs.py new file mode 100644 index 0000000..df55ab3 --- /dev/null +++ b/src/nn/lbs.py @@ -0,0 +1,378 @@ +# -*- coding: utf-8 -*- + +# Max-Planck-Gesellschaft zur Förderung der Wissenschaften e.V. (MPG) is +# holder of all proprietary rights on this computer program. +# You can only use this computer program if you have closed +# a license agreement with MPG or you get the right to use the computer +# program from someone who is authorized to grant you that right. +# Any use of the computer program without a valid license is prohibited and +# liable to prosecution. +# +# Copyright©2019 Max-Planck-Gesellschaft zur Förderung +# der Wissenschaften e.V. (MPG). acting on behalf of its Max Planck Institute +# for Intelligent Systems. All rights reserved. +# +# Contact: ps-license@tuebingen.mpg.de + +from __future__ import absolute_import +from __future__ import print_function +from __future__ import division + +import numpy as np + +import torch +import torch.nn.functional as F + +def rot_mat_to_euler(rot_mats): + # Calculates rotation matrix to euler angles + # Careful for extreme cases of eular angles like [0.0, pi, 0.0] + + sy = torch.sqrt(rot_mats[:, 0, 0] * rot_mats[:, 0, 0] + + rot_mats[:, 1, 0] * rot_mats[:, 1, 0]) + return torch.atan2(-rot_mats[:, 2, 0], sy) + +def find_dynamic_lmk_idx_and_bcoords(vertices, pose, dynamic_lmk_faces_idx, + dynamic_lmk_b_coords, + neck_kin_chain, dtype=torch.float32): + ''' Compute the faces, barycentric coordinates for the dynamic landmarks + + + To do so, we first compute the rotation of the neck around the y-axis + and then use a pre-computed look-up table to find the faces and the + barycentric coordinates that will be used. + + Special thanks to Soubhik Sanyal (soubhik.sanyal@tuebingen.mpg.de) + for providing the original TensorFlow implementation and for the LUT. + + Parameters + ---------- + vertices: torch.tensor BxVx3, dtype = torch.float32 + The tensor of input vertices + pose: torch.tensor Bx(Jx3), dtype = torch.float32 + The current pose of the body model + dynamic_lmk_faces_idx: torch.tensor L, dtype = torch.long + The look-up table from neck rotation to faces + dynamic_lmk_b_coords: torch.tensor Lx3, dtype = torch.float32 + The look-up table from neck rotation to barycentric coordinates + neck_kin_chain: list + A python list that contains the indices of the joints that form the + kinematic chain of the neck. + dtype: torch.dtype, optional + + Returns + ------- + dyn_lmk_faces_idx: torch.tensor, dtype = torch.long + A tensor of size BxL that contains the indices of the faces that + will be used to compute the current dynamic landmarks. + dyn_lmk_b_coords: torch.tensor, dtype = torch.float32 + A tensor of size BxL that contains the indices of the faces that + will be used to compute the current dynamic landmarks. + ''' + + batch_size = vertices.shape[0] + + aa_pose = torch.index_select(pose.view(batch_size, -1, 3), 1, + neck_kin_chain) + rot_mats = batch_rodrigues( + aa_pose.view(-1, 3), dtype=dtype).view(batch_size, -1, 3, 3) + + rel_rot_mat = torch.eye(3, device=vertices.device, + dtype=dtype).unsqueeze_(dim=0) + for idx in range(len(neck_kin_chain)): + rel_rot_mat = torch.bmm(rot_mats[:, idx], rel_rot_mat) + + y_rot_angle = torch.round( + torch.clamp(-rot_mat_to_euler(rel_rot_mat) * 180.0 / np.pi, + max=39)).to(dtype=torch.long) + neg_mask = y_rot_angle.lt(0).to(dtype=torch.long) + mask = y_rot_angle.lt(-39).to(dtype=torch.long) + neg_vals = mask * 78 + (1 - mask) * (39 - y_rot_angle) + y_rot_angle = (neg_mask * neg_vals + + (1 - neg_mask) * y_rot_angle) + + dyn_lmk_faces_idx = torch.index_select(dynamic_lmk_faces_idx, + 0, y_rot_angle) + dyn_lmk_b_coords = torch.index_select(dynamic_lmk_b_coords, + 0, y_rot_angle) + + return dyn_lmk_faces_idx, dyn_lmk_b_coords + + +def vertices2landmarks(vertices, faces, lmk_faces_idx, lmk_bary_coords): + ''' Calculates landmarks by barycentric interpolation + + Parameters + ---------- + vertices: torch.tensor BxVx3, dtype = torch.float32 + The tensor of input vertices + faces: torch.tensor Fx3, dtype = torch.long + The faces of the mesh + lmk_faces_idx: torch.tensor L, dtype = torch.long + The tensor with the indices of the faces used to calculate the + landmarks. + lmk_bary_coords: torch.tensor Lx3, dtype = torch.float32 + The tensor of barycentric coordinates that are used to interpolate + the landmarks + + Returns + ------- + landmarks: torch.tensor BxLx3, dtype = torch.float32 + The coordinates of the landmarks for each mesh in the batch + ''' + # Extract the indices of the vertices for each face + # BxLx3 + batch_size, num_verts = vertices.shape[:2] + device = vertices.device + + lmk_faces = torch.index_select(faces, 0, lmk_faces_idx.view(-1)).view( + batch_size, -1, 3) + + lmk_faces += torch.arange( + batch_size, dtype=torch.long, device=device).view(-1, 1, 1) * num_verts + + lmk_vertices = vertices.view(-1, 3)[lmk_faces].view( + batch_size, -1, 3, 3) + + landmarks = torch.einsum('blfi,blf->bli', [lmk_vertices, lmk_bary_coords]) + return landmarks + + +def lbs(betas, pose, v_template, shapedirs, posedirs, J_regressor, parents, + lbs_weights, pose2rot=True, dtype=torch.float32): + ''' Performs Linear Blend Skinning with the given shape and pose parameters + + Parameters + ---------- + betas : torch.tensor BxNB + The tensor of shape parameters + pose : torch.tensor Bx(J + 1) * 3 + The pose parameters in axis-angle format + v_template torch.tensor BxVx3 + The template mesh that will be deformed + shapedirs : torch.tensor 1xNB + The tensor of PCA shape displacements + posedirs : torch.tensor Px(V * 3) + The pose PCA coefficients + J_regressor : torch.tensor JxV + The regressor array that is used to calculate the joints from + the position of the vertices + parents: torch.tensor J + The array that describes the kinematic tree for the model + lbs_weights: torch.tensor N x V x (J + 1) + The linear blend skinning weights that represent how much the + rotation matrix of each part affects each vertex + pose2rot: bool, optional + Flag on whether to convert the input pose tensor to rotation + matrices. The default value is True. If False, then the pose tensor + should already contain rotation matrices and have a size of + Bx(J + 1)x9 + dtype: torch.dtype, optional + + Returns + ------- + verts: torch.tensor BxVx3 + The vertices of the mesh after applying the shape and pose + displacements. + joints: torch.tensor BxJx3 + The joints of the model + ''' + + batch_size = max(betas.shape[0], pose.shape[0]) + device = betas.device + + # Add shape contribution + v_shaped = v_template + blend_shapes(betas, shapedirs) + + # Get the joints + # NxJx3 array + J = vertices2joints(J_regressor, v_shaped) + + # 3. Add pose blend shapes + # N x J x 3 x 3 + ident = torch.eye(3, dtype=dtype, device=device) + if pose2rot: + rot_mats = batch_rodrigues( + pose.view(-1, 3), dtype=dtype).view([batch_size, -1, 3, 3]) + + pose_feature = (rot_mats[:, 1:, :, :] - ident).view([batch_size, -1]) + # (N x P) x (P, V * 3) -> N x V x 3 + pose_offsets = torch.matmul(pose_feature, posedirs) \ + .view(batch_size, -1, 3) + else: + pose_feature = pose[:, 1:].view(batch_size, -1, 3, 3) - ident + rot_mats = pose.view(batch_size, -1, 3, 3) + + pose_offsets = torch.matmul(pose_feature.view(batch_size, -1), + posedirs).view(batch_size, -1, 3) + + v_posed = pose_offsets + v_shaped + # 4. Get the global joint location + J_transformed, A = batch_rigid_transform(rot_mats, J, parents, dtype=dtype) + + # 5. Do skinning: + # W is N x V x (J + 1) + W = lbs_weights.unsqueeze(dim=0).expand([batch_size, -1, -1]) + # (N x V x (J + 1)) x (N x (J + 1) x 16) + num_joints = J_regressor.shape[0] + T = torch.matmul(W, A.view(batch_size, num_joints, 16)) \ + .view(batch_size, -1, 4, 4) + + homogen_coord = torch.ones([batch_size, v_posed.shape[1], 1], + dtype=dtype, device=device) + v_posed_homo = torch.cat([v_posed, homogen_coord], dim=2) + v_homo = torch.matmul(T, torch.unsqueeze(v_posed_homo, dim=-1)) + + verts = v_homo[:, :, :3, 0] + + return verts, J_transformed + + +def vertices2joints(J_regressor, vertices): + ''' Calculates the 3D joint locations from the vertices + + Parameters + ---------- + J_regressor : torch.tensor JxV + The regressor array that is used to calculate the joints from the + position of the vertices + vertices : torch.tensor BxVx3 + The tensor of mesh vertices + + Returns + ------- + torch.tensor BxJx3 + The location of the joints + ''' + + return torch.einsum('bik,ji->bjk', [vertices, J_regressor]) + + +def blend_shapes(betas, shape_disps): + ''' Calculates the per vertex displacement due to the blend shapes + + + Parameters + ---------- + betas : torch.tensor Bx(num_betas) + Blend shape coefficients + shape_disps: torch.tensor Vx3x(num_betas) + Blend shapes + + Returns + ------- + torch.tensor BxVx3 + The per-vertex displacement due to shape deformation + ''' + + # Displacement[b, m, k] = sum_{l} betas[b, l] * shape_disps[m, k, l] + # i.e. Multiply each shape displacement by its corresponding beta and + # then sum them. + blend_shape = torch.einsum('bl,mkl->bmk', [betas, shape_disps]) + return blend_shape + + +def batch_rodrigues(rot_vecs, epsilon=1e-8, dtype=torch.float32): + ''' Calculates the rotation matrices for a batch of rotation vectors + Parameters + ---------- + rot_vecs: torch.tensor Nx3 + array of N axis-angle vectors + Returns + ------- + R: torch.tensor Nx3x3 + The rotation matrices for the given axis-angle parameters + ''' + + batch_size = rot_vecs.shape[0] + device = rot_vecs.device + + angle = torch.norm(rot_vecs + 1e-8, dim=1, keepdim=True) + rot_dir = rot_vecs / angle + + cos = torch.unsqueeze(torch.cos(angle), dim=1) + sin = torch.unsqueeze(torch.sin(angle), dim=1) + + # Bx1 arrays + rx, ry, rz = torch.split(rot_dir, 1, dim=1) + K = torch.zeros((batch_size, 3, 3), dtype=dtype, device=device) + + zeros = torch.zeros((batch_size, 1), dtype=dtype, device=device) + K = torch.cat([zeros, -rz, ry, rz, zeros, -rx, -ry, rx, zeros], dim=1) \ + .view((batch_size, 3, 3)) + + ident = torch.eye(3, dtype=dtype, device=device).unsqueeze(dim=0) + rot_mat = ident + sin * K + (1 - cos) * torch.bmm(K, K) + return rot_mat + + +def transform_mat(R, t): + ''' Creates a batch of transformation matrices + Args: + - R: Bx3x3 array of a batch of rotation matrices + - t: Bx3x1 array of a batch of translation vectors + Returns: + - T: Bx4x4 Transformation matrix + ''' + # No padding left or right, only add an extra row + return torch.cat([F.pad(R, [0, 0, 0, 1]), + F.pad(t, [0, 0, 0, 1], value=1)], dim=2) + + +def batch_rigid_transform(rot_mats, joints, parents, dtype=torch.float32): + """ + Applies a batch of rigid transformations to the joints + + Parameters + ---------- + rot_mats : torch.tensor BxNx3x3 + Tensor of rotation matrices + joints : torch.tensor BxNx3 + Locations of joints + parents : torch.tensor BxN + The kinematic tree of each object + dtype : torch.dtype, optional: + The data type of the created tensors, the default is torch.float32 + + Returns + ------- + posed_joints : torch.tensor BxNx3 + The locations of the joints after applying the pose rotations + rel_transforms : torch.tensor BxNx4x4 + The relative (with respect to the root joint) rigid transformations + for all the joints + """ + + joints = torch.unsqueeze(joints, dim=-1) + + rel_joints = joints.clone() + rel_joints[:, 1:] -= joints[:, parents[1:]] + + # transforms_mat = transform_mat( + # rot_mats.view(-1, 3, 3), + # rel_joints.view(-1, 3, 1)).view(-1, joints.shape[1], 4, 4) + transforms_mat = transform_mat( + rot_mats.view(-1, 3, 3), + rel_joints.reshape(-1, 3, 1)).reshape(-1, joints.shape[1], 4, 4) + + transform_chain = [transforms_mat[:, 0]] + for i in range(1, parents.shape[0]): + # Subtract the joint location at the rest pose + # No need for rotation, since it's identity when at rest + curr_res = torch.matmul(transform_chain[parents[i]], + transforms_mat[:, i]) + transform_chain.append(curr_res) + + transforms = torch.stack(transform_chain, dim=1) + + # The last column of the transformations contains the posed joints + posed_joints = transforms[:, :, :3, 3] + + # The last column of the transformations contains the posed joints + posed_joints = transforms[:, :, :3, 3] + + joints_homogen = F.pad(joints, [0, 0, 0, 1]) + + rel_transforms = transforms - F.pad( + torch.matmul(transforms, joints_homogen), [3, 0, 0, 0, 0, 0, 0, 0]) + + return posed_joints, rel_transforms \ No newline at end of file diff --git a/src/nn/resnet.py b/src/nn/resnet.py new file mode 100644 index 0000000..77973dd --- /dev/null +++ b/src/nn/resnet.py @@ -0,0 +1,187 @@ +'''ResNet in PyTorch. +For Pre-activation ResNet, see 'preact_resnet.py'. +Reference: +[1] Kaiming He, Xiangyu Zhang, Shaoqing Ren, Jian Sun + Deep Residual Learning for Image Recognition. arXiv:1512.03385 +''' + +import torch +import torch.nn as nn +import torch.nn.functional as F + +def debug(opt=None, msg="", verbose=False): + if opt is None: + if verbose: print(msg) + + elif opt.DEBUG or verbose: + print(msg) + + + +class BasicBlock(nn.Module): + expansion = 1 + def __init__(self, in_planes, planes, stride=1): + super(BasicBlock, self).__init__() + self.conv1 = nn.Conv2d(in_planes, planes, kernel_size=(3,1), stride=(stride,1), padding=(1,0), bias=False) + self.bn1 = nn.BatchNorm2d(planes) + + self.conv2 = nn.Conv2d(planes, planes, kernel_size=(3,1), stride=(1,1), padding=(1,0), bias=False) + self.bn2 = nn.BatchNorm2d(planes) + + self.shortcut = nn.Sequential() + if stride != 1 or in_planes != self.expansion*planes: + self.shortcut = nn.Sequential( + nn.Conv2d(in_planes, self.expansion*planes, kernel_size=(1,1), stride=(stride,1), bias=False), + nn.BatchNorm2d(self.expansion*planes) + ) + + def forward(self, x): + out = F.relu(self.bn1(self.conv1(x))) + out = self.bn2(self.conv2(out)) + out += self.shortcut(x) + out = F.relu(out) + return out + +class Bottleneck(nn.Module): + expansion = 4 + + def __init__(self, in_planes, planes, stride=1): + super(Bottleneck, self).__init__() + self.conv1 = nn.Conv2d(in_planes, planes, kernel_size=(1,1), bias=False) + self.bn1 = nn.BatchNorm2d(planes) + + self.conv2 = nn.Conv2d(planes, planes, kernel_size=(3,1), stride=(stride,1), padding=(1,0), bias=False) + self.bn2 = nn.BatchNorm2d(planes) + + self.conv3 = nn.Conv2d(planes, self.expansion * planes, kernel_size=(1,1), bias=False) + self.bn3 = nn.BatchNorm2d(self.expansion*planes) + + self.shortcut = nn.Sequential() + if stride != 1 or in_planes != self.expansion*planes: + self.shortcut = nn.Sequential( + nn.Conv2d(in_planes, self.expansion*planes, kernel_size=(1,1), stride=(stride,1), bias=False), + nn.BatchNorm2d(self.expansion*planes) + ) + + def forward(self, x): + out = F.relu(self.bn1(self.conv1(x))) + out = F.relu(self.bn2(self.conv2(out))) + out = self.bn3(self.conv3(out)) + out += self.shortcut(x) + out = F.relu(out) + return out + + +class ResNet(nn.Module): + def __init__(self, block, num_blocks, num_input=3, num_classes=10): + super(ResNet, self).__init__() + self.in_planes = 64 + + self.conv1 = nn.Conv2d(num_input, 64, kernel_size=(3,1), stride=(1,1), padding=(1,0), bias=False) + self.bn1 = nn.BatchNorm2d(64) + self.avgpool = nn.AvgPool2d(kernel_size=(2,1)) + + self.layer1 = self._make_layer(block, 64, num_blocks[0], stride=1) + self.layer2 = self._make_layer(block, 128, num_blocks[1], stride=2) + self.layer3 = self._make_layer(block, 256, num_blocks[2], stride=2) + self.layer4 = self._make_layer(block, 512, num_blocks[3], stride=2) + self.linear = nn.Linear(512*block.expansion, num_classes) + + def _make_layer(self, block, planes, num_blocks, stride): + strides = [stride] + [1]*(num_blocks-1) + layers = [] + for stride in strides: + layers.append(block(self.in_planes, planes, stride)) + self.in_planes = planes * block.expansion + return nn.Sequential(*layers) + + def get_features(self, x): + out = F.relu(self.bn1(self.conv1(x))) + # debug(msg=f"[forward] conv1 shape = {out.shape}", verbose=True) + + out = self.layer1(out) + # debug(msg=f"[forward] layer1 shape = {out.shape}", verbose=True) + + out = self.layer2(out) + # debug(msg=f"[forward] layer2 shape = {out.shape}", verbose=True) + + out = self.layer3(out) + # debug(msg=f"[forward] layer3 shape = {out.shape}", verbose=True) + + out = self.layer4(out) + # debug(msg=f"[forward] layer4 shape = {out.shape}", verbose=True) + + # out = F.avg_pool2d(out, 2) + out = self.avgpool(out) + # debug(msg=f"[forward] avg shape = {out.shape}", verbose=True) + + out = out.view(out.size(0), -1) + # debug(msg=f"[forward] view shape = {out.shape}", verbose=True) + + return out + + + def forward(self, x): + # debug(msg=f"[forward] input x shape = {x.shape}", verbose=True) + + out = F.relu(self.bn1(self.conv1(x))) + # debug(msg=f"[forward] conv1 shape = {out.shape}", verbose=True) + + out = self.layer1(out) + # debug(msg=f"[forward] layer1 shape = {out.shape}", verbose=True) + + out = self.layer2(out) + # debug(msg=f"[forward] layer2 shape = {out.shape}", verbose=True) + + out = self.layer3(out) + # debug(msg=f"[forward] layer3 shape = {out.shape}", verbose=True) + + out = self.layer4(out) + # debug(msg=f"[forward] layer4 shape = {out.shape}", verbose=True) + + # out = F.avg_pool2d(out, 2) + out = self.avgpool(out) + # debug(msg=f"[forward] avg shape = {out.shape}", verbose=True) + + out = out.view(out.size(0), -1) + # debug(msg=f"[forward] view shape = {out.shape}", verbose=True) + + out = self.linear(out) + # debug(msg=f"[forward] output shape = {out.shape}", verbose=True) + + return out + + +def ResNet18(num_input=3, num_classes=10): + return ResNet(BasicBlock, [2, 2, 2, 2], num_input=num_input, num_classes=num_classes) + + +def ResNet34(num_input=3, num_classes=10): + return ResNet(BasicBlock, [3, 4, 6, 3], num_input=num_input, num_classes=num_classes) + + +def ResNet50(num_input=3, num_classes=10): + return ResNet(Bottleneck, [3, 4, 6, 3], num_input=num_input, num_classes=num_classes) + + +def ResNet101(num_input=3, num_classes=10): + return ResNet(Bottleneck, [3, 4, 23, 3], num_input=num_input, num_classes=num_classes) + + +# def ResNet101(): +# return ResNet(Bottleneck, [3, 4, 23, 3]) + +def ResNet152(): + return ResNet(Bottleneck, [3, 8, 36, 3]) + + +def test(): + net = ResNet50(num_input=1024, num_classes=256) + # y = net(torch.randn(1, 3, 32, 32)) + + # y = net(torch.randn(1, 1024, 16, 1)) + y = net.get_features(torch.randn(1, 1024, 16, 1)) + + print(y.size()) + +# test() \ No newline at end of file