Happy new years

This commit is contained in:
Sen Liang committed 2022-02-07 17:28:40 +08:00
1 parent c7175dd7ff
commit 8c4865effb
53 files changed
+4604 -61

No files matched your search

+13 -10
View File
@@ -71,13 +71,13 @@ config.MODEL.dim_motion = 0
config.MODEL.dim_speech = 0
config.MODEL.dim_hidden = 0
config.MODEL.n_lookprevs_motion = 3
config.MODEL.n_lookprevs_speech = 3
config.MODEL.n_lookprevs_motion = 0
config.MODEL.n_lookprevs_speech = 0
config.MODEL.n_lookahead_motion = 7
config.MODEL.n_lookahead_speech = 7
config.MODEL.n_lookahead_motion = 0
config.MODEL.n_lookahead_speech = 0
config.MODEL.n_layer_lstm = 2
config.MODEL.n_layer_lstm = 0
# # for wavenet
@@ -120,6 +120,8 @@ config.MODEL.n_layer_lstm = 2
##########################
# dataset related params
config.DATASET = edict()
config.DATASET.fps = 30
config.DATASET.sr = 16000
config.DATASET.name = 'ravdess'
config.DATASET.type = '' # "clips" | "frame" | "none"
config.DATASET.root = "../data/"
@@ -128,7 +130,7 @@ config.DATASET.root = "../data/"
config.DATASET.nwind_second_train = 0
config.DATASET.nwind_second_valid = 0
config.DATASET.nwind_second_test = 0
config.DATASET.speech_extractor = ''
# for data smooth
config.DATASET.filter = '' # "gaussian" | "savgol"
@@ -189,11 +191,12 @@ config.TRAIN.gamma2 = 0.0
# loss related params
config.LOSS = edict()
config.LOSS.names = ["all", "L1"]
config.LOSS.lambda_rec = 1
config.LOSS.lambda_kld = 0
config.LOSS.lambda_dif = 0
config.LOSS.lambda_cyc = 0
config.LOSS.lambda_trp = 0
config.LOSS.lambda_rec_exp = 0
config.LOSS.lambda_rec_pos = 0
config.LOSS.lambda_vol_exp = 0
config.LOSS.lambda_vol_pos = 0
config.LOSS.lambda_geo = 0
config.LOSS.lambda_rec_smooth = 0
config.LOSS.lambda_geo_smooth = 0
+115
View File
@@ -0,0 +1,115 @@
import numpy as np
import torch
import time
from torch.utils.data import Dataset
from pathlib import Path
from scipy.signal import savgol_filter
from common.debug import debug
class MotionLiveDataset(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(MotionLiveDataset, 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.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
elif self.phase == "valid":
return 1000
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]
# random select idx
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 = 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, )
# 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)
"vid": vid,
"nframe": nframe,
"frame_interval": [beg_frame, end_frame],
# "duration_interval": [beg_frame/nframe, end_frame/nframe]
}
return result
+9 -4
View File
@@ -178,7 +178,7 @@ class Base():
return visual_ret
def get_current_losses(self):
def get_current_losses(self, phase=None):
"""Return traning losses / errors.
train.py will print out these errors on console, and save them to a file"""
@@ -186,8 +186,13 @@ class Base():
for name in self.names_loss:
# print(f"name = ",name)
# errors_ret[name] = self.loss_dict["loss_" + name ].detach().float().cpu() # float(...) works for both scalar tensor and float number
errors_ret[name] = self.loss_dict["loss_" + name ].float().cpu() # float(...) works for both scalar tensor and float number
# errors_ret[name] = self.loss_dict["loss_" + name ].float().cpu() # float(...) works for both scalar tensor and float number
if phase == "valid":
errors_ret[name+"_val"] = self.loss_dict["loss_" + name ].float().cpu() # float(...) works for both scalar tensor and float number
else:
errors_ret[name] = self.loss_dict["loss_" + name ].float().cpu()
return errors_ret
def save_networks(self, epoch):
@@ -278,7 +283,7 @@ class Base():
if load_info:
# load training state
path_state = load_path.joinpath("checkpoints", f'{load_suffix}_net_train_state.pth')
load_state = torch.load(str(path_state))
load_state = torch.load(str(path_state), map_location=str(self.device))
for name in self.names_model:
optimizer_ = getattr(self, 'optimizer_' + name)
+6 -4
View File
@@ -53,11 +53,10 @@ class Audio2motionModel(Base):
self.mean_dict = np.load(path_deca_mean, allow_pickle=True).item()
print(self.mean_dict.keys())
def set_input(self, batch_input):
self.data = batch_input["data"].float().to(self.device) # (nsteps, dim_data)
self.cond = batch_input["cond"].float().to(self.device) # (nsteps, dim_cond)
self.data = batch_input["data"].float().to(self.device) # (B, nsteps, dim_data)
self.cond = batch_input["cond"].float().to(self.device) # (B, nsteps, dim_cond)
self.B = self.data.size(0)
debug(self.opt, f"data = {self.data.shape}, cond = {self.cond.shape}, dtype={self.data.dtype}", verbose=False)
@@ -254,7 +253,7 @@ class Audio2motionModel(Base):
# save animation
# print(f"testing v_render_pt = {len(v_render_pt)}, gt shape = {len(v_render_gt)}")
save_animation_with_gt2(v_render_pt, v_render_gt, jpath_save)
save_animation_with_gt2(v_render_pt, v_render_gt, jpath_save, fps=self.opt.DATASET.fps)
@@ -290,6 +289,9 @@ def define_netG(opt):
from src.nn.audio2motion import Audio2Motion
netG = Audio2Motion(opt)
elif opt.MODEL.name_netG == "audio2motion2":
from src.nn.audio2motion2 import Audio2Motion2
netG = Audio2Motion2(opt)
else:
raise NameError(f"The model of opt.MODEL.name_netAE(={opt.MODEL.name_netG}) not existing!")
+375
View File
@@ -0,0 +1,375 @@
import sys
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
from pathlib import Path
from src.models import init_net
from src.models.base import Base
from src.optims import get_optimizer, get_scheduler
# common
from common.animation import save_animation_with_gt2, save_images_with_audio
from common.debug import debug
from common.losses import WingLoss
# disentangle model
class Audio2motionLiveModel(Base):
def __init__(self, opt, logger):
Base.__init__(self, opt, logger)
self.opt = opt
self.logger = logger
self.names_model = ["G"] # G
# define networks
self.netG = define_netG(opt)
self.netG.to()
self.netG = torch.nn.DataParallel(self.netG, opt.GPUS) # multi-GPUs
init_net(self.netG, init_type='kaiming', gpu_ids=opt.GPUS)
self.loss_func_l1 = nn.L1Loss(reduction="mean")
self.loss_func_wing = WingLoss(reduction="mean")
if self.isTrain:
self.names_loss = opt.LOSS.names
# define optimizers
self.optimizer_G = get_optimizer(self.netG, opt)
self.optimizers.append(self.optimizer_G)
self.scheduler_G = get_scheduler(self.optimizer_G, opt)
self.schedulers.append(self.scheduler_G)
if self.opt.TRAIN.apply_testing or not self.isTrain:
# load mean lighting & shape
self.netR = define_netR(device=self.device)
# self.netG.init_reconstruct_model(self.netR)
path_deca_mean = Path("./data/DECA_obama_mean.npy")
self.mean_dict = np.load(path_deca_mean, allow_pickle=True).item()
print(self.mean_dict.keys())
if self.opt.DATASET.speech_extractor == "wav2vec":
from transformers import Wav2Vec2FeatureExtractor, Wav2Vec2Model
print("load Wav2Vec2Model ...")
MODEL_ID = "jonatasgrosman/wav2vec2-large-xlsr-53-chinese-zh-cn"
self.processor = Wav2Vec2FeatureExtractor.from_pretrained(MODEL_ID)
self.extractor = Wav2Vec2Model.from_pretrained(MODEL_ID).to(self.device)
def set_input(self, batch_input):
# motion data
self.data = batch_input["data"].float().to(self.device) # (B, nsteps, nc_motion)
self.B, self.nsteps = self.data.size(0), self.data.size(1)
debug(self.opt, f"data = {self.data.shape}, dtype={self.data.dtype}", verbose=False)
# speech data
raw_speech = batch_input["cond"].numpy() # (B, nsegments)
debug(self.opt, f"raw_speech = {raw_speech.shape}, dtype={raw_speech.dtype}", verbose=False)
if self.opt.DATASET.speech_extractor == "wav2vec":
# raw_speech = raw_speech.reshape(self.B * self.nsteps, -1) # (B*nsteps, nsegments)
# debug(self.opt, f"raw_speech = {raw_speech.shape}, dtype={raw_speech.dtype}", verbose=False)
# padding half frame length for bed and end
npad = int(0.5 * self.opt.DATASET.sr * ( 1 / self.opt.DATASET.fps) + 0.5)
raw_speech = np.pad(raw_speech, pad_width=((0,0), (npad, npad)), mode="edge")
debug(self.opt, f"after padding raw_speech = {raw_speech.shape}, dtype={raw_speech.dtype}", verbose=False)
raw_speech = list(raw_speech)
inputs = self.processor(raw_speech, sampling_rate=16000, return_tensors="pt")
inputs = inputs.to(self.device)
with torch.no_grad():
output = self.extractor(**inputs)
self.cond = output.last_hidden_state
# self.cond = output.extract_features
debug(self.opt, f"data = {self.data.shape}, dtype={self.data.dtype}, device={self.data.device}", verbose=False)
debug(self.opt, f"cond = {self.cond.shape}, dtype={self.cond.dtype}, device={self.cond.device}", verbose=False)
def training(self, batch_input):
self.train() # set train model
self.set_input(batch_input)
# forward
self.pred = self.netG(self.cond)
# loss
loss, self.loss_dict = self.eval_losses(self.pred, self.data)
# backward
self.optimizer_G.zero_grad()
loss.backward()
if self.opt.TRAIN.grad_clip_norm: # operate grad
torch.nn.utils.clip_grad_value_(self.netG.parameters(), self.opt.TRAIN.max_grad_clip)
torch.nn.utils.clip_grad_norm_(self.netG.parameters(), self.opt.TRAIN.max_grad_norm)
self.optimizer_G.step()
return loss
def validation(self, batch_input):
self.eval() # set eval model
self.set_input(batch_input)
with torch.no_grad():
self.pred = self.netG(self.cond)
loss, self.loss_dict = self.eval_losses(self.pred, self.data)
return loss
def infer(self, batch_cond, path_audio, suffix=""):
self.eval()
self.cond = batch_cond.float().to(self.device) # (nsteps, dim_cond)
with torch.no_grad():
samples_pt = self.netG(self.cond).cpu().numpy() # B x N x dim_motion
print(f"testing pt shape = {samples_pt.shape}")
self.save_reconstruct(samples_pt, path_audio,
path_save=Path(self.opt.OUTPUT_DIR),
suffix=suffix)
def testing(self, batch_input, cur_epoch=0, cur_batch=0):
self.eval() # set eval model
self.set_input(batch_input)
with torch.no_grad():
samples_pt = self.netG(self.cond).cpu().numpy() # B x N x dim_motion
samples_gt = self.data.cpu().numpy() # B x N x dim_motion
print(f"testing pt shape = {samples_pt.shape}, gt shape = {samples_gt.shape}")
self.save_reconstruct_with_gt(samples_pt, samples_gt,
path_save=Path(self.opt.OUTPUT_DIR),
suffix=f'sampled_{cur_epoch:05d}_{cur_batch:03d}')
def eval_losses(self, batch_pdt, batch_tgt):
""" Computes the VAE loss function.
pramas:
batch_pred, (nbatch, seqlen, dim_motion)
batch_targt, (nbatch, seqlen, dim_motion)
"""
loss = 0
loss_dict = {}
batch_pdt_exp = batch_pdt[..., :50]
batch_pdt_pos = batch_pdt[..., 50:]
batch_tgt_exp = batch_tgt[..., :50]
batch_tgt_pos = batch_tgt[..., 50:]
# rec loss
loss = 0
loss_rec_exp = self.loss_func_wing(batch_pdt_exp, batch_tgt_exp) / 50
loss_dict["loss_rec_exp"] = loss_rec_exp.detach()
loss_rec_pos = self.loss_func_wing(batch_pdt_pos, batch_tgt_pos) / 3
loss_dict["loss_rec_pos"] = loss_rec_pos.detach()
loss += loss_rec_exp * self.opt.LOSS.lambda_rec
loss += loss_rec_pos * self.opt.LOSS.lambda_rec * 10
# rec smooth
diff_pdt_exp = batch_pdt_exp[:, 1:, :] - batch_pdt_exp[:, :-1, :]
diff_tgt_exp = batch_tgt_exp[:, 1:, :] - batch_tgt_exp[:, :-1, :]
loss_vol_exp = self.loss_func_wing(diff_pdt_exp, diff_tgt_exp) / 50
loss_dict["loss_vol_exp"] = loss_vol_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_vol_pos = self.loss_func_wing(diff_pdt_pos, diff_tgt_pos) / 3
loss_dict["loss_vol_pos"] = loss_vol_pos.detach()
loss += loss_vol_exp * self.opt.LOSS.lambda_rec_smooth
loss += loss_vol_pos * self.opt.LOSS.lambda_rec_smooth * 10
# total loss
loss_dict['loss_all'] = loss.detach()
return loss, loss_dict
def save_reconstruct(self, samples_pt, path_audio, path_save, suffix=""):
# samples_pt, [B x N x dim_motion]
B, N, _ = samples_pt.shape
nbatch_render = 10
# for each batch
for j in range(B):
jcoeff_pt = samples_pt[j, :, :]
jpath_save = path_save.joinpath(f"{suffix}_{j:02d}.mp4")
v_render_pt = []
for k in range(0, N, nbatch_render):
jcodedict_pt = {}
jcodedict_pt["exp"] = jcoeff_pt[k:k+nbatch_render, :50] # (nbatch_render, 50)
nbatch_real = jcodedict_pt["exp"].shape[0]
# pose
jcodedict_pt["pose"] = np.repeat([self.mean_dict["pose"]], nbatch_real, axis=0) # (nbatch_render, 6)
jcodedict_pt["pose"][:, 3:6] = jcoeff_pt[k:k+nbatch_render, 50:53]
# others ==> to mean
mean_cam = [[5,0,0]] # or [self.mean_dict["cam"]]
jcodedict_pt["cam"] = np.repeat(mean_cam, nbatch_real, axis=0) # (nbatch_render, 3)
jcodedict_pt["light"] = np.repeat([self.mean_dict["light"]], nbatch_real, axis=0) # (nbatch_render, 9, 3)
jcodedict_pt["shape"] = np.repeat([self.mean_dict["shape"]], nbatch_real, axis=0) # (nbatch_render, 100)
jcodedict_pt["detail"] = np.repeat([self.mean_dict["detail"]], nbatch_real, axis=0) # (nbatch_render, 128)
_, visdict_pt = self.netR.decode_one(jcodedict_pt, nbatch_real, self.device)
render_pt = visdict_pt["shape_images"] # (nbatch_render, 3, 224, 224)
# print(f"render pt shape = {render_pt.shape}")
for m in range(nbatch_real):
# cv2.imwrite(str(kpath_image), util.tensor2image(render_image[m, ...]))
v_render_pt.append(tensor2image(render_pt[m, ...]))
# save animation
# print(f"testing v_render_pt = {len(v_render_pt)}")
save_images_with_audio(v_render_pt, path_audio, jpath_save)
def save_reconstruct_with_gt(self, samples_pt, samples_gt, path_save, suffix=""):
# samples_pt, [B x N x dim_motion]
# samples_gt, [B x N x dim_motion]
B, N, _ = samples_pt.shape
nbatch_render = 10
# for each batch
for j in range(B):
jcoeff_pt = samples_pt[j, :, :]
jcoeff_gt = samples_gt[j, :, :]
jpath_save = path_save.joinpath(f"{suffix}_{j:02d}.mp4")
v_render_pt = []
v_render_gt = []
for k in range(0, N, nbatch_render):
jcodedict_pt = {}
jcodedict_gt = {}
# exp
jcodedict_pt["exp"] = jcoeff_pt[k:k+nbatch_render, :50] # (nbatch_render, 50)
jcodedict_gt["exp"] = jcoeff_gt[k:k+nbatch_render, :50] # (nbatch_render, 50)
nbatch_real = jcodedict_pt["exp"].shape[0]
# pose
jcodedict_pt["pose"] = np.repeat([self.mean_dict["pose"]], nbatch_real, axis=0) # (nbatch_render, 6)
jcodedict_gt["pose"] = np.repeat([self.mean_dict["pose"]], nbatch_real, axis=0) # (nbatch_render, 6)
jcodedict_pt["pose"][:, 3:6] = jcoeff_pt[k:k+nbatch_render, 50:53]
jcodedict_gt["pose"][:, 3:6] = jcoeff_gt[k:k+nbatch_render, 50:53]
# others ==> to mean
mean_cam = [[5,0,0]] # or [self.mean_dict["cam"]]
jcodedict_pt["cam"] = np.repeat(mean_cam, nbatch_real, axis=0) # (nbatch_render, 3)
jcodedict_pt["light"] = np.repeat([self.mean_dict["light"]], nbatch_real, axis=0) # (nbatch_render, 9, 3)
jcodedict_pt["shape"] = np.repeat([self.mean_dict["shape"]], nbatch_real, axis=0) # (nbatch_render, 100)
jcodedict_pt["detail"] = np.repeat([self.mean_dict["detail"]], nbatch_real, axis=0) # (nbatch_render, 128)
jcodedict_gt["cam"] = np.repeat(mean_cam, nbatch_real, axis=0) # (nbatch_render, 3)
jcodedict_gt["light"] = np.repeat([self.mean_dict["light"]], nbatch_real, axis=0) # (nbatch_render, 9, 3)
jcodedict_gt["shape"] = np.repeat([self.mean_dict["shape"]], nbatch_real, axis=0) # (nbatch_render, 100)
jcodedict_gt["detail"] = np.repeat([self.mean_dict["detail"]], nbatch_real, axis=0) # (nbatch_render, 128)
_, visdict_pt = self.netR.decode_one(jcodedict_pt, nbatch_real, self.device)
_, visdict_gt = self.netR.decode_one(jcodedict_gt, nbatch_real, self.device)
render_pt = visdict_pt["shape_images"] # (nbatch_render, 3, 224, 224)
render_gt = visdict_gt["shape_images"] # (nbatch_render, 3, 224, 224)
# print(f"render pt shape = {render_pt.shape}, gt {render_gt.shape}")
for m in range(nbatch_real):
# cv2.imwrite(str(kpath_image), util.tensor2image(render_image[m, ...]))
v_render_pt.append(tensor2image(render_pt[m, ...]))
v_render_gt.append(tensor2image(render_gt[m, ...]))
# save animation
# print(f"testing v_render_pt = {len(v_render_pt)}, gt shape = {len(v_render_gt)}")
save_animation_with_gt2(v_render_pt, v_render_gt, jpath_save, fps=self.opt.DATASET.fps)
#########################################
def tensor2image(tensor):
image = tensor.detach().cpu().numpy()
image = image*255.
image = np.maximum(np.minimum(image, 255), 0)
image = image.transpose(1,2,0)[:,:,[2,1,0]]
return image.astype(np.uint8).copy()
def define_netG(opt):
netG = None
if opt.MODEL.name_netG == "audio2motion_head":
from src.nn.audio2motion_head import Audio2MotionHead
netG = Audio2MotionHead(opt)
elif opt.MODEL.name_netG == "audio2motion_voca":
from src.nn.audio2motion_voca import Audio2MotionVOCA
netG = Audio2MotionVOCA(opt)
elif opt.MODEL.name_netG == "audio2motion_voca2":
from src.nn.audio2motion_voca3 import Audio2MotionVOCA3
netG = Audio2MotionVOCA3(opt)
elif opt.MODEL.name_netG == "audio2motion_conv":
from src.nn.audio2motion_conv import Audio2MotionConv
netG = Audio2MotionConv(opt)
elif opt.MODEL.name_netG == "audio2motion":
from src.nn.audio2motion import Audio2Motion
netG = Audio2Motion(opt)
elif opt.MODEL.name_netG == "audio2motion2":
from src.nn.audio2motion2 import Audio2Motion2
netG = Audio2Motion2(opt)
else:
raise NameError(f"The model of opt.MODEL.name_netAE(={opt.MODEL.name_netG}) not existing!")
return netG
def define_netR(device):
# import
sys.path.insert(0, "/ssdata1/lsen/CODE/DECA_old")
from decalib.deca import DECA
from decalib.utils import util
from decalib.utils.config import cfg as deca_cfg
# use device
# device = "cuda:2"
# whether to use FLAME texture model to generate uv texture map
deca_cfg.model.use_tex = False
deca_cfg.dataset.image_size = 512
# reconstruction model
netR = DECA(config = deca_cfg, device=device)
return netR
+411
View File
@@ -0,0 +1,411 @@
import sys
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
from pathlib import Path
from src.models import init_net
from src.models.base import Base
from src.optims import get_optimizer, get_scheduler
# common
from common.animation import save_animation_with_gt2, save_images_with_audio
from common.debug import debug
from common.losses import WingLoss
# disentangle model
class Audio2motionLive2Model(Base):
def __init__(self, opt, logger):
Base.__init__(self, opt, logger)
self.opt = opt
self.logger = logger
self.names_model = ["G"] # G
# define networks
self.netG = define_netG(opt)
self.netG.to()
self.netG = torch.nn.DataParallel(self.netG, opt.GPUS) # multi-GPUs
init_net(self.netG, init_type='kaiming', gpu_ids=opt.GPUS)
self.loss_func_l1 = nn.L1Loss(reduction="mean")
self.loss_func_wing = WingLoss(reduction="mean")
if self.isTrain:
self.names_loss = opt.LOSS.names
# define optimizers
self.optimizer_G = get_optimizer(self.netG, opt)
self.optimizers.append(self.optimizer_G)
self.scheduler_G = get_scheduler(self.optimizer_G, opt)
self.schedulers.append(self.scheduler_G)
if self.opt.TRAIN.apply_testing or not self.isTrain:
# load mean lighting & shape
self.netR = define_netR(device=self.device)
# self.netG.init_reconstruct_model(self.netR)
path_deca_mean = Path("./data/DECA_obama_mean.npy")
self.mean_dict = np.load(path_deca_mean, allow_pickle=True).item()
print(self.mean_dict.keys())
if self.opt.DATASET.speech_extractor == "wav2vec":
from transformers import Wav2Vec2FeatureExtractor, Wav2Vec2Model
print("load Wav2Vec2Model ...")
MODEL_ID = "jonatasgrosman/wav2vec2-large-xlsr-53-chinese-zh-cn"
self.processor = Wav2Vec2FeatureExtractor.from_pretrained(MODEL_ID)
self.extractor = Wav2Vec2Model.from_pretrained(MODEL_ID).to(self.device)
def set_input(self, batch_input):
# motion data
self.data = batch_input["data"].float().to(self.device) # (B, nsteps, nc_motion)
self.batch_vid = batch_input['vid']
self.batch_nframe = batch_input['nframe']
self.batch_interv = batch_input['frame_interval']
debug(self.opt, f"data = {self.data.shape}, dtype={self.data.dtype}", verbose=False)
debug(self.opt, f"batch_vid = {self.batch_vid[:2]}", verbose=False)
debug(self.opt, f"batch_nframe = {self.batch_nframe[:2]}", verbose=False)
debug(self.opt, f"batch_interv len={len(self.batch_interv)} len([0])={len(self.batch_interv[0])}, \
beg={self.batch_interv[0][:4]}, end={self.batch_interv[1][:4]}", verbose=False)
self.B, self.nsteps = self.data.size(0), self.data.size(1)
# speech data
raw_speech = batch_input["cond"].numpy() # (B, nsegments)
debug(self.opt, f"raw_speech = {raw_speech.shape}, dtype={raw_speech.dtype}", verbose=False)
if self.opt.DATASET.speech_extractor == "wav2vec":
# raw_speech = raw_speech.reshape(self.B * self.nsteps, -1) # (B*nsteps, nsegments)
# debug(self.opt, f"raw_speech = {raw_speech.shape}, dtype={raw_speech.dtype}", verbose=False)
# padding half frame length for bed and end
npad = int(0.5 * self.opt.DATASET.sr * ( 1 / self.opt.DATASET.fps) + 0.5)
raw_speech = np.pad(raw_speech, pad_width=((0,0), (npad, npad)), mode="edge")
debug(self.opt, f"after padding raw_speech = {raw_speech.shape}, dtype={raw_speech.dtype}", verbose=False)
raw_speech = list(raw_speech)
inputs = self.processor(raw_speech, sampling_rate=16000, return_tensors="pt")
inputs = inputs.to(self.device)
with torch.no_grad():
output = self.extractor(**inputs)
self.cond = output.last_hidden_state
# self.cond = output.extract_features
# B x nsteps x nc_feat
debug(self.opt, f"data = {self.data.shape}, dtype={self.data.dtype}, device={self.data.device}", verbose=False)
debug(self.opt, f"cond = {self.cond.shape}, dtype={self.cond.dtype}, device={self.cond.device}", verbose=False)
# unfold
# self.data = self.data.unfold(dimension=1, size=16, step=1) # (B, nseqs, nc_motion, 16)
# self.data = self.data.permute(0, 1, 3, 2) # (B, nseqs, 16, 53)
self.cond = self.cond.unfold(dimension=1, size=16, step=1) # (nseqs, nc_motion, 16)
self.cond = self.cond.permute(0, 1, 3, 2) # (nseqs, 16, 53)
self.nseq = self.cond.size(1)
self.data = self.data[:, 7:7+self.nseq, :]
debug(self.opt, f"\n a data = {self.data.shape}, dtype={self.data.dtype}, device={self.data.device}", verbose=False)
debug(self.opt, f"a cond = {self.cond.shape}, dtype={self.cond.dtype}, device={self.cond.device}", verbose=False)
def training(self, batch_input):
self.train() # set train model
self.set_input(batch_input)
# forward
self.pred = self.netG(self.cond)
# loss
loss, self.loss_dict = self.eval_losses(self.pred, self.data)
# backward
self.optimizer_G.zero_grad()
loss.backward()
if self.opt.TRAIN.grad_clip_norm: # operate grad
torch.nn.utils.clip_grad_value_(self.netG.parameters(), self.opt.TRAIN.max_grad_clip)
torch.nn.utils.clip_grad_norm_(self.netG.parameters(), self.opt.TRAIN.max_grad_norm)
self.optimizer_G.step()
return loss
def validation(self, batch_input):
self.eval() # set eval model
self.set_input(batch_input)
with torch.no_grad():
self.pred = self.netG(self.cond)
loss, self.loss_dict = self.eval_losses(self.pred, self.data)
return loss
def infer(self, batch_cond, path_audio, suffix=""):
self.eval()
self.cond = batch_cond.float().to(self.device) # (nsteps, dim_cond)
with torch.no_grad():
samples_pt = self.netG(self.cond).cpu().numpy() # B x N x dim_motion
print(f"testing pt shape = {samples_pt.shape}")
self.save_reconstruct(samples_pt, path_audio,
path_save=Path(self.opt.OUTPUT_DIR),
suffix=suffix)
def testing(self, batch_input, cur_epoch=0, cur_batch=0):
self.eval() # set eval model
self.set_input(batch_input)
with torch.no_grad():
samples_pt = self.netG(self.cond).cpu().numpy() # B x N x dim_motion
samples_gt = self.data.cpu().numpy() # B x N x dim_motion
print(f"testing pt shape = {samples_pt.shape}, gt shape = {samples_gt.shape}")
self.save_reconstruct_with_gt(samples_pt, samples_gt,
path_save=Path(self.opt.OUTPUT_DIR),
suffix=f'sampled_{cur_epoch:05d}_{cur_batch:03d}')
def eval_losses(self, batch_pdt, batch_tgt):
""" Computes the VAE loss function.
pramas:
batch_pred, (nbatch, seqlen, dim_motion)
batch_targt, (nbatch, seqlen, dim_motion)
"""
loss = 0
loss_dict = {}
batch_pdt_exp = batch_pdt[..., :50]
batch_pdt_pos = batch_pdt[..., 50:]
batch_tgt_exp = batch_tgt[..., :50]
batch_tgt_pos = batch_tgt[..., 50:]
# rec loss
loss = 0
loss_rec_exp = self.loss_func_wing(batch_pdt_exp, batch_tgt_exp) / 50
loss_dict["loss_rec_exp"] = loss_rec_exp.detach()
loss_rec_pos = self.loss_func_wing(batch_pdt_pos, batch_tgt_pos) / 3
loss_dict["loss_rec_pos"] = loss_rec_pos.detach()
loss += loss_rec_exp * self.opt.LOSS.lambda_rec_exp
loss += loss_rec_pos * self.opt.LOSS.lambda_rec_pos
# rec smooth
diff_pdt_exp = batch_pdt_exp[:, 1:, :] - batch_pdt_exp[:, :-1, :]
diff_tgt_exp = batch_tgt_exp[:, 1:, :] - batch_tgt_exp[:, :-1, :]
loss_vol_exp = self.loss_func_wing(diff_pdt_exp, diff_tgt_exp) / 50
loss_dict["loss_vol_exp"] = loss_vol_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_vol_pos = self.loss_func_wing(diff_pdt_pos, diff_tgt_pos) / 3
loss_dict["loss_vol_pos"] = loss_vol_pos.detach()
loss += loss_vol_exp * self.opt.LOSS.lambda_vol_exp
loss += loss_vol_pos * self.opt.LOSS.lambda_vol_pos
# total loss
loss_dict['loss_all'] = loss.detach()
return loss, loss_dict
def save_reconstruct(self, samples_pt, path_audio, path_save, suffix=""):
# samples_pt, [B x N x dim_motion]
B, N, _ = samples_pt.shape
nbatch_render = 10
# for each batch
for j in range(B):
jcoeff_pt = samples_pt[j, :, :]
jpath_save = path_save.joinpath(f"{suffix}_{j:02d}.mp4")
v_render_pt = []
for k in range(0, N, nbatch_render):
jcodedict_pt = {}
jcodedict_pt["exp"] = jcoeff_pt[k:k+nbatch_render, :50] # (nbatch_render, 50)
nbatch_real = jcodedict_pt["exp"].shape[0]
# pose
jcodedict_pt["pose"] = np.repeat([self.mean_dict["pose"]], nbatch_real, axis=0) # (nbatch_render, 6)
jcodedict_pt["pose"][:, 3:6] = jcoeff_pt[k:k+nbatch_render, 50:53]
# others ==> to mean
mean_cam = [[5,0,0]] # or [self.mean_dict["cam"]]
jcodedict_pt["cam"] = np.repeat(mean_cam, nbatch_real, axis=0) # (nbatch_render, 3)
jcodedict_pt["light"] = np.repeat([self.mean_dict["light"]], nbatch_real, axis=0) # (nbatch_render, 9, 3)
jcodedict_pt["shape"] = np.repeat([self.mean_dict["shape"]], nbatch_real, axis=0) # (nbatch_render, 100)
jcodedict_pt["detail"] = np.repeat([self.mean_dict["detail"]], nbatch_real, axis=0) # (nbatch_render, 128)
_, visdict_pt = self.netR.decode_one(jcodedict_pt, nbatch_real, self.device)
render_pt = visdict_pt["shape_images"] # (nbatch_render, 3, 224, 224)
# print(f"render pt shape = {render_pt.shape}")
for m in range(nbatch_real):
# cv2.imwrite(str(kpath_image), util.tensor2image(render_image[m, ...]))
v_render_pt.append(tensor2image(render_pt[m, ...]))
# save animation
# print(f"testing v_render_pt = {len(v_render_pt)}")
save_images_with_audio(v_render_pt, path_audio, jpath_save)
def save_reconstruct_with_gt(self, samples_pt, samples_gt, path_save, suffix=""):
# samples_pt, [B x N x dim_motion]
# samples_gt, [B x N x dim_motion]
B, N, _ = samples_pt.shape
nbatch_render = 10
# for each batch
for j in range(B):
jcoeff_pt = samples_pt[j, :, :]
jcoeff_gt = samples_gt[j, :, :]
jpath_save = path_save.joinpath(f"{suffix}_{j:02d}.mp4")
v_render_pt = []
v_render_gt = []
for k in range(0, N, nbatch_render):
jcodedict_pt = {}
jcodedict_gt = {}
# exp
jcodedict_pt["exp"] = jcoeff_pt[k:k+nbatch_render, :50] # (nbatch_render, 50)
jcodedict_gt["exp"] = jcoeff_gt[k:k+nbatch_render, :50] # (nbatch_render, 50)
nbatch_real = jcodedict_pt["exp"].shape[0]
# pose
jcodedict_pt["pose"] = np.repeat([self.mean_dict["pose"]], nbatch_real, axis=0) # (nbatch_render, 6)
jcodedict_gt["pose"] = np.repeat([self.mean_dict["pose"]], nbatch_real, axis=0) # (nbatch_render, 6)
jcodedict_pt["pose"][:, 3:6] = jcoeff_pt[k:k+nbatch_render, 50:53]
jcodedict_gt["pose"][:, 3:6] = jcoeff_gt[k:k+nbatch_render, 50:53]
# others ==> to mean
mean_cam = [[5,0,0]] # or [self.mean_dict["cam"]]
jcodedict_pt["cam"] = np.repeat(mean_cam, nbatch_real, axis=0) # (nbatch_render, 3)
jcodedict_pt["light"] = np.repeat([self.mean_dict["light"]], nbatch_real, axis=0) # (nbatch_render, 9, 3)
jcodedict_pt["shape"] = np.repeat([self.mean_dict["shape"]], nbatch_real, axis=0) # (nbatch_render, 100)
jcodedict_pt["detail"] = np.repeat([self.mean_dict["detail"]], nbatch_real, axis=0) # (nbatch_render, 128)
jcodedict_gt["cam"] = np.repeat(mean_cam, nbatch_real, axis=0) # (nbatch_render, 3)
jcodedict_gt["light"] = np.repeat([self.mean_dict["light"]], nbatch_real, axis=0) # (nbatch_render, 9, 3)
jcodedict_gt["shape"] = np.repeat([self.mean_dict["shape"]], nbatch_real, axis=0) # (nbatch_render, 100)
jcodedict_gt["detail"] = np.repeat([self.mean_dict["detail"]], nbatch_real, axis=0) # (nbatch_render, 128)
_, visdict_pt = self.netR.decode_one(jcodedict_pt, nbatch_real, self.device)
_, visdict_gt = self.netR.decode_one(jcodedict_gt, nbatch_real, self.device)
render_pt = visdict_pt["shape_images"] # (nbatch_render, 3, 224, 224)
render_gt = visdict_gt["shape_images"] # (nbatch_render, 3, 224, 224)
# print(f"render pt shape = {render_pt.shape}, gt {render_gt.shape}")
for m in range(nbatch_real):
# cv2.imwrite(str(kpath_image), util.tensor2image(render_image[m, ...]))
v_render_pt.append(tensor2image(render_pt[m, ...]))
v_render_gt.append(tensor2image(render_gt[m, ...]))
# get audio
jvid = self.batch_vid[j]
jnframe = self.batch_nframe[j].numpy()
jstart_frame = self.batch_interv[0][j].numpy()
jpath_audio = f"/yrfs/lsen/DATA/LuoXData/processing2/{jvid}/audio/audio_trim.wav"
jstart_time = (jstart_frame + 7) / self.opt.DATASET.fps # xxx.yyy min
jend_time = (jstart_frame + 7 + self.nseq) / self.opt.DATASET.fps # xxx.yyy min
print(f"jvid={jvid}, jnfram={jnframe}, jstart_frame={jstart_frame}, jpath_audio={jpath_audio}")
print(f"jstart_time={jstart_time}, jend_time={jend_time}")
# save animation
# print(f"testing v_render_pt = {len(v_render_pt)}, gt shape = {len(v_render_gt)}")
save_animation_with_gt2(v_render_pt, v_render_gt, jpath_save, fps=self.opt.DATASET.fps,\
path_audio=jpath_audio, start_time=jstart_time, end_time=jend_time)
#########################################
def tensor2image(tensor):
image = tensor.detach().cpu().numpy()
image = image*255.
image = np.maximum(np.minimum(image, 255), 0)
image = image.transpose(1,2,0)[:,:,[2,1,0]]
return image.astype(np.uint8).copy()
def define_netG(opt):
netG = None
if opt.MODEL.name_netG == "audio2motion_voca4":
from src.nn.audio2motion_voca4 import Audio2MotionVOCA
netG = Audio2MotionVOCA(opt)
elif opt.MODEL.name_netG == "audio2motion_voca":
from src.nn.audio2motion_voca import Audio2MotionVOCA
netG = Audio2MotionVOCA(opt)
elif opt.MODEL.name_netG == "audio2motion_voca3":
from src.nn.audio2motion_voca3 import Audio2MotionVOCA3
netG = Audio2MotionVOCA3(opt)
elif opt.MODEL.name_netG == "audio2motion_voca33":
from src.nn.audio2motion_voca33 import Audio2MotionVOCA
netG = Audio2MotionVOCA(opt)
elif opt.MODEL.name_netG == "audio2motion":
from src.nn.audio2motion import Audio2Motion
netG = Audio2Motion(opt)
elif opt.MODEL.name_netG == "audio2motion2":
from src.nn.audio2motion2 import Audio2Motion2
netG = Audio2Motion2(opt)
else:
raise NameError(f"The model of opt.MODEL.name_netAE(={opt.MODEL.name_netG}) not existing!")
return netG
def define_netR(device):
# import
sys.path.insert(0, "/ssdata1/lsen/CODE/DECA_old")
from decalib.deca import DECA
from decalib.utils import util
from decalib.utils.config import cfg as deca_cfg
# use device
# device = "cuda:2"
# whether to use FLAME texture model to generate uv texture map
deca_cfg.model.use_tex = False
deca_cfg.dataset.image_size = 512
# reconstruction model
netR = DECA(config = deca_cfg, device=device)
return netR
+6 -4
View File
@@ -25,12 +25,14 @@ class Audio2Motion(nn.Module):
nn.Linear(in_features=self.dim_condit, out_features=self.dim_hidden),
nn.LayerNorm(self.dim_hidden),
nn.LeakyReLU(0.2),
nn.Dropout(0.5),
nn.Linear(in_features=self.dim_hidden, out_features=4*self.dim_hidden),
nn.LayerNorm(4*self.dim_hidden),
nn.LeakyReLU(0.2),
nn.Dropout(0.1),
nn.Dropout(0.5),
nn.Linear(in_features=4*self.dim_hidden, out_features=self.dim_hidden),
)
@@ -49,17 +51,17 @@ class Audio2Motion(nn.Module):
nn.Linear(in_features=self.dim_hidden, out_features=4*self.dim_hidden),
nn.LayerNorm(4*self.dim_hidden),
nn.LeakyReLU(0.2),
nn.Dropout(0.1),
nn.Dropout(0.5),
nn.Linear(in_features=4*self.dim_hidden, out_features=4*self.dim_hidden),
nn.LayerNorm(4*self.dim_hidden),
nn.LeakyReLU(0.2),
nn.Dropout(0.1),
nn.Dropout(0.5),
nn.Linear(in_features=4*self.dim_hidden, out_features=self.dim_hidden),
nn.LayerNorm(self.dim_hidden),
nn.LeakyReLU(0.2),
nn.Dropout(0.1),
nn.Dropout(0.5),
nn.Linear(in_features=self.dim_hidden, out_features=self.dim_motion),
nn.Tanh()
+84
View File
@@ -0,0 +1,84 @@
import torch
import torch.nn as nn
from common.debug import debug
class Audio2Motion2(nn.Module):
def __init__(self, opt):
super(Audio2Motion2, self).__init__()
self.opt = opt
nseqR_m = opt.MODEL.n_lookprevs_motion # 3
nseqR_s = opt.MODEL.n_lookprevs_speech # 3
nseqL_s = opt.MODEL.n_lookahead_speech # 1
nLSTM = opt.MODEL.n_layer_lstm # 3
self.dim_motion = opt.MODEL.dim_motion # 53
self.dim_speech = opt.MODEL.dim_speech # 27
self.dim_hidden = opt.MODEL.dim_hidden # 256
self.dim_condit = self.dim_motion * nseqR_m + self.dim_speech * (nseqR_s + 1 + nseqL_s)
print(f"dim_condit={self.dim_condit}")
# encoder
self.encoder = nn.Sequential( # nbatch x nseqlen x 27
nn.Linear(in_features=self.dim_condit, out_features=self.dim_hidden),
nn.LeakyReLU(0.2),
nn.Linear(in_features=self.dim_hidden, out_features=4*self.dim_hidden),
nn.LeakyReLU(0.2),
nn.Linear(in_features=4*self.dim_hidden, out_features=self.dim_hidden),
)
# lstm
self.LSTM = nn.LSTM(
input_size = self.dim_hidden,
hidden_size = self.dim_hidden,
num_layers= nLSTM,
dropout = 0,
bidirectional=False,
batch_first = True
)
# output
self.decoder = nn.Sequential(
nn.Linear(in_features=self.dim_hidden, out_features=4*self.dim_hidden),
nn.LeakyReLU(0.2),
nn.Linear(in_features=4*self.dim_hidden, out_features=4*self.dim_hidden),
nn.LeakyReLU(0.2),
nn.Linear(in_features=4*self.dim_hidden, out_features=self.dim_hidden),
nn.LeakyReLU(0.2),
nn.Linear(in_features=self.dim_hidden, out_features=self.dim_motion),
nn.Tanh()
)
def forward(self, x):
""" forward function
Args:
x: torch.Tensor, [nbatch x seqlen x dim_condit]
target: torch.Tensor, [nbatch x seqlen x dim_motion]
return:
pred: torch.Tensor, [nbatch x seqlen x dim_motion]
"""
(nbatch, nseqlen, nfeat) = x.shape
debug(self.opt, f"[forward] input x shape = {x.shape}", verbose=False)
feat = self.encoder(x) # [nbatch x nseqlen x dim_hidden]
debug(self.opt, f"[forward] encoder shape = {feat.shape}", verbose=False)
feat, _ = self.LSTM(feat) # [nbatch x nseqlen x dim_hidden]
debug(self.opt, f"[forward] lstm shape = {feat.shape}", verbose=False)
pred = self.decoder(feat) # [nbatch x nseqlen x dim_motion]
debug(self.opt, f"[forward] decoder shape = {pred.shape}", verbose=False)
return pred
+40
View File
@@ -0,0 +1,40 @@
import torch
import torch.nn as nn
from common.debug import debug
class Audio2MotionHead(nn.Module):
def __init__(self, opt):
super(Audio2MotionHead, self).__init__()
self.opt = opt
self.dim_motion = opt.MODEL.dim_motion # 53
self.dim_speech = opt.MODEL.dim_speech # 27
print(f"dim_speech={self.dim_speech}")
# encoder
self.head = nn.Sequential( # nbatch x nseqlen x 27
nn.Linear(in_features=self.dim_speech, out_features=256),
nn.LeakyReLU(0.2),
nn.Linear(in_features=256, out_features=self.dim_motion),
nn.Tanh()
)
def forward(self, x):
""" forward function
Args:
x: torch.Tensor, [nbatch x seqlen x dim_condit]
return:
pred: torch.Tensor, [nbatch x seqlen x dim_motion]
"""
debug(self.opt, f"[forward] input x shape = {x.shape}", verbose=False)
pred = self.head(x) # [nbatch x nseqlen x dim_hidden]
debug(self.opt, f"[forward] decoder shape = {pred.shape}", verbose=False)
return pred
+78
View File
@@ -0,0 +1,78 @@
import torch
import torch.nn as nn
from common.debug import debug
class Audio2MotionVOCA3(nn.Module):
def __init__(self, opt):
super(Audio2MotionVOCA3, self).__init__()
self.opt = opt
self.dim_motion = opt.MODEL.dim_motion # 53
self.dim_speech = opt.MODEL.dim_speech # 29
self.dim_hidden = opt.MODEL.dim_hidden # 256
# encoder
self.encoder = nn.Sequential( # (nbatch, nchannel=29, H=16, W=1)
nn.BatchNorm2d(self.dim_speech),
# block 1
nn.Conv2d(self.dim_speech, 512, kernel_size=(3,1), stride=(2,1), padding=(1,0), bias=True), # 32 x 8 x 1
nn.LeakyReLU(0.02, True),
nn.Conv2d(512, 512, kernel_size=(3,1), stride=(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=128) # 50,
)
# output
self.decoder = nn.Sequential(
nn.Linear(in_features=128, out_features=self.dim_motion),
)
def forward(self, x):
""" forward function
Args:
x: torch.Tensor, [nbatch x seqlen x nwind x dim_condit]
return:
pred: torch.Tensor, [nbatch x seqlen x dim_motion]
"""
(nbatch, nseqlen, nwind, nfeat) = x.shape # (B, nseq, 16, 29)
debug(self.opt, f"[forward] input x shape = {x.shape}", verbose=False)
# preprocessing data
x = x.reshape(nbatch * nseqlen, 1, nwind, nfeat) # (B * nseq, 1, 16, 29)
x = torch.transpose(x, 1, 3) # (B * nseq, 29, 16, 1)
debug(self.opt, f"[forward] transpose x shape = {x.shape}", verbose=False)
feat = self.encoder(x) # (B * nseq, 50)
debug(self.opt, f"[forward] encoder shape = {feat.shape}", verbose=False)
pred = self.decoder(feat) # (B * nseq, dim_motion)
debug(self.opt, f"[forward] decoder shape = {pred.shape}", verbose=False)
pred = pred.reshape(nbatch, nseqlen, -1) # (B, nseq, dim_motion)
debug(self.opt, f"[forward] reshape shape = {pred.shape}", verbose=False)
return pred
+89
View File
@@ -0,0 +1,89 @@
import torch
import torch.nn as nn
from common.debug import debug
class Audio2MotionVOCA(nn.Module):
def __init__(self, opt):
super(Audio2MotionVOCA, self).__init__()
self.opt = opt
self.dim_motion = opt.MODEL.dim_motion # 53
self.dim_speech = opt.MODEL.dim_speech # 29
self.dim_hidden = opt.MODEL.dim_hidden # 256
# encoder
self.encoder = nn.Sequential( # (nbatch, nchannel=29, H=16, W=1)
nn.BatchNorm2d(self.dim_speech),
# block 1
nn.Conv2d(self.dim_speech, 512, kernel_size=(3,1), stride=(2,1), padding=(1,0), bias=True), # 32 x 8 x 1
nn.LeakyReLU(0.02, True),
nn.Conv2d(512, 512, kernel_size=(3,1), stride=(1,1), padding=(1,0), bias=True), # 32 x 8 x 1
nn.LeakyReLU(0.02, True),
nn.Conv2d(512, 512, kernel_size=(3,1), stride=(2,1), padding=(1,0), bias=True), # 32 x 4 x 1
nn.LeakyReLU(0.02, True),
nn.Conv2d(512, 512, kernel_size=(3,1), stride=(1,1), padding=(1,0), bias=True), # 32 x 8 x 1
nn.LeakyReLU(0.02, True),
nn.Conv2d(512, 256, kernel_size=(3,1), stride=(2,1), padding=(1,0), bias=True), # 64 x 2 x 1
nn.LeakyReLU(0.02, True),
nn.Conv2d(256, 256, kernel_size=(3,1), stride=(1,1), padding=(1,0), bias=True), # 32 x 8 x 1
nn.LeakyReLU(0.02, True),
nn.Conv2d(256, 256, kernel_size=(3,1), stride=(2,1), padding=(1,0), bias=True), # 64 x 1 x 1
nn.LeakyReLU(0.02, True),
nn.Conv2d(256, 256, kernel_size=(3,1), stride=(1,1), padding=(1,0), bias=True), # 32 x 8 x 1
nn.LeakyReLU(0.02, True),
nn.Conv2d(256, 128, kernel_size=(3,1), stride=(2,1), padding=(1,0), bias=True), # 64 x 1 x 1
nn.LeakyReLU(0.02, True),
nn.Flatten(), # 64,
nn.Linear(in_features=128, out_features=2048), # 128,
nn.Tanh(),
nn.Linear(in_features=2048, out_features=128) # 50,
)
# output
self.decoder = nn.Sequential(
nn.Linear(in_features=128, out_features=self.dim_motion),
)
def forward(self, x):
""" forward function
Args:
x: torch.Tensor, [nbatch x seqlen x nwind x dim_condit]
return:
pred: torch.Tensor, [nbatch x seqlen x dim_motion]
"""
(nbatch, nseqlen, nwind, nfeat) = x.shape # (B, nseq, 16, 29)
debug(self.opt, f"[forward] input x shape = {x.shape}", verbose=False)
# preprocessing data
x = x.reshape(nbatch * nseqlen, 1, nwind, nfeat) # (B * nseq, 1, 16, 29)
x = torch.transpose(x, 1, 3) # (B * nseq, 29, 16, 1)
debug(self.opt, f"[forward] transpose x shape = {x.shape}", verbose=False)
feat = self.encoder(x) # (B * nseq, 50)
debug(self.opt, f"[forward] encoder shape = {feat.shape}", verbose=False)
pred = self.decoder(feat) # (B * nseq, dim_motion)
debug(self.opt, f"[forward] decoder shape = {pred.shape}", verbose=False)
pred = pred.reshape(nbatch, nseqlen, -1) # (B, nseq, dim_motion)
debug(self.opt, f"[forward] reshape shape = {pred.shape}", verbose=False)
return pred
+107
View File
@@ -0,0 +1,107 @@
import torch
import torch.nn as nn
from common.debug import debug
class Audio2MotionVOCA(nn.Module):
def __init__(self, opt):
super(Audio2MotionVOCA, self).__init__()
self.opt = opt
self.dim_motion = opt.MODEL.dim_motion # 53
self.dim_speech = opt.MODEL.dim_speech # 29
self.dim_hidden = opt.MODEL.dim_hidden # 256
# encoder
self.encoder = nn.Sequential( # (nbatch, nchannel=29, H=16, W=1)
nn.BatchNorm2d(self.dim_speech),
# block 1
nn.Conv2d(self.dim_speech, 128, kernel_size=(3,1), stride=(1,1), padding=(1,0), bias=True), # 128 x 16 x 1
nn.BatchNorm2d(128),
nn.LeakyReLU(0.02, True),
nn.Conv2d(128, 128, kernel_size=(3,1), stride=(1,1), padding=(1,0), bias=True), # 128 x 16 x 1
nn.BatchNorm2d(128),
nn.LeakyReLU(0.02, True),
nn.Conv2d(128, 128, kernel_size=(3,1), stride=(1,1), padding=(1,0), bias=True), # 128 x 16 x 1
nn.BatchNorm2d(128),
nn.LeakyReLU(0.02, True),
# block 2
nn.Conv2d(128, 256, kernel_size=(3,1), stride=(2,1), padding=(1,0), bias=True), # 256 x 8 x 1
nn.BatchNorm2d(256),
nn.LeakyReLU(0.02, True),
nn.Conv2d(256, 256, kernel_size=(3,1), stride=(1,1), padding=(1,0), bias=True), # 256 x 8 x 1
nn.BatchNorm2d(256),
nn.LeakyReLU(0.02, True),
nn.Conv2d(256, 256, kernel_size=(3,1), stride=(1,1), padding=(1,0), bias=True), # 256 x 8 x 1
nn.BatchNorm2d(256),
nn.LeakyReLU(0.02, True),
nn.Conv2d(256, 512, kernel_size=(3,1), stride=(1,1), padding=(1,0), bias=True), # 512 x 8 x 1
nn.BatchNorm2d(512),
nn.LeakyReLU(0.02, True),
# block 3
nn.Conv2d(512, 512, kernel_size=(3,1), stride=(2,1), padding=(1,0), bias=True), # 512 x 4 x 1
nn.BatchNorm2d(512),
nn.LeakyReLU(0.02, True),
nn.Conv2d(512, 512, kernel_size=(3,1), stride=(1,1), padding=(1,0), bias=True), # 512 x 4 x 1
nn.BatchNorm2d(512),
nn.LeakyReLU(0.02, True),
nn.Conv2d(512, 512, kernel_size=(3,1), stride=(2,1), padding=(1,0), bias=True), # 512 x 2 x 1
nn.BatchNorm2d(512),
nn.LeakyReLU(0.02, True),
nn.Conv2d(512, 512, kernel_size=(3,1), stride=(2,1), padding=(1,0), bias=True), # 512 x 1 x 1
nn.BatchNorm2d(512),
nn.LeakyReLU(0.02, True),
nn.Flatten(), # 256,
nn.Linear(in_features=512, out_features=128), # 2014,
nn.Tanh(),
nn.Linear(in_features=128, out_features=2048), # 2014,
nn.Tanh(),
nn.Linear(in_features=2048, out_features=128) # 128,
)
# output
self.decoder = nn.Sequential(
nn.Linear(in_features=128, out_features=self.dim_motion),
)
def forward(self, x):
""" forward function
Args:
x: torch.Tensor, [nbatch x seqlen x nwind x dim_condit]
return:
pred: torch.Tensor, [nbatch x seqlen x dim_motion]
"""
(nbatch, nseqlen, nwind, nfeat) = x.shape # (B, nseq, 16, 29)
debug(self.opt, f"[forward] input x shape = {x.shape}", verbose=False)
# preprocessing data
x = x.reshape(nbatch * nseqlen, 1, nwind, nfeat) # (B * nseq, 1, 16, 29)
x = torch.transpose(x, 1, 3) # (B * nseq, 29, 16, 1)
debug(self.opt, f"[forward] transpose x shape = {x.shape}", verbose=False)
feat = self.encoder(x) # (B * nseq, 50)
debug(self.opt, f"[forward] encoder shape = {feat.shape}", verbose=False)
pred = self.decoder(feat) # (B * nseq, dim_motion)
debug(self.opt, f"[forward] decoder shape = {pred.shape}", verbose=False)
pred = pred.reshape(nbatch, nseqlen, -1) # (B, nseq, dim_motion)
debug(self.opt, f"[forward] reshape shape = {pred.shape}", verbose=False)
return pred