add audio2mesh_ar

This commit is contained in:
Sen Liang committed 2022-03-14 18:13:13 +08:00
1 parent ded9b27f71
commit e0f24982d1
46 files changed
+3917 -325

No files matched your search

+2
View File
@@ -143,6 +143,8 @@ config.DATASET.filter = '' # "gaussian" | "savgol"
# augmentation
config.DATASET.flip = False
config.DATASET.shifting_speed = False
#############################
# Trainning related parameter
+192 -24
View File
@@ -1,11 +1,14 @@
import imp
import numpy as np
import torch
import time
import random
from torch.utils.data import Dataset
from pathlib import Path
from scipy.signal import savgol_filter
from common.debug import debug
# common
from common.resampling import resample_by_nsteps
class MotionLiveDataset(Dataset):
"""
@@ -18,15 +21,13 @@ class MotionLiveDataset(Dataset):
"""
super(MotionLiveDataset, self).__init__()
self.opt = opt
self.phase = phase
path_data= Path(opt.DATASET.root).joinpath(f"data_{phase}.npz")
# for test
# if phase == "valid":
# path_data= Path(opt.DATASET.root).joinpath(f"data_train.npz")
# if phase == "test":
# path_data= Path(opt.DATASET.root).joinpath(f"data_train.npz")
@@ -49,7 +50,6 @@ class MotionLiveDataset(Dataset):
f'''nsteps_frame={self.nsteps_frame}\t'''
f'''nsteps_segmt={self.nsteps_segmt} ''')
# path_motion = self.path_data.joinpath(f"motion_{phase}.npz")
# path_speech = self.path_data.joinpath(f"speech_{phase}.npz")
# print(f"load data ... --> {path_motion} | {path_speech}")
@@ -65,9 +65,9 @@ class MotionLiveDataset(Dataset):
def __len__(self):
if self.phase == "train":
return 20000 #40000
return 30000 #40000
elif self.phase == "valid":
return 2000 #5000
return 3000 #5000
else:
return 100
@@ -91,38 +91,206 @@ class MotionLiveDataset(Dataset):
data = self.annodb[vid]
data_motion = data["data_motion"] # (nframes, nc_motion)
data_speech = data["data_speech"] # (nsegemts, )
# data_shape = data["data_shape"] # (nframes, nc_shape)
data_motion = data["data_motion"] # (nframes, nc_motion)
data_speech = data["data_speech"] # (nsegemts, )
# data_shape = data["data_shape"] # (nframes, nc_shape)
nframe = data_motion.shape[0]
nsegmt = data_speech.shape[0]
# random select beg:end frame
beg_frame = np.random.randint(nframe - self.nsteps_frame - 10) + 5 # select from (5:-5)
end_frame = beg_frame + self.nsteps_frame
if self.phase == "train" and self.opt.DATASET.shifting_speed and random.random() < 0.3:
speed = random.sample({0.5, 0.7, 0.8, 0.9, 1.1, 1.2, 1.3, 1.4, 1.5},1)[0]
beg_segmt = int((1.0 * beg_frame / nframe) * nsegmt)
end_segmt = beg_segmt + self.nsteps_segmt
# print(f"nframe-{self.nsteps_frame:04d} =[{beg_frame:04d},{end_frame:04d})\t nsegmet-{self.nsteps_segmt:04d}=[{beg_segmt:04d},{end_segmt:04d}), vid={vid}")
beg_frame = np.random.randint(nframe - int(self.nsteps_frame * speed) - 10) + 5 # select from (5:-5)
end_frame = beg_frame + int(self.nsteps_frame * speed)
data_motion = data_motion[beg_frame:end_frame, :] # (nteps, 53)
data_speech = data_speech[beg_segmt:end_segmt] # (nsegmt_steps, )
# data_shape = data_shape[beg_frame:end_frame, :] # (nsteps, 100)
beg_segmt = int((1.0 * beg_frame / nframe) * nsegmt)
end_segmt = beg_segmt + int(self.nsteps_segmt * speed)
data_motion = data_motion[beg_frame:end_frame] # (nteps, 53)
data_speech = data_speech[beg_segmt:end_segmt] # (nsegmt_steps, )
assert data_speech.shape[0] == int(self.nsteps_segmt * speed), f"data_speech shape={data_speech.shape}, vid={vid}"
assert data_motion.shape[0] == int(self.nsteps_frame * speed), f"data_motion shape={data_motion.shape}, vid={vid}"
# print(f"speed={speed}, data_speech shape={data_speech.shape} data_motion shape={data_motion.shape}")
# resample to same nsteps
data_motion = resample_by_nsteps(data_motion, nsteps_tgt=self.nsteps_frame)
data_speech = resample_by_nsteps(data_speech, nsteps_tgt=self.nsteps_segmt)
# print(f"resampling > data_speech shape={data_speech.shape} data_motion shape={data_motion.shape} \n")
else:
# random select beg:end frame
beg_frame = np.random.randint(nframe - self.nsteps_frame - 10) + 5 # select from (5:-5)
end_frame = beg_frame + self.nsteps_frame
beg_segmt = int((1.0 * beg_frame / nframe) * nsegmt)
end_segmt = beg_segmt + self.nsteps_segmt
# print(f"nframe-{self.nsteps_frame:04d} =[{beg_frame:04d},{end_frame:04d})\t nsegmet-{self.nsteps_segmt:04d}=[{beg_segmt:04d},{end_segmt:04d}), vid={vid}")
data_motion = data_motion[beg_frame:end_frame] # (nteps, 53)
data_speech = data_speech[beg_segmt:end_segmt] # (nsegmt_steps, )
assert data_speech.shape[0] == self.nsteps_segmt, f"data_speech shape={data_speech.shape}, vid={vid}"
assert data_motion.shape[0] == self.nsteps_frame, f"data_motion shape={data_motion.shape}, vid={vid}"
# filter, explore doc: ./notebook/explore_pose.ipynb
if self.opt.DATASET.filter == "savgol":
data_motion = savgol_filter(data_motion, window_length=5, polyorder=3, axis=0, mode='nearest')
# data_shape = savgol_filter(data_shape, window_length=5, polyorder=3, axis=0, mode='nearest')
# random augments: reverse
if self.phase == "train" and self.opt.DATASET.flip:
data_motion, data_speech = self.make_auguments_flip(data_motion, data_speech, p=0.3)
# print(f"flip: data_motion-{data_motion.shape} data_speech={data_speech.shape}")
# random augments: shuffle speed
result = {
"data": data_motion, # (nsteps_frame, dim_motion)
"cond": data_speech, # (nsteps_frame, dim_speech)
"vid": vid,
"nframe": nframe,
"frame_interval": [beg_frame, end_frame],
}
return result
def make_auguments_flip(self, data_motion, data_speech, p=0.5):
'''
parameters:
data_motion: (nsteps_motion, 53)
data_speech: (nsteps_speech, ), where nsteps_speech!= nsteps_motion
'''
if random.random() < p:
data_motion = data_motion[::-1].copy()
data_speech = data_speech[::-1].copy()
return data_motion, data_speech
def make_auguments_speed(self, data_motion, data_speech, p=0.5):
'''
parameters:
data_motion: (nsteps_motion, 53)
data_speech: (nsteps_speech, ), where nsteps_speech!= nsteps_motion
'''
if random.random() > p:
return data_motion, data_speech
nsteps_motion = data_motion.shape[0]
nsteps_speech = data_speech.shape[0]
speed = random.sample({0.5, 0.7, 0.8, 0.9, 1.1, 1.2, 1.3, 1.4, 1.5},1)[0]
if speed < 0:
data_motion = data_motion[:nsteps_motion*speed]
data_speech = data_speech[:nsteps_speech*speed]
return data_motion, data_speech
class MotionLiveEvalDataset(Dataset):
"""
Motion dataset.
Prepares conditioning information (previous poses + control signal) and the corresponding next poses"""
def __init__(self, opt, phase="train"):
"""
phase = "train | valid | test "
"""
super(MotionLiveEvalDataset, self).__init__()
self.opt = opt
self.phase = phase
path_data= Path(opt.DATASET.root).joinpath(f"data_{phase}.npz")
print(f"\n [{self.phase}] load data ... --> {path_data}")
# dict vid: {"data_motion", # [nframe, 53]
# "data_speech", # [duration * sample_rate, ] raw deepseep
# "nframe", "fps", "sr"}
self.annodb = np.load(path_data, allow_pickle=True)['data'].item()
self.num_pid = len(self.annodb)
self.pids = list(self.annodb.keys())
self.annodb_accums = self.count_annotations()
self.overlap = 0.5
self.fps = opt.DATASET.fps # 50
self.sr = opt.DATASET.sr # 16000
self.nwind = eval(f"opt.DATASET.nwind_second_{phase}")
self.nsteps_frame = self.nwind * self.fps
self.nsteps_segmt = self.nwind * self.sr
print(f'''len(annodb)={len(self.annodb)}\t'''
f'''nsteps_frame={self.nsteps_frame}\t'''
f'''nsteps_segmt={self.nsteps_segmt} ''')
def __len__(self):
return self.annodb_accums[-1]
def count_annotations(self):
acc = 0
annodb_accums = np.zeros(self.num_pid + 1, dtype=int) # the first element set 0
for i, anno_dict in enumerate(self.annodb.values()):
acc += anno_dict["data_motion"].shape[0] // (self.nsteps_frame * self.overlap) - 1 # ncount_windows
annodb_accums[i+1] = acc # 2
return annodb_accums
def __getitem__(self, idx):
"""
Returns poses and conditioning.
If data-dropout sould be applied, a random selection of the previous poses is masked.
The control is not masked
return:
motion: (nsteps, nc_motion), current frame's pose (15 joint, xyz position)
speech: (nsteps, nc_speech), conditional data = previous motion data + full windows contrl data
"""
for i, iacc in enumerate(self.annodb_accums):
if idx > iacc -1 and idx < self.annodb_accums[i+1]:
pid, new_idx = i, idx - iacc
break
print(f"DEBUG: idx={idx}, pid = {pid}, iacc ={self.annodb_accums[i]}, new_idx = {new_idx}")
# return item
vid = self.pids[pid]
data = self.annodb[vid]
data_motion = data["data_motion"] # (nframes, nc_motion)
data_speech = data["data_speech"] # (nsegemts, )
nframe = data_motion.shape[0]
nsegmt = data_speech.shape[0]
# random select beg:end frame
beg_frame = new_idx
end_frame = beg_frame + self.nsteps_frame
beg_segmt = int((1.0 * beg_frame / nframe) * nsegmt)
end_segmt = beg_segmt + self.nsteps_segmt
print(f"nframe-{self.nsteps_frame:04d} =[{beg_frame:04d},{end_frame:04d})\nnsegmet-{self.nsteps_segmt:04d}=[{beg_segmt:04d},{end_segmt:04d}), vid={vid}")
data_motion = data_motion[beg_frame:end_frame] # (nteps, 53)
data_speech = data_speech[beg_segmt:end_segmt] # (nsegmt_steps, )
print(f"data_motion-{data_motion.shape} data_speech={data_speech.shape}")
# filter, explore doc: ./notebook/explore_pose.ipynb
if self.opt.DATASET.filter == "savgol":
data_motion = savgol_filter(data_motion, window_length=5, polyorder=3, axis=0, mode='nearest')
result = {
"data": data_motion, # (nsteps_frame, dim_motion)
"cond": data_speech, # (nsteps_frame, dim_speech)
# "shape": data_shape,
"vid": vid,
"nframe": nframe,
"frame_interval": [beg_frame, end_frame],
@@ -131,4 +299,4 @@ class MotionLiveDataset(Dataset):
assert data_speech.shape[0] == self.nsteps_segmt, f"data_speech shape={data_speech.shape}, vid={vid}"
return result
return result
+46 -3
View File
@@ -1,3 +1,4 @@
from random import random
import numpy as np
import torch
import time
@@ -10,7 +11,9 @@ from common.debug import debug
class MotionLive2Dataset(Dataset):
"""
Motion dataset.
Prepares conditioning information (previous poses + control signal) and the corresponding next poses"""
Prepares conditioning information (previous poses + control signal) and the corresponding next poses
+ shape
"""
def __init__(self, opt, phase="train"):
"""
@@ -110,7 +113,6 @@ class MotionLive2Dataset(Dataset):
data_shape = data_shape[beg_frame:end_frame, :] # (nsteps, 100)
# filter, explore doc: ./notebook/explore_pose.ipynb
if self.opt.DATASET.filter == "savgol":
data_motion = savgol_filter(data_motion, window_length=5, polyorder=3, axis=0, mode='nearest')
@@ -129,4 +131,45 @@ class MotionLive2Dataset(Dataset):
assert data_speech.shape[0] == self.nsteps_segmt, f"data_speech shape={data_speech.shape}, vid={vid}"
return result
return result
def make_auguments_reverse(self, data_motion, data_speech, p=0.5):
'''
parameters:
data_motion: (nsteps_motion, 53)
data_speech: (nsteps_speech, ), where nsteps_speech!= nsteps_motion
'''
if random.random() < p:
data_motion = data_motion[::-1]
data_speech = data_speech[::-1]
return data_motion, data_speech
def make_auguments_speed(self, data_motion, data_speech, p=0.5):
'''
parameters:
data_motion: (nsteps_motion, 53)
data_speech: (nsteps_speech, ), where nsteps_speech!= nsteps_motion
'''
if random.random() > p:
return data_motion, data_speech
nsteps_motion = data_motion.shape[0]
nsteps_speech = data_speech.shape[0]
speed = random.sample({0.5, 0.7, 0.8, 0.9, 1.1, 1.2, 1.3, 1.4, 1.5},1)[0]
if speed < 0:
data_motion = data_motion[:nsteps_motion*speed]
data_speech = data_speech[:nsteps_speech*speed]
return data_motion, data_speech
+160
View File
@@ -0,0 +1,160 @@
import numpy as np
import random
import time
from torch.utils.data import Dataset
from pathlib import Path
from scipy.signal import savgol_filter
from common.debug import debug
class MotionLive3Dataset(Dataset):
"""
Motion dataset.
Prepares conditioning information (previous poses + control signal) and the corresponding next poses
+ shape
+ selected idx
"""
def __init__(self, opt, phase="train"):
"""
phase = "train | valid | test "
"""
super(MotionLive3Dataset, self).__init__()
self.opt = opt
self.phase = phase
path_data= Path(opt.DATASET.root).joinpath(f"data_{phase}.npz")
# for test
# if phase == "valid":
# path_data= Path(opt.DATASET.root).joinpath(f"data_train.npz")
# if phase == "test":
# path_data= Path(opt.DATASET.root).joinpath(f"data_train.npz")
print(f"\n [{self.phase}] load data ... --> {path_data}")
# dict vid: {"data_motion", # [nframe, 53]
# "data_speech", # [duration * sample_rate, ] raw deepseep
# "nframe", "fps", "sr"}
self.annodb = np.load(path_data, allow_pickle=True)['data'].item()
self.num_pid = len(self.annodb)
self.pids = list(self.annodb.keys())
self.fps = opt.DATASET.fps # 50
self.sr = opt.DATASET.sr # 16000
self.nwind = eval(f"opt.DATASET.nwind_second_{phase}")
self.nsteps_frame = self.nwind * self.fps
self.nsteps_segmt = self.nwind * self.sr
print(f'''len(annodb)={len(self.annodb)}\t'''
f'''nsteps_frame={self.nsteps_frame}\t'''
f'''nsteps_segmt={self.nsteps_segmt} ''')
# path_motion = self.path_data.joinpath(f"motion_{phase}.npz")
# path_speech = self.path_data.joinpath(f"speech_{phase}.npz")
# print(f"load data ... --> {path_motion} | {path_speech}")
# self.data_motion = np.load(path_motion)['data'].astype(np.float32) # (N, nsteps, dim_motion)
# self.data_speech = np.load(path_speech)['data'].astype(np.float32) # (N, nsteps, dim_speech)
# print(f"motion data ={self.data_motion.shape}, output={self.data_speech.shape}")
# self.nc_motion = self.data_motion.shape[-1]
# self.nc_speech = self.data_speech.shape[-1]
# debug(opt, f"nc_motion={self.nc_motion}, nc_speech ={self.nc_speech }")
def __len__(self):
if self.phase == "train":
return 20000 #40000
elif self.phase == "valid":
return 2000 #5000
else:
return 100
def __getitem__(self, idx):
"""
Returns poses and conditioning.
If data-dropout sould be applied, a random selection of the previous poses is masked.
The control is not masked
return:
motion: (nsteps, nc_motion), current frame's pose (15 joint, xyz position)
speech: (nsteps, nc_speech), conditional data = previous motion data + full windows contrl data
"""
np.random.seed(int(idx + time.time()))
vid = self.pids[idx % self.num_pid]
# # filter "2021-P29"
# while vid == "2021-P29":
# vid = self.pids[idx % self.num_pid]
# random select idx
data = self.annodb[vid]
data_motion = data["data_motion"] # (nframes, nc_motion)
data_speech = data["data_speech"] # (nsegemts, )
# data_shape = data["data_shape"] # (nframes, nc_shape)\
set_idx = data["idx_sampling"] # (nframes_sampling)
nframe = data_motion.shape[0]
nsegmt = data_speech.shape[0]
# random select beg:end frame
if self.phase == "train":
beg_frame = random.sample(set_idx,1)[0]
if beg_frame + self.nsteps_frame > nframe: # resampling when last
beg_frame = nframe - self.nsteps_frame - 5
else:
beg_frame = np.random.randint(nframe - self.nsteps_frame - 10) + 5 # select from (5:-5)
end_frame = beg_frame + self.nsteps_frame
beg_segmt = int((1.0 * beg_frame / nframe) * nsegmt)
end_segmt = beg_segmt + self.nsteps_segmt
# print(f"nframe-{self.nsteps_frame:04d} =[{beg_frame:04d},{end_frame:04d})\t nsegmet-{self.nsteps_segmt:04d}=[{beg_segmt:04d},{end_segmt:04d}), vid={vid}")
data_motion = data_motion[beg_frame:end_frame, :] # (nteps, 53)
data_speech = data_speech[beg_segmt:end_segmt] # (nsegmt_steps, )
# data_shape = data_shape[beg_frame:end_frame, :] # (nsteps, 100)
# filter, explore doc: ./notebook/explore_pose.ipynb
if self.opt.DATASET.filter == "savgol":
data_motion = savgol_filter(data_motion, window_length=5, polyorder=3, axis=0, mode='nearest')
# data_shape = savgol_filter(data_shape, window_length=5, polyorder=3, axis=0, mode='nearest')
# random augments: reverse
if self.phase == "train" and self.opt.DATASET.flip:
data_motion, data_speech = self.make_auguments_flip(data_motion, data_speech, p=0.3)
# random augments: shuffle speed
result = {
"data": data_motion, # (nsteps_frame, dim_motion)
"cond": data_speech, # (nsteps_frame, dim_speech)
# "shape": data_shape,
"vid": vid,
"nframe": nframe,
"frame_interval": [beg_frame, end_frame],
# "duration_interval": [beg_frame/nframe, end_frame/nframe]
}
assert data_speech.shape[0] == self.nsteps_segmt, f"data_speech shape={data_speech.shape}, vid={vid}"
return result
def make_auguments_flip(self, data_motion, data_speech, p=0.5):
'''
parameters:
data_motion: (nsteps_motion, 53)
data_speech: (nsteps_speech, ), where nsteps_speech!= nsteps_motion
'''
if random.random() < p:
data_motion = data_motion[::-1].copy()
data_speech = data_speech[::-1].copy()
return data_motion, data_speech
+16 -17
View File
@@ -195,7 +195,6 @@ class Audio2MeshModel(Base):
return loss
def infer(self, batch_cond, path_audio, suffix=""):
self.eval()
self.cond = batch_cond.float().to(self.device) # (nsteps, dim_cond)
@@ -210,12 +209,12 @@ class Audio2MeshModel(Base):
path_save=Path(self.opt.OUTPUT_DIR),
suffix=suffix)
# save result
samples_pt = samples_pt.cpu().numpy()
path_save_npy = Path(self.opt.OUTPUT_DIR).joinpath(f"{suffix}.npy")
np.save(path_save_npy, samples_pt)
print(f"save infer_result shape = {samples_pt.shape} -> {path_save_npy}")
# # save result
# samples_pt = samples_pt.cpu().numpy()
# path_save_npy = Path(self.opt.OUTPUT_DIR).joinpath(f"{suffix}.npy")
# np.save(path_save_npy, samples_pt)
# print(f"save infer_result shape = {samples_pt.shape} -> {path_save_npy}")
def testing(self, batch_input, cur_epoch=0, cur_batch=0):
self.eval() # set eval model
@@ -307,7 +306,7 @@ class Audio2MeshModel(Base):
return loss_stack
def eval_losses(self, batch_pdt_geo, batch_tgt):
def eval_losses_active(self, batch_pdt_geo, batch_tgt):
""" Computes the VAE loss function.
pramas:
batch_tgt, (nbatch, seqlen, dim_motion)
@@ -378,8 +377,7 @@ class Audio2MeshModel(Base):
return loss, loss_dict
def eval_losses_old(self, batch_pdt_geo, batch_tgt):
def eval_losses(self, batch_pdt_geo, batch_tgt):
""" Computes the VAE loss function.
pramas:
batch_tgt, (nbatch, seqlen, dim_motion)
@@ -394,23 +392,24 @@ class Audio2MeshModel(Base):
# synthesis geo rec
loss = 0
loss_rec_geo = self.loss_func_wing(batch_pdt_geo, batch_tgt_geo)
loss_dict["loss_rec_geo"] = loss_rec_geo.detach()
loss_dict["loss_rec_geo"] = loss_rec_geo.mean().detach()
loss_rec_geo2 = self.loss_func_wing(batch_pdt_geo, batch_tgt_geo, weight=self.vertices_weight)
loss_dict["loss_rec_geo_w"] = loss_rec_geo2.detach()
loss += loss_rec_geo2 * self.opt.LOSS.lambda_rec_geo
loss_dict["loss_rec_geo_w"] = loss_rec_geo2.mean().detach()
# loss += loss_rec_geo.mean() * self.opt.LOSS.lambda_rec_geo
loss += loss_rec_geo2.mean() * self.opt.LOSS.lambda_rec_geo
# synthesis geo volocity
diff_pdt_geo = batch_pdt_geo[:, 1:, :] - batch_pdt_geo[:, :-1, :]
diff_tgt_geo = batch_tgt_geo[:, 1:, :] - batch_tgt_geo[:, :-1, :]
loss_vel_geo = self.loss_func_wing(diff_pdt_geo, diff_tgt_geo)
loss_dict["loss_vel_geo"] = loss_vel_geo.detach()
loss_dict["loss_vel_geo"] = loss_vel_geo.mean().detach()
loss_vel_geo2 = self.loss_func_wing(diff_pdt_geo, diff_tgt_geo, weight=self.vertices_weight)
loss_dict["loss_vel_geo_w"] = loss_vel_geo2.detach()
loss += loss_vel_geo2 * self.opt.LOSS.lambda_vel_geo
loss_dict["loss_vel_geo_w"] = loss_vel_geo2.mean().detach()
# loss += loss_vel_geo.mean() * self.opt.LOSS.lambda_vel_geo
loss += loss_vel_geo2.mean() * self.opt.LOSS.lambda_vel_geo
# total loss
loss_dict['loss_all'] = loss.detach()
+577
View File
@@ -0,0 +1,577 @@
import sys
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
from pathlib import Path
from src.models.info import flame_mouth_idx
from src.models import init_net
from src.models.base import Base
from src.optims import get_optimizer, get_scheduler
# common
from common.animation import save_animation_with_gt2, save_images_with_audio
from common.debug import debug
from common.losses import WingLoss
# disentangle model
class Audio2MeshARModel(Base):
def __init__(self, opt, logger):
Base.__init__(self, opt, logger)
self.opt = opt
self.logger = logger
self.names_model = ["G"] # G
# define networks
self.netG = define_netG(opt)
init_net(self.netG, init_type='kaiming', gpu_ids=opt.GPUS)
# init last layer
init_exp_weight = np.load("/ssdata1/lsen/CODE/voca/training_data/init_expression_basis.npy")
init_exp_weight = torch.from_numpy(init_exp_weight).float().to(self.device)
init_exp_weight = init_exp_weight[:, :50]
self.netG.module.decoder_mesh.weight.data = init_exp_weight
print(f"init_exp_weight shape = {init_exp_weight.shape}")
# # print network parameters
# for name, param in self.netG.named_parameters():
# print(name, '\t\t', param.size())
# load mean lighting & shape
self.netR, self.flame = define_netR(device=self.device)
# self.netG.init_reconstruct_model(self.netR)
path_deca_mean = Path("./data/DECA_obama_mean.npy")
self.mean_dict = np.load(path_deca_mean, allow_pickle=True).item()
self.template_verts = self.get_template_vertices()
debug(opt, f"template_verts shape = {self.template_verts.shape}")
debug(opt, f"mean_dict keys = {self.mean_dict.keys()}", verbose=True)
# if filter outlier
# if self.opt.LOSS.filter_outlier:
self.loss_func_wing = WingLoss(reduction="none") # return (B, )
self.loss_func_l1 = nn.L1Loss(reduction="none")
if self.isTrain:
self.names_loss = opt.LOSS.names
# define optimizers
self.optimizer_G = get_optimizer(self.netG, opt)
self.optimizers.append(self.optimizer_G)
self.scheduler_G = get_scheduler(self.optimizer_G, opt)
self.schedulers.append(self.scheduler_G)
# define loss weight
self.vertices_weight = torch.ones((1, 1, self.opt.MODEL.num_vertices, 3)).to(self.device)
self.vertices_weight[:, :, flame_mouth_idx, :] = 10
if self.opt.DATASET.speech_extractor == "wav2vec":
from transformers import Wav2Vec2FeatureExtractor, Wav2Vec2Model
print("load Wav2Vec2Model ...")
MODEL_ID = "jonatasgrosman/wav2vec2-large-xlsr-53-chinese-zh-cn"
self.processor = Wav2Vec2FeatureExtractor.from_pretrained(MODEL_ID)
self.extractor = Wav2Vec2Model.from_pretrained(MODEL_ID).to(self.device)
def set_input(self, batch_input):
# motion data
y = batch_input["data"].float().to(self.device) # (B, nsteps, nc_motion)
self.batch_vid = batch_input['vid']
self.batch_nframe = batch_input['nframe']
self.batch_interv = batch_input['frame_interval']
self.B, self.nsteps = y.size(0), y.size(1)
debug(self.opt, f"data = {y.shape}, dtype={y.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
x = None
raw_speech = batch_input["cond"].numpy() # (B, nsegments)
debug(self.opt, f"raw_speech = {raw_speech.shape}, dtype={raw_speech.dtype}", verbose=False)
if self.opt.DATASET.speech_extractor == "wav2vec":
# raw_speech = raw_speech.reshape(self.B * self.nsteps, -1) # (B*nsteps, nsegments)
# debug(self.opt, f"raw_speech = {raw_speech.shape}, dtype={raw_speech.dtype}", verbose=False)
# padding half frame length for bed and end
npad = int(0.5 * self.opt.DATASET.sr * ( 1 / self.opt.DATASET.fps) + 0.5)
raw_speech = np.pad(raw_speech, pad_width=((0,0), (npad, npad)), mode="edge")
debug(self.opt, f"after padding raw_speech = {raw_speech.shape}, dtype={raw_speech.dtype}", verbose=False)
raw_speech = list(raw_speech)
inputs = self.processor(raw_speech, sampling_rate=16000, return_tensors="pt")
inputs = inputs.to(self.device)
with torch.no_grad():
output = self.extractor(**inputs)
x = output.last_hidden_state
# x = output.extract_features
else:
assert 0, "opt.DATASET.speech_extractor should be 'wav2vec | deepspeech | mfcc ' "
# B x nsteps x nc_feat
debug(self.opt, f"data = {y.shape}, dtype={y.dtype}, device={y.device}", verbose=False)
debug(self.opt, f"cond = {x.shape}, dtype={x.dtype}, device={x.device}", verbose=False)
# unfold speech data
x = x.unfold(dimension=1, size=16, step=1) # (nseqs, nc_motion, 16)
x = x.permute(0, 1, 3, 2) # (nseqs, 16, 53)
self.nsteps_align = x.size(1)
y = y[:, 7:7+self.nsteps_align] # B x nsteps x nc_motion
y = self.get_vertices(y) # B x nsteps x 5023 x 3
debug(self.opt, f"\n a data = {y.shape}, dtype={y.dtype}, device={y.device}", verbose=False)
debug(self.opt, f"a cond = {x.shape}, dtype={x.dtype}, device={x.device}", verbose=False)
# for autoregressive training
self.x = x # B x nseq x nwind x nc_condit
self.y_tgt = y # B x nseq x 5023 x 3
def training(self, batch_input):
self.train() # set train model
self.set_input(batch_input)
batch_x = self.x[:, 1:] # B x nsteps-1 x nwind x nc_condit
batch_y_tgt = self.y_tgt[:, 1:] # B x nsteps-1 x 5023 x 3
batch_y_pre = self.y_tgt[:, :-1] # B x nsteps-1 x 5023 x 3
batch_y_pdf = self.netG(batch_x, batch_y_pre) # B x nsteps-1 x 5023 x 3
batch_y_pdf += self.template_verts # B x nsteps-1 x 5023 x 3
debug(self.opt, f"traing batch_y_pdf = {batch_y_pdf.shape}, batch_y_tgt = {batch_y_tgt.shape}", verbose=False)
# loss
loss, self.loss_dict = self.eval_losses(batch_y_pdf, batch_y_tgt)
# backward
self.optimizer_G.zero_grad()
loss.backward()
if self.opt.TRAIN.grad_clip_norm: # operate grad
torch.nn.utils.clip_grad_value_(self.netG.parameters(), self.opt.TRAIN.max_grad_clip)
torch.nn.utils.clip_grad_norm_(self.netG.parameters(), self.opt.TRAIN.max_grad_norm)
self.optimizer_G.step()
return loss
def validation(self, batch_input):
self.eval() # set eval model
self.set_input(batch_input)
with torch.no_grad():
batch_x = self.x[:, 1:] # B x nsteps-1 x nwind x nc_condit
batch_y_tgt = self.y_tgt[:, 1:] # B x nsteps-1 x 5023 x 3
batch_y_pre = self.y_tgt[:, :-1] # B x nsteps-1 x 5023 x 3
batch_y_pdf = self.netG(batch_x, batch_y_pre) # B x nsteps-1 x 5023 x 3
batch_y_pdf += self.template_verts # B x nsteps-1 x 5023 x 3
loss, self.loss_dict = self.eval_losses(batch_y_pdf, batch_y_tgt)
return loss
def infer(self, batch_cond, path_audio, suffix=""):
self.eval()
x = batch_cond.float().to(self.device) # B x nsteps x nwind x nc_condit
B, nsteps, *_ = x.shape
with torch.no_grad():
# prepare batch_y_pdf
batch_y_pdf = torch.zeros(B, nsteps, self.template_verts.shape[-2], 3) # B x nsteps x 5023 x 3
ibatch_y_pre = self.template_verts.expand(B, -1, -1, -1) # B x 1 x 5023 x 3
for istep in range(nsteps):
ibatch_x = x[:, istep:istep+1] # B x 1 x nwind x nc_condit
ibatch_y_pdt = self.netG(ibatch_x, ibatch_y_pre) # B x 1 x 5023 x 3
ibatch_y_pdt += self.template_verts # B x 1 x 5023 x 3
ibatch_y_pre = ibatch_y_pdt[:] # update ibatch_y_pre
batch_y_pdf[:, istep] = ibatch_y_pdt.cpu().detach()[:, -1] # update y_tgt
print(f"testing pt shape = {batch_y_pdf.shape}, x shape = {x.shape}")
self.save_reconstruct(batch_y_pdf, path_audio, path_save=Path(self.opt.OUTPUT_DIR), suffix=suffix)
# save result
samples_pt = samples_pt.numpy()
path_save_npy = Path(self.opt.OUTPUT_DIR).joinpath(f"{suffix}.npy")
np.save(path_save_npy, samples_pt)
print(f"save infer_result shape = {samples_pt.shape} -> {path_save_npy}")
def testing(self, batch_input, cur_epoch=0, cur_batch=0):
self.eval() # set eval model
self.set_input(batch_input)
B, nsteps, *_ = self.x.shape
with torch.no_grad():
batch_y_pdf = torch.zeros_like(self.y_tgt) # B x nsteps x 5023 x 3
# batch_y_pdf[:, 0] = self.y_tgt[:, 0] # init first GT as PT
batch_y_pdf[:, 0] = self.template_verts.expand(B, -1, -1, -1) # init first GT as PT
# ibatch_y_pre = self.y_tgt[:, 0] # B x 1 x 5023 x 3
ibatch_y_pre = self.template_verts.expand(B, -1, -1, -1) # B x 1 x 5023 x 3
for istep in range(1, self.nsteps_align):
ibatch_x = self.x[:, istep:istep+1] # B x 1 x nwind x nc_condit
ibatch_y_pdt = self.netG(ibatch_x, ibatch_y_pre) # B x 1 x 5023 x 3
ibatch_y_pdt += self.template_verts # B x 1 x 5023 x 3
ibatch_y_pre = ibatch_y_pdt[:] # update ibatch_y_pre
batch_y_pdf[:, istep] = ibatch_y_pdt[:, -1] # update y_tgt
# samples_gt = samples_gt.cpu().numpy() # B x N x 5023 x 3
print(f"testing pt shape = {batch_y_pdf.shape}, gt shape = {self.y_tgt.shape}")
self.save_reconstruct_with_gt(batch_y_pdf, self.y_tgt,
path_save=Path(self.opt.OUTPUT_DIR),
suffix=f'sampled_{cur_epoch:05d}_{cur_batch:03d}')
def get_template_vertices(self, mean_dict=None):
if mean_dict is not None:
pass
else:
batch_shape = torch.zeros(1, 100).to(self.device)
batch_exp = torch.zeros(1, 50).to(self.device)
batch_pos = torch.zeros(1, 6).to(self.device)
verts, _, _ = self.netR.get_vertices(batch_shape, batch_exp, batch_pos) # 1 x 5023 x 3
verts = verts.unsqueeze(dim=0) # 1 x 1 x 5023 x 3
print(f"template verts reshape = {verts.shape}")
return verts
def get_vertices(self, batch_motion):
"""
batch_motion, (nbatch, seqlen, 53)
"""
batch_exp = batch_motion[..., :50]
batch_pos = batch_motion[..., 50:]
nbatch, seqlen = batch_exp.size(0), batch_exp.size(1)
batch_exp = batch_exp.reshape(nbatch * seqlen, -1) # nbatch * seqlen x 50
batch_pos = batch_pos.reshape(nbatch * seqlen, -1) # nbatch * seqlen x 3
batch_shape= torch.zeros(nbatch * seqlen, 100).to(self.device) # nbatch * seqlen x 50
batch_pose = torch.zeros(nbatch * seqlen, 6).to(self.device) # nbatch * seqlen x 6
batch_pose[:, 3:6] = batch_pos
verts, _, _ = self.netR.get_vertices(batch_shape, batch_exp, batch_pose) # nbatch * seqlen x 5023 x 3
verts = verts.reshape(nbatch, seqlen, -1, 3) # nbatch x seqlen x 5023 x 3
# print(f"verts reshape = {verts.shape}")
return verts
def eval_losses_for_infer_loss(self, batch_pdt_geo, batch_tgt_geo):
""" Computes the VAE loss function.
pramas:
batch_tgt_geo, (nbatch, seqlen, num_vertices, 3)
batch_pdt_geo, (nbatch, seqlen, num_vertices, 3)
"""
# synthesis geo rec
loss_rec_geo = self.loss_func_wing(batch_pdt_geo, batch_tgt_geo) # B x nsteps x num_vertices x 3
loss_rec_geo = loss_rec_geo.sum(dim=(2, 3)) / (3 * self.opt.MODEL.num_vertices) # B x nsteps
loss_rec_geo = loss_rec_geo.detach()
# synthesis geo volocity
diff_pdt_geo = batch_pdt_geo[:, 1:, :] - batch_pdt_geo[:, :-1, :]
diff_tgt_geo = batch_tgt_geo[:, 1:, :] - batch_tgt_geo[:, :-1, :]
loss_vel_geo1 = self.loss_func_wing(diff_pdt_geo, diff_tgt_geo) # B x nsteps-1
loss_vel_geo1 = loss_vel_geo1.sum(dim=(2, 3)) / (3 * self.opt.MODEL.num_vertices) # B x nsteps-1
loss_vel_geo1 = F.pad(loss_vel_geo1, pad=(0, 1), mode="replicate").detach() # B x nsteps
diff_pdt_geo = batch_pdt_geo[:, 2:, :] - batch_pdt_geo[:, :-2, :]
diff_tgt_geo = batch_tgt_geo[:, 2:, :] - batch_tgt_geo[:, :-2, :]
loss_vel_geo2 = self.loss_func_wing(diff_pdt_geo, diff_tgt_geo) # B x nsteps-2
loss_vel_geo2 = loss_vel_geo2.sum(dim=(2, 3)) / (3 * self.opt.MODEL.num_vertices) # B x nsteps-2
loss_vel_geo2 = F.pad(loss_vel_geo2, pad=(0, 2), mode="replicate").detach() # B x nsteps
# stack among these losses
loss_stack = torch.stack([loss_rec_geo, loss_vel_geo1, loss_vel_geo2], dim=2) # B x nsteps x 3
return loss_stack
def eval_losses_active(self, batch_pdt_geo, batch_tgt_geo):
""" Computes the VAE loss function.
pramas:
batch_tgt_geo, (nbatch, seqlen, num_vertices, 3)
batch_pdt_geo, (nbatch, seqlen, num_vertices, 3)
"""
loss = 0
loss_dict = {}
# B = batch_pdt_geo.size(0)
# print(f"batch_pdt_geo = {batch_pdt_geo.shape}, batch_tgt_geo = {batch_tgt_geo.shape}, B = {B}")
# synthesis geo rec
loss = 0
loss_rec_geo = self.loss_func_wing(batch_pdt_geo, batch_tgt_geo) # B
loss_dict["loss_rec_geo"] = loss_rec_geo.mean().detach()
loss_rec_geo = self.loss_func_l1(batch_pdt_geo, batch_tgt_geo) # B
loss_dict["loss_rec_geo_l1"] = loss_rec_geo.mean().detach()
loss_rec_geo2 = self.loss_func_wing(batch_pdt_geo, batch_tgt_geo, weight=self.vertices_weight) # B x nsteps x num_vertices x 3
loss_rec_geo2 = loss_rec_geo2.sum(dim=(2, 3)) / (3 * self.opt.MODEL.num_vertices) # B x nsteps
# filter outliar
threshold_rec, mean_rec = torch.quantile(loss_rec_geo2, q=0.75) * 1.5, torch.quantile(loss_rec_geo2, q=0.5)
b_outlier_rec = loss_rec_geo2 > threshold_rec # B x nsteps
# print(f"threshold_rec = {threshold_rec.shape}")
# synthesis geo volocity
diff_pdt_geo = batch_pdt_geo[:, 1:, :] - batch_pdt_geo[:, :-1, :]
diff_tgt_geo = batch_tgt_geo[:, 1:, :] - batch_tgt_geo[:, :-1, :]
loss_vel_geo = self.loss_func_wing(diff_pdt_geo, diff_tgt_geo) # 1,
loss_dict["loss_vel_geo"] = loss_vel_geo.mean().detach()
loss_vel_geo = self.loss_func_l1(diff_pdt_geo, diff_tgt_geo) # 1,
loss_dict["loss_vel_geo_l1"] = loss_vel_geo.mean().detach()
loss_vel_geo2 = self.loss_func_wing(diff_pdt_geo, diff_tgt_geo, weight=self.vertices_weight) # B x nsteps x num_vertices x 3
loss_vel_geo2 = loss_vel_geo2.sum(dim=(2, 3)) / (3 * self.opt.MODEL.num_vertices) # B x nsteps
# filter outliar
threshold_vel, mean_vel = torch.quantile(loss_vel_geo2, q=0.75) * 1.5, torch.quantile(loss_vel_geo2, q=0.5)
b_outlier_vel = loss_vel_geo2 > threshold_vel # B x (nsteps-1)
# print(f"threshold_vel = {threshold_vel.shape}")
# find outliar in both loss data
b_outlier_rec[:, :-1] = b_outlier_rec[:, :-1] & b_outlier_vel[:, :]
if torch.any(b_outlier_rec):
# print(f"b_outlier_rec = {b_outlier_rec}")
# print(f"outerliar size= {loss_rec_geo2[b_outlier_rec].shape} / {loss_rec_geo2.numel()} ")
loss_rec_geo2[b_outlier_rec] = mean_rec
loss_vel_geo2[b_outlier_rec[:, :-1]] = mean_vel
# calculate again
loss_rec_geo2 = loss_rec_geo2.mean()
loss_dict["loss_rec_geo_w"] = loss_rec_geo2.detach()
loss += loss_rec_geo2 * self.opt.LOSS.lambda_rec_geo
loss_vel_geo2 = loss_vel_geo2.mean()
loss_dict["loss_vel_geo_w"] = loss_vel_geo2.detach()
loss += loss_vel_geo2 * self.opt.LOSS.lambda_vel_geo
# total loss
loss_dict['loss_all'] = loss.detach()
return loss, loss_dict
def eval_losses(self, batch_pdt_geo, batch_tgt_geo):
""" Computes the VAE loss function.
pramas:
batch_tgt_geo, (nbatch, seqlen, num_vertices, 3)
batch_pdt_geo, (nbatch, seqlen, num_vertices, 3)
"""
loss = 0
loss_dict = {}
# synthesis geo rec
loss_rec_geo = self.loss_func_wing(batch_pdt_geo, batch_tgt_geo)
loss_dict["loss_rec_geo"] = loss_rec_geo.mean().detach()
loss_rec_geo2 = self.loss_func_wing(batch_pdt_geo, batch_tgt_geo, weight=self.vertices_weight)
loss_dict["loss_rec_geo_w"] = loss_rec_geo2.mean().detach()
loss += loss_rec_geo.mean() * self.opt.LOSS.lambda_rec_geo
# loss += loss_rec_geo2.mean() * self.opt.LOSS.lambda_rec_geo
# synthesis geo volocity
diff_pdt_geo = batch_pdt_geo[:, 1:, :] - batch_pdt_geo[:, :-1, :]
diff_tgt_geo = batch_tgt_geo[:, 1:, :] - batch_tgt_geo[:, :-1, :]
loss_vel_geo = self.loss_func_wing(diff_pdt_geo, diff_tgt_geo)
loss_dict["loss_vel_geo"] = loss_vel_geo.mean().detach()
loss_vel_geo2 = self.loss_func_wing(diff_pdt_geo, diff_tgt_geo, weight=self.vertices_weight)
loss_dict["loss_vel_geo_w"] = loss_vel_geo2.mean().detach()
if self.opt.LOSS.lambda_vel_geo > 0:
loss += loss_vel_geo.mean() * self.opt.LOSS.lambda_vel_geo
# loss += loss_vel_geo2.mean() * self.opt.LOSS.lambda_vel_geo
# total loss
loss_dict['loss_all'] = loss.detach()
return loss, loss_dict
def save_reconstruct(self, samples_pt, path_audio, path_save, suffix=""):
# samples_pt, [B x N x dim_motion]
B, N, *_ = samples_pt.shape
nbatch_render = 10
# for each batch
for i in range(B):
igeo_pt = samples_pt[i, ...]
ipath_save = path_save.joinpath(f"{suffix}_{i:02d}.mp4")
v_render_pt = []
for k in range(0, N, nbatch_render):
# split
kgeo_pt = igeo_pt[k:k+nbatch_render, ...] # [nbatch_real x 5023 x 3]
nbatch_real = kgeo_pt.size(0)
# cam
cam = torch.tensor([5, 0, 0], device=self.device) # (1, 3)
cam = cam.repeat(nbatch_real, 1) # (nbatch_real, 3)
# print(f"cam shape = {cam.shape}")
# render
render_pt = self.netR.render_geometry(kgeo_pt, cam, self.device) # (nbatch_real, 3, 512, 512)
# print(f"render_pt ={render_pt.shape}, render_gt={render_gt.shape}")
# append each frame
for m in range(nbatch_real):
v_render_pt.append(tensor2image(render_pt[m, ...]))
# save animation
# print(f"testing v_render_pt = {len(v_render_pt)}")
save_images_with_audio(v_render_pt, path_audio, ipath_save)
def save_reconstruct_with_gt(self, samples_pt, samples_gt, path_save, suffix=""):
# samples_pt, [B x N x 5023 x 3]
# samples_gt, [B x N x 5023 x 3]
B, N, *_ = samples_pt.shape
nbatch_render = 10
# for each batch
for i in range(B):
igeo_pt = samples_pt[i, ...] # [N x 5023 x 3]
igeo_gt = samples_gt[i, ...] # [N x 5023 x 3]
ipath_save = path_save.joinpath(f"{suffix}_{i:02d}.mp4")
v_render_pt = []
v_render_gt = []
for k in range(0, N, nbatch_render):
# split
kgeo_pt = igeo_pt[k:k+nbatch_render, ...] # [nbatch_real x 5023 x 3]
kgeo_gt = igeo_gt[k:k+nbatch_render, ...] # [nbatch_real x 5023 x 3]
nbatch_real = kgeo_pt.size(0)
# cam
cam = torch.tensor([5, 0, 0], device=self.device) # (1, 3)
cam = cam.repeat(nbatch_real, 1) # (nbatch_real, 3)
# print(f"cam shape = {cam.shape}")
# render
render_pt = self.netR.render_geometry(kgeo_pt, cam, self.device) # (nbatch_real, 3, 512, 512)
render_gt = self.netR.render_geometry(kgeo_gt, cam, self.device) # (nbatch_real, 3, 512, 512)
# print(f"render_pt ={render_pt.shape}, render_gt={render_gt.shape}")
# append each frame
for m in range(nbatch_real):
v_render_pt.append(tensor2image(render_pt[m, ...]))
v_render_gt.append(tensor2image(render_gt[m, ...]))
# get audio
jvid = self.batch_vid[i]
jnframe = self.batch_nframe[i].numpy()
jstart_frame = self.batch_interv[0][i].numpy()
jpath_audio = f"{self.opt.DATASET.root_raw}/{jvid}/audio/audio_trim.wav"
jstart_time = (jstart_frame + 7) / self.opt.DATASET.fps # xxx.yyy min
jend_time = (jstart_frame + 7 + self.nsteps_align) / self.opt.DATASET.fps # xxx.yyy min
# print(f"jvid={jvid}, jnfram={jnframe}, jstart_frame={jstart_frame}, jpath_audio={jpath_audio}")
# print(f"jstart_time={jstart_time}, jend_time={jend_time}")
# save animation
# print(f"testing v_render_pt = {len(v_render_pt)}, gt shape = {len(v_render_gt)}")
save_animation_with_gt2(v_render_pt, v_render_gt, ipath_save, fps=self.opt.DATASET.fps,\
path_audio=jpath_audio, start_time=jstart_time, end_time=jend_time)
#########################################
def tensor2image(tensor):
image = tensor.detach().cpu().numpy()
image = image*255.
image = np.maximum(np.minimum(image, 255), 0)
image = image.transpose(1,2,0)[:,:,[2,1,0]]
return image.astype(np.uint8).copy()
def define_netG(opt):
netG = None
if opt.MODEL.name_netG == "audio2mesh_ar":
from src.nn.audio2mesh_ar import Audio2Mesh
netG = Audio2Mesh(opt)
elif opt.MODEL.name_netG == "audio2mesh_voca":
from src.nn.audio2mesh_voca import Audio2Mesh
netG = Audio2Mesh(opt)
elif opt.MODEL.name_netG == "audio2mesh_resnet":
from src.nn.audio2mesh_resnet import Audio2Mesh
netG = Audio2Mesh(opt)
else:
raise NameError(f"The model of opt.MODEL.name_netAE(={opt.MODEL.name_netG}) not existing!")
# to GPU
netG.to(f"cuda:{opt.GPUS[0]}")
netG = torch.nn.DataParallel(netG, opt.GPUS) # multi-GPUs
return netG
def define_netR(device):
# import
from src.nn.FLAME import FLAME
sys.path.insert(0, "/ssdata1/lsen/CODE/DECA_old")
from decalib.deca import DECA
from decalib.utils import util
from decalib.utils.config import cfg as deca_cfg
# use device
# device = "cuda:2"
# whether to use FLAME texture model to generate uv texture map
deca_cfg.model.use_tex = False
deca_cfg.dataset.image_size = 512
# reconstruction model
netR = DECA(config = deca_cfg, device=device)
# flame model
flame = FLAME(deca_cfg.model).to(device)
return netR, flame
-1
View File
@@ -251,7 +251,6 @@ class Audio2MeshSpecificModel(Base):
else:
batch_shape = torch.zeros(1, 100).to(self.device)
verts, _, _ = self.netR.get_vertices(batch_shape, batch_exp, batch_pos) # 1 x 5023 x 3
verts = verts.unsqueeze(dim=0) # 1 x 1 x 5023 x 3
print(f"template verts reshape = {verts.shape}")
+2 -1
View File
@@ -46,7 +46,8 @@ class Audio2Mesh(nn.Module):
nn.Flatten(), # 64,
nn.Linear(in_features=128, out_features=2048), # 128,
nn.Linear(in_features=128, out_features=2048),
# nn.Dropout(0.3), # 128,
nn.Tanh(),
nn.Linear(in_features=2048, out_features=50) # 50,
+107
View File
@@ -0,0 +1,107 @@
from tkinter.tix import Y_REGION
import torch
import torch.nn as nn
from common.debug import debug
class Audio2Mesh(nn.Module):
def __init__(self, opt):
super(Audio2Mesh, self).__init__()
self.opt = opt
self.num_vertices = opt.MODEL.num_vertices
self.nc_motion = 3 * self.num_vertices # 3 * 5023
self.dim_cond = opt.MODEL.dim_speech # 1024
# encoder
self.encoder_x = nn.Sequential( # (nbatch, nchannel=1024, H=16, W=1)
nn.BatchNorm2d(self.dim_cond),
# block 1
nn.Conv2d(self.dim_cond, 512, kernel_size=(3,1), stride=(2,1), padding=(1,0), bias=True), # 32 x 8 x 1
nn.LeakyReLU(0.02, True),
nn.Conv2d(512, 512, kernel_size=(3,1), stride=(1,1), padding=(1,0), bias=True), # 32 x 8 x 1
nn.LeakyReLU(0.02, True),
nn.Conv2d(512, 512, kernel_size=(3,1), stride=(2,1), padding=(1,0), bias=True), # 32 x 4 x 1
nn.LeakyReLU(0.02, True),
nn.Conv2d(512, 512, kernel_size=(3,1), stride=(1,1), padding=(1,0), bias=True), # 32 x 8 x 1
nn.LeakyReLU(0.02, True),
nn.Conv2d(512, 256, kernel_size=(3,1), stride=(2,1), padding=(1,0), bias=True), # 64 x 2 x 1
nn.LeakyReLU(0.02, True),
nn.Conv2d(256, 256, kernel_size=(3,1), stride=(1,1), padding=(1,0), bias=True), # 32 x 8 x 1
nn.LeakyReLU(0.02, True),
nn.Conv2d(256, 256, kernel_size=(3,1), stride=(2,1), padding=(1,0), bias=True), # 64 x 1 x 1
nn.LeakyReLU(0.02, True),
nn.Conv2d(256, 256, kernel_size=(3,1), stride=(1,1), padding=(1,0), bias=True), # 32 x 8 x 1
nn.LeakyReLU(0.02, True),
nn.Conv2d(256, 128, kernel_size=(3,1), stride=(2,1), padding=(1,0), bias=True), # 64 x 1 x 1
nn.LeakyReLU(0.02, True),
nn.Flatten(), # 64,
)
self.encoder_y = nn.Sequential( # (nbatch x seqlen x nc_motion)
nn.Linear(in_features=self.nc_motion, out_features=256),
nn.LeakyReLU(0.02, True),
nn.Linear(in_features=256, out_features=128),
nn.Tanh(),
)
self.fusion_net = nn.Sequential(
nn.Linear(in_features=256, out_features=2048),
# nn.Dropout(0.3), # 128,
nn.Tanh(),
nn.Linear(in_features=2048, out_features=50) # 50,
)
# output FLAME mesh
self.decoder_mesh = nn.Linear(in_features=50, out_features=self.nc_motion)
def forward(self, x, y_prev):
""" forward function
Args:
x: [nbatch x seqlen x nwind x nc_condit]
y_prev: [nbatch x seqlen x nc_motion]
return:
y: [nbatch x seqlen x nc_motion]
"""
(nbatch, nseqlen, nwind, nfeat) = x.shape # (B, nseq, 16, 29)
debug(self.opt, f"[forward] input x shape = {x.shape}", verbose=False)
# preprocessing data
y_prev = y_prev.reshape(nbatch * nseqlen, -1) # (B * nseq, nc_motion)
x = x.reshape(nbatch * nseqlen, 1, nwind, nfeat) # (B * nseq, 1, 16, 29)
x = torch.transpose(x, 1, 3) # (B * nseq, 29, 16, 1)
debug(self.opt, f"[forward] transpose x shape = {x.shape}", verbose=False)
feat_x = self.encoder_x(x) # (B * nseq, 128)
feat_y = self.encoder_y(y_prev) # (B * nseq, 128)
feat = torch.cat([feat_x, feat_y], dim=1) # (B * nseq, 256)
debug(self.opt, f"[forward] feat_x = {feat_x.shape}, feat_y = {feat_y.shape}, feat = {feat.shape}, ", verbose=False)
feat = self.fusion_net(feat) # (B * nseq, 50)
debug(self.opt, f"[forward] fusion feat = {feat.shape}, ", verbose=False)
# predict FLAME mesh
pred_vert = self.decoder_mesh(feat) # (B * nseq, nc_motion)
debug(self.opt, f"[forward] decoder mesh shape = {pred_vert.shape}", verbose=False)
pred_vert = pred_vert.reshape(nbatch, nseqlen, self.num_vertices, 3) # (B, nseq, num_vertices, 3)
debug(self.opt, f"[forward] reshape shape = {pred_vert.shape}", verbose=False)
return pred_vert