update audduio2pose v1.0

This commit is contained in:
Sen Liang committed 2022-04-24 14:06:52 +08:00
1 parent c2797657f8
commit 3a15011f4d
28 files changed
+1817 -483

No files matched your search

+53 -44
View File
@@ -2,9 +2,6 @@
import numpy as np
from collections import OrderedDict
import tempfile
from scipy.io import wavfile
import torch
import torch.nn as nn
from pathlib import Path
@@ -19,7 +16,7 @@ from src.optims import get_optimizer, get_scheduler
from src.utils import util
# common
from common.animation import save_animation_with_gt2, save_images_with_audio
from common.animation import save_animation_with_gt2, write_video, write_video_with_gt
from common.debug import debug
from common.losses import WingLoss
@@ -101,7 +98,7 @@ class Audio2MeshModel(Base):
def set_input(self, batch_input):
""" """
# motion data
data = batch_input["data"].float().to(self.device) # (B, nsteps, nc_motion)
@@ -170,7 +167,7 @@ class Audio2MeshModel(Base):
return pred
def training(self, batch_input):
def training(self, batch_input, idx_epoch=0, idx_batch=0):
self.train() # set train model
self.set_input(batch_input)
@@ -195,7 +192,7 @@ class Audio2MeshModel(Base):
return loss_dict
def validation(self, batch_input):
def validation(self, batch_input, idx_epoch=0, idx_batch=0):
self.eval() # set eval model
self.set_input(batch_input)
@@ -224,11 +221,18 @@ class Audio2MeshModel(Base):
# !! add specific when render & output !!
batch_pdt_geo = batch_pdt_geo - self.temp_verts + self.temp_verts_specific
# render & and save
self.save_reconstruct(batch_pdt_geo, audio_raw,
path_save=Path(self.opt.OUTPUT_DIR),
suffix=suffix, vis_landmarks=False)
# render & and save
print(f"testing pt shape = {batch_pdt_geo.shape}, gt shape = {vert.shape}")
self.save_reconstruct_with_gt2(batch_pdt_geo, vert, audio_raw,
path_save=Path(self.opt.OUTPUT_DIR),
suffix=suffix)
suffix=suffix,vis_landmarks=False)
if save_npy:
# save result
batch_pdt_geo = batch_pdt_geo.cpu().numpy()
@@ -237,7 +241,7 @@ class Audio2MeshModel(Base):
print(f"save infer_result shape = {batch_pdt_geo.shape} -> {path_save_npy}")
def infer(self, batch_cond, path_audio, suffix="", save_npy=True):
def infer(self, batch_cond, raw_speech, suffix="", save_npy=True):
self.eval()
self.cond = batch_cond.float().to(self.device) # (nsteps, dim_cond)
@@ -251,10 +255,9 @@ class Audio2MeshModel(Base):
batch_pdt_geo = batch_pdt_geo - self.temp_verts + self.temp_verts_specific
# render & and save
self.save_reconstruct(batch_pdt_geo, path_audio,
path_save=Path(self.opt.OUTPUT_DIR),
suffix=suffix)
self.save_reconstruct(batch_pdt_geo, raw_speech, path_save=Path(self.opt.OUTPUT_DIR),
suffix=suffix, vis_landmarks=False)
if save_npy:
# save result
batch_pdt_geo = batch_pdt_geo.cpu().numpy()
@@ -263,7 +266,7 @@ class Audio2MeshModel(Base):
print(f"save infer_result shape = {batch_pdt_geo.shape} -> {path_save_npy}")
def testing(self, batch_input, cur_epoch=0, cur_batch=0):
def testing(self, batch_input, idx_epoch=0, idx_batch=0):
self.eval() # set eval model
self.set_input(batch_input)
@@ -277,9 +280,9 @@ class Audio2MeshModel(Base):
print(f"testing pt shape = {batch_pdt_geo.shape}, gt shape = {self.vert.shape}")
self.save_reconstruct_with_gt(batch_pdt_geo, self.vert,
path_save=Path(self.opt.OUTPUT_DIR),
suffix=f'sampled_{cur_epoch:05d}_{cur_batch:03d}')
suffix=f'sampled_{idx_epoch:05d}_{idx_batch:03d}')
def get_template_vertices(self, mean_dict=None):
batch_exp = torch.zeros(1, 50).to(self.device)
@@ -299,9 +302,6 @@ class Audio2MeshModel(Base):
ldmk3d = ldmk3d.reshape(1, 1, -1, 3) # 1 x 1 x 68 x 3
print(f"template verts reshape = {verts.shape}")
# np.save("./data/template.npy", verts.squeeze().cpu().numpy())
# print(f"save template.npy = {verts.squeeze().shape}")
# assert False
return verts, ldmk2d, ldmk3d
@@ -402,8 +402,7 @@ class Audio2MeshModel(Base):
return loss, loss_dict
def save_reconstruct(self, batch_pdt_geo, path_audio, path_save, suffix=""):
def save_reconstruct(self, batch_pdt_geo, raw_speech, path_save, suffix="", vis_landmarks=False):
# batch_pdt_geo, [B x N x dim_motion]
B, N, *_ = batch_pdt_geo.shape
@@ -412,7 +411,6 @@ class Audio2MeshModel(Base):
# for each batch
for i in range(B):
igeo_pt = batch_pdt_geo[i, ...]
ipath_save = path_save.joinpath(f"{suffix}_{i:02d}.mp4")
v_render_pt = []
for k in range(0, N, nbatch_render):
@@ -427,16 +425,24 @@ class Audio2MeshModel(Base):
# render
render_pt = self.render_geometry(kgeo_pt, cam, self.device) # (nbatch_real, 3, 512, 512)
render_pt = render_pt.cpu()
# print(f"render_pt ={render_pt.shape}, render_gt={render_gt.shape}")
if vis_landmarks:
kldmk3d_pt = self.netF.seletec_3d68(kgeo_pt) # [nbatch_real x 68 x 3]
kldmk3d_pt = util.batch_orth_proj(kldmk3d_pt, cam);
kldmk3d_pt[:,:,1:] = -kldmk3d_pt[:,:,1:];
render_pt = util.tensor_vis_landmarks(render_pt, kldmk3d_pt, isScale=True, color = (255, 0, 0))
else:
render_pt = render_pt.cpu()
# append each frame
for m in range(nbatch_real):
v_render_pt.append(tensor2image(render_pt[m, ...]))
# save animation
# print(f"testing v_render_pt = {len(v_render_pt)}")
save_images_with_audio(v_render_pt, path_audio, ipath_save)
# write video
ipath_save = path_save.joinpath(f"{suffix}_{i:02d}_pt.mp4")
write_video(v_render_pt, raw_speech, ipath_save, fps=50)
self.logger.info(f"save video to -> {str(ipath_save)}")
@torch.no_grad()
@@ -459,7 +465,7 @@ class Audio2MeshModel(Base):
return images
@torch.no_grad()
def save_reconstruct_with_gt2(self, batch_pdt_geo, batch_tgt_geo, raw_speech, path_save, suffix=""):
def save_reconstruct_with_gt2(self, batch_pdt_geo, batch_tgt_geo, raw_speech, path_save, suffix="", vis_landmarks=True):
# batch_pdt_geo, [1 x N x 5023 x 3]
# batch_tgt_geo, [1 x N x 5023 x 3]
@@ -467,7 +473,7 @@ class Audio2MeshModel(Base):
igeo_pt = batch_pdt_geo[0, ...] # [N x 5023 x 3]
igeo_gt = batch_tgt_geo[0, ...] # [N x 5023 x 3]
ipath_save = path_save.joinpath(f"{suffix}_{0:02d}.mp4")
ipath_save = path_save.joinpath(f"{suffix}_{0:02d}_pt_gt.mp4")
v_render_pt = []
v_render_gt = []
@@ -488,18 +494,22 @@ class Audio2MeshModel(Base):
render_gt = self.render_geometry(kgeo_gt, cam, self.device) # (nbatch_real, 3, 512, 512)
# print(f"render_pt ={render_pt.shape}, render_gt={render_gt.shape}")
# landmarks 3d
kldmk3d_pt = self.netF.seletec_3d68(kgeo_pt) # [nbatch_real x 68 x 3]
kldmk3d_gt = self.netF.seletec_3d68(kgeo_gt) # [nbatch_real x 68 x 3]
kldmk3d_pt = util.batch_orth_proj(kldmk3d_pt, cam);
kldmk3d_pt[:,:,1:] = -kldmk3d_pt[:,:,1:];
kldmk3d_gt = util.batch_orth_proj(kldmk3d_gt, cam);
kldmk3d_gt[:,:,1:] = -kldmk3d_gt[:,:,1:];
if vis_landmarks:
# landmarks 3d
kldmk3d_pt = self.netF.seletec_3d68(kgeo_pt) # [nbatch_real x 68 x 3]
kldmk3d_gt = self.netF.seletec_3d68(kgeo_gt) # [nbatch_real x 68 x 3]
kldmk3d_pt = util.batch_orth_proj(kldmk3d_pt, cam);
kldmk3d_pt[:,:,1:] = -kldmk3d_pt[:,:,1:];
kldmk3d_gt = util.batch_orth_proj(kldmk3d_gt, cam);
kldmk3d_gt[:,:,1:] = -kldmk3d_gt[:,:,1:];
render_pt = util.tensor_vis_landmarks(render_pt, kldmk3d_pt, gt_landmarks=kldmk3d_gt, isScale=True, color = (255, 0, 0), color_gt=(0, 255, 0))
render_gt = util.tensor_vis_landmarks(render_gt, kldmk3d_gt, isScale=True, color = (0, 255, 0))
render_pt = util.tensor_vis_landmarks(render_pt, kldmk3d_pt, gt_landmarks=kldmk3d_gt, isScale=True, color = (255, 0, 0), color_gt=(0, 255, 0))
render_gt = util.tensor_vis_landmarks(render_gt, kldmk3d_gt, isScale=True, color = (0, 255, 0))
else:
render_pt = render_pt.cpu()
render_gt = render_gt.cpu()
# append each frame
for m in range(nbatch_real):
@@ -507,13 +517,9 @@ class Audio2MeshModel(Base):
v_render_gt.append(tensor2image(render_gt[m, ...]))
# write tmp audio
tmp_audio = tempfile.NamedTemporaryFile(suffix='.wav')
wavfile.write(tmp_audio.name, rate=16000, data=raw_speech)
# save animation
write_video_with_gt(v_render_pt, v_render_gt, raw_speech, ipath_save, fps=50, sr=16000)
# 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=50, path_audio=tmp_audio.name)
@torch.no_grad()
@@ -589,6 +595,9 @@ class Audio2MeshModel(Base):
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()
+221 -155
View File
@@ -30,9 +30,9 @@ class Audio2PoseModel(Base):
self.logger = logger
self.names_model = ["G"] # G
self.nc_motion = opt.MODEL.dim_motion # 9-dim pose (rotation-3 + translation-2 + sacle-1)
self.nc_speech = opt.MODEL.dim_speech # 1024-dim
self.nc_latent = opt.MODEL.nc_latent # 64
self.dim_motion = opt.MODEL.dim_motion # 6-dim pose (rotation-3 + translation-2 + sacle-1)
self.dim_speech = opt.MODEL.dim_speech # 1024-dim
self.dim_latent = opt.MODEL.dim_hidden # 64
# define networks
self.netG = define_netG(opt)
@@ -67,17 +67,32 @@ class Audio2PoseModel(Base):
self.scheduler_G = get_scheduler(self.optimizer_G, opt)
self.schedulers.append(self.scheduler_G)
# schedule traning
self.sample_schedule = torch.cat((
# First part is pure teacher forcing
torch.zeros(self.opt.TRAIN.epoch_teacher),
# Second part with schedule sampling
torch.linspace(0.0, 1.0, self.opt.TRAIN.epoch_sampling),
# last part is pure student
torch.ones(self.opt.TRAIN.epoch_end - self.opt.TRAIN.epoch_sampling - self.opt.TRAIN.epoch_teacher),
))
def set_input(self, batch_input):
# motion data
x = batch_input["pose"].float().to(self.device) # (B, nsteps, nc_motion)
x = batch_input["pos"].float().to(self.device) # (B, nsteps, 9) 3-headpose 3-mouthpose, 1-scale, 2-translate
self.idn = batch_input["idn"].float().to(self.device) # (B, nsteps, 100)
self.exp = batch_input["exp"].float().to(self.device) # (B, nsteps, 50)
self.pos_mouth = x[..., 3:6] # (B, nsteps, 3)
self.x = x[..., [0,1,2,6,7,8]] # (B, nsteps, 6)
self.batch_vid = batch_input['vid']
self.batch_nframe = batch_input['nframe']
self.batch_interv = batch_input['frame_interval']
debug(self.opt, f"x = {x.shape}, dtype={x.dtype}", verbose=False)
debug(self.opt, f"pos = {self.x.shape}, dtype={self.x.dtype},exp = {self.exp.shape}, idn = {self.idn.shape}, ", 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])}, \
@@ -89,10 +104,10 @@ class Audio2PoseModel(Base):
# 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_pad = np.pad(raw_speech, pad_width=((0,0), (npad, npad)), mode="edge")
debug(self.opt, f"after padding raw_pad = {raw_pad.shape}, dtype={raw_pad.dtype}", verbose=False)
inputs = self.processor(list(raw_speech), sampling_rate=16000, return_tensors="pt")
inputs = self.processor(list(raw_pad), sampling_rate=16000, return_tensors="pt")
with torch.no_grad():
cond = self.extractor(**inputs.to(self.device)).last_hidden_state # B x nsteps x nc_feat
debug(self.opt, f"cond = {cond.shape}, dtype={cond.dtype}, device={cond.device}", verbose=False)
@@ -102,13 +117,20 @@ class Audio2PoseModel(Base):
cond = cond.permute(0, 1, 3, 2) # (B, nsteps, 16, nc_speech)
# setup
self.c = cond # (B, nsteps, 16, nc_speech)
self.B, self.nsteps, self.nwind, self.nc_speech = cond.size()
self.x = x[:, 7:7+self.nsteps, :] # (B, nsteps, nc_motion)
self.c = cond # (B, nsteps, 16, nc_speech)
self.B, self.nsteps, self.nwind, self.dim_speech = cond.size()
self.x = self.x[:, 7:7+self.nsteps, :] # (B, nsteps, nc_motion)
self.raw_speech = raw_speech[:, 7*self.opt.DATASET.sr: (7+self.nsteps)*self.opt.DATASET.sr] # (B, nsteps * sr)
self.idn = self.idn[:, 7:7+self.nsteps, :]
self.exp = self.exp[:, 7:7+self.nsteps, :]
self.pos_mouth = self.pos_mouth[:, 7:7+self.nsteps, :]
debug(self.opt, f"x = {self.x.shape}, dtype={self.x.dtype}, device={self.x.device}", verbose=False)
debug(self.opt, f"c = {self.c.shape}, dtype={self.c.dtype}, device={self.c.device}", verbose=False)
debug(self.opt, f"idn = {self.idn.shape}, dtype={self.idn.dtype}, device={self.idn.device}", verbose=False)
debug(self.opt, f"exp = {self.exp.shape}, dtype={self.exp.dtype}, device={self.exp.device}", verbose=False)
def forward(self, batch_input):
@@ -121,20 +143,79 @@ class Audio2PoseModel(Base):
return pred
def training(self, batch_input):
def update_parameters(self, epoch):
# update beta
N = self.opt.TRAIN.n_cycle_period # 50
n = epoch % N
if n < N * 0.1: # 5
beta_update = 0
elif n < N * 0.3: # 5 ~ 15 => 0.0001 ~ 0.01
beta_update = 0.0001 + (n - 0.1 * N) * ((0.01 - 0.0001) / (0.2 * N))
elif n < N * 0.5: # 15~25 => 0.01 ~ 0.1
beta_update = 0.01 + (n - 0.3 * N) * ((0.1 - 0.01) / (0.2 * N))
elif n < N * 0.7: # 35~25 => 0.1 ~ 1
beta_update = 0.1 + (n - 0.5 * N) * ((1 - 0.1) / (0.2 * N))
elif n < N * 0.8: # 35~40 => 0.1 ~ 1
beta_update = 1
else: # 40~50 => 1 ~0
beta_update = 1 + (n - 0.8 * N) * ((0 - 1) / (0.2 * N))
self.opt.LOSS.lambda_kl = beta_update
self.logger.info(f"\t[UPDATE] lambda_kl = {self.opt.LOSS.lambda_kl}")
def training(self, batch_input, idx_epoch=0, idx_batch=0):
self.train() # set train model
self.set_input(batch_input)
batch_x = self.x[:, 1:].reshape(-1, self.nc_motion) # [B*(nsteps-1), nc_motion]
batch_c = self.c[:, 1:].reshape(-1, self.nwind, self.nc_speech) # [B*(nsteps-1), nwind, nc_speech]
batch_x_prev = self.x[:, :-1] # [B*(nsteps-1), nc_motion]
# forward
batch_pt, batch_mu, batch_lv = self.netG(batch_x, batch_x_prev, batch_c) # [B*(nsteps-1), nc_motion]
debug(self.opt, f"traing batch_pt = {batch_pt.shape}, batch_gt = {batch_x.shape}")
# loss
loss, loss_dict = self.eval_losses(batch_pt, batch_x, batch_mu, batch_lv)
# get input
batch_gt = self.x[:, 1:, :].reshape(-1, self.dim_motion) # [B * (nstep-1), nc_motion]
# random
use_student = torch.rand(1) < self.sample_schedule[idx_epoch]
if not use_student:
batch_c = self.c[:, 1:].reshape(-1, self.nwind, self.dim_speech) # [B*(nsteps-1), nwind, nc_speech]
batch_x_prev = self.x[:, :-1].reshape(-1, self.dim_motion) # [B*(nsteps-1), nc_motion]
# forward
batch_pt, batch_mu, batch_lv = self.netG(batch_gt, batch_x_prev, batch_c) # [B*(nsteps-1), nc_motion]
debug(self.opt, f"traing batch_pt = {batch_pt.shape}, batch_gt = {batch_gt.shape}")
else:
batch_pt = torch.zeros_like(self.x) # [B, nsteps, nc_motion]
batch_pt[:, 0] = self.x[:, 0] # assign first frame
batch_mu = []
batch_lv = []
for istep in range(1, self.nsteps):
ibatch_x = self.x[:, istep] # [B, nc_motion]
ibatch_c = self.c[:, istep] # [B, nwind, nc_speech]
ibatch_x_prev = batch_pt[:, istep-1] # [B, nc_motion]
# forward
ibatch_pt, ibatch_mu, ibatch_lv = self.netG(ibatch_x, ibatch_x_prev, ibatch_c) # [B, nc_motion]
debug(self.opt, f"[test] ibatch_pt = {ibatch_pt.shape}")
batch_pt[:, istep] = ibatch_pt.detach().clone() # update batch_pt
batch_mu.append(ibatch_mu)
batch_lv.append(ibatch_lv)
# prepare data for eval_loss
batch_mu = torch.stack(batch_mu, dim=1) # [B, nstep-1, latent_size]
batch_lv = torch.stack(batch_lv, dim=1) # [B, nstep-1, latent_size]
debug(self.opt, f"[valid] batch_mu = {batch_mu.shape}, batch_lv = {batch_lv.shape}, batch_pt= {batch_pt.shape}")
batch_mu = batch_mu.reshape(-1, self.dim_latent) # [B * (nstep-1), nc_latent]
batch_lv = batch_lv.reshape(-1, self.dim_latent) # [B * (nstep-1), nc_latent]
batch_pt = batch_pt[:, 1:, :].reshape(-1, self.dim_motion) # [B * (nstep-1), nc_motion]
# evaluate loss
loss, loss_dict = self.eval_losses(batch_pt, batch_gt, batch_mu, batch_lv)
# backward
self.optimizer_G.zero_grad()
@@ -147,8 +228,7 @@ class Audio2PoseModel(Base):
return loss_dict
def validation(self, batch_input):
def validation(self, batch_input, idx_epoch=0, idx_batch=0):
self.eval() # set eval model
self.set_input(batch_input)
@@ -165,7 +245,7 @@ class Audio2PoseModel(Base):
# forward
ibatch_pt, ibatch_mu, ibatch_lv = self.netG(ibatch_x, ibatch_x_prev, ibatch_c) # [B, nc_motion]
self.logger.info(f"[test] ibatch_pt = {ibatch_pt.shape}")
debug(self.opt, f"[test] ibatch_pt = {ibatch_pt.shape}")
batch_pt[:, istep] = ibatch_pt.detach().clone() # update batch_pt
batch_mu.append(ibatch_mu)
@@ -176,74 +256,73 @@ class Audio2PoseModel(Base):
batch_lv = torch.stack(batch_lv, dim=1) # [B, nstep-1, latent_size]
debug(self.opt, f"[valid] batch_mu = {batch_mu.shape}, batch_lv = {batch_lv.shape}, batch_pt= {batch_pt.shape}")
batch_mu = batch_mu.reshape(-1, self.nc_latent) # [B * (nstep-1), nc_latent]
batch_lv = batch_lv.reshape(-1, self.nc_latent) # [B * (nstep-1), nc_latent]
batch_pt = batch_pt[:, 1:, self.nc_motion].reshape(-1, self.nc_motion) # [B * (nstep-1), nc_motion]
batch_gt = self.x[:, 1:, self.nc_motion].reshape(-1, self.nc_motion) # [B * (nstep-1), nc_motion]
batch_mu = batch_mu.reshape(-1, self.dim_latent) # [B * (nstep-1), nc_latent]
batch_lv = batch_lv.reshape(-1, self.dim_latent) # [B * (nstep-1), nc_latent]
batch_pt = batch_pt[:, 1:, :].reshape(-1, self.dim_motion) # [B * (nstep-1), nc_motion]
batch_gt = self.x[:, 1:, :].reshape(-1, self.dim_motion) # [B * (nstep-1), nc_motion]
loss, loss_dict = self.eval_losses(batch_pt, batch_gt, batch_mu, batch_lv)
return loss_dict
def infer(self, batch_cond, path_audio, suffix="", save_npy=True):
self.eval()
c = batch_cond.float().to(self.device) # (B, nsteps, 16, nc_speech)
nbtach, nstep, *_ = c.shape
with torch.no_grad():
batch_pdt_geo = self.netG(self.cond) # B x N x dim_motion
batch_pdt_geo += self.temp_verts # B x N x 5023 x 3
batch_pos = self.netG(self.cond) # B x N x dim_motion
batch_pos += self.temp_verts # B x N x 5023 x 3
print(f"testing pt shape = {batch_pdt_geo.shape}")
print(f"testing pt shape = {batch_pos.shape}")
# !! add specific when render & output !!
batch_pdt_geo = batch_pdt_geo - self.temp_verts + self.temp_verts_specific
batch_pos = batch_pos - self.temp_verts + self.temp_verts_specific
# render & and save
self.save_reconstruct(batch_pdt_geo, path_audio,
self.save_reconstruct(batch_pos, path_audio,
path_save=Path(self.opt.OUTPUT_DIR),
suffix=suffix)
if save_npy:
# save result
batch_pdt_geo = batch_pdt_geo.cpu().numpy()
batch_pos = batch_pos.cpu().numpy()
path_save_npy = Path(self.opt.OUTPUT_DIR).joinpath(f"{suffix}.npy")
np.save(path_save_npy, batch_pdt_geo)
print(f"save infer_result shape = {batch_pdt_geo.shape} -> {path_save_npy}")
np.save(path_save_npy, batch_pos)
print(f"save infer_result shape = {batch_pos.shape} -> {path_save_npy}")
def testing(self, batch_input, cur_epoch=0, cur_batch=0):
def testing(self, batch_input, idx_epoch=0, idx_batch=0):
self.eval() # set eval model
self.set_input(batch_input)
with torch.no_grad():
batch_pt = torch.zeros_like(self.x) # [B, nsteps, nc_motion]
batch_pt[:, 0] = self.x[:, 0] # assign first frame
# batch_pt[:, 0, 3] = self.x[:, 0, 3] # T-pose + first scale from input data
batch_pt[:, 0] = self.x[:, 0] # T-pose + first scale from input data
for istep in range(1, self.nsteps):
ibatch_x = self.x[:, istep] # [B, nc_motion]
ibatch_z = torch.randn((self.B, self.dim_latent), device=self.device) # [B, dim_latent]
ibatch_c = self.c[:, istep] # [B, nwind, nc_speech]
ibatch_x_prev = batch_pt[:, istep-1] # [B, nc_motion]
# forward
ibatch_pt, *_ = self.netG(ibatch_x, ibatch_x_prev, ibatch_c) # [B, nc_motion]
self.logger.info(f"[test] ibatch_pt = {ibatch_pt.shape}")
ibatch_pt = self.netG.sample(ibatch_z, ibatch_x_prev, ibatch_c) # [B, nc_motion]
batch_pt[:, istep] = ibatch_pt.detach().clone() # update batch_pt
debug(self.opt, f"[test] ibatch_pt = {ibatch_pt.shape}")
batch_pt[:, istep] = ibatch_pt.detach().clone() # update batch_pt
# save video
print(f"testing pt shape = {batch_pt.shape}, gt shape = {self.x.shape}")
# print(f"testing pt shape = {batch_pt.shape}, gt shape = {self.x.shape}")
self.save_reconstruct_with_gt(batch_pt, self.x,
path_save=Path(self.opt.OUTPUT_DIR),
suffix=f'sampled_{cur_epoch:05d}_{cur_batch:03d}')
suffix=f'sampled_{idx_epoch:05d}_{idx_batch:03d}')
@torch.no_grad()
def get_template_vertices(self, mean_dict=None):
batch_exp = torch.zeros(1, 50).to(self.device)
@@ -255,46 +334,17 @@ class Audio2PoseModel(Base):
else:
batch_shape = torch.zeros(1, 100).to(self.device)
with torch.no_grad():
# verts = 1 x 5023 x 3, ldmk2d=1 x 68 x 3, ldmk3d=1 x 68 x 3
verts, ldmk2d, ldmk3d = self.netF(batch_shape, batch_exp, batch_pose)
verts = verts.reshape(1, 1, -1, 3) # 1 x 1 x 5023 x 3
ldmk2d = ldmk2d.reshape(1, 1, -1, 3) # 1 x 1 x 68 x 3
ldmk3d = ldmk3d.reshape(1, 1, -1, 3) # 1 x 1 x 68 x 3
# verts = 1 x 5023 x 3, ldmk2d=1 x 68 x 3, ldmk3d=1 x 68 x 3
verts, ldmk2d, ldmk3d = self.netF(batch_shape, batch_exp, batch_pose)
verts = verts.reshape(1, 1, -1, 3) # 1 x 1 x 5023 x 3
ldmk2d = ldmk2d.reshape(1, 1, -1, 3) # 1 x 1 x 68 x 3
ldmk3d = ldmk3d.reshape(1, 1, -1, 3) # 1 x 1 x 68 x 3
print(f"template verts reshape = {verts.shape}")
# np.save("./data/template.npy", verts.squeeze().cpu().numpy())
# print(f"save template.npy = {verts.squeeze().shape}")
# assert False
# print(f"template verts reshape = {verts.shape}")
return verts, ldmk2d, ldmk3d
def get_vertices(self, batch_motion):
"""
batch_motion, (nbatch, seqlen, 53)
"""
batch_exp = batch_motion[..., :50]
batch_pos_mouth = batch_motion[..., 50:]
nbatch, seqlen = batch_exp.size(0), batch_exp.size(1)
batch_exp = batch_exp.reshape(nbatch * seqlen, -1) # nbatch * seqlen x 50
batch_pos_mouth = batch_pos_mouth.reshape(nbatch * seqlen, -1) # nbatch * seqlen x 3
batch_shape= torch.zeros(nbatch * seqlen, 100).to(self.device) # nbatch * seqlen x 50
batch_pose = torch.zeros(nbatch * seqlen, 6).to(self.device) # nbatch * seqlen x 6
batch_pose[:, 3:6] = batch_pos_mouth
with torch.no_grad():
verts, ldmk2d, ldmk3d = self.netF(batch_shape, batch_exp, batch_pose) # nbatch * seqlen x 5023 x 3
verts = verts.reshape(nbatch, seqlen, -1, 3) # nbatch x seqlen x 5023 x 3
ldmk2d = ldmk2d.reshape(nbatch, seqlen, -1, 3) # nbatch x seqlen x 5023 x 3
ldmk3d = ldmk3d.reshape(nbatch, seqlen, -1, 3) # nbatch x seqlen x 5023 x 3
return verts, ldmk2d, ldmk3d
def eval_losses(self, batch_pt, batch_gt, batch_mu, batch_lv):
""" Computes the VAE loss function.
pramas:
@@ -302,12 +352,13 @@ class Audio2PoseModel(Base):
batch_mu, batch_lv: [B * nsteps, nc_latent]
"""
loss = 0
loss_dict = OrderedDict()
# recon loss
loss_rec = (batch_pt - batch_gt).pow(2).mean()
loss_dict["rec"] = loss_rec.detach()
loss = loss_rec
loss += loss_rec
# kl loss
loss_kl = -0.5 * (1 + batch_lv - batch_mu.pow(2) - batch_lv.exp()).sum().clamp(max=0) # [B*nsteps, ]
@@ -317,19 +368,17 @@ class Audio2PoseModel(Base):
if self.opt.LOSS.lambda_kl > 0:
loss += loss_kl * self.opt.LOSS.lambda_kl
# velocity loss
batch_pt = batch_pt.reshape(self.B, self.nsteps, self.nc_motion)
batch_gt = batch_gt.reshape(self.B, self.nsteps, self.nc_motion)
batch_pt = batch_pt.reshape(self.B, -1, self.dim_motion)
batch_gt = batch_gt.reshape(self.B, -1, self.dim_motion)
diff_pt = batch_pt[:, 1:, :] - batch_pt[:, :-1, :] # [B, nsteps-1, nc_motion]
diff_gt = batch_gt[:, 1:, :] - batch_gt[:, :-1, :] # (B, nsteps-1, nc_motion)
diff_pt = batch_pt[:, 1:, :] - batch_pt[:, :-1, :] # [B, nsteps-2, nc_motion]
diff_gt = batch_gt[:, 1:, :] - batch_gt[:, :-1, :] # (B, nsteps-2, nc_motion)
loss_vel_rec = (diff_pt - diff_gt).pow(2).mean()
loss_dict["vel_rec"] = loss_vel_rec.detach()
if self.opt.LOSS.lambda_vel_rec > 0:
loss += loss_vel_rec * self.opt.LOSS.lambda_vel_rec
loss_dict["vel"] = loss_vel_rec.detach()
if self.opt.LOSS.lambda_vel > 0:
loss += loss_vel_rec * self.opt.LOSS.lambda_vel
# total loss
loss_dict["all"] = loss.detach()
@@ -337,40 +386,54 @@ class Audio2PoseModel(Base):
return loss, loss_dict
def save_reconstruct(self, batch_pdt_geo, path_audio, path_save, suffix=""):
# batch_pdt_geo, [B x N x dim_motion]
@torch.no_grad()
def save_reconstruct(self, batch_pdt_pos, raw_speech, path_save, suffix="", vis_landmarks=True):
# batch_pdt_pos, [B x N x dim_motion]
B, N, *_ = batch_pdt_geo.shape
B, N, *_ = batch_pdt_pos.shape
nbatch_render = 10
# for each batch
for i in range(B):
ipos_pt = batch_pdt_geo[i, ...]
ipos_pt = batch_pdt_pos[i, ...] # [N x 9]
ipath_save = path_save.joinpath(f"{suffix}_{i:02d}.mp4")
v_render_pt = []
for k in range(0, N, nbatch_render):
# split
kpos_pt = ipos_pt[k:k+nbatch_render, ...] # [nbatch_real x 5023 x 3]
nbatch_real = kpos_pt.size(0)
# get gt coeff
kpos_mouth_gt= self.pos_mouth[i, k:k+nbatch_render, :] # [nbatch_real, 3]
kidn_gt = self.idn[i, k:k+nbatch_render, :] # [nbatch_real, 100]
kexp_gt = self.exp[i, k:k+nbatch_render, :] # [nbatch_real, 50]
# 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}")
# get exp & cam
kpos_pt = torch.cat([ipos_pt[k:k+nbatch_render, :3], kpos_mouth_gt], dim=1) # [nbatch_real x 6]
kcam_pt = ipos_pt[k:k+nbatch_render, 3:] # [nbatch_real x 3]
# render
render_pt = self.render_geometry(kpos_pt, cam, self.device) # (nbatch_real, 3, 512, 512)
render_pt = render_pt.cpu()
# print(f"render_pt ={render_pt.shape}, render_gt={render_gt.shape}")
# print(f"kidn_gt={kidn_gt.shape}, kexp_gt={kexp_gt.shape}, kpos_pt={kpos_pt.shape}")
# get geometry & render
kgeo_pt, kldmk2d_pt, kldmk3d_pt = self.netF(kidn_gt, kexp_gt, kpos_pt) # [nbatch x 5023 x 3], [nbatch x 68 x 3]
render_pt = self.render_geometry(kgeo_pt, kcam_pt, self.device) # (nbatch_real, 3, 512, 512)
# print(f"testing v_render_pt = {len(v_render_pt)}")
if vis_landmarks:
kldmk3d_pt = util.batch_orth_proj(kldmk3d_pt, kcam_pt);
kldmk3d_pt[:,:,1:] = -kldmk3d_pt[:,:,1:];
render_pt = util.tensor_vis_landmarks(render_pt, kldmk3d_pt, isScale=True, color = (255, 0, 0))
else:
render_pt = render_pt.cpu()
# append each frame
nbatch_real = kpos_pt.size(0)
for m in range(nbatch_real):
v_render_pt.append(tensor2image(render_pt[m, ...]))
# write tmp audio
tmp_audio = tempfile.NamedTemporaryFile(suffix='.wav')
wavfile.write(tmp_audio.name, rate=16000, data=raw_speech)
# save animation
# print(f"testing v_render_pt = {len(v_render_pt)}")
save_images_with_audio(v_render_pt, path_audio, ipath_save)
save_images_with_audio(v_render_pt, tmp_audio.name, ipath_save)
@torch.no_grad()
@@ -392,14 +455,15 @@ class Audio2PoseModel(Base):
return images
@torch.no_grad()
def save_reconstruct_with_gt2(self, batch_pdt_geo, batch_tgt_geo, raw_speech, path_save, suffix=""):
# batch_pdt_geo, [1 x N x 5023 x 3]
def save_reconstruct_with_gt2(self, batch_pdt_pos, batch_tgt_geo, raw_speech, path_save, suffix="", vis_landmarks=True):
# batch_pdt_pos, [1 x N x 5023 x 3]
# batch_tgt_geo, [1 x N x 5023 x 3]
B, N, *_ = batch_pdt_geo.shape
B, N, *_ = batch_pdt_pos.shape
ipos_pt = batch_pdt_geo[0, ...] # [N x 5023 x 3]
ipos_pt = batch_pdt_pos[0, ...] # [N x 5023 x 3]
ipos_gt = batch_tgt_geo[0, ...] # [N x 5023 x 3]
ipath_save = path_save.joinpath(f"{suffix}_{0:02d}.mp4")
@@ -422,19 +486,22 @@ class Audio2PoseModel(Base):
render_gt = self.render_geometry(kpos_gt, cam, self.device) # (nbatch_real, 3, 512, 512)
# print(f"render_pt ={render_pt.shape}, render_gt={render_gt.shape}")
# landmarks 3d
kldmk3d_pt = self.netF.seletec_3d68(kpos_pt) # [nbatch_real x 68 x 3]
kldmk3d_gt = self.netF.seletec_3d68(kpos_gt) # [nbatch_real x 68 x 3]
kldmk3d_pt = util.batch_orth_proj(kldmk3d_pt, cam);
kldmk3d_pt[:,:,1:] = -kldmk3d_pt[:,:,1:];
kldmk3d_gt = util.batch_orth_proj(kldmk3d_gt, cam);
kldmk3d_gt[:,:,1:] = -kldmk3d_gt[:,:,1:];
render_pt = util.tensor_vis_landmarks(render_pt, kldmk3d_pt, gt_landmarks=kldmk3d_gt, isScale=True, color = (255, 0, 0), color_gt=(0, 255, 0))
render_gt = util.tensor_vis_landmarks(render_gt, kldmk3d_gt, isScale=True, color = (0, 255, 0))
if vis_landmarks:
# landmarks 3d
kldmk3d_pt = self.netF.seletec_3d68(kgeo_pt) # [nbatch_real x 68 x 3]
kldmk3d_gt = self.netF.seletec_3d68(kgeo_gt) # [nbatch_real x 68 x 3]
kldmk3d_pt = util.batch_orth_proj(kldmk3d_pt, cam);
kldmk3d_pt[:,:,1:] = -kldmk3d_pt[:,:,1:];
kldmk3d_gt = util.batch_orth_proj(kldmk3d_gt, cam);
kldmk3d_gt[:,:,1:] = -kldmk3d_gt[:,:,1:];
render_pt = util.tensor_vis_landmarks(render_pt, kldmk3d_pt, gt_landmarks=kldmk3d_gt, isScale=True, color = (255, 0, 0), color_gt=(0, 255, 0))
render_gt = util.tensor_vis_landmarks(render_gt, kldmk3d_gt, isScale=True, color = (0, 255, 0))
else:
render_pt = render_pt.cpu()
render_gt = render_gt.cpu()
# append each frame
for m in range(nbatch_real):
v_render_pt.append(tensor2image(render_pt[m, ...]))
@@ -452,40 +519,47 @@ class Audio2PoseModel(Base):
@torch.no_grad()
def save_reconstruct_with_gt(self, batch_pdt_pos, batch_tgt_pos, path_save, suffix=""):
# batch_pdt_pos, [B x N x nc_motion=9]
# batch_pdt_pos, [B x N x nc_motion=9]
# batch_pdt_pos, [B x N x nc_motion=6]
# batch_pdt_pos, [B x N x nc_motion=6]
B, N, *_ = batch_pdt_pos.shape
nbatch_render = 10
# for each batch
for i in range(B):
ipos_pt = batch_pdt_pos[i, ...] # [N x 9]
ipos_gt = batch_tgt_pos[i, ...] # [N x 9]
ipos_pt = batch_pdt_pos[i, ...] # [N x 6]
ipos_gt = batch_tgt_pos[i, ...] # [N x 6]
ipath_save = path_save.joinpath(f"{suffix}_{i:02d}.mp4")
v_render_pt = []
v_render_gt = []
for k in range(0, N, nbatch_render):
# get gt coeff
kpos_mouth_gt= self.pos_mouth[i, k:k+nbatch_render, :] # [nbatch_real, 3]
kidn_gt = self.idn[i, k:k+nbatch_render, :] # [nbatch_real, 100]
kexp_gt = self.exp[i, k:k+nbatch_render, :] # [nbatch_real, 50]
# split
kpos_pt = ipos_pt[k:k+nbatch_render, :6] # [nbatch_real x 6]
kpos_gt = ipos_gt[k:k+nbatch_render, :6] # [nbatch_real x 6]
kcam_pt = ipos_pt[k:k+nbatch_render, 6:] # [nbatch_real x 3]
kcam_gt = ipos_gt[k:k+nbatch_render, 6:] # [nbatch_real x 3]
# get exp
kpos_pt = torch.cat([ipos_pt[k:k+nbatch_render, :3], kpos_mouth_gt], dim=1) # [nbatch_real x 6]
kpos_gt = torch.cat([ipos_gt[k:k+nbatch_render, :3], kpos_mouth_gt], dim=1) # [nbatch_real x 6]
kidn_gt = self.idn[k:k+nbatch_render, :] # [nbatch_real, 100]
kexp_gt = self.exp[k:k+nbatch_render, :] # [nbatch_real, 50]
# get cam
kcam_pt = ipos_pt[k:k+nbatch_render, 3:] # [nbatch_real x 3]
kcam_gt = ipos_gt[k:k+nbatch_render, 3:] # [nbatch_real x 3]
kcam_pt[:, 0] *= 0.7
kcam_gt[:, 0] *= 0.7
# print(f"kidn_gt={kidn_gt.shape}, kexp_gt={kexp_gt.shape}, kpos_pt={kpos_pt.shape}")
# get geometry
kgeo_pt = self.get_vertices(kidn_gt.clone(), kexp_gt.clone(), kpos_pt) # (nbatch_read, 5023, 3)
kgeo_gt = self.get_vertices(kidn_gt.clone(), kexp_gt.clone(), kpos_gt) # (nbatch_read, 5023, 3)
kgeo_pt, *_ = self.netF(kidn_gt, kexp_gt, kpos_pt) # [nbatch x 5023 x 3], [nbatch x 68 x 3]
kgeo_gt, *_ = self.netF(kidn_gt, kexp_gt, kpos_gt) # [nbatch x 5023 x 3], [nbatch x 68 x 3]
# render geometry
render_pt = self.render_geometry(kgeo_pt, kcam_pt, self.device).detach().cpu() # (nbatch_real, 3, 512, 512)
render_gt = self.render_geometry(kgeo_gt, kcam_gt, self.device).detach().cpu() # (nbatch_real, 3, 512, 512)
render_pt = self.render_geometry(kgeo_pt, kcam_pt, self.device).cpu() # (nbatch_real, 3, 512, 512)
render_gt = self.render_geometry(kgeo_gt, kcam_gt, self.device).cpu() # (nbatch_real, 3, 512, 512)
# print(f"render_pt ={render_pt.shape}, render_gt={render_gt.shape}")
# append each frame
@@ -524,18 +598,10 @@ def tensor2image(tensor):
def define_netG(opt):
netG = None
if opt.MODEL.name_netG == "audio2mesh":
from src.nn.audio2mesh import Audio2Mesh
netG = Audio2Mesh(opt)
if opt.MODEL.name_netG == "audio2pose_mvae":
from src.nn.audio2pose_mvae import PoseMixtureVAE
netG = PoseMixtureVAE(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!")