Files
audio2motion/faceformer.py
T
2022-07-14 19:21:09 +08:00

270 lines
11 KiB
Python

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