diff --git a/experiments/audio2mesh/train_audio2mesh_CN_20220527.yaml b/experiments/audio2mesh/train_audio2mesh_CN_20220527.yaml new file mode 100644 index 0000000..8b6fb36 --- /dev/null +++ b/experiments/audio2mesh/train_audio2mesh_CN_20220527.yaml @@ -0,0 +1,86 @@ +GPUS: '1' +WORKERS: 4 +OUTPUT_DIR: 'experiments/audio2mesh' + +DEBUG: False +verbose: False + +FREQ: + epoch_save: 5 + epoch_valid: 1 + batch_print: 20 + epoch_test: 5 + +MODEL: + name: 'audio2mesh' + name_netG: "audio2mesh" + + dim_motion: 53 # 68*2 + dim_speech: 1024 + num_vertices: 5023 + + pretrain: False + path_checkpoint: "experiments/audio2mesh/train_audio2mesh_CN_20220520/20220525-07H18M45S" + load_epoch: 45 + + +DATASET: + fps: 50 + sr: 16000 + name_train: "motion_live" + name_valid: "motion_eval" + flip: False + shifting_speed: True + + root: './data/Actor7/Actor7-raw-processing-2h' + path_mean_dict: './data/Actor7/mean_deca_coeff_Actor7_processing.npy' + + + filter: 'savgol' + speech_extractor: 'wav2vec' + + nwind_second_train: 3 + nwind_second_valid: 3 + nwind_second_test: 15 + +TEST: + batch_size: 2 + + +TRAIN: + lr: 0.0001 + batch_size: 128 + shuffle: True + + apply_testing: True + apply_validation: True + apply_lr_scheduler: True + apply_update_parameters: True + + optimizer: 'Adam' + momentum: 0.9 + beta1: 0.5 + beta2: 0.999 + weight_decay: 0.0001 + + nesterov: True + lr_policy: 'plateau' + + # lr_step_gamma: 0.5 + # lr_policy: 'multistep' + # lr_milestones: [10, 30, 50] + + resume: False + reset_lr: True + resume_suffix: "20220524-21H54M38S" + epoch_begin: 0 # 5000 # 2300 # 2600 + epoch_end: 300 + + +LOSS: + names: ["rec_geo", "vel_geo", "rec_ldmk", "closure_x", "closure_y", "all"] + lambda_rec_geo: 1 + lambda_vel_geo: 10 + lambda_rec_ldmk: 1 + lambda_closure_x: 1 + lambda_closure_y: 1 \ No newline at end of file diff --git a/experiments/audio2motion/train_audio2motion_CN_20220527.yaml b/experiments/audio2motion/train_audio2motion_CN_20220527.yaml new file mode 100644 index 0000000..13a0ca6 --- /dev/null +++ b/experiments/audio2motion/train_audio2motion_CN_20220527.yaml @@ -0,0 +1,88 @@ +GPUS: '0' +WORKERS: 8 +OUTPUT_DIR: 'experiments/audio2motion' + +DEBUG: False +verbose: False + +FREQ: + epoch_save: 5 + epoch_valid: 1 + batch_print: 20 + epoch_test: 5 + +MODEL: + name: 'audio2motion' + name_netG: "audio2motion_voca33" + + dim_motion: 53 # 68*2 + dim_speech: 1024 + num_vertices: 5023 + + pretrain: False + path_checkpoint: "experiments/audio2mesh/train_audio2mesh_CN_20220520/20220525-07H18M45S" + load_epoch: 45 + + +DATASET: + fps: 50 + sr: 16000 + name_train: "motion_live" + name_valid: "motion_eval" + flip: False + shifting_speed: True + + root: './data/Actor7/Actor7-raw-processing-2h' + path_mean_dict: './data/Actor7/mean_deca_coeff_Actor7_processing.npy' + + + filter: 'savgol' + speech_extractor: 'wav2vec' + + nwind_second_train: 3 + nwind_second_valid: 3 + nwind_second_test: 15 + +TEST: + batch_size: 2 + + +TRAIN: + lr: 0.0001 + batch_size: 128 + shuffle: True + + apply_testing: True + apply_validation: True + apply_lr_scheduler: True + apply_update_parameters: True + + optimizer: 'Adam' + momentum: 0.9 + beta1: 0.5 + beta2: 0.999 + weight_decay: 0.0001 + + nesterov: True + lr_policy: 'plateau' + + # lr_step_gamma: 0.5 + # lr_policy: 'multistep' + # lr_milestones: [10, 30, 50] + + resume: False + reset_lr: True + resume_suffix: "20220524-21H54M38S" + epoch_begin: 0 # 5000 # 2300 # 2600 + epoch_end: 300 + + +LOSS: + names: ["rec_exp","rec_pos", "rec_geo", "vel_exp","vel_pos", "vel_geo", "all"] + lambda_rec_exp: 1 + lambda_rec_pos: 1 + lambda_rec_geo: 1 + lambda_vel_exp: 10 + lambda_vel_pos: 10 + lambda_vel_geo: 10 + diff --git a/src/models/model_audio2mesh.py b/src/models/model_audio2mesh.py index e9a2d56..7e6dd7b 100644 --- a/src/models/model_audio2mesh.py +++ b/src/models/model_audio2mesh.py @@ -112,7 +112,6 @@ class Audio2MeshModel(Base): beg={self.batch_interv[0][:4]}, end={self.batch_interv[1][:4]}", verbose=False) # speech data - 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) diff --git a/src/models/model_audio2motion.py b/src/models/model_audio2motion.py index ac2c6fd..212e72c 100644 --- a/src/models/model_audio2motion.py +++ b/src/models/model_audio2motion.py @@ -1,21 +1,27 @@ import sys import numpy as np +import pickle + 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 +from src.utils import util # common -from common.animation import save_animation_with_gt2, save_images_with_audio +from common.animation import write_video, write_video_with_gt from common.debug import debug from common.losses import WingLoss # disentangle model -class Audio2motionModel(Base): +class Audio2MotionModel(Base): def __init__(self, opt, logger): Base.__init__(self, opt, logger) @@ -24,53 +30,120 @@ class Audio2motionModel(Base): 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) + + # define FLAME & render + self.netF = define_FLAME(opt, self.device) + self.netR = define_render(opt, self.device) + self.processor, self.extractor = define_extractor(opt, self.device) + + # path_deca_mean = Path("./data/DECA_obama_mean.npy") + path_deca_mean = self.opt.DATASET.path_mean_dict + self.mean_dict = np.load(path_deca_mean, allow_pickle=True).item() + print(f"load mean deca coeff from > {path_deca_mean}, \nkeys = {self.mean_dict.keys()}") + + # get template + self.temp_verts, self.temp_ldmk2d, self.temp_ldmk3d \ + = self.get_template_vertices() # verts: (1 x 1 x 5023 x 3), ldmk: (1 x 1 x 68 x 3) + + self.temp_verts_specific, self.temp_ldmk2d_specific, self.temp_ldmk3d_specific \ + = self.get_template_vertices(self.mean_dict) # verts: (1 x 1 x 5023 x 3), ldmk: (1 x 1 x 68 x 3) + + # save template mesh + path_deca_mean = Path(path_deca_mean) + path_temp_pkl = path_deca_mean.parent.joinpath(path_deca_mean.stem + "_data_template_mesh.pkl") + if not path_temp_pkl.exists(): # load from cache + self.logger.info(f"Load template mesh from raw 3DMM... (!NOT FOUND {path_temp_pkl}) ") + template_mesh = self.temp_verts_specific.cpu().numpy() # verts: (1 x 1 x 5023 x 3) + # save template data + with open(str(path_temp_pkl), 'wb') as f: + pickle.dump(template_mesh, f) + + + self.loss_func_l1 = nn.L1Loss(reduction="mean") self.loss_func_wing = WingLoss(reduction="mean") - - if self.isTrain: - self.names_loss = opt.LOSS.names + self.names_loss = opt.LOSS.names + # 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.isTrain: # define optimizers self.optimizer_G = get_optimizer(self.netG, opt) self.optimizers.append(self.optimizer_G) + # define scheduler self.scheduler_G = get_scheduler(self.optimizer_G, opt) self.schedulers.append(self.scheduler_G) - if self.opt.TRAIN.apply_testing or not self.isTrain: - # load mean lighting & shape - self.netR = define_netR(device=self.device) - # self.netG.init_reconstruct_model(self.netR) - - path_deca_mean = Path("./data/DECA_obama_mean.npy") - self.mean_dict = np.load(path_deca_mean, allow_pickle=True).item() - print(self.mean_dict.keys()) + @torch.no_grad() def set_input(self, batch_input): - self.data = batch_input["data"].float().to(self.device) # (B, nsteps, dim_data) - self.cond = batch_input["cond"].float().to(self.device) # (B, nsteps, dim_cond) + # motion data + self.data = batch_input["data"].float().to(self.device) # (B, nsteps, nc_motion) - self.B = self.data.size(0) - debug(self.opt, f"data = {self.data.shape}, cond = {self.cond.shape}, dtype={self.data.dtype}", verbose=False) + 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) - def training(self, batch_input): + # 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) + + # padding half frame length for bed and end + npad = int(0.5 * self.opt.DATASET.sr * ( 1 / self.opt.DATASET.fps) + 0.5) + pad_speech = np.pad(raw_speech, pad_width=((0,0), (npad, npad)), mode="edge") + debug(self.opt, f"after padding pad_speech = {pad_speech.shape}, dtype={pad_speech.dtype}", verbose=False) + + inputs = self.processor(list(pad_speech), sampling_rate=16000, return_tensors="pt") + cond = self.extractor(**inputs.to(self.device)).last_hidden_state # B x nsteps x nc_feat + debug(self.opt, f"cond = {cond.shape}, dtype={cond.dtype}, device={cond.device}", verbose=False) + + # unfold speech data + cond = cond.unfold(dimension=1, size=16, step=1) # (B, nseqs, nc_codit, 16) + cond = cond.permute(0, 1, 3, 2) # (B, nseqs, 16, nc_condit) + + # setup + self.cond = cond # (B, N, 16, nc_condit=1024) + self.B, self.nsteps, self.nwind, self.dim_speech = cond.size() + + self.data = self.data[:, 7:7+self.nsteps, :] # (B, N, 53) + self.vert, self.ldmk2d, self.ldmk3d = self.get_vertices(self.data) # (B, N, 5023, 3) + + # cut audio clips + idx_beg = int(7 * self.opt.DATASET.sr / self.opt.DATASET.fps + 0.5) + idx_end = int((7 + self.nsteps) * self.opt.DATASET.sr / self.opt.DATASET.fps + 0.5) + self.raw_speech = raw_speech[:, idx_beg: idx_end] # (B, nsteps * sr / fps) + + debug(self.opt, f"[set_input] data = {self.data.shape}, dtype={self.data.dtype}, device={self.data.device}", verbose=False) + debug(self.opt, f"[set_input] vert = {self.vert.shape}, dtype={self.vert.dtype}, device={self.vert.device}", verbose=False) + debug(self.opt, f"[set_input] cond = {self.cond.shape}, dtype={self.cond.dtype}, device={self.cond.device}", verbose=False) + debug(self.opt, f"[set_input] ldmk2d = {self.ldmk2d.shape}, dtype={self.ldmk2d.dtype}, device={self.ldmk2d.device}", verbose=False) + debug(self.opt, f"[set_input] ldmk3d = {self.ldmk3d.shape}, dtype={self.ldmk3d.dtype}, device={self.ldmk3d.device}", verbose=False) + + + def training(self, batch_input, idx_epoch=0, idx_batch=0): self.train() # set train model self.set_input(batch_input) # forward - self.pred = self.netG(self.cond) + pred = self.netG(self.cond) # (B, N, 53) # loss - loss, self.loss_dict = self.eval_losses(self.pred, self.data) + loss, loss_dict = self.eval_losses(pred, self.data) # backward self.optimizer_G.zero_grad() @@ -82,7 +155,8 @@ class Audio2motionModel(Base): self.optimizer_G.step() - return loss + return loss_dict + def validation(self, batch_input): @@ -90,10 +164,12 @@ class Audio2motionModel(Base): 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) + pred = self.netG(self.cond) + + loss, loss_dict = self.eval_losses(pred, self.data) - return loss + return loss_dict + def infer(self, batch_cond, path_audio, suffix=""): self.eval() @@ -107,22 +183,76 @@ class Audio2motionModel(Base): 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): + + def testing(self, batch_input, idx_epoch=0, idx_batch=0): self.eval() # set eval model self.set_input(batch_input) with torch.no_grad(): - 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 + batch_pdt = self.netG(self.cond) # B x N x dim_motion - print(f"testing pt shape = {samples_pt.shape}, gt shape = {samples_gt.shape}") + batch_pdt_geo, *_ = self.get_vertices(batch_pdt) # B x N x 5023 x 3 + print(f"testing batch_pdt shape = {batch_pdt.shape}, batch_pdt_geo = {batch_pdt_geo.shape}") - self.save_reconstruct_with_gt(samples_pt, samples_gt, + + self.save_reconstruct_with_gt(batch_pdt_geo, self.vert, self.raw_speech, path_save=Path(self.opt.OUTPUT_DIR), - suffix=f'sampled_{cur_epoch:05d}_{cur_batch:03d}') + suffix=f'sampled_{idx_epoch:05d}_{idx_batch:03d}') + def get_template_vertices(self, mean_dict=None): + + batch_exp = torch.zeros(1, 50).to(self.device) + batch_pose = 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) + + with torch.no_grad(): + # verts = 1 x 5023 x 3, ldmk2d=1 x 68 x 3, ldmk3d=1 x 68 x 3 + verts, ldmk2d, ldmk3d = self.netF(batch_shape, batch_exp, batch_pose) + verts = verts.reshape(1, 1, -1, 3) # 1 x 1 x 5023 x 3 + ldmk2d = ldmk2d.reshape(1, 1, -1, 3) # 1 x 1 x 68 x 3 + ldmk3d = ldmk3d.reshape(1, 1, -1, 3) # 1 x 1 x 68 x 3 + + print(f"template verts reshape = {verts.shape}") + + + return verts, ldmk2d, ldmk3d + + + def get_vertices(self, batch_motion): + """ + batch_motion, (nbatch, seqlen, 53) + """ + batch_exp = batch_motion[..., :50] + batch_pos_mouth = batch_motion[..., 50:] + nbatch, seqlen = batch_exp.size(0), batch_exp.size(1) + + batch_exp = batch_exp.reshape(nbatch * seqlen, -1) # nbatch * seqlen x 50 + batch_pos_mouth = batch_pos_mouth.reshape(nbatch * seqlen, -1) # nbatch * seqlen x 3 + + batch_shape= torch.zeros(nbatch * seqlen, 100).to(self.device) # nbatch * seqlen x 50 + batch_pose = torch.zeros(nbatch * seqlen, 6).to(self.device) # nbatch * seqlen x 6 + batch_pose[:, 3:6] = batch_pos_mouth + + with torch.no_grad(): + verts, ldmk2d, ldmk3d = self.netF(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 + ldmk2d = ldmk2d.reshape(nbatch, seqlen, -1, 3) # nbatch x seqlen x 5023 x 3 + ldmk3d = ldmk3d.reshape(nbatch, seqlen, -1, 3) # nbatch x seqlen x 5023 x 3 + + return verts, ldmk2d, ldmk3d + + def eval_losses(self, batch_pdt, batch_tgt): """ Computes the VAE loss function. pramas: @@ -131,131 +261,188 @@ class Audio2motionModel(Base): """ 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) # B x nseq x num_vertices x 3 + batch_tgt_geo, *_ = self.get_vertices(batch_tgt) # B x nseq x num_vertices x 3 # rec loss - loss_rec = self.loss_func_wing(batch_pdt, batch_tgt) - loss = loss_rec * self.opt.LOSS.lambda_rec - loss_dict["loss_rec"] = loss_rec.detach() - loss_dict["loss_rec_l1"] = self.loss_func_l1(batch_pdt, batch_tgt).detach() + loss = 0 + loss_rec_exp = self.loss_func_wing(batch_pdt_exp, batch_tgt_exp).mean() + loss_dict["rec_exp"] = loss_rec_exp.detach() + loss_rec_pos = self.loss_func_wing(batch_pdt_pos, batch_tgt_pos).mean() + loss_dict["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 = batch_pdt[:, 1:, :] - batch_pdt[:, :-1, :] - diff_tgt = batch_tgt[:, 1:, :] - batch_tgt[:, :-1, :] - loss_rec_smooth = self.loss_func_wing(diff_pdt, diff_tgt) - loss += loss_rec_smooth * self.opt.LOSS.lambda_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_vel_exp = self.loss_func_wing(diff_pdt_exp, diff_tgt_exp).mean() + loss_dict["vel_exp"] = loss_vel_exp.detach() - loss_dict["loss_rec_smooth"] = loss_rec_smooth.detach() - loss_dict["loss_rec_smooth_l1"] = self.loss_func_l1(diff_pdt, diff_tgt).detach() + + diff_pdt_pos = batch_pdt_pos[:, 1:, :] - batch_pdt_pos[:, :-1, :] + diff_tgt_pos = batch_tgt_pos[:, 1:, :] - batch_tgt_pos[:, :-1, :] + loss_vel_pos = self.loss_func_wing(diff_pdt_pos, diff_tgt_pos).mean() + loss_dict["vel_pos"] = loss_vel_pos.detach() + + loss += loss_vel_exp * self.opt.LOSS.lambda_vel_exp + loss += loss_vel_pos * self.opt.LOSS.lambda_vel_pos + + # geo rec + loss_rec_geo = self.loss_func_wing(batch_pdt_geo, batch_tgt_geo).mean() + loss_dict["rec_geo"] = loss_rec_geo.detach() + + loss_rec_geo2 = self.loss_func_wing(batch_pdt_geo, batch_tgt_geo, weight=self.vertices_weight) + loss += loss_rec_geo2 * 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_vel_geo = self.loss_func_wing(diff_pdt_geo, diff_tgt_geo).mean() + loss_dict["vel_geo"] = loss_vel_geo.detach() + + loss_vel_geo2 = self.loss_func_wing(diff_pdt_geo, diff_tgt_geo, weight=self.vertices_weight).mean() + loss += loss_vel_geo2 * self.opt.LOSS.lambda_vel_geo # total loss - loss_dict['loss_all'] = loss.detach() + loss_dict['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] + def save_reconstruct(self, batch_pdt_geo, batch_speech, path_save, suffix="", vis_landmarks=False): + # batch_pdt_pos, [B x N x dim_motion] + # batch_speech, [B x N*sr/fps ] - B, N, _ = samples_pt.shape + B, N, *_ = batch_pdt_geo.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") + for i in range(B): + igeo_pt = batch_pdt_geo[i, ...] 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] + # split + kgeo_pt = igeo_pt[k:k+nbatch_render, ...] # [nbatch_real x 5023 x 3] + nbatch_real = kgeo_pt.size(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}") + # 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.render_geometry(kgeo_pt, cam, self.device) # (nbatch_real, 3, 512, 512) + # print(f"render_pt ={render_pt.shape}, render_gt={render_gt.shape}") + + if vis_landmarks: + kldmk3d_pt = self.netF.seletec_3d68(kgeo_pt) # [nbatch_real x 68 x 3] + kldmk3d_pt = util.batch_orth_proj(kldmk3d_pt, cam); + kldmk3d_pt[:,:,1:] = -kldmk3d_pt[:,:,1:]; + render_pt = util.tensor_vis_landmarks(render_pt, kldmk3d_pt, isScale=True, color = (255, 0, 0)) + else: + render_pt = render_pt.cpu() + + # append each frame 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) + # write video + ipath_save = path_save.joinpath(f"{suffix}_{i:02d}_pt.mp4") + write_video(v_render_pt, batch_speech[i], ipath_save, fps=50) + self.logger.info(f"save video to -> {str(ipath_save)}") + @torch.no_grad() + def render_geometry(self, verts, cam=None, device=None): + """ + verts: [N x 5023 x 3] + """ + batch_size = verts.size(0) - 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 + if cam is None: + cam = torch.zeros(batch_size, 3).to(device) # (batch_size, 3) + + # orth_proj + verts_proj = util.batch_orth_proj(verts, cam); + verts_proj[:,:,1:] = -verts_proj[:,:,1:] + + # render + images = self.netR.render_shape(verts, verts_proj) # (batch_size, 3, 512, 512) + + return images + + + @torch.no_grad() + def save_reconstruct_with_gt(self, batch_pdt_geo, batch_tgt_geo, batch_speech, path_save, suffix="", vis_landmarks=True): + # batch_pdt_geo, [B x N x 5023 x 3] + # batch_tgt_geo, [B x N x 5023 x 3] + # batch_speech, [B x N*sr/fps ] + + B, N, *_ = batch_pdt_geo.shape nbatch_render = 10 # 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") + for i in range(B): + igeo_pt = batch_pdt_geo[i, ...] # [N x 5023 x 3] + igeo_gt = batch_tgt_geo[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): - 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] + # 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] - # 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] + nbatch_real = kgeo_pt.size(0) - # 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}") - + # cam + cam = torch.tensor([5, 0, 0], device=self.device).repeat(nbatch_real, 1) # (nbatch_real, 3) + # print(f"cam shape = {cam.shape}") + + # render + render_pt = self.render_geometry(kgeo_pt, cam, self.device) # (nbatch_real, 3, 512, 512) + render_gt = self.render_geometry(kgeo_gt, cam, self.device) # (nbatch_real, 3, 512, 512) + # print(f"render_pt ={render_pt.shape}, render_gt={render_gt.shape}") + + if vis_landmarks: + # landmarks 3d + kldmk3d_pt = self.netF.seletec_3d68(kgeo_pt) # [nbatch_real x 68 x 3] + kldmk3d_gt = self.netF.seletec_3d68(kgeo_gt) # [nbatch_real x 68 x 3] + + kldmk3d_pt = util.batch_orth_proj(kldmk3d_pt, cam); + kldmk3d_pt[:,:,1:] = -kldmk3d_pt[:,:,1:]; + + kldmk3d_gt = util.batch_orth_proj(kldmk3d_gt, cam); + kldmk3d_gt[:,:,1:] = -kldmk3d_gt[:,:,1:]; + + render_pt = util.tensor_vis_landmarks(render_pt, kldmk3d_pt, gt_landmarks=kldmk3d_gt, isScale=True, color = (255, 0, 0), color_gt=(0, 255, 0)) + render_gt = util.tensor_vis_landmarks(render_gt, kldmk3d_gt, isScale=True, color = (0, 255, 0)) + else: + render_pt = render_pt.cpu() + render_gt = render_gt.cpu() + + # append each frame for m in range(nbatch_real): - # cv2.imwrite(str(kpath_image), util.tensor2image(render_image[m, ...])) v_render_pt.append(tensor2image(render_pt[m, ...])) v_render_gt.append(tensor2image(render_gt[m, ...])) # save animation - # print(f"testing v_render_pt = {len(v_render_pt)}, gt shape = {len(v_render_gt)}") - save_animation_with_gt2(v_render_pt, v_render_gt, jpath_save, fps=self.opt.DATASET.fps) - - + write_video_with_gt(v_render_pt, v_render_gt, batch_speech[i], ipath_save, fps=50, sr=16000) ######################################### def tensor2image(tensor): @@ -269,21 +456,17 @@ def tensor2image(tensor): def define_netG(opt): netG = None - if opt.MODEL.name_netG == "audio2motion_conv_lstm": - from src.nn.audio2motion_conv_lstm import Audio2MotionConvLSTM - netG = Audio2MotionConvLSTM(opt) + 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_voca2": - from src.nn.audio2motion_voca2 import Audio2MotionVOCA2 - netG = Audio2MotionVOCA2(opt) - - elif opt.MODEL.name_netG == "audio2motion_conv": - from src.nn.audio2motion_conv import Audio2MotionConv - netG = Audio2MotionConv(opt) + elif opt.MODEL.name_netG == "audio2motion_voca33": + from src.nn.audio2motion_voca33 import Audio2Motion + netG = Audio2Motion(opt) elif opt.MODEL.name_netG == "audio2motion": from src.nn.audio2motion import Audio2Motion @@ -299,23 +482,41 @@ def define_netG(opt): return netG -def define_netR(device): - # import - sys.path.insert(0, "/ssdata1/lsen/CODE/DECA_old") - from decalib.deca import DECA - from decalib.utils import util - from decalib.utils.config import cfg as deca_cfg - # use device - # device = "cuda:2" - # whether to use FLAME texture model to generate uv texture map - deca_cfg.model.use_tex = False - deca_cfg.dataset.image_size = 512 +def define_FLAME(opt, device): + from src.nn.FLAME import FLAME - # reconstruction model - netR = DECA(config = deca_cfg, device=device) + model = FLAME(opt.FLAME).to(device) + + return model + + +def define_render(opt, device): + from src.utils.renderer import SRenderY, set_rasterizer + + set_rasterizer(opt.RENDER.rasterizer_type) + + model = SRenderY(opt.RENDER.image_size, + obj_filename=opt.RENDER.topology_path, + uv_size=opt.RENDER.uv_size, + rasterizer_type=opt.RENDER.rasterizer_type + ).to(device) + + return model + +def define_extractor(opt, device): + from transformers import Wav2Vec2FeatureExtractor, Wav2Vec2Model + print("load Wav2Vec2Model ...") + # MODEL_ID = "jonatasgrosman/wav2vec2-large-xlsr-53-chinese-zh-cn" + # self.processor = Wav2Vec2FeatureExtractor.from_pretrained(MODEL_ID) + # self.extractor = Wav2Vec2Model.from_pretrained(MODEL_ID).to(self.device) + + path_ckpt_wav2vec = "./checkpoints/wav2vec2" + processor = Wav2Vec2FeatureExtractor.from_pretrained(path_ckpt_wav2vec) + extractor = Wav2Vec2Model.from_pretrained(path_ckpt_wav2vec).to(device) + + return processor, extractor - return netR diff --git a/src/models/model_audio2motion_live.py b/src/models/model_audio2motion_live.py deleted file mode 100644 index c9255d0..0000000 --- a/src/models/model_audio2motion_live.py +++ /dev/null @@ -1,372 +0,0 @@ -import sys -import numpy as np - -import torch -import torch.nn as nn -import torch.nn.functional as F -from pathlib import Path - -from src.models import init_net -from src.models.base import Base -from src.optims import get_optimizer, get_scheduler - -# common -from common.animation import save_animation_with_gt2, save_images_with_audio -from common.debug import debug -from common.losses import WingLoss - -# disentangle model -class Audio2motionLiveModel(Base): - - def __init__(self, opt, logger): - Base.__init__(self, opt, logger) - - self.opt = opt - self.logger = logger - self.names_model = ["G"] # G - - - # define networks - self.netG = define_netG(opt) - self.netG.to() - self.netG = torch.nn.DataParallel(self.netG, opt.GPUS) # multi-GPUs - init_net(self.netG, init_type='kaiming', gpu_ids=opt.GPUS) - - self.loss_func_l1 = nn.L1Loss(reduction="mean") - self.loss_func_wing = WingLoss(reduction="mean") - - if self.isTrain: - self.names_loss = opt.LOSS.names - - # define optimizers - self.optimizer_G = get_optimizer(self.netG, opt) - self.optimizers.append(self.optimizer_G) - - self.scheduler_G = get_scheduler(self.optimizer_G, opt) - self.schedulers.append(self.scheduler_G) - - if self.opt.TRAIN.apply_testing or not self.isTrain: - # load mean lighting & shape - self.netR = define_netR(device=self.device) - # self.netG.init_reconstruct_model(self.netR) - - path_deca_mean = Path("./data/DECA_obama_mean.npy") - self.mean_dict = np.load(path_deca_mean, allow_pickle=True).item() - print(self.mean_dict.keys()) - - if self.opt.DATASET.speech_extractor == "wav2vec": - from transformers import Wav2Vec2FeatureExtractor, Wav2Vec2Model - print("load Wav2Vec2Model ...") - MODEL_ID = "jonatasgrosman/wav2vec2-large-xlsr-53-chinese-zh-cn" - self.processor = Wav2Vec2FeatureExtractor.from_pretrained(MODEL_ID) - self.extractor = Wav2Vec2Model.from_pretrained(MODEL_ID).to(self.device) - - - - def set_input(self, batch_input): - - # motion data - self.data = batch_input["data"].float().to(self.device) # (B, nsteps, nc_motion) - self.B, self.nsteps = self.data.size(0), self.data.size(1) - debug(self.opt, f"data = {self.data.shape}, dtype={self.data.dtype}", verbose=False) - - # speech data - raw_speech = batch_input["cond"].numpy() # (B, nsegments) - debug(self.opt, f"raw_speech = {raw_speech.shape}, dtype={raw_speech.dtype}", verbose=False) - - if self.opt.DATASET.speech_extractor == "wav2vec": - # raw_speech = raw_speech.reshape(self.B * self.nsteps, -1) # (B*nsteps, nsegments) - # debug(self.opt, f"raw_speech = {raw_speech.shape}, dtype={raw_speech.dtype}", verbose=False) - - # padding half frame length for bed and end - npad = int(0.5 * self.opt.DATASET.sr * ( 1 / self.opt.DATASET.fps) + 0.5) - raw_speech = np.pad(raw_speech, pad_width=((0,0), (npad, npad)), mode="edge") - debug(self.opt, f"after padding raw_speech = {raw_speech.shape}, dtype={raw_speech.dtype}", verbose=False) - - raw_speech = list(raw_speech) - inputs = self.processor(raw_speech, sampling_rate=16000, return_tensors="pt") - inputs = inputs.to(self.device) - - with torch.no_grad(): - output = self.extractor(**inputs) - self.cond = output.last_hidden_state - # self.cond = output.extract_features - - - debug(self.opt, f"data = {self.data.shape}, dtype={self.data.dtype}, device={self.data.device}", verbose=False) - debug(self.opt, f"cond = {self.cond.shape}, dtype={self.cond.dtype}, device={self.cond.device}", verbose=False) - - - def training(self, batch_input): - self.train() # set train model - self.set_input(batch_input) - - # forward - self.pred = self.netG(self.cond) - - # loss - loss, self.loss_dict = self.eval_losses(self.pred, self.data) - - # backward - self.optimizer_G.zero_grad() - loss.backward() - - if self.opt.TRAIN.grad_clip_norm: # operate grad - torch.nn.utils.clip_grad_value_(self.netG.parameters(), self.opt.TRAIN.max_grad_clip) - torch.nn.utils.clip_grad_norm_(self.netG.parameters(), self.opt.TRAIN.max_grad_norm) - - self.optimizer_G.step() - - return loss - - - def validation(self, batch_input): - self.eval() # set eval model - self.set_input(batch_input) - - with torch.no_grad(): - self.pred = self.netG(self.cond) - loss, self.loss_dict = self.eval_losses(self.pred, self.data) - - return loss - - def infer(self, batch_cond, path_audio, suffix=""): - self.eval() - self.cond = batch_cond.float().to(self.device) # (nsteps, dim_cond) - - with torch.no_grad(): - samples_pt = self.netG(self.cond).cpu().numpy() # B x N x dim_motion - print(f"testing pt shape = {samples_pt.shape}") - - self.save_reconstruct(samples_pt, path_audio, - path_save=Path(self.opt.OUTPUT_DIR), - suffix=suffix) - - - def testing(self, batch_input, cur_epoch=0, cur_batch=0): - self.eval() # set eval model - self.set_input(batch_input) - - with torch.no_grad(): - samples_pt = self.netG(self.cond).cpu().numpy() # B x N x dim_motion - samples_gt = self.data.cpu().numpy() # B x N x dim_motion - - print(f"testing pt shape = {samples_pt.shape}, gt shape = {samples_gt.shape}") - - self.save_reconstruct_with_gt(samples_pt, samples_gt, - path_save=Path(self.opt.OUTPUT_DIR), - suffix=f'sampled_{cur_epoch:05d}_{cur_batch:03d}') - - - def eval_losses(self, batch_pdt, batch_tgt): - """ Computes the VAE loss function. - pramas: - batch_pred, (nbatch, seqlen, dim_motion) - batch_targt, (nbatch, seqlen, dim_motion) - """ - loss = 0 - loss_dict = {} - - - batch_pdt_exp = batch_pdt[..., :50] - batch_pdt_pos = batch_pdt[..., 50:] - - batch_tgt_exp = batch_tgt[..., :50] - batch_tgt_pos = batch_tgt[..., 50:] - - - # rec loss - loss = 0 - - loss_rec_exp = self.loss_func_wing(batch_pdt_exp, batch_tgt_exp) / 50 - loss_dict["loss_rec_exp"] = loss_rec_exp.detach() - - loss_rec_pos = self.loss_func_wing(batch_pdt_pos, batch_tgt_pos) / 3 - loss_dict["loss_rec_pos"] = loss_rec_pos.detach() - - loss += loss_rec_exp * self.opt.LOSS.lambda_rec - loss += loss_rec_pos * self.opt.LOSS.lambda_rec * 10 - - - # rec smooth - diff_pdt_exp = batch_pdt_exp[:, 1:, :] - batch_pdt_exp[:, :-1, :] - diff_tgt_exp = batch_tgt_exp[:, 1:, :] - batch_tgt_exp[:, :-1, :] - loss_vel_exp = self.loss_func_wing(diff_pdt_exp, diff_tgt_exp) / 50 - loss_dict["loss_vel_exp"] = loss_vel_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_vel_pos = self.loss_func_wing(diff_pdt_pos, diff_tgt_pos) / 3 - loss_dict["loss_vel_pos"] = loss_vel_pos.detach() - - loss += loss_vel_exp * self.opt.LOSS.lambda_rec_smooth - loss += loss_vel_pos * self.opt.LOSS.lambda_rec_smooth * 10 - - # total loss - loss_dict['loss_all'] = loss.detach() - - return loss, loss_dict - - - def save_reconstruct(self, samples_pt, path_audio, path_save, suffix=""): - # samples_pt, [B x N x dim_motion] - - B, N, _ = samples_pt.shape - nbatch_render = 10 - - # for each batch - for j in range(B): - jcoeff_pt = samples_pt[j, :, :] - jpath_save = path_save.joinpath(f"{suffix}_{j:02d}.mp4") - - v_render_pt = [] - for k in range(0, N, nbatch_render): - jcodedict_pt = {} - - jcodedict_pt["exp"] = jcoeff_pt[k:k+nbatch_render, :50] # (nbatch_render, 50) - nbatch_real = jcodedict_pt["exp"].shape[0] - - # pose - jcodedict_pt["pose"] = np.repeat([self.mean_dict["pose"]], nbatch_real, axis=0) # (nbatch_render, 6) - jcodedict_pt["pose"][:, 3:6] = jcoeff_pt[k:k+nbatch_render, 50:53] - - # others ==> to mean - mean_cam = [[5,0,0]] # or [self.mean_dict["cam"]] - jcodedict_pt["cam"] = np.repeat(mean_cam, nbatch_real, axis=0) # (nbatch_render, 3) - jcodedict_pt["light"] = np.repeat([self.mean_dict["light"]], nbatch_real, axis=0) # (nbatch_render, 9, 3) - jcodedict_pt["shape"] = np.repeat([self.mean_dict["shape"]], nbatch_real, axis=0) # (nbatch_render, 100) - jcodedict_pt["detail"] = np.repeat([self.mean_dict["detail"]], nbatch_real, axis=0) # (nbatch_render, 128) - - _, visdict_pt = self.netR.decode_one(jcodedict_pt, nbatch_real, self.device) - - render_pt = visdict_pt["shape_images"] # (nbatch_render, 3, 224, 224) - # print(f"render pt shape = {render_pt.shape}") - - for m in range(nbatch_real): - # cv2.imwrite(str(kpath_image), util.tensor2image(render_image[m, ...])) - v_render_pt.append(tensor2image(render_pt[m, ...])) - - # save animation - # print(f"testing v_render_pt = {len(v_render_pt)}") - save_images_with_audio(v_render_pt, path_audio, jpath_save) - - - - def save_reconstruct_with_gt(self, samples_pt, samples_gt, path_save, suffix=""): - # samples_pt, [B x N x dim_motion] - # samples_gt, [B x N x dim_motion] - B, N, _ = samples_pt.shape - nbatch_render = 10 - - # for each batch - for j in range(B): - jcoeff_pt = samples_pt[j, :, :] - jcoeff_gt = samples_gt[j, :, :] - jpath_save = path_save.joinpath(f"{suffix}_{j:02d}.mp4") - - v_render_pt = [] - v_render_gt = [] - - for k in range(0, N, nbatch_render): - jcodedict_pt = {} - jcodedict_gt = {} - - # exp - jcodedict_pt["exp"] = jcoeff_pt[k:k+nbatch_render, :50] # (nbatch_render, 50) - jcodedict_gt["exp"] = jcoeff_gt[k:k+nbatch_render, :50] # (nbatch_render, 50) - nbatch_real = jcodedict_pt["exp"].shape[0] - - # pose - jcodedict_pt["pose"] = np.repeat([self.mean_dict["pose"]], nbatch_real, axis=0) # (nbatch_render, 6) - jcodedict_gt["pose"] = np.repeat([self.mean_dict["pose"]], nbatch_real, axis=0) # (nbatch_render, 6) - jcodedict_pt["pose"][:, 3:6] = jcoeff_pt[k:k+nbatch_render, 50:53] - jcodedict_gt["pose"][:, 3:6] = jcoeff_gt[k:k+nbatch_render, 50:53] - - # others ==> to mean - mean_cam = [[5,0,0]] # or [self.mean_dict["cam"]] - jcodedict_pt["cam"] = np.repeat(mean_cam, nbatch_real, axis=0) # (nbatch_render, 3) - jcodedict_pt["light"] = np.repeat([self.mean_dict["light"]], nbatch_real, axis=0) # (nbatch_render, 9, 3) - jcodedict_pt["shape"] = np.repeat([self.mean_dict["shape"]], nbatch_real, axis=0) # (nbatch_render, 100) - jcodedict_pt["detail"] = np.repeat([self.mean_dict["detail"]], nbatch_real, axis=0) # (nbatch_render, 128) - - jcodedict_gt["cam"] = np.repeat(mean_cam, nbatch_real, axis=0) # (nbatch_render, 3) - jcodedict_gt["light"] = np.repeat([self.mean_dict["light"]], nbatch_real, axis=0) # (nbatch_render, 9, 3) - jcodedict_gt["shape"] = np.repeat([self.mean_dict["shape"]], nbatch_real, axis=0) # (nbatch_render, 100) - jcodedict_gt["detail"] = np.repeat([self.mean_dict["detail"]], nbatch_real, axis=0) # (nbatch_render, 128) - - _, visdict_pt = self.netR.decode_one(jcodedict_pt, nbatch_real, self.device) - _, visdict_gt = self.netR.decode_one(jcodedict_gt, nbatch_real, self.device) - - render_pt = visdict_pt["shape_images"] # (nbatch_render, 3, 224, 224) - render_gt = visdict_gt["shape_images"] # (nbatch_render, 3, 224, 224) - # print(f"render pt shape = {render_pt.shape}, gt {render_gt.shape}") - - for m in range(nbatch_real): - # cv2.imwrite(str(kpath_image), util.tensor2image(render_image[m, ...])) - v_render_pt.append(tensor2image(render_pt[m, ...])) - v_render_gt.append(tensor2image(render_gt[m, ...])) - - # save animation - # print(f"testing v_render_pt = {len(v_render_pt)}, gt shape = {len(v_render_gt)}") - save_animation_with_gt2(v_render_pt, v_render_gt, jpath_save, fps=self.opt.DATASET.fps) - - - -######################################### -def tensor2image(tensor): - image = tensor.detach().cpu().numpy() - image = image*255. - image = np.maximum(np.minimum(image, 255), 0) - image = image.transpose(1,2,0)[:,:,[2,1,0]] - return image.astype(np.uint8).copy() - - -def define_netG(opt): - netG = None - - if opt.MODEL.name_netG == "audio2motion_voca": - from src.nn.audio2motion_voca import Audio2MotionVOCA - netG = Audio2MotionVOCA(opt) - - elif opt.MODEL.name_netG == "audio2motion_voca2": - from src.nn.audio2motion_voca3 import Audio2MotionVOCA3 - netG = Audio2MotionVOCA3(opt) - - elif opt.MODEL.name_netG == "audio2motion_conv": - from src.nn.audio2motion_conv import Audio2MotionConv - netG = Audio2MotionConv(opt) - - elif opt.MODEL.name_netG == "audio2motion": - from src.nn.audio2motion import Audio2Motion - netG = Audio2Motion(opt) - - elif opt.MODEL.name_netG == "audio2motion2": - from src.nn.audio2motion2 import Audio2Motion2 - netG = Audio2Motion2(opt) - else: - raise NameError(f"The model of opt.MODEL.name_netAE(={opt.MODEL.name_netG}) not existing!") - - - return netG - - -def define_netR(device): - # import - sys.path.insert(0, "/ssdata1/lsen/CODE/DECA_old") - from decalib.deca import DECA - from decalib.utils import util - from decalib.utils.config import cfg as deca_cfg - - # use device - # device = "cuda:2" - # whether to use FLAME texture model to generate uv texture map - deca_cfg.model.use_tex = False - deca_cfg.dataset.image_size = 512 - - # reconstruction model - netR = DECA(config = deca_cfg, device=device) - - return netR - - - diff --git a/src/models/model_audio2motion_live2.py b/src/models/model_audio2motion_live2.py deleted file mode 100644 index a73e203..0000000 --- a/src/models/model_audio2motion_live2.py +++ /dev/null @@ -1,414 +0,0 @@ -import sys -import numpy as np - -import torch -import torch.nn as nn -import torch.nn.functional as F -from pathlib import Path - -from src.models import init_net -from src.models.base import Base -from src.optims import get_optimizer, get_scheduler - -# common -from common.animation import save_animation_with_gt2, save_images_with_audio -from common.debug import debug -from common.losses import WingLoss - -# disentangle model -class Audio2motionLive2Model(Base): - - def __init__(self, opt, logger): - Base.__init__(self, opt, logger) - - self.opt = opt - self.logger = logger - self.names_model = ["G"] # G - - - # define networks - self.netG = define_netG(opt) - self.netG.to() - self.netG = torch.nn.DataParallel(self.netG, opt.GPUS) # multi-GPUs - init_net(self.netG, init_type='kaiming', gpu_ids=opt.GPUS) - - self.loss_func_l1 = nn.L1Loss(reduction="mean") - self.loss_func_wing = WingLoss(reduction="mean") - - if self.isTrain: - self.names_loss = opt.LOSS.names - - # define optimizers - self.optimizer_G = get_optimizer(self.netG, opt) - self.optimizers.append(self.optimizer_G) - - self.scheduler_G = get_scheduler(self.optimizer_G, opt) - self.schedulers.append(self.scheduler_G) - - if self.opt.TRAIN.apply_testing or not self.isTrain: - # load mean lighting & shape - self.netR = define_netR(device=self.device) - # self.netG.init_reconstruct_model(self.netR) - - path_deca_mean = Path("./data/DECA_obama_mean.npy") - self.mean_dict = np.load(path_deca_mean, allow_pickle=True).item() - print(self.mean_dict.keys()) - - if self.opt.DATASET.speech_extractor == "wav2vec": - from transformers import Wav2Vec2FeatureExtractor, Wav2Vec2Model - print("load Wav2Vec2Model ...") - MODEL_ID = "jonatasgrosman/wav2vec2-large-xlsr-53-chinese-zh-cn" - self.processor = Wav2Vec2FeatureExtractor.from_pretrained(MODEL_ID) - self.extractor = Wav2Vec2Model.from_pretrained(MODEL_ID).to(self.device) - - - - def set_input(self, batch_input): - - # motion data - self.data = batch_input["data"].float().to(self.device) # (B, nsteps, nc_motion) - - self.batch_vid = batch_input['vid'] - self.batch_nframe = batch_input['nframe'] - self.batch_interv = batch_input['frame_interval'] - - debug(self.opt, f"data = {self.data.shape}, dtype={self.data.dtype}", verbose=False) - debug(self.opt, f"batch_vid = {self.batch_vid[:2]}", verbose=False) - debug(self.opt, f"batch_nframe = {self.batch_nframe[:2]}", verbose=False) - debug(self.opt, f"batch_interv len={len(self.batch_interv)} len([0])={len(self.batch_interv[0])}, \ - beg={self.batch_interv[0][:4]}, end={self.batch_interv[1][:4]}", verbose=False) - - self.B, self.nsteps = self.data.size(0), self.data.size(1) - - # speech data - raw_speech = batch_input["cond"].numpy() # (B, nsegments) - debug(self.opt, f"raw_speech = {raw_speech.shape}, dtype={raw_speech.dtype}", verbose=False) - - if self.opt.DATASET.speech_extractor == "wav2vec": - # raw_speech = raw_speech.reshape(self.B * self.nsteps, -1) # (B*nsteps, nsegments) - # debug(self.opt, f"raw_speech = {raw_speech.shape}, dtype={raw_speech.dtype}", verbose=False) - - # padding half frame length for bed and end - npad = int(0.5 * self.opt.DATASET.sr * ( 1 / self.opt.DATASET.fps) + 0.5) - raw_speech = np.pad(raw_speech, pad_width=((0,0), (npad, npad)), mode="edge") - debug(self.opt, f"after padding raw_speech = {raw_speech.shape}, dtype={raw_speech.dtype}", verbose=False) - - raw_speech = list(raw_speech) - inputs = self.processor(raw_speech, sampling_rate=16000, return_tensors="pt") - inputs = inputs.to(self.device) - - with torch.no_grad(): - output = self.extractor(**inputs) - self.cond = output.last_hidden_state - # self.cond = output.extract_features - - # B x nsteps x nc_feat - debug(self.opt, f"data = {self.data.shape}, dtype={self.data.dtype}, device={self.data.device}", verbose=False) - debug(self.opt, f"cond = {self.cond.shape}, dtype={self.cond.dtype}, device={self.cond.device}", verbose=False) - - # unfold - # self.data = self.data.unfold(dimension=1, size=16, step=1) # (B, nseqs, nc_motion, 16) - # self.data = self.data.permute(0, 1, 3, 2) # (B, nseqs, 16, 53) - - self.cond = self.cond.unfold(dimension=1, size=16, step=1) # (nseqs, nc_motion, 16) - self.cond = self.cond.permute(0, 1, 3, 2) # (nseqs, 16, 53) - - self.nseq = self.cond.size(1) - self.data = self.data[:, 7:7+self.nseq, :] - - debug(self.opt, f"\n a data = {self.data.shape}, dtype={self.data.dtype}, device={self.data.device}", verbose=False) - debug(self.opt, f"a cond = {self.cond.shape}, dtype={self.cond.dtype}, device={self.cond.device}", verbose=False) - - - def training(self, batch_input): - self.train() # set train model - self.set_input(batch_input) - - # forward - self.pred = self.netG(self.cond) - - # loss - loss, self.loss_dict = self.eval_losses(self.pred, self.data) - - # backward - self.optimizer_G.zero_grad() - loss.backward() - - if self.opt.TRAIN.grad_clip_norm: # operate grad - torch.nn.utils.clip_grad_value_(self.netG.parameters(), self.opt.TRAIN.max_grad_clip) - torch.nn.utils.clip_grad_norm_(self.netG.parameters(), self.opt.TRAIN.max_grad_norm) - - self.optimizer_G.step() - - return loss - - - def validation(self, batch_input): - self.eval() # set eval model - self.set_input(batch_input) - - with torch.no_grad(): - self.pred = self.netG(self.cond) - loss, self.loss_dict = self.eval_losses(self.pred, self.data) - - return loss - - - def infer(self, batch_cond, path_audio, suffix=""): - self.eval() - self.cond = batch_cond.float().to(self.device) # (nsteps, dim_cond) - - with torch.no_grad(): - samples_pt = self.netG(self.cond).cpu().numpy() # B x N x dim_motion - print(f"testing pt shape = {samples_pt.shape}") - - self.save_reconstruct(samples_pt, path_audio, - path_save=Path(self.opt.OUTPUT_DIR), - suffix=suffix) - - - def testing(self, batch_input, cur_epoch=0, cur_batch=0): - self.eval() # set eval model - self.set_input(batch_input) - - with torch.no_grad(): - samples_pt = self.netG(self.cond).cpu().numpy() # B x N x dim_motion - samples_gt = self.data.cpu().numpy() # B x N x dim_motion - - print(f"testing pt shape = {samples_pt.shape}, gt shape = {samples_gt.shape}") - - self.save_reconstruct_with_gt(samples_pt, samples_gt, - path_save=Path(self.opt.OUTPUT_DIR), - suffix=f'sampled_{cur_epoch:05d}_{cur_batch:03d}') - - - def eval_losses(self, batch_pdt, batch_tgt): - """ Computes the VAE loss function. - pramas: - batch_pred, (nbatch, seqlen, dim_motion) - batch_targt, (nbatch, seqlen, dim_motion) - """ - loss = 0 - loss_dict = {} - - batch_pdt_exp = batch_pdt[..., :50] - batch_pdt_pos = batch_pdt[..., 50:] - - batch_tgt_exp = batch_tgt[..., :50] - batch_tgt_pos = batch_tgt[..., 50:] - - - # rec loss - loss = 0 - loss_rec_exp = self.loss_func_wing(batch_pdt_exp, batch_tgt_exp) / 50 - loss_dict["loss_rec_exp"] = loss_rec_exp.detach() - - loss_rec_pos = self.loss_func_wing(batch_pdt_pos, batch_tgt_pos) / 3 - loss_dict["loss_rec_pos"] = loss_rec_pos.detach() - - loss += loss_rec_exp * self.opt.LOSS.lambda_rec_exp - loss += loss_rec_pos * self.opt.LOSS.lambda_rec_pos - - - # rec smooth - diff_pdt_exp = batch_pdt_exp[:, 1:, :] - batch_pdt_exp[:, :-1, :] - diff_tgt_exp = batch_tgt_exp[:, 1:, :] - batch_tgt_exp[:, :-1, :] - loss_vel_exp = self.loss_func_wing(diff_pdt_exp, diff_tgt_exp) / 50 - loss_dict["loss_vel_exp"] = loss_vel_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_vel_pos = self.loss_func_wing(diff_pdt_pos, diff_tgt_pos) / 3 - loss_dict["loss_vel_pos"] = loss_vel_pos.detach() - - loss += loss_vel_exp * self.opt.LOSS.lambda_vel_exp - loss += loss_vel_pos * self.opt.LOSS.lambda_vel_pos - - # total loss - loss_dict['loss_all'] = loss.detach() - - return loss, loss_dict - - - def save_reconstruct(self, samples_pt, path_audio, path_save, suffix=""): - # samples_pt, [B x N x dim_motion] - - B, N, _ = samples_pt.shape - nbatch_render = 10 - - # for each batch - for j in range(B): - jcoeff_pt = samples_pt[j, :, :] - jpath_save = path_save.joinpath(f"{suffix}_{j:02d}.mp4") - - v_render_pt = [] - for k in range(0, N, nbatch_render): - jcodedict_pt = {} - - jcodedict_pt["exp"] = jcoeff_pt[k:k+nbatch_render, :50] # (nbatch_render, 50) - nbatch_real = jcodedict_pt["exp"].shape[0] - - # pose - jcodedict_pt["pose"] = np.repeat([self.mean_dict["pose"]], nbatch_real, axis=0) # (nbatch_render, 6) - jcodedict_pt["pose"][:, 3:6] = jcoeff_pt[k:k+nbatch_render, 50:53] - - # others ==> to mean - mean_cam = [[5,0,0]] # or [self.mean_dict["cam"]] - jcodedict_pt["cam"] = np.repeat(mean_cam, nbatch_real, axis=0) # (nbatch_render, 3) - jcodedict_pt["light"] = np.repeat([self.mean_dict["light"]], nbatch_real, axis=0) # (nbatch_render, 9, 3) - jcodedict_pt["shape"] = np.repeat([self.mean_dict["shape"]], nbatch_real, axis=0) # (nbatch_render, 100) - jcodedict_pt["detail"] = np.repeat([self.mean_dict["detail"]], nbatch_real, axis=0) # (nbatch_render, 128) - - _, visdict_pt = self.netR.decode_one(jcodedict_pt, nbatch_real, self.device) - - render_pt = visdict_pt["shape_images"] # (nbatch_render, 3, 224, 224) - # print(f"render pt shape = {render_pt.shape}") - - for m in range(nbatch_real): - # cv2.imwrite(str(kpath_image), util.tensor2image(render_image[m, ...])) - v_render_pt.append(tensor2image(render_pt[m, ...])) - - # save animation - # print(f"testing v_render_pt = {len(v_render_pt)}") - save_images_with_audio(v_render_pt, path_audio, jpath_save) - - - def save_reconstruct_with_gt(self, samples_pt, samples_gt, path_save, suffix=""): - # samples_pt, [B x N x dim_motion] - # samples_gt, [B x N x dim_motion] - B, N, _ = samples_pt.shape - nbatch_render = 10 - - # for each batch - for j in range(B): - jcoeff_pt = samples_pt[j, :, :] - jcoeff_gt = samples_gt[j, :, :] - jpath_save = path_save.joinpath(f"{suffix}_{j:02d}.mp4") - - v_render_pt = [] - v_render_gt = [] - - for k in range(0, N, nbatch_render): - jcodedict_pt = {} - jcodedict_gt = {} - - # exp - jcodedict_pt["exp"] = jcoeff_pt[k:k+nbatch_render, :50] # (nbatch_render, 50) - jcodedict_gt["exp"] = jcoeff_gt[k:k+nbatch_render, :50] # (nbatch_render, 50) - nbatch_real = jcodedict_pt["exp"].shape[0] - - # pose - jcodedict_pt["pose"] = np.repeat([self.mean_dict["pose"]], nbatch_real, axis=0) # (nbatch_render, 6) - jcodedict_gt["pose"] = np.repeat([self.mean_dict["pose"]], nbatch_real, axis=0) # (nbatch_render, 6) - jcodedict_pt["pose"][:, 3:6] = jcoeff_pt[k:k+nbatch_render, 50:53] - jcodedict_gt["pose"][:, 3:6] = jcoeff_gt[k:k+nbatch_render, 50:53] - - # others ==> to mean - mean_cam = [[5,0,0]] # or [self.mean_dict["cam"]] - jcodedict_pt["cam"] = np.repeat(mean_cam, nbatch_real, axis=0) # (nbatch_render, 3) - jcodedict_pt["light"] = np.repeat([self.mean_dict["light"]], nbatch_real, axis=0) # (nbatch_render, 9, 3) - jcodedict_pt["shape"] = np.repeat([self.mean_dict["shape"]], nbatch_real, axis=0) # (nbatch_render, 100) - jcodedict_pt["detail"] = np.repeat([self.mean_dict["detail"]], nbatch_real, axis=0) # (nbatch_render, 128) - - jcodedict_gt["cam"] = np.repeat(mean_cam, nbatch_real, axis=0) # (nbatch_render, 3) - jcodedict_gt["light"] = np.repeat([self.mean_dict["light"]], nbatch_real, axis=0) # (nbatch_render, 9, 3) - jcodedict_gt["shape"] = np.repeat([self.mean_dict["shape"]], nbatch_real, axis=0) # (nbatch_render, 100) - jcodedict_gt["detail"] = np.repeat([self.mean_dict["detail"]], nbatch_real, axis=0) # (nbatch_render, 128) - - _, visdict_pt = self.netR.decode_one(jcodedict_pt, nbatch_real, self.device) - _, visdict_gt = self.netR.decode_one(jcodedict_gt, nbatch_real, self.device) - - render_pt = visdict_pt["shape_images"] # (nbatch_render, 3, 224, 224) - render_gt = visdict_gt["shape_images"] # (nbatch_render, 3, 224, 224) - # print(f"render pt shape = {render_pt.shape}, gt {render_gt.shape}") - - for m in range(nbatch_real): - # cv2.imwrite(str(kpath_image), util.tensor2image(render_image[m, ...])) - v_render_pt.append(tensor2image(render_pt[m, ...])) - v_render_gt.append(tensor2image(render_gt[m, ...])) - - # get audio - jvid = self.batch_vid[j] - jnframe = self.batch_nframe[j].numpy() - jstart_frame = self.batch_interv[0][j].numpy() - - - jpath_audio = f"{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 - - - - 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 - sys.path.insert(0, "/ssdata1/lsen/CODE/DECA_old") - from decalib.deca import DECA - from decalib.utils import util - from decalib.utils.config import cfg as deca_cfg - - # use device - # device = "cuda:2" - # whether to use FLAME texture model to generate uv texture map - deca_cfg.model.use_tex = False - deca_cfg.dataset.image_size = 512 - - # reconstruction model - netR = DECA(config = deca_cfg, device=device) - - return netR - - - diff --git a/src/models/model_audio2motion_live3.py b/src/models/model_audio2motion_live3.py deleted file mode 100644 index c47af7c..0000000 --- a/src/models/model_audio2motion_live3.py +++ /dev/null @@ -1,464 +0,0 @@ -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_vel_exp = self.loss_func_wing(diff_pdt_exp, diff_tgt_exp) / 50 - loss_dict["loss_vel_exp"] = loss_vel_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_vel_pos = self.loss_func_wing(diff_pdt_pos, diff_tgt_pos) / 3 - loss_dict["loss_vel_pos"] = loss_vel_pos.detach() - - loss += loss_vel_exp * self.opt.LOSS.lambda_vel_exp - loss += loss_vel_pos * self.opt.LOSS.lambda_vel_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_vel_geo = self.loss_func_wing(diff_pdt_geo, diff_tgt_geo) - loss_dict["loss_vel_geo"] = loss_vel_geo.detach() - loss += loss_vel_geo * self.opt.LOSS.lambda_vel_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/audio2motion_voca33.py b/src/nn/audio2motion_voca33.py index 40bff80..9ecf629 100644 --- a/src/nn/audio2motion_voca33.py +++ b/src/nn/audio2motion_voca33.py @@ -2,10 +2,10 @@ import torch import torch.nn as nn from common.debug import debug -class Audio2MotionVOCA(nn.Module): +class Audio2Motion(nn.Module): def __init__(self, opt): - super(Audio2MotionVOCA, self).__init__() + super(Audio2Motion, self).__init__() self.opt = opt self.dim_motion = opt.MODEL.dim_motion # 53 @@ -48,7 +48,8 @@ class Audio2MotionVOCA(nn.Module): nn.Linear(in_features=128, out_features=2048), # 128, nn.Tanh(), - nn.Linear(in_features=2048, out_features=128) # 50, + nn.Linear(in_features=2048, out_features=128), # 50, + nn.LeakyReLU(), ) # output diff --git a/src/nn/audio2motion_voca34.py b/src/nn/audio2motion_voca34.py deleted file mode 100644 index 005353c..0000000 --- a/src/nn/audio2motion_voca34.py +++ /dev/null @@ -1,116 +0,0 @@ -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 - -