add FaceFormer
This commit is contained in:
1 parent
a7cd20b689
commit
b0bb5de24b
5 files changed
+1115
-3
No files matched your search
+269
@@ -0,0 +1,269 @@
|
|||||||
|
import torch
|
||||||
|
import torch.nn as nn
|
||||||
|
import torch.nn.functional as F
|
||||||
|
import numpy as np
|
||||||
|
import copy
|
||||||
|
import math
|
||||||
|
from wav2vec import Wav2Vec2Model
|
||||||
|
|
||||||
|
import time
|
||||||
|
|
||||||
|
# Temporal Bias, inspired by ALiBi: https://github.com/ofirpress/attention_with_linear_biases
|
||||||
|
def init_biased_mask(n_head, max_seq_len, period):
|
||||||
|
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))
|
||||||
|
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)
|
||||||
|
|
||||||
|
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
|
||||||
|
|
||||||
|
|
||||||
|
# Alignment Bias
|
||||||
|
def enc_dec_mask(device, dataset, T, S):
|
||||||
|
mask = torch.ones(T, S) # T x S
|
||||||
|
|
||||||
|
if dataset == "BIWI":
|
||||||
|
for i in range(T):
|
||||||
|
mask[i, i*2:i*2+2] = 0 # 60fps audio --> 30fps frame: 2:1
|
||||||
|
|
||||||
|
elif dataset == "vocaset":
|
||||||
|
for i in range(T):
|
||||||
|
mask[i, i] = 0 # 60fps audio --> 60fps frame: 1:1
|
||||||
|
|
||||||
|
# convert to True or false
|
||||||
|
mask = (mask==1).to(device=device)
|
||||||
|
|
||||||
|
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
|
||||||
|
|
||||||
|
|
||||||
|
class Faceformer(nn.Module):
|
||||||
|
def __init__(self, opt):
|
||||||
|
super(Faceformer, self).__init__()
|
||||||
|
"""
|
||||||
|
audio: (batch_size, raw_wav)
|
||||||
|
template: (batch_size, V*3)
|
||||||
|
vertice: (batch_size, seq_len, V*3)
|
||||||
|
"""
|
||||||
|
|
||||||
|
self.dataset = opt.dataset
|
||||||
|
self.audio_encoder = Wav2Vec2Model.from_pretrained("facebook/wav2vec2-base-960h")
|
||||||
|
# wav2vec 2.0 weights initialization
|
||||||
|
self.audio_encoder.feature_extractor._freeze_parameters()
|
||||||
|
self.audio_feature_map = nn.Linear(768, opt.feature_dim)
|
||||||
|
|
||||||
|
# motion encoder
|
||||||
|
self.vertice_map = nn.Linear(opt.vertice_dim, opt.feature_dim)
|
||||||
|
# periodic positional encoding
|
||||||
|
self.PPE = PeriodicPositionalEncoding(opt.feature_dim, period = opt.period)
|
||||||
|
# temporal bias
|
||||||
|
self.biased_mask = init_biased_mask(n_head = 4, max_seq_len = 600, period=opt.period)
|
||||||
|
|
||||||
|
decoder_layer = nn.TransformerDecoderLayer(d_model=opt.feature_dim, nhead=4, dim_feedforward=2*opt.feature_dim, batch_first=True)
|
||||||
|
self.transformer_decoder = nn.TransformerDecoder(decoder_layer, num_layers=1)
|
||||||
|
|
||||||
|
# motion decoder
|
||||||
|
self.vertice_map_r = nn.Linear(opt.feature_dim, opt.vertice_dim)
|
||||||
|
|
||||||
|
# style embedding
|
||||||
|
self.subject_header = nn.Linear(len(opt.train_subjects.split()), opt.feature_dim, bias=False)
|
||||||
|
self.device = opt.device
|
||||||
|
|
||||||
|
nn.init.constant_(self.vertice_map_r.weight, 0)
|
||||||
|
nn.init.constant_(self.vertice_map_r.bias, 0)
|
||||||
|
|
||||||
|
def forward(self, audio, template, vertice, one_hot, criterion, teacher_forcing=True):
|
||||||
|
"""
|
||||||
|
audio: shape=(B, nsegmt)
|
||||||
|
tempate: shape=(B, V*3), tempate mesh
|
||||||
|
vertice: shape=(B, N, V*3), ground-truth mesh # each N are different
|
||||||
|
one_hot: shape=(B, M=8)
|
||||||
|
"""
|
||||||
|
# tgt_mask: :math:`(T, T)`.
|
||||||
|
# memory_mask: :math:`(T, S)`.
|
||||||
|
print(f"[forward] audio = {audio.shape}, template={template.shape}, vertice={vertice.shape}, one_hot={one_hot.shape}")
|
||||||
|
|
||||||
|
template = template.unsqueeze(1) # (1, 1, V*3)
|
||||||
|
embedding = self.subject_header(one_hot) # (1, feature_dim)
|
||||||
|
print(f"[forward] embedding = {embedding.shape}, template={template.shape}")
|
||||||
|
|
||||||
|
frame_num = vertice.shape[1]
|
||||||
|
hidden_states = self.audio_encoder(audio, self.dataset, frame_num=frame_num).last_hidden_state # (B, N, 768)
|
||||||
|
print(f"[forward] hidden_states = {hidden_states.shape}")
|
||||||
|
|
||||||
|
|
||||||
|
if self.dataset == "BIWI":
|
||||||
|
if hidden_states.shape[1]< frame_num*2:
|
||||||
|
vertice = vertice[:, :hidden_states.shape[1]//2]
|
||||||
|
frame_num = hidden_states.shape[1]//2
|
||||||
|
|
||||||
|
hidden_states = self.audio_feature_map(hidden_states) # (B, N, 64)
|
||||||
|
print(f"[forward] hidden_states = {hidden_states.shape}")
|
||||||
|
|
||||||
|
|
||||||
|
if teacher_forcing:
|
||||||
|
vertice_emb = embedding.unsqueeze(1) # (1, 1, feature_dim)
|
||||||
|
style_emb = vertice_emb # (1, 1, feature_dim)
|
||||||
|
|
||||||
|
vertice_input = torch.cat((template, vertice[:, :-1]), 1) # shift one position, (B, 1, V*3) + (B, N-1, V*3) --> (B, N, V*3)
|
||||||
|
vertice_input = vertice_input - template
|
||||||
|
|
||||||
|
vertice_input = self.vertice_map(vertice_input) # (B, N, feature_dim)
|
||||||
|
vertice_input = vertice_input + style_emb # + style encoding
|
||||||
|
vertice_input = self.PPE(vertice_input) # + Positional Encoding
|
||||||
|
|
||||||
|
N = vertice_input.shape[1]
|
||||||
|
|
||||||
|
tgt_mask = self.biased_mask[:, :N, :N].clone().detach().to(device=self.device) # biased causal mask
|
||||||
|
memory_mask = enc_dec_mask(self.device, self.dataset, N, hidden_states.shape[1]) # biassd memory mask
|
||||||
|
|
||||||
|
vertice_out = self.transformer_decoder(vertice_input, hidden_states, tgt_mask=tgt_mask, memory_mask=memory_mask) # (B, N, feature_dim)
|
||||||
|
vertice_out = self.vertice_map_r(vertice_out) # (B, N, V*3)
|
||||||
|
|
||||||
|
else:
|
||||||
|
for i in range(frame_num):
|
||||||
|
if i==0:
|
||||||
|
vertice_emb = embedding.unsqueeze(1) # (1,1,feature_dim)
|
||||||
|
style_emb = vertice_emb
|
||||||
|
vertice_input = self.PPE(style_emb)
|
||||||
|
else:
|
||||||
|
vertice_input = self.PPE(vertice_emb)
|
||||||
|
|
||||||
|
N = vertice_input.shape[1]
|
||||||
|
tgt_mask = self.biased_mask[:, :N, :N].clone().detach().to(device=self.device)
|
||||||
|
memory_mask = enc_dec_mask(self.device, self.dataset, N, hidden_states.shape[1])
|
||||||
|
|
||||||
|
vertice_out = self.transformer_decoder(vertice_input, hidden_states, tgt_mask=tgt_mask, memory_mask=memory_mask)
|
||||||
|
vertice_out = self.vertice_map_r(vertice_out)
|
||||||
|
|
||||||
|
new_output = self.vertice_map(vertice_out[:,-1,:]).unsqueeze(1)
|
||||||
|
new_output = new_output + style_emb
|
||||||
|
vertice_emb = torch.cat((vertice_emb, new_output), 1)
|
||||||
|
|
||||||
|
vertice_out = vertice_out + template
|
||||||
|
|
||||||
|
|
||||||
|
loss = criterion(vertice_out, vertice) # (batch, seq_len, V*3)
|
||||||
|
loss = torch.mean(loss)
|
||||||
|
return loss
|
||||||
|
|
||||||
|
def predict(self, audio, template, one_hot):
|
||||||
|
time_beg = time.time()
|
||||||
|
|
||||||
|
template = template.unsqueeze(1) # (1, 1, V*3)
|
||||||
|
embedding = self.subject_header(one_hot)
|
||||||
|
hidden_states = self.audio_encoder(audio, self.dataset).last_hidden_state # (B, N, 768)
|
||||||
|
print(f"\n hidden_states={hidden_states.shape} ")
|
||||||
|
|
||||||
|
if self.dataset == "BIWI":
|
||||||
|
frame_num = hidden_states.shape[1]//2
|
||||||
|
elif self.dataset == "vocaset":
|
||||||
|
frame_num = hidden_states.shape[1]
|
||||||
|
|
||||||
|
hidden_states = self.audio_feature_map(hidden_states) # (B, N, 64)
|
||||||
|
print(f"\n hidden_states={hidden_states.shape} ")
|
||||||
|
|
||||||
|
total_time_audio2motion = []
|
||||||
|
|
||||||
|
time_beg2 = time.time()
|
||||||
|
for i in range(frame_num):
|
||||||
|
time_beg3 = time.time()
|
||||||
|
|
||||||
|
if i==0:
|
||||||
|
vertice_emb = embedding.unsqueeze(1) # (B, 1, feature_dim=64)
|
||||||
|
style_emb = vertice_emb
|
||||||
|
vertice_input = self.PPE(style_emb) # (B, 1, feature_dim=64)
|
||||||
|
else:
|
||||||
|
vertice_input = self.PPE(vertice_emb) # (B, N, feature_dim=64)
|
||||||
|
|
||||||
|
# print(f"\nthe {i:03d}-th: style_emb={style_emb.shape}, vertice_input={vertice_input.shape}")
|
||||||
|
|
||||||
|
N = vertice_input.shape[1]
|
||||||
|
|
||||||
|
# (4, N, N)
|
||||||
|
tgt_mask = self.biased_mask[:, :N, :N].clone().detach().to(device=self.device)
|
||||||
|
|
||||||
|
# (N, 282)
|
||||||
|
memory_mask = enc_dec_mask(self.device, self.dataset, N, hidden_states.shape[1])
|
||||||
|
|
||||||
|
# (B, N, 5023*3)
|
||||||
|
vertice_out = self.transformer_decoder(vertice_input, hidden_states, tgt_mask=tgt_mask, memory_mask=memory_mask)
|
||||||
|
vertice_out = self.vertice_map_r(vertice_out)
|
||||||
|
|
||||||
|
total_time_audio2motion.append( time.time() - time_beg3)
|
||||||
|
# print(f"\t the tgt_mask={tgt_mask.shape}, memory_mask={memory_mask.shape}, vertice_out={vertice_out.shape}")
|
||||||
|
|
||||||
|
|
||||||
|
new_output = self.vertice_map(vertice_out[:,-1,:]).unsqueeze(1) # (B, 1, feature_dim=64)
|
||||||
|
new_output = new_output + style_emb # (B, 1, feature_dim=64)
|
||||||
|
vertice_emb = torch.cat((vertice_emb, new_output), 1) # (B, N+1, feature_dim=64)
|
||||||
|
# print(f"\t the new_output={new_output.shape}, vertice_emb={vertice_emb.shape}")
|
||||||
|
|
||||||
|
|
||||||
|
vertice_out = vertice_out + template # (B, N, 5023*3)
|
||||||
|
print(f"\nthe last output vertice_out={vertice_out.shape}")
|
||||||
|
|
||||||
|
|
||||||
|
# calculate time
|
||||||
|
total_time1 = time.time() - time_beg
|
||||||
|
print(f"all = {total_time1:.2f}, total_frame = {frame_num}, fps = {frame_num / total_time1 : 0.2f}")
|
||||||
|
total_time2 = time.time() - time_beg2
|
||||||
|
print(f"total_time_audio2motion = {total_time2:.2f}, total_frame = {frame_num}, fps = {frame_num / total_time2 : 0.2f}")
|
||||||
|
mean_time_audio2motion = np.mean(total_time_audio2motion)
|
||||||
|
print(f"one forward mean_time_audio2motion = {mean_time_audio2motion:.6f}, one forward fps = {1 / mean_time_audio2motion : 0.2f}")
|
||||||
|
|
||||||
|
|
||||||
|
return vertice_out
|
||||||
@@ -36,7 +36,6 @@ if __name__ == "__main__":
|
|||||||
ipath_vis = path_vis.joinpath(f"{iname}_vis.mp4")
|
ipath_vis = path_vis.joinpath(f"{iname}_vis.mp4")
|
||||||
ipath_json = path_json.joinpath(f"{iname}_wholepose.json")
|
ipath_json = path_json.joinpath(f"{iname}_wholepose.json")
|
||||||
|
|
||||||
|
|
||||||
cmd = f"CUDA_VISIBLE_DEVICES=9 \
|
cmd = f"CUDA_VISIBLE_DEVICES=9 \
|
||||||
python -m openpifpaf.video \
|
python -m openpifpaf.video \
|
||||||
--source={ipath_item} \
|
--source={ipath_item} \
|
||||||
|
|||||||
@@ -15,8 +15,6 @@ if __name__ == "__main__":
|
|||||||
path_video = path_root.joinpath(fname, "video")
|
path_video = path_root.joinpath(fname, "video")
|
||||||
path_video.mkdir(parents=True, exist_ok=True)
|
path_video.mkdir(parents=True, exist_ok=True)
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
# path_peaks = path_video.joinpath("reference_peaks.txt") # SSIM-based
|
# path_peaks = path_video.joinpath("reference_peaks.txt") # SSIM-based
|
||||||
path_peaks = path_video.joinpath("reference_peaks_landmarks.txt") # Landmark based
|
path_peaks = path_video.joinpath("reference_peaks_landmarks.txt") # Landmark based
|
||||||
vpeaks = np.loadtxt(path_peaks, dtype=int)
|
vpeaks = np.loadtxt(path_peaks, dtype=int)
|
||||||
|
|||||||
@@ -0,0 +1,618 @@
|
|||||||
|
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()}")
|
||||||
|
|
||||||
|
# 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)
|
||||||
|
|
||||||
|
|
||||||
|
@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']
|
||||||
|
|
||||||
|
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)
|
||||||
|
batch_y = self.data # (B, num_y, 53)
|
||||||
|
template_y = self.template_data # (B, 53)
|
||||||
|
# one_hot = self.one_hot # (B, M)
|
||||||
|
|
||||||
|
|
||||||
|
# forward
|
||||||
|
pred = self.netG(batch_x, batch_y, template_y) # (B, N, 53)
|
||||||
|
|
||||||
|
# loss
|
||||||
|
loss, loss_dict = self.eval_losses(pred, batch_y)
|
||||||
|
|
||||||
|
# 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():
|
||||||
|
pred = self.netG(self.cond)
|
||||||
|
|
||||||
|
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()
|
||||||
|
cond = batch_cond.float().to(self.device) # (nsteps, dim_cond)
|
||||||
|
|
||||||
|
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}")
|
||||||
|
|
||||||
|
|
||||||
|
# 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():
|
||||||
|
batch_pdt = self.netG(self.cond) # B x N x dim_motion
|
||||||
|
|
||||||
|
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
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
@@ -0,0 +1,228 @@
|
|||||||
|
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
|
||||||
|
|
||||||
|
|
||||||
|
# object header
|
||||||
|
self.subject_head = nn.Linear(opt.num_train_subjects, opt.feature_dim, bias=False)
|
||||||
|
|
||||||
|
# audio header
|
||||||
|
# self.speech_head = nn.Linear(768, opt.feature_dim)
|
||||||
|
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=opt.feature_dim) # 50,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
# batch_y
|
||||||
|
self.motion_head = nn.Linear(opt.vertice_dim, opt.feature_dim)
|
||||||
|
self.motion_tail = nn.Linear(opt.feature_dim, opt.vertice_dim)
|
||||||
|
|
||||||
|
# positional encoding
|
||||||
|
self.PPE = PeriodicPositionalEncoding(opt.feature_dim, period = opt.period)
|
||||||
|
|
||||||
|
# Transformer
|
||||||
|
_decoder_layer = nn.TransformerDecoderLayer(d_model=opt.feature_dim, nhead=4, dim_feedforward=2*opt.feature_dim, batch_first=True)
|
||||||
|
self.decoder = nn.TransformerDecoder(_decoder_layer, num_layers=1)
|
||||||
|
|
||||||
|
# init temporal bias
|
||||||
|
self.biased_mask = self.generate_biased_mask(n_head = 4, max_seq_len = 600, period=opt.period)
|
||||||
|
|
||||||
|
# init weigt
|
||||||
|
nn.init.constant_(self.motion_tail.weight, 0)
|
||||||
|
nn.init.constant_(self.motion_tail.bias, 0)
|
||||||
|
|
||||||
|
|
||||||
|
def generate_mask(self, T, S):
|
||||||
|
mask = torch.ones(T, S) # T x S
|
||||||
|
for i in range(T):
|
||||||
|
mask[i, i] = 0 # 60fps audio --> 60fps frame: 1:1
|
||||||
|
|
||||||
|
# convert to True or false
|
||||||
|
mask = (mask==1).to(device=self.device)
|
||||||
|
|
||||||
|
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))
|
||||||
|
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)
|
||||||
|
|
||||||
|
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
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
def forward(self, batch_x, batch_y, template_y, one_hot, 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, dim_motion=3V]
|
||||||
|
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)
|
||||||
|
num_y = batch_y.size(1) # (B, num_y, 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)
|
||||||
|
|
||||||
|
# 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:
|
||||||
|
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=self.device) # biased causal mask
|
||||||
|
memory_mask = self.generate_mask(num_y, x_feat.shape[1]).to(device=self.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:
|
||||||
|
pred = torch.zeros_like(batch_y, requires_grad=True) # (B, num_y, dim_motion)
|
||||||
|
for i in range(num_y):
|
||||||
|
inum_y = i+1
|
||||||
|
|
||||||
|
ifeat_y = self.motion_head(pred[:, :inum_y, :]) # (B, inum_y, dim_feat)
|
||||||
|
ifeat_y += embedding # add style encoding
|
||||||
|
ifeat_y = self.PPE(ifeat_y) # (B, inum_y, dim_feat)
|
||||||
|
|
||||||
|
|
||||||
|
tgt_mask = self.biased_mask[:, :inum_y, :inum_y].clone().to(device=self.device) # biased causal mask
|
||||||
|
memory_mask = self.generate_mask(inum_y, num_x).to(device=self.device) # biassd memory mask
|
||||||
|
|
||||||
|
# decoder
|
||||||
|
ipred = self.decoder(ifeat_y, x_feat, tgt_mask=tgt_mask, memory_mask=memory_mask)
|
||||||
|
ipred = self.motion_tail(pred) # (B x inum_y x dim_motion)
|
||||||
|
|
||||||
|
# update
|
||||||
|
pred[:, i, :] = ipred[:, -1:, :]
|
||||||
|
|
||||||
|
|
||||||
|
return pred
|
||||||
|
|
||||||
|
|
||||||
|
# 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