add ffaceformer code
This commit is contained in:
1 parent
5fcb839ad4
commit
b6567d5902
17 files changed
+2013
-114
No files matched your search
+17
-15
@@ -115,21 +115,21 @@ config.MODEL.lambda_std = []
|
||||
config.MODEL.fix_dims = []
|
||||
|
||||
# # for transformer
|
||||
# config.MODEL.n_src_vocab = 0
|
||||
# config.MODEL.n_tgt_vocab = 0
|
||||
# config.MODEL.src_pad_idx = 0
|
||||
# config.MODEL.tgt_pad_idx = 0
|
||||
# config.MODEL.d_input = 68*2
|
||||
# config.MODEL.d_output = 68*2
|
||||
# config.MODEL.d_embed = 512
|
||||
# config.MODEL.d_model = 512
|
||||
# config.MODEL.d_latent = 256
|
||||
# config.MODEL.d_inner = 2048
|
||||
# config.MODEL.d_k = 64
|
||||
# config.MODEL.d_v = 64
|
||||
# config.MODEL.n_head = 8
|
||||
# config.MODEL.n_layers = 6
|
||||
# config.MODEL.max_position = 200
|
||||
config.MODEL.n_src_vocab = 0
|
||||
config.MODEL.n_tgt_vocab = 0
|
||||
config.MODEL.src_pad_idx = 0
|
||||
config.MODEL.tgt_pad_idx = 0
|
||||
config.MODEL.d_input = 68*2
|
||||
config.MODEL.d_output = 68*2
|
||||
config.MODEL.d_embed = 512
|
||||
config.MODEL.d_model = 512
|
||||
config.MODEL.d_latent = 256
|
||||
config.MODEL.d_inner = 2048
|
||||
config.MODEL.d_k = 64
|
||||
config.MODEL.d_v = 64
|
||||
config.MODEL.n_head = 8
|
||||
config.MODEL.n_layers = 6
|
||||
config.MODEL.max_position = 200
|
||||
|
||||
# In section 3.4 of paper "Attention Is All You Need", there is such detail:
|
||||
# "In our model, we share the same weight matrix between the two
|
||||
@@ -158,6 +158,8 @@ config.DATASET.root = "../data/"
|
||||
config.DATASET.root_raw = "/data/lsen/DATA/xxxx/processing"
|
||||
config.DATASET.path_mean_dict = "./data/xxxx_mean.npy"
|
||||
|
||||
config.DATASET.num_train_items = 20000
|
||||
|
||||
# from dataset iteratiion
|
||||
config.DATASET.nwind_second_train = 0
|
||||
config.DATASET.nwind_second_valid = 0
|
||||
|
||||
@@ -25,7 +25,7 @@ class MotionLiveDataset(Dataset):
|
||||
self.opt = opt
|
||||
self.phase = phase
|
||||
path_data= Path(opt.DATASET.root).joinpath(f"data_{phase}.npz")
|
||||
|
||||
assert phase == "train"
|
||||
|
||||
print(f"[{self.phase}] load data ... --> {path_data}")
|
||||
self.annodb = np.load(path_data, allow_pickle=True)['data'].item()
|
||||
@@ -50,12 +50,8 @@ class MotionLiveDataset(Dataset):
|
||||
|
||||
|
||||
def __len__(self):
|
||||
if self.phase == "train":
|
||||
return 20000
|
||||
elif self.phase == "valid":
|
||||
return 2000 #3000
|
||||
else:
|
||||
return 100
|
||||
return self.opt.DATASET.num_train_items # 20000
|
||||
|
||||
|
||||
def __getitem__(self, idx):
|
||||
"""
|
||||
|
||||
@@ -71,63 +71,6 @@ def calculate_model_params(model):
|
||||
nparam += iparam.numel()
|
||||
return nparam
|
||||
|
||||
def define_netGlow(opt):
|
||||
netG = None
|
||||
if opt.MODEL.name_netG == "MoGlow":
|
||||
from src.nn.moglow import MoGlow
|
||||
netG = MoGlow(opt)
|
||||
elif opt.MODEL.name_netG == "PiorGlow":
|
||||
from src.nn.piorglow import PiorGlow
|
||||
netG = PiorGlow(opt)
|
||||
elif opt.MODEL.name_netG == "MotionFlow":
|
||||
from src.nn.MotionFlow import MotionFlow
|
||||
netG = MotionFlow(opt)
|
||||
else:
|
||||
raise NameError(f"The model of opt.MODEL.name_netG(={opt.MODEL.name_netG}) not existing!")
|
||||
|
||||
return netG
|
||||
|
||||
def define_netG(opt):
|
||||
netG = None
|
||||
|
||||
if opt.MODEL.name_netAE == "VAE":
|
||||
from src.models.sequencial_vae import SequencialVAE
|
||||
netG = SequencialVAE(opt)
|
||||
|
||||
elif opt.MODEL.name_netAE == "MLP":
|
||||
from src.models.vae_vanilla import VanillaVAE
|
||||
netG = VanillaVAE(opt)
|
||||
|
||||
elif opt.MODEL.name_netAE == "ATC":
|
||||
from src.models.atcnet import ATCNet
|
||||
netG = ATCNet(opt)
|
||||
|
||||
elif opt.MODEL.name_netAE == "ATC_BIG":
|
||||
from src.models.atcnet_big import ATC_BIGNet
|
||||
netG = ATC_BIGNet(opt)
|
||||
|
||||
elif opt.MODEL.name_netAE == "ATC_REG":
|
||||
from src.models.atcnet_regression import ATC_REG_Net
|
||||
netG = ATC_REG_Net(opt)
|
||||
|
||||
elif opt.MODEL.name_netAE == "transformer-vae":
|
||||
from src.models.transformer_vae import TransformerVAE
|
||||
netG = TransformerVAE(opt)
|
||||
|
||||
elif opt.MODEL.name_netAE == "transformer":
|
||||
from src.models.transformer import Transformer
|
||||
netG = Transformer(opt)
|
||||
|
||||
elif opt.MODEL.name_netAE == "transformer-a2l":
|
||||
from src.models.transformer_a2l import TransformerA2L
|
||||
netG = TransformerA2L(opt)
|
||||
else:
|
||||
raise NameError(f"The model of opt.MODEL.name_netAE(={opt.MODEL.name_netAE}) not existing!")
|
||||
|
||||
|
||||
return netG
|
||||
|
||||
|
||||
|
||||
def init_weights(net, init_type='normal', init_gain=0.02):
|
||||
"""Initialize network weights.
|
||||
|
||||
@@ -89,7 +89,7 @@ class FaceFormerModel(Base):
|
||||
data_exp = mean_dict["exp"].reshape(1, 1, 50)
|
||||
data_pos = mean_dict["pose"].reshape(1, 1, 6)[:, :, 3:]
|
||||
|
||||
template_motion = np.concatenate([data_exp, data_pos], axis=2) # (1, 1, 53)
|
||||
template_motion = np.concatenate([data_exp, data_pos], axis=2) # (1, 1, 53)
|
||||
template_motion = torch.from_numpy(template_motion).float().to(self.device)
|
||||
self.logger.info(f"template_motion = {template_motion.shape}")
|
||||
|
||||
@@ -259,11 +259,17 @@ class FaceFormerModel(Base):
|
||||
@torch.no_grad()
|
||||
def infer(self, batch_cond, batch_speech, suffix="", save_npy=True):
|
||||
self.eval()
|
||||
cond = batch_cond.float().to(self.device) # (nsteps, dim_cond)
|
||||
B, N, *_ = batch_cond.size()
|
||||
|
||||
batch_x = batch_cond.float().to(self.device) # (B, num_x, 16, 1024)
|
||||
template_y = self.temp_coeff.repeat(B, 1,1) # (B, 1, 53)
|
||||
|
||||
batch_pdt = self.netG(batch_x, None, template_y) # (B, N, 53)
|
||||
batch_pdt += template_y # (B, N, 53)
|
||||
|
||||
|
||||
batch_pdt = self.netG(cond) # B x N x dim_motion
|
||||
self.logger.info(f"testing pt shape = {batch_pdt.shape}")
|
||||
|
||||
|
||||
# to geo
|
||||
batch_pdt_geo, *_ = self.get_vertices(batch_pdt) # B x N x 5023 x 3
|
||||
self.logger.info(f"testing batch_pdt shape = {batch_pdt.shape}, batch_pdt_geo = {batch_pdt_geo.shape}")
|
||||
|
||||
@@ -0,0 +1,648 @@
|
||||
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 write_video, write_video_with_gt
|
||||
from common.debug import debug
|
||||
from common.losses import WingLoss
|
||||
|
||||
# disentangle model
|
||||
class FaceFormer2Model(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)
|
||||
|
||||
# define FLAME & render
|
||||
self.netF = define_FLAME(opt, self.device)
|
||||
self.netR = define_render(opt, self.device)
|
||||
|
||||
if self.isTrain:
|
||||
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()
|
||||
self.logger.info(f"load mean deca coeff from > {path_deca_mean}, \nkeys = {self.mean_dict.keys()}")
|
||||
|
||||
self.temp_coeff = self.get_template_coeff(self.mean_dict) # (1, 1, 53)
|
||||
|
||||
# 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")
|
||||
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)
|
||||
|
||||
def get_template_coeff(self, mean_dict):
|
||||
|
||||
data_exp = mean_dict["exp"].reshape(1, 1, 50)
|
||||
data_pos = mean_dict["pose"].reshape(1, 1, 6)[:, :, 3:]
|
||||
|
||||
template_motion = np.concatenate([data_exp, data_pos], axis=2) # (1, 1, 53)
|
||||
template_motion = torch.from_numpy(template_motion).float().to(self.device)
|
||||
self.logger.info(f"template_motion = {template_motion.shape}")
|
||||
|
||||
return template_motion
|
||||
|
||||
|
||||
|
||||
@torch.no_grad()
|
||||
def set_input(self, batch_input, useless=False):
|
||||
|
||||
# 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[:2] = {self.batch_vid[:2]}", verbose=False)
|
||||
debug(self.opt, f"batch_nframe[:2] = {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.raw_speech = batch_input["cond"].numpy() # (B, nsegments)
|
||||
debug(self.opt, f"raw_speech = {self.raw_speech.shape}, dtype={self.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(self.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")
|
||||
self.cond = self.extractor(**inputs.to(self.device)).last_hidden_state # B x nsteps x nc_feat
|
||||
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] cond = {self.cond.shape}, dtype={self.cond.dtype}, device={self.cond.device}", verbose=False)
|
||||
|
||||
# nsteps should be same
|
||||
assert self.cond.shape[1] == self.data.shape[1], f"nsteps should be equal, data={self.data.shape}, cond={self.cond.shape}"
|
||||
|
||||
if useless:
|
||||
self.vert, self.ldmk2d, self.ldmk3d = self.get_vertices(self.data) # (B, N, 5023, 3)
|
||||
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] 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)
|
||||
|
||||
|
||||
@torch.no_grad()
|
||||
def forward(self, batch_cond):
|
||||
self.eval()
|
||||
|
||||
cond = batch_cond.float().to(self.device) # B x N x 16 x nc_speech
|
||||
|
||||
batch_pdt = self.netG(cond) # B x N x dim_motion
|
||||
# self.logger.info(f"testing batch_pdt shape = {batch_pdt.shape}, batch_pdt_geo = {batch_pdt_geo.shape}")
|
||||
|
||||
return batch_pdt
|
||||
|
||||
|
||||
def training(self, batch_input, idx_epoch=0, idx_batch=0):
|
||||
self.train() # set train model
|
||||
self.set_input(batch_input)
|
||||
|
||||
B, N, *_ = self.cond.size()
|
||||
|
||||
batch_x = self.cond # (B, num_x, 16, 1024)
|
||||
template_y = self.temp_coeff.repeat(B, 1,1) # (B, 1, 53)
|
||||
batch_y = self.data - template_y # (B, num_y, 53)
|
||||
|
||||
# forward
|
||||
pred = self.netG(batch_x, batch_y, template_y) # (B, N, 53)
|
||||
pred += template_y
|
||||
|
||||
# loss
|
||||
loss, loss_dict = self.eval_losses(pred, self.data)
|
||||
# print(f"loss = {loss}, loss_dict = {loss_dict}")
|
||||
|
||||
# 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_dict
|
||||
|
||||
|
||||
def validation(self, batch_input):
|
||||
self.eval() # set eval model
|
||||
self.set_input(batch_input)
|
||||
|
||||
|
||||
with torch.no_grad():
|
||||
B, N, *_ = self.cond.size()
|
||||
|
||||
batch_x = self.cond # (B, num_x, 16, 1024)
|
||||
template_y = self.temp_coeff.repeat(B, 1,1) # (B, 1, 53)
|
||||
batch_y = self.data - template_y # (B, num_y, 53)
|
||||
|
||||
# forward
|
||||
pred = self.netG(batch_x, batch_y, template_y) # (B, N, 53)
|
||||
pred += template_y
|
||||
|
||||
# loss
|
||||
loss, loss_dict = self.eval_losses(pred, self.data)
|
||||
|
||||
return loss_dict
|
||||
|
||||
|
||||
def testing(self, batch_input, idx_epoch=0, idx_batch=0):
|
||||
self.eval() # set eval model
|
||||
self.set_input(batch_input, useless=True)
|
||||
|
||||
with torch.no_grad():
|
||||
|
||||
B, N, *_ = self.cond.size()
|
||||
|
||||
batch_x = self.cond # (B, num_x, 16, 1024)
|
||||
template_y = self.temp_coeff.repeat(B, 1,1) # (B, 1, 53)
|
||||
batch_y = self.data - template_y # (B, num_y, 53)
|
||||
|
||||
# forward
|
||||
batch_pdt = self.netG(batch_x, batch_y, template_y) # (B, N, 53)
|
||||
batch_pdt += template_y
|
||||
|
||||
batch_pdt_geo, *_ = self.get_vertices(batch_pdt) # B x N x 5023 x 3
|
||||
self.logger.info(f"testing batch_pdt shape = {batch_pdt.shape}, batch_pdt_geo = {batch_pdt_geo.shape}")
|
||||
|
||||
self.save_reconstruct_with_gt(batch_pdt_geo, self.vert, self.raw_speech,
|
||||
path_save=Path(self.opt.OUTPUT_DIR),
|
||||
suffix=f'sampled_{idx_epoch:05d}_{idx_batch:03d}')
|
||||
|
||||
|
||||
|
||||
@torch.no_grad()
|
||||
def infer_with_gt(self, batch_cond, batch_data, batch_speech, suffix="", save_npy=True, eval_loss=True):
|
||||
self.eval()
|
||||
|
||||
cond = batch_cond.float().to(self.device) # B x N x 16 x nc_condit
|
||||
data = batch_data.float().to(self.device) # B x N x nc_motion
|
||||
|
||||
batch_pdt = self.netG(cond) # B x N x nc_motion
|
||||
self.logger.info(f"testing pt shape = {batch_pdt.shape}")
|
||||
|
||||
batch_pdt_geo, *_ = self.get_vertices(batch_pdt) # B x N x 5023 x 3
|
||||
batch_tgt_geo, *_ = self.get_vertices(data) # B x N x 5023 x 3
|
||||
self.logger.info(f"testing batch_pdt shape = {batch_pdt.shape}, batch_pdt_geo = {batch_pdt_geo.shape}, batch_tgt_geo = {batch_tgt_geo.shape}")
|
||||
|
||||
|
||||
if save_npy:
|
||||
# save result
|
||||
path_save_npy = Path(self.opt.OUTPUT_DIR).joinpath(f"{suffix}_coeff.npy")
|
||||
np.save(path_save_npy, batch_pdt.cpu().numpy())
|
||||
self.logger.info(f"save infer_result shape = {batch_pdt.shape} -> {path_save_npy}")
|
||||
|
||||
|
||||
if eval_loss:
|
||||
loss, loss_dict = self.eval_losses(batch_pdt, data)
|
||||
self.logger.info(loss_dict)
|
||||
|
||||
# l1 loss
|
||||
diff = torch.abs(batch_pdt - data).mean()
|
||||
self.logger.info(f"l1 coeff rec loss = {diff:0.6f}")
|
||||
|
||||
|
||||
# render & and save
|
||||
self.save_reconstruct(batch_pdt_geo, batch_speech, path_save=Path(self.opt.OUTPUT_DIR),
|
||||
suffix=suffix, vis_landmarks=False)
|
||||
|
||||
# save with GT
|
||||
self.save_reconstruct_with_gt(batch_pdt_geo, batch_tgt_geo, batch_speech,
|
||||
path_save=Path(self.opt.OUTPUT_DIR),
|
||||
suffix=suffix, vis_landmarks=False)
|
||||
|
||||
|
||||
@torch.no_grad()
|
||||
def infer(self, batch_cond, batch_speech, suffix="", save_npy=True):
|
||||
self.eval()
|
||||
B, N, *_ = batch_cond.size()
|
||||
|
||||
batch_x = batch_cond.float().to(self.device) # (B, num_x, 16, 1024)
|
||||
template_y = self.temp_coeff.repeat(B, 1, 1) # (B, 1, 53)
|
||||
|
||||
batch_pdt = self.netG(batch_x, None, template_y) # (B, N, 53)
|
||||
batch_pdt += template_y # (B, N, 53)
|
||||
|
||||
|
||||
self.logger.info(f"testing pt shape = {batch_pdt.shape}")
|
||||
|
||||
# to geo
|
||||
batch_pdt_geo, *_ = self.get_vertices(batch_pdt) # B x N x 5023 x 3
|
||||
self.logger.info(f"testing batch_pdt shape = {batch_pdt.shape}, batch_pdt_geo = {batch_pdt_geo.shape}")
|
||||
|
||||
|
||||
# render & and save
|
||||
self.save_reconstruct(batch_pdt_geo, batch_speech, path_save=Path(self.opt.OUTPUT_DIR),
|
||||
suffix=suffix, vis_landmarks=False)
|
||||
|
||||
if save_npy:
|
||||
# save result
|
||||
# batch_pdt_geo = batch_pdt_geo.cpu().numpy()
|
||||
batch_pdt = batch_pdt.cpu().numpy()
|
||||
path_save_npy = Path(self.opt.OUTPUT_DIR).joinpath(f"{suffix}_coeff.npy")
|
||||
np.save(path_save_npy, batch_pdt)
|
||||
self.logger.info(f"save infer_result shape = {batch_pdt.shape} -> {path_save_npy}")
|
||||
|
||||
|
||||
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
|
||||
|
||||
self.logger.info(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:
|
||||
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) # 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 = 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_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()
|
||||
|
||||
|
||||
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['all'] = loss.detach()
|
||||
|
||||
return loss, loss_dict
|
||||
|
||||
|
||||
def save_reconstruct(self, batch_pdt_geo, batch_speech, path_save, suffix="", vis_landmarks=False):
|
||||
# batch_pdt_pos, [B x N x dim_motion]
|
||||
# batch_speech, [B x N*sr/fps ]
|
||||
|
||||
B, N, *_ = batch_pdt_geo.shape
|
||||
nbatch_render = 10
|
||||
|
||||
# for each batch
|
||||
for i in range(B):
|
||||
igeo_pt = batch_pdt_geo[i, ...]
|
||||
|
||||
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)
|
||||
# self.logger.info(f"cam shape = {cam.shape}")
|
||||
|
||||
# render
|
||||
render_pt = self.render_geometry(kgeo_pt, cam, self.device) # (nbatch_real, 3, 512, 512)
|
||||
# self.logger.info(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):
|
||||
v_render_pt.append(tensor2image(render_pt[m, ...]))
|
||||
|
||||
# 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_batch(self, pred_mesh, vis_landmarks=True):
|
||||
""" render geometry from audio2mesh prediction
|
||||
pred_mesh: shape = N x 5023 x 3
|
||||
return:
|
||||
batch_faces: shape = N x 512 x 512 x 3
|
||||
"""
|
||||
|
||||
N, *_ = pred_mesh.shape
|
||||
|
||||
v_render_pt = []
|
||||
nbatch_render = 10
|
||||
|
||||
for k in range(0, N, nbatch_render):
|
||||
kgeo_pt = pred_mesh[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)
|
||||
# self.logger.info(f"cam shape = {cam.shape}")
|
||||
|
||||
# render
|
||||
render_pt = self.render_geometry(kgeo_pt, cam, self.device) # (nbatch_real, 3, 512, 512)
|
||||
# self.logger.info(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):
|
||||
v_render_pt.append(tensor2image(render_pt[m, ...]))
|
||||
|
||||
|
||||
return v_render_pt
|
||||
|
||||
|
||||
@torch.no_grad()
|
||||
def render_geometry(self, verts, cam=None, device=None):
|
||||
"""
|
||||
verts: [N x 5023 x 3]
|
||||
"""
|
||||
batch_size = verts.size(0)
|
||||
|
||||
if cam is None:
|
||||
cam = torch.zeros(batch_size, 3).to(device) # (batch_size, 3)
|
||||
|
||||
# orth_proj
|
||||
verts_proj = util.batch_orth_proj(verts, cam);
|
||||
verts_proj[:,:,1:] = -verts_proj[:,:,1:]
|
||||
|
||||
# render
|
||||
images = self.netR.render_shape(verts, verts_proj) # (batch_size, 3, 512, 512)
|
||||
|
||||
return images
|
||||
|
||||
|
||||
@torch.no_grad()
|
||||
def save_reconstruct_with_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 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):
|
||||
|
||||
# split
|
||||
kgeo_pt = igeo_pt[k:k+nbatch_render, ...] # [nbatch_real x 5023 x 3]
|
||||
kgeo_gt = igeo_gt[k:k+nbatch_render, ...] # [nbatch_real x 5023 x 3]
|
||||
|
||||
nbatch_real = kgeo_pt.size(0)
|
||||
|
||||
# cam
|
||||
cam = torch.tensor([5, 0, 0], device=self.device).repeat(nbatch_real, 1) # (nbatch_real, 3)
|
||||
# self.logger.info(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)
|
||||
# self.logger.info(f"render_pt ={render_pt.shape}, render_gt={render_gt.shape}")
|
||||
|
||||
if vis_landmarks:
|
||||
# landmarks 3d
|
||||
kldmk3d_pt = self.netF.seletec_3d68(kgeo_pt) # [nbatch_real x 68 x 3]
|
||||
kldmk3d_gt = self.netF.seletec_3d68(kgeo_gt) # [nbatch_real x 68 x 3]
|
||||
|
||||
kldmk3d_pt = util.batch_orth_proj(kldmk3d_pt, cam);
|
||||
kldmk3d_pt[:,:,1:] = -kldmk3d_pt[:,:,1:];
|
||||
|
||||
kldmk3d_gt = util.batch_orth_proj(kldmk3d_gt, cam);
|
||||
kldmk3d_gt[:,:,1:] = -kldmk3d_gt[:,:,1:];
|
||||
|
||||
render_pt = util.tensor_vis_landmarks(render_pt, kldmk3d_pt, gt_landmarks=kldmk3d_gt, isScale=True, color = (255, 0, 0), color_gt=(0, 255, 0))
|
||||
render_gt = util.tensor_vis_landmarks(render_gt, kldmk3d_gt, isScale=True, color = (0, 255, 0))
|
||||
else:
|
||||
render_pt = render_pt.cpu()
|
||||
render_gt = render_gt.cpu()
|
||||
|
||||
# append each frame
|
||||
for m in range(nbatch_real):
|
||||
v_render_pt.append(tensor2image(render_pt[m, ...]))
|
||||
v_render_gt.append(tensor2image(render_gt[m, ...]))
|
||||
|
||||
# save animation
|
||||
write_video_with_gt(v_render_pt, v_render_gt, batch_speech[i], ipath_save, fps=50, sr=16000)
|
||||
|
||||
#########################################
|
||||
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 == "faceformer":
|
||||
from src.nn.faceformer import FaceFormer
|
||||
netG = FaceFormer(opt)
|
||||
|
||||
elif opt.MODEL.name_netG == "faceformer2":
|
||||
from src.nn.faceformer2 import FaceFormer
|
||||
netG = FaceFormer(opt)
|
||||
else:
|
||||
raise NameError(f"The model of opt.MODEL.name_netAE(={opt.MODEL.name_netG}) not existing!")
|
||||
|
||||
|
||||
return netG
|
||||
|
||||
|
||||
|
||||
def define_FLAME(opt, device):
|
||||
from src.nn.FLAME import FLAME
|
||||
|
||||
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
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,657 @@
|
||||
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 write_video, write_video_with_gt
|
||||
from common.debug import debug
|
||||
from common.losses import WingLoss
|
||||
|
||||
# disentangle model
|
||||
class FaceFormerModel(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)
|
||||
|
||||
# define FLAME & render
|
||||
self.netF = define_FLAME(opt, self.device)
|
||||
self.netR = define_render(opt, self.device)
|
||||
|
||||
if self.isTrain:
|
||||
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()
|
||||
self.logger.info(f"load mean deca coeff from > {path_deca_mean}, \nkeys = {self.mean_dict.keys()}")
|
||||
|
||||
self.temp_coeff = self.get_template_coeff(self.mean_dict) # (1, 1, 53)
|
||||
|
||||
# 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")
|
||||
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)
|
||||
|
||||
def get_template_coeff(self, mean_dict):
|
||||
|
||||
data_exp = mean_dict["exp"].reshape(1, 1, 50)
|
||||
data_pos = mean_dict["pose"].reshape(1, 1, 6)[:, :, 3:]
|
||||
|
||||
template_motion = np.concatenate([data_exp, data_pos], axis=2) # (1, 1, 53)
|
||||
template_motion = torch.from_numpy(template_motion).float().to(self.device)
|
||||
self.logger.info(f"template_motion = {template_motion.shape}")
|
||||
|
||||
return template_motion
|
||||
|
||||
|
||||
@torch.no_grad()
|
||||
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.batch_onehot = batch_input['onehot'] # (num_subjects, 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
|
||||
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)
|
||||
|
||||
|
||||
@torch.no_grad()
|
||||
def forward(self, batch_cond):
|
||||
self.eval()
|
||||
|
||||
cond = batch_cond.float().to(self.device) # B x N x 16 x nc_speech
|
||||
|
||||
batch_pdt = self.netG(cond) # B x N x dim_motion
|
||||
# self.logger.info(f"testing batch_pdt shape = {batch_pdt.shape}, batch_pdt_geo = {batch_pdt_geo.shape}")
|
||||
|
||||
return batch_pdt
|
||||
|
||||
|
||||
def training(self, batch_input, idx_epoch=0, idx_batch=0):
|
||||
self.train() # set train model
|
||||
self.set_input(batch_input)
|
||||
|
||||
B, N, *_ = self.cond.size()
|
||||
|
||||
batch_x = self.cond # (B, num_x, 16, 1024)
|
||||
template_y = self.temp_coeff.repeat(B, 1,1) # (B, 1, 53)
|
||||
batch_y = self.data - template_y # (B, num_y, 53)
|
||||
|
||||
# forward
|
||||
pred = self.netG(batch_x, batch_y, template_y) # (B, N, 53)
|
||||
pred += template_y
|
||||
|
||||
|
||||
# loss
|
||||
loss, loss_dict = self.eval_losses(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_dict
|
||||
|
||||
def validation(self, batch_input):
|
||||
self.eval() # set eval model
|
||||
self.set_input(batch_input)
|
||||
|
||||
|
||||
with torch.no_grad():
|
||||
B, N, *_ = self.cond.size()
|
||||
|
||||
batch_x = self.cond # (B, num_x, 16, 1024)
|
||||
template_y = self.temp_coeff.repeat(B, 1,1) # (B, 1, 53)
|
||||
batch_y = self.data - template_y # (B, num_y, 53)
|
||||
|
||||
# forward
|
||||
pred = self.netG(batch_x, batch_y, template_y) # (B, N, 53)
|
||||
pred += template_y
|
||||
|
||||
# loss
|
||||
loss, loss_dict = self.eval_losses(pred, self.data)
|
||||
|
||||
return loss_dict
|
||||
|
||||
|
||||
|
||||
@torch.no_grad()
|
||||
def infer_with_gt(self, batch_cond, batch_data, batch_speech, suffix="", save_npy=True, eval_loss=True):
|
||||
self.eval()
|
||||
|
||||
cond = batch_cond.float().to(self.device) # B x N x 16 x nc_condit
|
||||
data = batch_data.float().to(self.device) # B x N x nc_motion
|
||||
|
||||
batch_pdt = self.netG(cond) # B x N x nc_motion
|
||||
self.logger.info(f"testing pt shape = {batch_pdt.shape}")
|
||||
|
||||
batch_pdt_geo, *_ = self.get_vertices(batch_pdt) # B x N x 5023 x 3
|
||||
batch_tgt_geo, *_ = self.get_vertices(data) # B x N x 5023 x 3
|
||||
self.logger.info(f"testing batch_pdt shape = {batch_pdt.shape}, batch_pdt_geo = {batch_pdt_geo.shape}, batch_tgt_geo = {batch_tgt_geo.shape}")
|
||||
|
||||
|
||||
if save_npy:
|
||||
# save result
|
||||
path_save_npy = Path(self.opt.OUTPUT_DIR).joinpath(f"{suffix}_coeff.npy")
|
||||
np.save(path_save_npy, batch_pdt.cpu().numpy())
|
||||
self.logger.info(f"save infer_result shape = {batch_pdt.shape} -> {path_save_npy}")
|
||||
|
||||
|
||||
if eval_loss:
|
||||
loss, loss_dict = self.eval_losses(batch_pdt, data)
|
||||
self.logger.info(loss_dict)
|
||||
|
||||
# l1 loss
|
||||
diff = torch.abs(batch_pdt - data).mean()
|
||||
self.logger.info(f"l1 coeff rec loss = {diff:0.6f}")
|
||||
|
||||
|
||||
# render & and save
|
||||
self.save_reconstruct(batch_pdt_geo, batch_speech, path_save=Path(self.opt.OUTPUT_DIR),
|
||||
suffix=suffix, vis_landmarks=False)
|
||||
|
||||
# save with GT
|
||||
self.save_reconstruct_with_gt(batch_pdt_geo, batch_tgt_geo, batch_speech,
|
||||
path_save=Path(self.opt.OUTPUT_DIR),
|
||||
suffix=suffix, vis_landmarks=False)
|
||||
|
||||
|
||||
@torch.no_grad()
|
||||
def infer(self, batch_cond, batch_speech, suffix="", save_npy=True):
|
||||
self.eval()
|
||||
B, N, *_ = batch_cond.size()
|
||||
|
||||
batch_x = batch_cond.float().to(self.device) # (B, num_x, 16, 1024)
|
||||
template_y = self.temp_coeff.repeat(B, 1,1) # (B, 1, 53)
|
||||
|
||||
batch_pdt = self.netG(batch_x, None, template_y) # (B, N, 53)
|
||||
batch_pdt += template_y # (B, N, 53)
|
||||
|
||||
|
||||
self.logger.info(f"testing pt shape = {batch_pdt.shape}")
|
||||
|
||||
# to geo
|
||||
batch_pdt_geo, *_ = self.get_vertices(batch_pdt) # B x N x 5023 x 3
|
||||
self.logger.info(f"testing batch_pdt shape = {batch_pdt.shape}, batch_pdt_geo = {batch_pdt_geo.shape}")
|
||||
|
||||
|
||||
# render & and save
|
||||
self.save_reconstruct(batch_pdt_geo, batch_speech, path_save=Path(self.opt.OUTPUT_DIR),
|
||||
suffix=suffix, vis_landmarks=False)
|
||||
|
||||
if save_npy:
|
||||
# save result
|
||||
# batch_pdt_geo = batch_pdt_geo.cpu().numpy()
|
||||
batch_pdt = batch_pdt.cpu().numpy()
|
||||
path_save_npy = Path(self.opt.OUTPUT_DIR).joinpath(f"{suffix}_coeff.npy")
|
||||
np.save(path_save_npy, batch_pdt)
|
||||
self.logger.info(f"save infer_result shape = {batch_pdt.shape} -> {path_save_npy}")
|
||||
|
||||
|
||||
|
||||
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():
|
||||
|
||||
B, N, *_ = self.cond.size()
|
||||
|
||||
batch_x = self.cond # (B, num_x, 16, 1024)
|
||||
template_y = self.temp_coeff.repeat(B, 1,1) # (B, 1, 53)
|
||||
batch_y = self.data - template_y # (B, num_y, 53)
|
||||
|
||||
# forward
|
||||
batch_pdt = self.netG(batch_x, batch_y, template_y) # (B, N, 53)
|
||||
batch_pdt += template_y
|
||||
|
||||
batch_pdt_geo, *_ = self.get_vertices(batch_pdt) # B x N x 5023 x 3
|
||||
self.logger.info(f"testing batch_pdt shape = {batch_pdt.shape}, batch_pdt_geo = {batch_pdt_geo.shape}")
|
||||
|
||||
self.save_reconstruct_with_gt(batch_pdt_geo, self.vert, self.raw_speech,
|
||||
path_save=Path(self.opt.OUTPUT_DIR),
|
||||
suffix=f'sampled_{idx_epoch:05d}_{idx_batch:03d}')
|
||||
|
||||
|
||||
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
|
||||
|
||||
self.logger.info(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:
|
||||
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) # 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 = 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_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()
|
||||
|
||||
|
||||
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['all'] = loss.detach()
|
||||
|
||||
return loss, loss_dict
|
||||
|
||||
|
||||
def save_reconstruct(self, batch_pdt_geo, batch_speech, path_save, suffix="", vis_landmarks=False):
|
||||
# batch_pdt_pos, [B x N x dim_motion]
|
||||
# batch_speech, [B x N*sr/fps ]
|
||||
|
||||
B, N, *_ = batch_pdt_geo.shape
|
||||
nbatch_render = 10
|
||||
|
||||
# for each batch
|
||||
for i in range(B):
|
||||
igeo_pt = batch_pdt_geo[i, ...]
|
||||
|
||||
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)
|
||||
# self.logger.info(f"cam shape = {cam.shape}")
|
||||
|
||||
# render
|
||||
render_pt = self.render_geometry(kgeo_pt, cam, self.device) # (nbatch_real, 3, 512, 512)
|
||||
# self.logger.info(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):
|
||||
v_render_pt.append(tensor2image(render_pt[m, ...]))
|
||||
|
||||
# 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_batch(self, pred_mesh, vis_landmarks=True):
|
||||
""" render geometry from audio2mesh prediction
|
||||
pred_mesh: shape = N x 5023 x 3
|
||||
return:
|
||||
batch_faces: shape = N x 512 x 512 x 3
|
||||
"""
|
||||
|
||||
N, *_ = pred_mesh.shape
|
||||
|
||||
v_render_pt = []
|
||||
nbatch_render = 10
|
||||
|
||||
for k in range(0, N, nbatch_render):
|
||||
kgeo_pt = pred_mesh[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)
|
||||
# self.logger.info(f"cam shape = {cam.shape}")
|
||||
|
||||
# render
|
||||
render_pt = self.render_geometry(kgeo_pt, cam, self.device) # (nbatch_real, 3, 512, 512)
|
||||
# self.logger.info(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):
|
||||
v_render_pt.append(tensor2image(render_pt[m, ...]))
|
||||
|
||||
|
||||
return v_render_pt
|
||||
|
||||
|
||||
@torch.no_grad()
|
||||
def render_geometry(self, verts, cam=None, device=None):
|
||||
"""
|
||||
verts: [N x 5023 x 3]
|
||||
"""
|
||||
batch_size = verts.size(0)
|
||||
|
||||
if cam is None:
|
||||
cam = torch.zeros(batch_size, 3).to(device) # (batch_size, 3)
|
||||
|
||||
# orth_proj
|
||||
verts_proj = util.batch_orth_proj(verts, cam);
|
||||
verts_proj[:,:,1:] = -verts_proj[:,:,1:]
|
||||
|
||||
# render
|
||||
images = self.netR.render_shape(verts, verts_proj) # (batch_size, 3, 512, 512)
|
||||
|
||||
return images
|
||||
|
||||
|
||||
@torch.no_grad()
|
||||
def save_reconstruct_with_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 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):
|
||||
|
||||
# split
|
||||
kgeo_pt = igeo_pt[k:k+nbatch_render, ...] # [nbatch_real x 5023 x 3]
|
||||
kgeo_gt = igeo_gt[k:k+nbatch_render, ...] # [nbatch_real x 5023 x 3]
|
||||
|
||||
nbatch_real = kgeo_pt.size(0)
|
||||
|
||||
# cam
|
||||
cam = torch.tensor([5, 0, 0], device=self.device).repeat(nbatch_real, 1) # (nbatch_real, 3)
|
||||
# self.logger.info(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)
|
||||
# self.logger.info(f"render_pt ={render_pt.shape}, render_gt={render_gt.shape}")
|
||||
|
||||
if vis_landmarks:
|
||||
# landmarks 3d
|
||||
kldmk3d_pt = self.netF.seletec_3d68(kgeo_pt) # [nbatch_real x 68 x 3]
|
||||
kldmk3d_gt = self.netF.seletec_3d68(kgeo_gt) # [nbatch_real x 68 x 3]
|
||||
|
||||
kldmk3d_pt = util.batch_orth_proj(kldmk3d_pt, cam);
|
||||
kldmk3d_pt[:,:,1:] = -kldmk3d_pt[:,:,1:];
|
||||
|
||||
kldmk3d_gt = util.batch_orth_proj(kldmk3d_gt, cam);
|
||||
kldmk3d_gt[:,:,1:] = -kldmk3d_gt[:,:,1:];
|
||||
|
||||
render_pt = util.tensor_vis_landmarks(render_pt, kldmk3d_pt, gt_landmarks=kldmk3d_gt, isScale=True, color = (255, 0, 0), color_gt=(0, 255, 0))
|
||||
render_gt = util.tensor_vis_landmarks(render_gt, kldmk3d_gt, isScale=True, color = (0, 255, 0))
|
||||
else:
|
||||
render_pt = render_pt.cpu()
|
||||
render_gt = render_gt.cpu()
|
||||
|
||||
# append each frame
|
||||
for m in range(nbatch_real):
|
||||
v_render_pt.append(tensor2image(render_pt[m, ...]))
|
||||
v_render_gt.append(tensor2image(render_gt[m, ...]))
|
||||
|
||||
# save animation
|
||||
write_video_with_gt(v_render_pt, v_render_gt, batch_speech[i], ipath_save, fps=50, sr=16000)
|
||||
|
||||
#########################################
|
||||
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 == "faceformer":
|
||||
from src.nn.faceformer import FaceFormer
|
||||
netG = FaceFormer(opt)
|
||||
|
||||
else:
|
||||
raise NameError(f"The model of opt.MODEL.name_netAE(={opt.MODEL.name_netG}) not existing!")
|
||||
|
||||
|
||||
return netG
|
||||
|
||||
|
||||
|
||||
def define_FLAME(opt, device):
|
||||
from src.nn.FLAME import FLAME
|
||||
|
||||
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
|
||||
|
||||
|
||||
|
||||
|
||||
+12
-13
@@ -49,7 +49,6 @@ class FaceFormer(nn.Module):
|
||||
nn.Linear(in_features=1024, out_features=self.dim_hidden) # 50,
|
||||
)
|
||||
|
||||
|
||||
# batch_y
|
||||
self.motion_head = nn.Linear(self.dim_motion, self.dim_hidden)
|
||||
self.motion_tail = nn.Linear(self.dim_hidden, self.dim_motion)
|
||||
@@ -60,13 +59,13 @@ class FaceFormer(nn.Module):
|
||||
|
||||
# Transformer
|
||||
_decoder_layer = nn.TransformerDecoderLayer(d_model=self.dim_hidden, nhead=4, dim_feedforward=2*self.dim_hidden, batch_first=True)
|
||||
self.decoder = nn.TransformerDecoder(_decoder_layer, num_layers=1)
|
||||
self.decoder = nn.TransformerDecoder(_decoder_layer, num_layers=2)
|
||||
|
||||
# init temporal bias
|
||||
self.biased_mask = self.generate_biased_mask(n_head = 4, max_seq_len = self.max_seq_len, period=self.period)
|
||||
|
||||
|
||||
def forward(self, batch_x, batch_y, template_y, teacher_forcing=False):
|
||||
def forward(self, batch_x, batch_y=None, template_y=None, teacher_forcing=False):
|
||||
""" forward function
|
||||
Args:
|
||||
batch_x: (B, num_x, dim_condit=1024]
|
||||
@@ -78,10 +77,8 @@ class FaceFormer(nn.Module):
|
||||
pred: [B x num_y x dim_motion]
|
||||
"""
|
||||
|
||||
|
||||
num_x = batch_x.size(1) # (B, num_x, 16, dim_condit)
|
||||
num_y = batch_y.size(1) # (B, num_y, dim_motion)
|
||||
template_y = template_y.unsqueeze(1) # (B, 1, dim_motion)
|
||||
# template_y = template_y.unsqueeze(1) # (B, 1, dim_motion)
|
||||
|
||||
debug(self.opt, f"[forward] input x shape = {batch_x.shape}", verbose=False)
|
||||
|
||||
@@ -101,6 +98,8 @@ class FaceFormer(nn.Module):
|
||||
|
||||
# teacher forcing
|
||||
if teacher_forcing:
|
||||
num_y = batch_y.size(1) # (B, num_y, dim_motion)
|
||||
|
||||
# embedding_style = embedding # (B, 1, dim_feat)
|
||||
|
||||
# GT right shift && add template
|
||||
@@ -112,8 +111,8 @@ class FaceFormer(nn.Module):
|
||||
feat_y = self.PPE(feat_y) # (B x num_y x dim_feat)
|
||||
|
||||
# prepare mask
|
||||
tgt_mask = self.biased_mask[:, :num_y, :num_y].clone().to(device=batch_y.device) # biased causal mask
|
||||
memory_mask = self.generate_mask(num_y, x_feat.shape[1]).to(device=batch_y.device) # biassd memory mask
|
||||
tgt_mask = self.biased_mask[:, :num_y, :num_y].clone().to(device=batch_x.device) # biased causal mask
|
||||
memory_mask = self.generate_mask(num_y, x_feat.shape[1]).to(device=batch_x.device) # biassd memory mask
|
||||
|
||||
# decoder
|
||||
pred = self.decoder(feat_y, x_feat, tgt_mask=tgt_mask, memory_mask=memory_mask)
|
||||
@@ -121,9 +120,9 @@ class FaceFormer(nn.Module):
|
||||
|
||||
# auto-regression
|
||||
else:
|
||||
vertice_emb = torch.zeros((B, 1, self.dim_motion)).float().to(batch_y.device)
|
||||
for i in range(num_y):
|
||||
|
||||
vertice_emb = torch.zeros((B, 1, self.dim_motion)).float().to(batch_x.device)
|
||||
|
||||
for i in range(num_x):
|
||||
inum_y = i+1
|
||||
debug(self.opt, f"[forward] inum_y = {inum_y}", verbose=False)
|
||||
|
||||
@@ -134,8 +133,8 @@ class FaceFormer(nn.Module):
|
||||
debug(self.opt, f"\t [forward] ifeat_y = {ifeat_y.shape}", verbose=False)
|
||||
|
||||
|
||||
tgt_mask = self.biased_mask[:, :inum_y, :inum_y].repeat(B, 1, 1).to(device=batch_y.device) # biased causal mask
|
||||
memory_mask = self.generate_mask(inum_y, num_x).to(device=batch_y.device) # biassd memory mask
|
||||
tgt_mask = self.biased_mask[:, :inum_y, :inum_y].repeat(B, 1, 1).to(device=batch_x.device) # biased causal mask
|
||||
memory_mask = self.generate_mask(inum_y, num_x).to(device=batch_x.device) # biassd memory mask
|
||||
debug(self.opt, f"\t [forward] tgt_mask = {tgt_mask.shape}, memory_mask = {memory_mask.shape}", verbose=False)
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,231 @@
|
||||
import math
|
||||
import torch
|
||||
import torch.nn as nn
|
||||
from common.debug import debug
|
||||
|
||||
# form https://github.com/EvelynFan/FaceFormer
|
||||
class FaceFormer(nn.Module):
|
||||
|
||||
def __init__(self, opt):
|
||||
super(FaceFormer, self).__init__()
|
||||
|
||||
self.opt = opt
|
||||
self.dim_motion = opt.MODEL.dim_motion # 53
|
||||
self.dim_speech = opt.MODEL.dim_speech # 29
|
||||
|
||||
d_model = opt.MODEL.d_model # 128
|
||||
|
||||
period = 1*50 # 1s
|
||||
max_position = opt.MODEL.max_position # 20s = 20*50
|
||||
|
||||
|
||||
# object header
|
||||
# self.subject_head = nn.Linear(opt.num_train_subjects, d_model, bias=False)
|
||||
|
||||
# audio header
|
||||
self.speech_head = nn.Linear(self.dim_speech, d_model)
|
||||
|
||||
# batch_y
|
||||
self.motion_head = nn.Linear(self.dim_motion, d_model)
|
||||
self.motion_tail = nn.Linear(d_model, self.dim_motion)
|
||||
|
||||
# positional encoding
|
||||
self.PPE = PeriodicPositionalEncoding(
|
||||
d_model,
|
||||
period = period,
|
||||
max_seq_len=max_position
|
||||
)
|
||||
|
||||
# Transformer
|
||||
_decoder_layer = nn.TransformerDecoderLayer(
|
||||
d_model = d_model,
|
||||
nhead = opt.MODEL.n_head,
|
||||
dim_feedforward= opt.MODEL.d_inner,
|
||||
batch_first=True
|
||||
)
|
||||
|
||||
self.decoder = nn.TransformerDecoder(_decoder_layer, num_layers=opt.MODEL.n_layers)
|
||||
|
||||
# init temporal bias
|
||||
self.biased_mask = self.generate_biased_mask(
|
||||
n_head = opt.MODEL.n_head,
|
||||
max_seq_len = max_position,
|
||||
period=period
|
||||
)
|
||||
|
||||
|
||||
def forward(self, batch_x, batch_y=None, template_y=None, teacher_forcing=False):
|
||||
""" forward function
|
||||
Args:
|
||||
batch_x: (B, num_x, dim_condit=1024]
|
||||
batch_y: (B, num_y, dim_motion=3V]
|
||||
template_y: (B, 1, dim_motion]
|
||||
# onehot: (B, M subjects]
|
||||
|
||||
return:
|
||||
pred: [B x num_y x dim_motion]
|
||||
"""
|
||||
|
||||
B, num_x, *_ = batch_x.shape # (B, num_x, dim_condit)
|
||||
# template_y = template_y.unsqueeze(1) # (B, 1, dim_motion)
|
||||
debug(self.opt, f"[forward] input batch_x = {batch_x.shape}", verbose=False)
|
||||
|
||||
# speech header
|
||||
x_feat = self.speech_head(batch_x) # (B, num_x, dim_feat)
|
||||
debug(self.opt, f"[forward] speech-head x shape = {x_feat.shape}", verbose=False)
|
||||
|
||||
# # subject embedding
|
||||
# embedding = self.subject_head(one_hot) # (B x dim_feat)
|
||||
# embedding = embedding.unsqueeze(1) # (B x 1 x dim_feat)
|
||||
|
||||
# teacher forcing
|
||||
if teacher_forcing:
|
||||
num_y = batch_y.size(1) # (B, num_y, dim_motion)
|
||||
|
||||
# embedding_style = embedding # (B, 1, dim_feat)
|
||||
|
||||
# GT right shift && add template
|
||||
y = torch.cat([template_y, batch_y[:, :-1]]) # (B, num_y, dim_motion)
|
||||
y = y - template_y # - mean
|
||||
|
||||
feat_y = self.motion_head(y) # (B x num_y x dim_feat)
|
||||
# feat_y += embedding_style # add style encoding
|
||||
feat_y = self.PPE(feat_y) # (B x num_y x dim_feat)
|
||||
|
||||
# prepare mask
|
||||
tgt_mask = self.biased_mask[:, :num_y, :num_y].clone().to(device=batch_x.device) # biased causal mask
|
||||
# memory_mask = self.generate_mask(num_y, x_feat.shape[1]).to(device=batch_x.device) # biassd memory mask
|
||||
memory_mask = self.generate_mask2(num_y, x_feat.shape[1], windows=15).to(device=batch_x.device) # biassd memory mask
|
||||
|
||||
# decoder
|
||||
pred = self.decoder(feat_y, x_feat, tgt_mask=tgt_mask, memory_mask=memory_mask)
|
||||
pred = self.motion_tail(pred) # (B x num_y x dim_motion)
|
||||
|
||||
# auto-regression
|
||||
else:
|
||||
vertice_emb = torch.zeros((B, 1, self.dim_motion)).float().to(batch_x.device)
|
||||
|
||||
for i in range(num_x):
|
||||
inum_y = i+1
|
||||
debug(self.opt, f"[forward] inum_y = {inum_y}", verbose=False)
|
||||
|
||||
|
||||
ifeat_y = self.motion_head(vertice_emb) # (B, inum_y, dim_feat)
|
||||
# ifeat_y += embedding # add style encoding
|
||||
ifeat_y = self.PPE(ifeat_y) # (B, inum_y, dim_feat)
|
||||
debug(self.opt, f"\t [forward] ifeat_y = {ifeat_y.shape}", verbose=False)
|
||||
|
||||
|
||||
tgt_mask = self.biased_mask[:, :inum_y, :inum_y].repeat(B, 1, 1).to(device=batch_x.device) # biased causal mask
|
||||
# memory_mask = self.generate_mask(inum_y, num_x).to(device=batch_x.device) # biassd memory mask
|
||||
memory_mask = self.generate_mask2(inum_y, num_x, windows=15).to(device=batch_x.device) # biassd memory mask
|
||||
# memory_mask = self.biased_mask[:, :inum_y, :inum_y].repeat(B, 1, 1).to(device=batch_x.device) # biased causal mask
|
||||
|
||||
debug(self.opt, f"\t [forward] tgt_mask = {tgt_mask.shape}, memory_mask = {memory_mask.shape}", verbose=False)
|
||||
|
||||
|
||||
# decoder
|
||||
ipred = self.decoder(ifeat_y, x_feat, tgt_mask=tgt_mask, memory_mask=memory_mask)
|
||||
ipred = self.motion_tail(ipred) # (B x inum_y x dim_motion)
|
||||
debug(self.opt, f"\t [forward] ipred = {ipred.shape}", verbose=False)
|
||||
|
||||
# update
|
||||
vertice_emb = torch.cat((vertice_emb, ipred[:, -1:, :]), 1) # (B, inum_y+1, dim_motion)
|
||||
|
||||
return ipred # NOTE: not return pred, but last ipred
|
||||
|
||||
|
||||
def generate_mask2(self, T, S, windows=7):
|
||||
mask = torch.ones(T, S) # T x S
|
||||
|
||||
half_windows = int((windows-1) // 2)
|
||||
|
||||
for i in range(T):
|
||||
mask[i, max(0, i-half_windows):min(S, i+half_windows+1)] = 0 # 50fps audio --> 50fps frame: 1:1
|
||||
|
||||
# convert to True or false
|
||||
mask = (mask==1)
|
||||
return mask
|
||||
|
||||
|
||||
def generate_mask(self, T, S):
|
||||
mask = torch.ones(T, S) # T x S
|
||||
|
||||
for i in range(T):
|
||||
mask[i, i] = 0 # 50fps audio --> 50fps frame: 1:1
|
||||
|
||||
# convert to True or false
|
||||
mask = (mask==1)
|
||||
return mask
|
||||
|
||||
|
||||
def generate_biased_mask(self, n_head, max_seq_len, period):
|
||||
"""
|
||||
# Temporal Bias, inspired by ALiBi: https://github.com/ofirpress/attention_with_linear_biases
|
||||
"""
|
||||
def get_slopes(n):
|
||||
def get_slopes_power_of_2(n):
|
||||
start = (2**(-2**-(math.log2(n)-3)))
|
||||
ratio = start
|
||||
return [start*ratio**i for i in range(n)]
|
||||
|
||||
if math.log2(n).is_integer():
|
||||
return get_slopes_power_of_2(n)
|
||||
else:
|
||||
closest_power_of_2 = 2**math.floor(math.log2(n))
|
||||
return get_slopes_power_of_2(closest_power_of_2) + get_slopes(2*closest_power_of_2)[0::2][:n-closest_power_of_2]
|
||||
|
||||
slopes = torch.Tensor(get_slopes(n_head)) #(4,)
|
||||
print(f"slops = {slopes}")
|
||||
|
||||
bias = torch.arange(start=0, end=max_seq_len, step=period).unsqueeze(1).repeat(1,period).view(-1)//(period)
|
||||
bias = - torch.flip(bias,dims=[0])
|
||||
|
||||
alibi = torch.zeros(max_seq_len, max_seq_len)
|
||||
for i in range(max_seq_len):
|
||||
alibi[i, :i+1] = bias[-(i+1):]
|
||||
|
||||
alibi = slopes.unsqueeze(1).unsqueeze(1) * alibi.unsqueeze(0) # (4, 1, 1) * (1, N, N) --> (4, N, N)
|
||||
|
||||
mask = torch.ones(max_seq_len, max_seq_len)
|
||||
mask = (torch.triu(mask) == 1).transpose(0, 1)
|
||||
|
||||
mask = mask.float()\
|
||||
.masked_fill(mask == 0, float('-inf'))\
|
||||
.masked_fill(mask == 1, float(0.0))
|
||||
mask = mask.unsqueeze(0) + alibi
|
||||
|
||||
return mask
|
||||
|
||||
|
||||
|
||||
# Periodic Positional Encoding
|
||||
class PeriodicPositionalEncoding(nn.Module):
|
||||
def __init__(self, d_model, dropout=0.1, period=25, max_seq_len=600):
|
||||
super(PeriodicPositionalEncoding, self).__init__()
|
||||
|
||||
self.dropout = nn.Dropout(p=dropout)
|
||||
|
||||
position = torch.arange(0, period, dtype=torch.float).unsqueeze(1) # shape=(1, period), (0,1,2,3,....,24)
|
||||
div_term = torch.exp(torch.arange(0, d_model, 2).float() * (-math.log(10000.0) / d_model))
|
||||
|
||||
pe = torch.zeros(period, d_model)
|
||||
pe[:, 0::2] = torch.sin(position * div_term)
|
||||
pe[:, 1::2] = torch.cos(position * div_term)
|
||||
|
||||
pe = pe.unsqueeze(0) # (1, period, d_model)
|
||||
|
||||
repeat_num = (max_seq_len//period) + 1
|
||||
pe = pe.repeat(1, repeat_num, 1) # (1, perid*repate_num, d_model)
|
||||
self.register_buffer('pe', pe)
|
||||
|
||||
def forward(self, x):
|
||||
x = x + self.pe[:, :x.size(1), :]
|
||||
x = self.dropout(x)
|
||||
|
||||
return x
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,231 @@
|
||||
import math
|
||||
import torch
|
||||
import torch.nn as nn
|
||||
from common.debug import debug
|
||||
|
||||
# form https://github.com/EvelynFan/FaceFormer
|
||||
class FaceFormer(nn.Module):
|
||||
|
||||
def __init__(self, opt):
|
||||
super(FaceFormer, 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
|
||||
|
||||
self.period = 1*50 # 1s
|
||||
self.max_seq_len = 20 * 50 # 20s
|
||||
|
||||
# object header
|
||||
# self.subject_head = nn.Linear(opt.num_train_subjects, self.dim_hidden, bias=False)
|
||||
|
||||
# audio header
|
||||
# self.speech_head = nn.Linear(768, self.dim_hidden)
|
||||
self.speech_head = nn.Sequential( # (nbatch, nchannel=29, H=16, W=1)
|
||||
nn.BatchNorm2d(self.dim_speech),
|
||||
|
||||
# block 1
|
||||
nn.Conv2d(self.dim_speech, 512, kernel_size=(3,1), stride=(2,1), padding=(1,0), bias=True), # 32 x 8 x 1
|
||||
nn.LeakyReLU(0.02, True),
|
||||
|
||||
nn.Conv2d(512, 512, kernel_size=(3,1), stride=(2,1), padding=(1,0), bias=True), # 32 x 4 x 1
|
||||
nn.LeakyReLU(0.02, True),
|
||||
|
||||
nn.Conv2d(512, 256, kernel_size=(3,1), stride=(2,1), padding=(1,0), bias=True), # 64 x 2 x 1
|
||||
nn.LeakyReLU(0.02, True),
|
||||
|
||||
nn.Conv2d(256, 256, kernel_size=(3,1), stride=(2,1), padding=(1,0), bias=True), # 64 x 1 x 1
|
||||
nn.LeakyReLU(0.02, True),
|
||||
|
||||
nn.Conv2d(256, 128, kernel_size=(3,1), stride=(2,1), padding=(1,0), bias=True), # 64 x 1 x 1
|
||||
nn.LeakyReLU(0.02, True),
|
||||
|
||||
nn.Flatten(), # 64,
|
||||
|
||||
nn.Linear(in_features=128, out_features=1024), # 128,
|
||||
nn.Tanh(),
|
||||
|
||||
nn.Linear(in_features=1024, out_features=self.dim_hidden) # 50,
|
||||
)
|
||||
|
||||
# batch_y
|
||||
self.motion_head = nn.Linear(self.dim_motion, self.dim_hidden)
|
||||
self.motion_tail = nn.Linear(self.dim_hidden, self.dim_motion)
|
||||
|
||||
# positional encoding
|
||||
self.PPE = PeriodicPositionalEncoding(self.dim_hidden, period = self.period, max_seq_len=self.max_seq_len)
|
||||
|
||||
|
||||
# Transformer
|
||||
_decoder_layer = nn.TransformerDecoderLayer(d_model=self.dim_hidden, nhead=4, dim_feedforward=2*self.dim_hidden, batch_first=True)
|
||||
self.decoder = nn.TransformerDecoder(_decoder_layer, num_layers=2)
|
||||
|
||||
# init temporal bias
|
||||
self.biased_mask = self.generate_biased_mask(n_head = 4, max_seq_len = self.max_seq_len, period=self.period)
|
||||
|
||||
|
||||
def forward(self, batch_x, batch_y=None, template_y=None, teacher_forcing=False):
|
||||
""" forward function
|
||||
Args:
|
||||
batch_x: (B, num_x, dim_condit=1024]
|
||||
batch_y: (B, num_y, dim_motion=3V]
|
||||
template_y: (B, 1, dim_motion]
|
||||
# onehot: (B, M subjects]
|
||||
|
||||
return:
|
||||
pred: [B x num_y x dim_motion]
|
||||
"""
|
||||
|
||||
num_x = batch_x.size(1) # (B, num_x, 16, dim_condit)
|
||||
# template_y = template_y.unsqueeze(1) # (B, 1, dim_motion)
|
||||
|
||||
debug(self.opt, f"[forward] input x shape = {batch_x.shape}", verbose=False)
|
||||
|
||||
# processing speech data
|
||||
(B, num_x, nwind, dim_condit) = batch_x.shape # (B, num_x, 16, dim_condit)
|
||||
x = batch_x.reshape(B * num_x, 1, nwind, dim_condit) # (B * num_x, 1, 16, dim_condit)
|
||||
x = torch.transpose(x, 1, 3) # (B * num_x, dim_condit, 16, 1)
|
||||
debug(self.opt, f"[forward] transpose x shape = {x.shape}", verbose=False)
|
||||
|
||||
# speech header
|
||||
x_feat = self.speech_head(x) # (B * num_x, dim_feat)
|
||||
x_feat = x_feat.reshape(B, num_x, -1) # (B, num_x, dim_feat)
|
||||
|
||||
# # subject embedding
|
||||
# embedding = self.subject_head(one_hot) # (B x dim_feat)
|
||||
# embedding = embedding.unsqueeze(1) # (B x 1 x dim_feat)
|
||||
|
||||
# teacher forcing
|
||||
if teacher_forcing:
|
||||
num_y = batch_y.size(1) # (B, num_y, dim_motion)
|
||||
|
||||
# embedding_style = embedding # (B, 1, dim_feat)
|
||||
|
||||
# GT right shift && add template
|
||||
y = torch.cat([template_y, batch_y[:, :-1]]) # (B, num_y, dim_motion)
|
||||
y = y - template_y # - mean
|
||||
|
||||
feat_y = self.motion_head(y) # (B x num_y x dim_feat)
|
||||
# feat_y += embedding_style # add style encoding
|
||||
feat_y = self.PPE(feat_y) # (B x num_y x dim_feat)
|
||||
|
||||
# prepare mask
|
||||
tgt_mask = self.biased_mask[:, :num_y, :num_y].clone().to(device=batch_x.device) # biased causal mask
|
||||
memory_mask = self.generate_mask(num_y, x_feat.shape[1]).to(device=batch_x.device) # biassd memory mask
|
||||
|
||||
# decoder
|
||||
pred = self.decoder(feat_y, x_feat, tgt_mask=tgt_mask, memory_mask=memory_mask)
|
||||
pred = self.motion_tail(pred) # (B x num_y x dim_motion)
|
||||
|
||||
# auto-regression
|
||||
else:
|
||||
vertice_emb = torch.zeros((B, 1, self.dim_motion)).float().to(batch_x.device)
|
||||
|
||||
for i in range(num_x):
|
||||
inum_y = i+1
|
||||
debug(self.opt, f"[forward] inum_y = {inum_y}", verbose=False)
|
||||
|
||||
|
||||
ifeat_y = self.motion_head(vertice_emb) # (B, inum_y, dim_feat)
|
||||
# ifeat_y += embedding # add style encoding
|
||||
ifeat_y = self.PPE(ifeat_y) # (B, inum_y, dim_feat)
|
||||
debug(self.opt, f"\t [forward] ifeat_y = {ifeat_y.shape}", verbose=False)
|
||||
|
||||
|
||||
tgt_mask = self.biased_mask[:, :inum_y, :inum_y].repeat(B, 1, 1).to(device=batch_x.device) # biased causal mask
|
||||
memory_mask = self.generate_mask(inum_y, num_x).to(device=batch_x.device) # biassd memory mask
|
||||
debug(self.opt, f"\t [forward] tgt_mask = {tgt_mask.shape}, memory_mask = {memory_mask.shape}", verbose=False)
|
||||
|
||||
|
||||
# decoder
|
||||
ipred = self.decoder(ifeat_y, x_feat, tgt_mask=tgt_mask, memory_mask=memory_mask)
|
||||
ipred = self.motion_tail(ipred) # (B x inum_y x dim_motion)
|
||||
debug(self.opt, f"\t [forward] ipred = {ipred.shape}", verbose=False)
|
||||
|
||||
# update
|
||||
vertice_emb = torch.cat((vertice_emb, ipred[:, -1:, :]), 1) # (B, inum_y+1, dim_motion)
|
||||
|
||||
return ipred # NOTE: not return pred, but last ipred
|
||||
|
||||
|
||||
def generate_mask(self, T, S):
|
||||
mask = torch.ones(T, S) # T x S
|
||||
for i in range(T):
|
||||
mask[i, i] = 0 # 50fps audio --> 50fps frame: 1:1
|
||||
|
||||
# convert to True or false
|
||||
mask = (mask==1)
|
||||
return mask
|
||||
|
||||
|
||||
def generate_biased_mask(self, n_head, max_seq_len, period):
|
||||
"""
|
||||
# Temporal Bias, inspired by ALiBi: https://github.com/ofirpress/attention_with_linear_biases
|
||||
"""
|
||||
def get_slopes(n):
|
||||
def get_slopes_power_of_2(n):
|
||||
start = (2**(-2**-(math.log2(n)-3)))
|
||||
ratio = start
|
||||
return [start*ratio**i for i in range(n)]
|
||||
|
||||
if math.log2(n).is_integer():
|
||||
return get_slopes_power_of_2(n)
|
||||
else:
|
||||
closest_power_of_2 = 2**math.floor(math.log2(n))
|
||||
return get_slopes_power_of_2(closest_power_of_2) + get_slopes(2*closest_power_of_2)[0::2][:n-closest_power_of_2]
|
||||
|
||||
slopes = torch.Tensor(get_slopes(n_head)) #(4,)
|
||||
print(f"slops = {slopes}")
|
||||
|
||||
bias = torch.arange(start=0, end=max_seq_len, step=period).unsqueeze(1).repeat(1,period).view(-1)//(period)
|
||||
bias = - torch.flip(bias,dims=[0])
|
||||
|
||||
alibi = torch.zeros(max_seq_len, max_seq_len)
|
||||
for i in range(max_seq_len):
|
||||
alibi[i, :i+1] = bias[-(i+1):]
|
||||
|
||||
alibi = slopes.unsqueeze(1).unsqueeze(1) * alibi.unsqueeze(0) # (4, 1, 1) * (1, N, N) --> (4, N, N)
|
||||
|
||||
mask = torch.ones(max_seq_len, max_seq_len)
|
||||
mask = (torch.triu(mask) == 1).transpose(0, 1)
|
||||
|
||||
mask = mask.float()\
|
||||
.masked_fill(mask == 0, float('-inf'))\
|
||||
.masked_fill(mask == 1, float(0.0))
|
||||
mask = mask.unsqueeze(0) + alibi
|
||||
|
||||
return mask
|
||||
|
||||
|
||||
|
||||
# Periodic Positional Encoding
|
||||
class PeriodicPositionalEncoding(nn.Module):
|
||||
def __init__(self, d_model, dropout=0.1, period=25, max_seq_len=600):
|
||||
super(PeriodicPositionalEncoding, self).__init__()
|
||||
|
||||
self.dropout = nn.Dropout(p=dropout)
|
||||
|
||||
position = torch.arange(0, period, dtype=torch.float).unsqueeze(1) # shape=(1, period), (0,1,2,3,....,24)
|
||||
div_term = torch.exp(torch.arange(0, d_model, 2).float() * (-math.log(10000.0) / d_model))
|
||||
|
||||
pe = torch.zeros(period, d_model)
|
||||
pe[:, 0::2] = torch.sin(position * div_term)
|
||||
pe[:, 1::2] = torch.cos(position * div_term)
|
||||
|
||||
pe = pe.unsqueeze(0) # (1, period, d_model)
|
||||
|
||||
repeat_num = (max_seq_len//period) + 1
|
||||
pe = pe.repeat(1, repeat_num, 1) # (1, perid*repate_num, d_model)
|
||||
self.register_buffer('pe', pe)
|
||||
|
||||
def forward(self, x):
|
||||
x = x + self.pe[:, :x.size(1), :]
|
||||
x = self.dropout(x)
|
||||
|
||||
return x
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
Reference in new issue
Block a user