add eval.py with metrics
This commit is contained in:
1 parent
11277e478f
commit
baed1fffe3
53 files changed
+5844
-378
No files matched your search
+8
-6
@@ -107,7 +107,6 @@ class Base():
|
||||
"""
|
||||
# if train
|
||||
if self.isTrain:
|
||||
|
||||
# load model for resume
|
||||
if opt.TRAIN.resume:
|
||||
self.logger.info("SETUP: resume network training")
|
||||
@@ -127,13 +126,14 @@ class Base():
|
||||
|
||||
# if test or infer
|
||||
else:
|
||||
self.logger.info("SETUP: TEST or INFER, load pretrain network")
|
||||
# self.logger.info("SETUP: TEST or INFER, load pretrain network")
|
||||
load_suffix = f'iter_{opt.TRAIN.load_iter}' if opt.TRAIN.load_iter > 0 else opt.MODEL.load_epoch
|
||||
path_chekpoints = Path(opt.MODEL.path_checkpoint)
|
||||
self.load_networks(load_suffix, path_chekpoints, load_info=False)
|
||||
|
||||
# printer networks
|
||||
self.print_networks(opt.verbose)
|
||||
if opt.verbose:
|
||||
self.print_networks(opt.verbose)
|
||||
|
||||
|
||||
def update_parameters(self, epoch):
|
||||
@@ -185,10 +185,11 @@ class Base():
|
||||
errors_ret = OrderedDict()
|
||||
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 ].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
|
||||
|
||||
if phase == "valid":
|
||||
errors_ret[name+"_val"] = self.loss_dict["loss_" + name ].float().cpu() # float(...) works for both scalar tensor and float number
|
||||
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()
|
||||
|
||||
@@ -301,6 +302,7 @@ class Base():
|
||||
verbose (bool) -- if verbose: print the network architecture
|
||||
"""
|
||||
self.logger.info('---------- Networks initialized -------------')
|
||||
|
||||
for name in self.names_model:
|
||||
net = getattr(self, 'net' + name)
|
||||
num_params = 0
|
||||
|
||||
+64
-1
@@ -1,4 +1,65 @@
|
||||
|
||||
idx_upper_mouth_68ldmk = [
|
||||
49, 50, 51, 52, 53,
|
||||
61, 62, 63,
|
||||
]
|
||||
|
||||
|
||||
idx_lower_mouth_68ldmk = [
|
||||
59, 58, 57, 56, 55,
|
||||
67, 66, 65,
|
||||
]
|
||||
|
||||
|
||||
idx_left_mouth_68ldmk = [
|
||||
48,
|
||||
49, 60, 59,
|
||||
50, 61, 67, 58
|
||||
]
|
||||
|
||||
idx_right_mouth_68ldmk = [
|
||||
54,
|
||||
53, 64, 55,
|
||||
52, 63, 65, 56
|
||||
]
|
||||
|
||||
|
||||
flame_mouth_upper_idx = [
|
||||
540, 577, 1576, 1579, 1657, 1658, 1659, 1660, 1661, 1662,
|
||||
1663, 1664, 1665, 1666, 1667, 1668, 1669, 1670, 1686, 1691,
|
||||
1693, 1694, 1695, 1696, 1697, 1700, 1702, 1703, 1704, 1709,
|
||||
1710, 1711, 1712, 1713, 1714, 1715, 1716, 1717, 1718, 1719,
|
||||
1720, 1721, 1722, 1723, 1725, 1730, 1731, 1732, 1733, 1734,
|
||||
1735, 1736, 1737, 1738, 1739, 1740, 1743, 1748, 1749, 1750,
|
||||
1751, 2712, 2774, 2775, 2776, 2777, 2778, 2779, 2780, 2781,
|
||||
2782, 2783, 2784, 2785, 2786, 2787, 2808, 2810, 2811, 2812,
|
||||
2813, 2814, 2817, 2818, 2819, 2820, 2821, 2822, 2826, 2827,
|
||||
2828, 2829, 2830, 2831, 2832, 2833, 2834, 2835, 2836, 2837,
|
||||
2838, 2840, 2842, 2846, 2847, 2848, 2849, 2850, 2851, 2852,
|
||||
2853, 2855, 2858, 2863, 2864, 2865, 2866, 3514, 3531, 3533,
|
||||
3537, 3541, 3543, 3546, 3547, 3549, 3791, 3792, 3795, 3797,
|
||||
3799, 3914, 3915, 3920,
|
||||
]
|
||||
|
||||
flame_mouth_lower_idx = [
|
||||
1572, 1573, 1576, 1577, 1578, 1579, 1580, 1581, 1582, 1583,
|
||||
1592, 1593, 1597, 1702, 1728, 1729, 1730, 1758, 1763, 1764,
|
||||
1765, 1766, 1767, 1768, 1769, 1770, 1771, 1773, 1774, 1775,
|
||||
1776, 1777, 1778, 1779, 1780, 1781, 1782, 1787, 1788, 1789,
|
||||
1791, 1792, 1793, 1794, 1795, 1796, 1797, 1799, 1801, 1802,
|
||||
1803, 1804, 1826, 1827, 1830, 1831, 1832, 1835, 1836, 1846,
|
||||
1847, 1848, 1849, 1850, 1851, 1852, 1854, 1860, 1861, 1862,
|
||||
1864, 1865, 1866, 2713, 2714, 2715, 2716, 2717, 2718, 2719,
|
||||
2843, 2844, 2869, 2871, 2873, 2876, 2878, 2879, 2880, 2881,
|
||||
2882, 2883, 2884, 2885, 2886, 2887, 2888, 2889, 2890, 2891,
|
||||
2892, 2894, 2895, 2896, 2897, 2898, 2899, 2900, 2902, 2904,
|
||||
2905, 2906, 2907, 2928, 2929, 2930, 2931, 2932, 2933, 2934,
|
||||
2935, 2936, 2937, 2938, 2939, 2940, 2941, 2944, 2947, 2948,
|
||||
2949, 3497, 3500, 3502, 3503, 3504, 3506, 3509, 3511, 3512,
|
||||
3513, 3790, 3796, 3798, 3800, 3805, 3806, 3916, 3919, 3921,
|
||||
3923, 3927, 3928,
|
||||
]
|
||||
|
||||
flame_mouth_idx = [
|
||||
1576, 1577, 1578, 1579, 1580, 1581, 1582, 1583, 1584, 1585,
|
||||
1586, 1587, 1590, 1596, 1597, 1598, 1599, 1601, 1603, 1657,
|
||||
@@ -108,4 +169,6 @@ flame_eye_idx = [
|
||||
3823, 3827, 3828, 3832, 3833, 3835, 3840, 3847, 3848, 3852,
|
||||
3853, 3854, 3855, 3856, 3857, 3858, 3859, 3860, 3861, 3881,
|
||||
3882, 3891, 3895, 3900, 3902, 3903, 3907, 3910,
|
||||
]
|
||||
]
|
||||
|
||||
|
||||
+107
-79
@@ -6,10 +6,11 @@ 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.info import flame_mouth_idx, flame_mouth_upper_idx, flame_mouth_lower_idx
|
||||
from src.models import init_net
|
||||
from src.models.base import Base
|
||||
from src.optims import get_optimizer, get_scheduler
|
||||
from src.losses.metrics import MeanDictMetric
|
||||
|
||||
# common
|
||||
from common.animation import save_animation_with_gt2, save_images_with_audio
|
||||
@@ -46,7 +47,6 @@ class Audio2MeshModel(Base):
|
||||
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")
|
||||
path_deca_mean = self.opt.DATASET.path_mean_dict
|
||||
self.mean_dict = np.load(path_deca_mean, allow_pickle=True).item()
|
||||
print(f"load mean deca coeff from > {path_deca_mean}, \nkeys = {self.mean_dict.keys()}")
|
||||
@@ -59,10 +59,15 @@ class Audio2MeshModel(Base):
|
||||
# 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
|
||||
|
||||
self.names_loss = opt.LOSS.names
|
||||
|
||||
# define loss weight
|
||||
self.vertices_weight = torch.ones((1, 1, self.opt.MODEL.num_vertices, 3)).to(self.device)
|
||||
self.vertices_weight[:, :, flame_mouth_idx, :] = 10
|
||||
|
||||
|
||||
if self.isTrain:
|
||||
# define optimizers
|
||||
self.optimizer_G = get_optimizer(self.netG, opt)
|
||||
self.optimizers.append(self.optimizer_G)
|
||||
@@ -70,10 +75,6 @@ class Audio2MeshModel(Base):
|
||||
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
|
||||
@@ -172,32 +173,12 @@ class Audio2MeshModel(Base):
|
||||
self.pred = self.netG(self.cond)
|
||||
self.pred += self.template_verts
|
||||
|
||||
loss, self.loss_dict = self.eval_losses(self.pred, self.data)
|
||||
|
||||
return loss
|
||||
_, loss_dict = self.eval_losses(self.pred, self.data)
|
||||
|
||||
return loss_dict
|
||||
|
||||
|
||||
def infer_loss(self, batch_cond, batch_data):
|
||||
"""
|
||||
input parameters:
|
||||
batch_cond: B x nsteps x 16 x nfeat_speech
|
||||
batch_data: B x nsteps x nfeat_motion
|
||||
return:
|
||||
loss: B x nsteps x 3
|
||||
"""
|
||||
self.eval()
|
||||
cond = batch_cond.float().to(self.device) # (B x nsteps x 16 x nc_condit)
|
||||
data = batch_data.float().to(self.device) # (B x nsteps x nc_motion)
|
||||
|
||||
with torch.no_grad():
|
||||
samples_pt = self.netG(cond) # B x N x 16 x nc_condit
|
||||
samples_pt += self.template_verts # B x N x 5023 x 3
|
||||
loss = self.eval_losses_for_infer_loss(samples_pt, data)
|
||||
|
||||
return loss
|
||||
|
||||
|
||||
def infer(self, batch_cond, path_audio, suffix=""):
|
||||
def infer(self, batch_cond, path_audio, suffix="", save_npy=True):
|
||||
self.eval()
|
||||
self.cond = batch_cond.float().to(self.device) # (nsteps, dim_cond)
|
||||
|
||||
@@ -207,19 +188,21 @@ class Audio2MeshModel(Base):
|
||||
|
||||
print(f"testing pt shape = {samples_pt.shape}")
|
||||
|
||||
self.save_reconstruct(samples_pt, path_audio,
|
||||
path_save=Path(self.opt.OUTPUT_DIR),
|
||||
suffix=suffix)
|
||||
|
||||
# !! add specific when render & output !!
|
||||
samples_pt = samples_pt - self.template_verts + self.template_verts_specific
|
||||
|
||||
# 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}")
|
||||
|
||||
# render & and save
|
||||
self.save_reconstruct(samples_pt, path_audio,
|
||||
path_save=Path(self.opt.OUTPUT_DIR),
|
||||
suffix=suffix)
|
||||
|
||||
if 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
|
||||
@@ -260,28 +243,6 @@ class Audio2MeshModel(Base):
|
||||
|
||||
return verts.unsqueeze(dim=0) # 1 x 1 x 5023 x 3
|
||||
|
||||
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
|
||||
|
||||
# np.save("./data/template.npy", verts.squeeze().cpu().numpy())
|
||||
# print(f"save template.npy = {verts.squeeze().shape}")
|
||||
# assert False
|
||||
|
||||
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):
|
||||
"""
|
||||
@@ -355,9 +316,9 @@ class Audio2MeshModel(Base):
|
||||
# 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_dict["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_dict["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
|
||||
@@ -373,9 +334,9 @@ class Audio2MeshModel(Base):
|
||||
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_dict["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_dict["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
|
||||
@@ -397,18 +358,70 @@ class Audio2MeshModel(Base):
|
||||
|
||||
# calculate again
|
||||
loss_rec_geo2 = loss_rec_geo2.mean()
|
||||
loss_dict["loss_rec_geo_w"] = loss_rec_geo2.detach()
|
||||
loss_dict["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_dict["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()
|
||||
loss_dict['all'] = loss.detach()
|
||||
|
||||
return loss, loss_dict
|
||||
|
||||
|
||||
def eval_losses_for_valid(self, batch_pdt_geo, batch_tgt):
|
||||
""" Computes the VAE loss function.
|
||||
pramas:
|
||||
batch_tgt, (nbatch, seqlen, dim_motion)
|
||||
batch_pdt_geo, (nbatch, seqlen, num_vertices, 3)
|
||||
"""
|
||||
|
||||
loss_dict = {}
|
||||
|
||||
# get mesh geometry
|
||||
batch_tgt_geo = self.get_vertices(batch_tgt) # B x nseq x num_vertices x 3
|
||||
|
||||
# synthesis geo rec
|
||||
loss_rec_geo = self.loss_func_wing(batch_pdt_geo, batch_tgt_geo)
|
||||
loss_dict["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["rec_geo_w"] = loss_rec_geo2.mean().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_geo = self.loss_func_wing(diff_pdt_geo, diff_tgt_geo)
|
||||
loss_dict["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["vel_geo_w"] = loss_vel_geo2.mean().detach()
|
||||
|
||||
|
||||
|
||||
# closure loss
|
||||
diff_pdf_closure = batch_pdt_geo[:,:,flame_mouth_upper_idx].sum(dim=[2,3]) / len(flame_mouth_upper_idx) \
|
||||
- batch_pdt_geo[:,:,flame_mouth_lower_idx].sum(dim=[2,3]) / len(flame_mouth_upper_idx)
|
||||
|
||||
diff_tgt_closure = batch_tgt_geo[:,:,flame_mouth_upper_idx].sum(dim=[2,3]) / len(flame_mouth_upper_idx) \
|
||||
- batch_tgt_geo[:,:,flame_mouth_lower_idx].sum(dim=[2,3]) / len(flame_mouth_upper_idx)
|
||||
|
||||
loss_closure = self.loss_func_wing(diff_pdf_closure, diff_tgt_closure)
|
||||
loss_dict["closure"] = loss_closure.mean().detach()
|
||||
|
||||
if self.opt.LOSS.lambda_closure > 0:
|
||||
loss += loss_closure.mean() * self.opt.LOSS.lambda_closure
|
||||
|
||||
# total loss
|
||||
loss_dict["all"] = loss.clone().detach()
|
||||
|
||||
# return
|
||||
return loss, loss_dict
|
||||
|
||||
|
||||
def eval_losses(self, batch_pdt_geo, batch_tgt):
|
||||
""" Computes the VAE loss function.
|
||||
pramas:
|
||||
@@ -422,12 +435,11 @@ class Audio2MeshModel(Base):
|
||||
batch_tgt_geo = self.get_vertices(batch_tgt) # B x nseq x num_vertices x 3
|
||||
|
||||
# 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.mean().detach()
|
||||
loss_dict["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_dict["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
|
||||
|
||||
@@ -436,17 +448,33 @@ class Audio2MeshModel(Base):
|
||||
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_dict["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()
|
||||
loss_dict["vel_geo_w"] = loss_vel_geo2.mean().detach()
|
||||
# loss += loss_vel_geo.mean() * self.opt.LOSS.lambda_vel_geo
|
||||
|
||||
if 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()
|
||||
|
||||
|
||||
# closure loss
|
||||
diff_pdf_closure = batch_pdt_geo[:,:,flame_mouth_upper_idx].sum(dim=[2,3]) / len(flame_mouth_upper_idx) \
|
||||
- batch_pdt_geo[:,:,flame_mouth_lower_idx].sum(dim=[2,3]) / len(flame_mouth_upper_idx)
|
||||
|
||||
diff_tgt_closure = batch_tgt_geo[:,:,flame_mouth_upper_idx].sum(dim=[2,3]) / len(flame_mouth_upper_idx) \
|
||||
- batch_tgt_geo[:,:,flame_mouth_lower_idx].sum(dim=[2,3]) / len(flame_mouth_upper_idx)
|
||||
|
||||
loss_closure = self.loss_func_wing(diff_pdf_closure, diff_tgt_closure)
|
||||
loss_dict["closure"] = loss_closure.mean().detach()
|
||||
|
||||
if self.opt.LOSS.lambda_closure > 0:
|
||||
loss += loss_closure.mean() * self.opt.LOSS.lambda_closure
|
||||
|
||||
# total loss
|
||||
loss_dict["all"] = loss.clone().detach()
|
||||
|
||||
# return
|
||||
return loss, loss_dict
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,629 @@
|
||||
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.info import idx_upper_mouth_68ldmk, idx_lower_mouth_68ldmk
|
||||
from src.models.info import idx_left_mouth_68ldmk, idx_right_mouth_68ldmk
|
||||
|
||||
from src.models import init_net
|
||||
from src.models.base import Base
|
||||
from src.optims import get_optimizer, get_scheduler
|
||||
from src.utils import util
|
||||
|
||||
from torchmetrics import MaxMetric, MeanMetric
|
||||
|
||||
# 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 Audio2Mesh2Model(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("./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)
|
||||
|
||||
self.netF = define_FLAME(opt, self.device)
|
||||
self.netR = define_render(opt, self.device)
|
||||
|
||||
# path_deca_mean = Path("./data/DECA_obama_mean.npy")
|
||||
path_deca_mean = self.opt.DATASET.path_mean_dict
|
||||
self.mean_dict = np.load(path_deca_mean, allow_pickle=True).item()
|
||||
print(f"load mean deca coeff from > {path_deca_mean}, \nkeys = {self.mean_dict.keys()}")
|
||||
|
||||
# get template
|
||||
self.temp_verts, self.temp_ldmk2d, self.temp_ldmk3d \
|
||||
= self.get_template_vertices() # verts: (1 x 1 x 5023 x 3), ldmk: (1 x 1 x 68 x 3)
|
||||
self.temp_verts_specific, self.temp_ldmk2d_specific, self.temp_ldmk3d_specific \
|
||||
= self.get_template_vertices(self.mean_dict) # verts: (1 x 1 x 5023 x 3), ldmk: (1 x 1 x 68 x 3)
|
||||
|
||||
# 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")
|
||||
|
||||
self.names_loss = opt.LOSS.names
|
||||
|
||||
# define loss weight
|
||||
self.vertices_weight = torch.ones((1, 1, self.opt.MODEL.num_vertices, 3)).to(self.device)
|
||||
self.vertices_weight[:, :, flame_mouth_idx, :] = 10
|
||||
|
||||
if self.isTrain:
|
||||
# define optimizers
|
||||
self.optimizer_G = get_optimizer(self.netG, opt)
|
||||
self.optimizers.append(self.optimizer_G)
|
||||
|
||||
self.scheduler_G = get_scheduler(self.optimizer_G, opt)
|
||||
self.schedulers.append(self.scheduler_G)
|
||||
|
||||
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
|
||||
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']
|
||||
self.B, self.nsteps = data.size(0), data.size(1)
|
||||
|
||||
debug(self.opt, f"data = {data.shape}, dtype={data.dtype}", verbose=False)
|
||||
debug(self.opt, f"batch_vid = {self.batch_vid[:2]}", verbose=False)
|
||||
debug(self.opt, f"batch_nframe = {self.batch_nframe[:2]}", verbose=False)
|
||||
debug(self.opt, f"batch_interv len={len(self.batch_interv)} len([0])={len(self.batch_interv[0])}, \
|
||||
beg={self.batch_interv[0][:4]}, end={self.batch_interv[1][:4]}", verbose=False)
|
||||
|
||||
# speech data
|
||||
cond = 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)
|
||||
cond = output.last_hidden_state
|
||||
# cond = 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 = {data.shape}, dtype={data.dtype}, device={data.device}", verbose=False)
|
||||
debug(self.opt, f"cond = {cond.shape}, dtype={cond.dtype}, device={cond.device}", verbose=False)
|
||||
|
||||
# unfold speech data
|
||||
cond = cond.unfold(dimension=1, size=16, step=1) # (nseqs, nc_motion, 16)
|
||||
cond = cond.permute(0, 1, 3, 2) # (nseqs, 16, 53)
|
||||
self.cond = cond
|
||||
|
||||
self.nseq = cond.size(1)
|
||||
data = data[:, 7:7+self.nseq, :]
|
||||
self.vert, self.ldmk2d, self.ldmk3d = self.get_vertices(data)
|
||||
|
||||
debug(self.opt, f"[set_input] vert = {self.vert.shape}, dtype={self.vert.dtype}, device={self.vert.device}", verbose=False)
|
||||
debug(self.opt, f"[set_input] cond = {self.cond.shape}, dtype={self.cond.dtype}, device={self.cond.device}", verbose=False)
|
||||
debug(self.opt, f"[set_input] ldmk2d = {self.ldmk2d.shape}, dtype={self.ldmk2d.dtype}, device={self.ldmk2d.device}", verbose=False)
|
||||
debug(self.opt, f"[set_input] ldmk3d = {self.ldmk3d.shape}, dtype={self.ldmk3d.dtype}, device={self.ldmk3d.device}", verbose=False)
|
||||
|
||||
def training(self, batch_input):
|
||||
self.train() # set train model
|
||||
self.set_input(batch_input)
|
||||
|
||||
# forward
|
||||
self.pred = self.netG(self.cond)
|
||||
self.pred += self.temp_verts
|
||||
debug(self.opt, f"traing pred = {self.pred.shape}", verbose=False)
|
||||
|
||||
# loss
|
||||
loss, self.loss_dict = self.eval_losses(self.pred, self.vert)
|
||||
|
||||
# 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)
|
||||
self.pred += self.temp_verts
|
||||
|
||||
loss_dict = self.eval_losses_for_valid(self.pred, self.vert)
|
||||
|
||||
return loss_dict
|
||||
|
||||
|
||||
def infer(self, batch_cond, path_audio, suffix="", save_npy=True):
|
||||
self.eval()
|
||||
self.cond = batch_cond.float().to(self.device) # (nsteps, dim_cond)
|
||||
|
||||
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
|
||||
|
||||
print(f"testing pt shape = {batch_pdt_geo.shape}")
|
||||
|
||||
# !! 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, path_audio,
|
||||
path_save=Path(self.opt.OUTPUT_DIR),
|
||||
suffix=suffix)
|
||||
|
||||
if save_npy:
|
||||
# save result
|
||||
batch_pdt_geo = batch_pdt_geo.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}")
|
||||
|
||||
|
||||
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():
|
||||
batch_pdt_geo = self.netG(self.cond) # B x N x 5023 x 3
|
||||
batch_pdt_geo += self.temp_verts # B x N x 5023 x 3
|
||||
|
||||
# !! add specific when render & output !!
|
||||
batch_pdt_geo = batch_pdt_geo - self.temp_verts + self.temp_verts_specific
|
||||
|
||||
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}')
|
||||
|
||||
|
||||
def get_template_vertices(self, mean_dict=None):
|
||||
|
||||
batch_exp = torch.zeros(1, 50).to(self.device)
|
||||
batch_pose = torch.zeros(1, 6).to(self.device)
|
||||
|
||||
if mean_dict is not None:
|
||||
batch_shape = self.mean_dict["shape"].reshape(1, 100)
|
||||
batch_shape = torch.from_numpy(batch_shape).float().to(self.device)
|
||||
else:
|
||||
batch_shape = torch.zeros(1, 100).to(self.device)
|
||||
|
||||
with torch.no_grad():
|
||||
# verts = 1 x 5023 x 3, ldmk2d=1 x 68 x 3, ldmk3d=1 x 68 x 3
|
||||
verts, ldmk2d, ldmk3d = self.netF(batch_shape, batch_exp, batch_pose)
|
||||
verts = verts.reshape(1, 1, -1, 3) # 1 x 1 x 5023 x 3
|
||||
ldmk2d = ldmk2d.reshape(1, 1, -1, 3) # 1 x 1 x 68 x 3
|
||||
ldmk3d = ldmk3d.reshape(1, 1, -1, 3) # 1 x 1 x 68 x 3
|
||||
|
||||
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
|
||||
|
||||
|
||||
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_for_valid(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_dict = {}
|
||||
|
||||
# synthesis geo rec
|
||||
loss_rec_geo = self.loss_func_wing(batch_pdt_geo, batch_tgt_geo) # (B, N, num_vertices, 3)
|
||||
loss_dict["rec_geo"] = loss_rec_geo.mean().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_geo = self.loss_func_wing(diff_pdt_geo, diff_tgt_geo) # (B, N-1, num_vertices, 3)
|
||||
loss_dict["vel_geo"] = loss_vel_geo.mean().detach()
|
||||
|
||||
# landmarks loss
|
||||
ldmk3d_pdt = self.netF.seletec_3d68(batch_pdt_geo.reshape(-1, self.opt.MODEL.num_vertices, 3)) # (B*N, 68, 3)
|
||||
ldmk3d_tgt = self.netF.seletec_3d68(batch_tgt_geo.reshape(-1, self.opt.MODEL.num_vertices, 3)) # (B*N, 68, 3)
|
||||
loss_rec_ldmk = torch.sqrt(((ldmk3d_pdt - ldmk3d_tgt)**2).sum(2)) # (B*N, 68, 3) => (B*N, 68)
|
||||
loss_dict["rec_ldmk"] = loss_rec_ldmk.mean().detach()
|
||||
|
||||
# ldmk3d_pdt_dis = torch.sqrt(((ldmk3d_pdt)**2).sum(2)) # (B*N, 68, 3) => (B*N, 68)
|
||||
# ldmk3d_tgt_dis = torch.sqrt(((ldmk3d_tgt)**2).sum(2)) # (B*N, 68, 3) => (B*N, 68)
|
||||
# loss_rec_ldmk = (ldmk3d_pdt_dis - ldmk3d_tgt_dis).abs().mean() # (B*N, 68) ==> (1,)
|
||||
|
||||
# loss_rec_ldmk= self.loss_func_wing(ldmk3d_pdt_dis, ldmk3d_tgt_dis)
|
||||
loss_dict["rec_ldmk"] = loss_rec_ldmk.mean().detach()
|
||||
|
||||
# mouth closure_x loss (left/right mouth)
|
||||
ldmk3d_pdt_left, ldmk3d_pdt_right = ldmk3d_pdt[:, idx_left_mouth_68ldmk], ldmk3d_pdt[:, idx_right_mouth_68ldmk]
|
||||
ldmk3d_tgt_left, ldmk3d_tgt_right = ldmk3d_tgt[:, idx_left_mouth_68ldmk], ldmk3d_tgt[:, idx_right_mouth_68ldmk]
|
||||
diff_pdt_mouth_x = torch.sqrt(((ldmk3d_pdt_left - ldmk3d_pdt_right)**2).sum(2)) # (B*N, 8, 3) => (B*N, 8)
|
||||
diff_tgt_mouth_x = torch.sqrt(((ldmk3d_tgt_left - ldmk3d_tgt_right)**2).sum(2)) # (B*N, 8, 3) => (B*N, 8)
|
||||
|
||||
loss_closure_x = (diff_pdt_mouth_x - diff_tgt_mouth_x).abs().mean() # (B*N, 8) ==> (1,)
|
||||
loss_dict["closure_x"] = loss_closure_x.mean().detach()
|
||||
|
||||
# mouth closure_y loss (upper/lower mouth)
|
||||
ldmk3d_pdt_upper, ldmk3d_pdt_lower = ldmk3d_pdt[:, idx_upper_mouth_68ldmk], ldmk3d_pdt[:, idx_lower_mouth_68ldmk]
|
||||
ldmk3d_tgt_upper, ldmk3d_tgt_lower = ldmk3d_tgt[:, idx_upper_mouth_68ldmk], ldmk3d_tgt[:, idx_lower_mouth_68ldmk]
|
||||
diff_pdt_mouth_y = torch.sqrt(((ldmk3d_pdt_upper - ldmk3d_pdt_lower)**2).sum(2)) # (B*N, 8, 3) => (B*N, 8)
|
||||
diff_tgt_mouth_y = torch.sqrt(((ldmk3d_tgt_upper - ldmk3d_tgt_lower)**2).sum(2)) # (B*N, 8, 3) => (B*N, 8)
|
||||
|
||||
loss_closure_y = (diff_pdt_mouth_y - diff_tgt_mouth_y).abs().mean() # (B*N, 8) ==> (1,)
|
||||
loss_dict["closure_y"] = loss_closure_y.mean().detach()
|
||||
|
||||
|
||||
# # closure loss
|
||||
# diff_pdf_closure = batch_pdt_geo[:,:,flame_mouth_upper_idx].sum(dim=[2,3]) / len(flame_mouth_upper_idx) \
|
||||
# - batch_pdt_geo[:,:,flame_mouth_lower_idx].sum(dim=[2,3]) / len(flame_mouth_upper_idx)
|
||||
|
||||
# diff_tgt_closure = batch_tgt_geo[:,:,flame_mouth_upper_idx].sum(dim=[2,3]) / len(flame_mouth_upper_idx) \
|
||||
# - batch_tgt_geo[:,:,flame_mouth_lower_idx].sum(dim=[2,3]) / len(flame_mouth_upper_idx)
|
||||
|
||||
# loss_closure = self.loss_func_wing(diff_pdf_closure, diff_tgt_closure)
|
||||
# loss_dict["closure"] = loss_closure.mean().detach()
|
||||
|
||||
# if self.opt.LOSS.lambda_closure > 0:
|
||||
# loss += loss_closure.mean() * self.opt.LOSS.lambda_closure
|
||||
|
||||
|
||||
return 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 = 0
|
||||
loss_rec_geo = self.loss_func_wing(batch_pdt_geo, batch_tgt_geo)
|
||||
loss_dict["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["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["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["vel_geo_w"] = loss_vel_geo2.mean().detach()
|
||||
# loss += loss_vel_geo.mean() * self.opt.LOSS.lambda_vel_geo
|
||||
|
||||
if self.opt.LOSS.lambda_vel_geo > 0:
|
||||
loss += loss_vel_geo2.mean() * self.opt.LOSS.lambda_vel_geo
|
||||
|
||||
# landmarks loss
|
||||
ldmk3d_pdt = self.netF.seletec_3d68(batch_pdt_geo.reshape(-1, self.opt.MODEL.num_vertices, 3)) # [nbatch_real x 68 x 3]
|
||||
ldmk3d_tgt = self.netF.seletec_3d68(batch_tgt_geo.reshape(-1, self.opt.MODEL.num_vertices, 3)) # [nbatch_real x 68 x 3]
|
||||
|
||||
loss_rec_ldmk= self.loss_func_wing(ldmk3d_pdt, ldmk3d_tgt)
|
||||
loss_dict["rec_ldmk"] = loss_rec_ldmk.mean().detach()
|
||||
|
||||
if self.opt.LOSS.lambda_rec_ldmk > 0:
|
||||
loss += loss_rec_ldmk.mean() * self.opt.LOSS.lambda_rec_ldmk
|
||||
|
||||
|
||||
# mouth closure_x loss (left/right mouth)
|
||||
ldmk3d_pdt_left, ldmk3d_pdt_right = ldmk3d_pdt[:, idx_left_mouth_68ldmk], ldmk3d_pdt[:, idx_right_mouth_68ldmk]
|
||||
ldmk3d_tgt_left, ldmk3d_tgt_right = ldmk3d_tgt[:, idx_left_mouth_68ldmk], ldmk3d_tgt[:, idx_right_mouth_68ldmk]
|
||||
diff_pdt_mouth_x = ldmk3d_pdt_left - ldmk3d_pdt_right
|
||||
diff_tgt_mouth_x = ldmk3d_tgt_left - ldmk3d_tgt_right
|
||||
|
||||
loss_closure_x = self.loss_func_wing(diff_pdt_mouth_x, diff_tgt_mouth_x)
|
||||
loss_dict["closure_x"] = loss_closure_x.mean().detach()
|
||||
|
||||
if self.opt.LOSS.lambda_closure_x > 0:
|
||||
loss += loss_closure_x.mean() * self.opt.LOSS.lambda_closure_x
|
||||
|
||||
|
||||
# mouth closure_y loss (upper/lower mouth)
|
||||
ldmk3d_pdt_upper, ldmk3d_pdt_lower = ldmk3d_pdt[:, idx_upper_mouth_68ldmk], ldmk3d_pdt[:, idx_lower_mouth_68ldmk]
|
||||
ldmk3d_tgt_upper, ldmk3d_tgt_lower = ldmk3d_tgt[:, idx_upper_mouth_68ldmk], ldmk3d_tgt[:, idx_lower_mouth_68ldmk]
|
||||
diff_pdt_mouth_y = ldmk3d_pdt_upper - ldmk3d_pdt_lower
|
||||
diff_tgt_mouth_y = ldmk3d_tgt_upper - ldmk3d_tgt_lower
|
||||
|
||||
loss_closure_y = self.loss_func_wing(diff_pdt_mouth_y, diff_tgt_mouth_y)
|
||||
loss_dict["closure_y"] = loss_closure_y.mean().detach()
|
||||
|
||||
if self.opt.LOSS.lambda_closure_y > 0:
|
||||
loss += loss_closure_y.mean() * self.opt.LOSS.lambda_closure_y
|
||||
|
||||
|
||||
# # closure loss
|
||||
# diff_pdf_closure = batch_pdt_geo[:,:,flame_mouth_upper_idx].sum(dim=[2,3]) / len(flame_mouth_upper_idx) \
|
||||
# - batch_pdt_geo[:,:,flame_mouth_lower_idx].sum(dim=[2,3]) / len(flame_mouth_upper_idx)
|
||||
|
||||
# diff_tgt_closure = batch_tgt_geo[:,:,flame_mouth_upper_idx].sum(dim=[2,3]) / len(flame_mouth_upper_idx) \
|
||||
# - batch_tgt_geo[:,:,flame_mouth_lower_idx].sum(dim=[2,3]) / len(flame_mouth_upper_idx)
|
||||
|
||||
# loss_closure = self.loss_func_wing(diff_pdf_closure, diff_tgt_closure)
|
||||
# loss_dict["closure"] = loss_closure.mean().detach()
|
||||
|
||||
# if self.opt.LOSS.lambda_closure > 0:
|
||||
# loss += loss_closure.mean() * self.opt.LOSS.lambda_closure
|
||||
|
||||
# total loss
|
||||
loss_dict["all"] = loss.detach()
|
||||
|
||||
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]
|
||||
|
||||
B, N, *_ = batch_pdt_geo.shape
|
||||
nbatch_render = 10
|
||||
|
||||
# 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):
|
||||
# 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.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)
|
||||
|
||||
|
||||
@torch.no_grad()
|
||||
def render_geometry(self, verts, cam=None, device=None):
|
||||
"""
|
||||
verts: [N x 5023 x 3]
|
||||
"""
|
||||
batch_size = verts.size(0)
|
||||
|
||||
if cam is None:
|
||||
cam = torch.zeros(batch_size, 3).to(device) # (batch_size, 3)
|
||||
|
||||
# orth_proj
|
||||
verts_proj = util.batch_orth_proj(verts, cam);
|
||||
verts_proj[:,:,1:] = -verts_proj[:,:,1:]
|
||||
|
||||
# render
|
||||
images = self.netR.render_shape(verts, verts_proj) # (batch_size, 3, 512, 512)
|
||||
|
||||
return images
|
||||
|
||||
@torch.no_grad()
|
||||
def save_reconstruct_with_gt(self, batch_pdt_geo, batch_tgt_geo, path_save, suffix=""):
|
||||
# batch_pdt_geo, [B x N x 5023 x 3]
|
||||
# batch_tgt_geo, [B x N x 5023 x 3]
|
||||
B, N, *_ = batch_pdt_geo.shape
|
||||
nbatch_render = 10
|
||||
|
||||
# for each batch
|
||||
for i in range(B):
|
||||
igeo_pt = batch_pdt_geo[i, ...] # [N x 5023 x 3]
|
||||
igeo_gt = batch_tgt_geo[i, ...] # [N x 5023 x 3]
|
||||
ipath_save = path_save.joinpath(f"{suffix}_{i:02d}.mp4")
|
||||
|
||||
v_render_pt = []
|
||||
v_render_gt = []
|
||||
|
||||
for k in range(0, N, nbatch_render):
|
||||
|
||||
# split
|
||||
kgeo_pt = igeo_pt[k:k+nbatch_render, ...] # [nbatch_real x 5023 x 3]
|
||||
kgeo_gt = igeo_gt[k:k+nbatch_render, ...] # [nbatch_real x 5023 x 3]
|
||||
|
||||
nbatch_real = kgeo_pt.size(0)
|
||||
|
||||
# cam
|
||||
cam = torch.tensor([5, 0, 0], device=self.device).repeat(nbatch_real, 1) # (nbatch_real, 3)
|
||||
# print(f"cam shape = {cam.shape}")
|
||||
|
||||
# render
|
||||
render_pt = self.render_geometry(kgeo_pt, cam, self.device) # (nbatch_real, 3, 512, 512)
|
||||
render_gt = self.render_geometry(kgeo_gt, cam, self.device) # (nbatch_real, 3, 512, 512)
|
||||
# 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_pt = kldmk3d_pt * self.opt.RENDER.image_size/2 + self.opt.RENDER.image_size/2
|
||||
|
||||
kldmk3d_gt = util.batch_orth_proj(kldmk3d_gt, cam);
|
||||
kldmk3d_gt[:,:,1:] = -kldmk3d_gt[:,:,1:];
|
||||
# kldmk3d_gt = kldmk3d_gt * self.opt.RENDER.image_size/2 + self.opt.RENDER.image_size/2
|
||||
|
||||
# write to image
|
||||
# render_pt = tensor2image(render_pt) # (nbatch_real, 3, 512, 512), on cpu
|
||||
# render_gt = tensor2image(render_gt) # (nbatch_real, 3, 512, 512), on cpu
|
||||
|
||||
render_pt = util.tensor_vis_landmarks(render_pt, kldmk3d_pt, gt_landmarks=kldmk3d_gt, isScale=True, color = 'r', gt_color='g')
|
||||
render_gt = util.tensor_vis_landmarks(render_gt, kldmk3d_gt, isScale=True, color = 'g')
|
||||
|
||||
# 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.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, 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 = tensor.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":
|
||||
from src.nn.audio2mesh 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_FLAME(opt, device):
|
||||
from src.nn.FLAME import FLAME
|
||||
|
||||
model = FLAME(opt.FLAME).to(device)
|
||||
|
||||
return model
|
||||
|
||||
|
||||
def define_render(opt, device):
|
||||
from src.utils.renderer import SRenderY, set_rasterizer
|
||||
|
||||
set_rasterizer(opt.RENDER.rasterizer_type)
|
||||
|
||||
model = SRenderY(opt.RENDER.image_size,
|
||||
obj_filename=opt.RENDER.topology_path,
|
||||
uv_size=opt.RENDER.uv_size,
|
||||
rasterizer_type=opt.RENDER.rasterizer_type
|
||||
).to(device)
|
||||
|
||||
return model
|
||||
|
||||
|
||||
@@ -173,42 +173,47 @@ class Audio2MeshARModel(Base):
|
||||
|
||||
|
||||
|
||||
def validation_orignal(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 validation(self, batch_input):
|
||||
self.eval() # set eval model
|
||||
self.set_input(batch_input)
|
||||
|
||||
B, nsteps, *_ = self.x.shape
|
||||
|
||||
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
|
||||
# prepare batch_y_pdf
|
||||
batch_y_pdf = torch.zeros_like(self.y_tgt) # 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
|
||||
|
||||
loss, self.loss_dict = self.eval_losses(batch_y_pdf, batch_y_tgt)
|
||||
for istep in range(nsteps):
|
||||
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
|
||||
|
||||
# eval loss
|
||||
loss, self.loss_dict = self.eval_losses(batch_y_pdf, self.y_tgt)
|
||||
|
||||
return loss
|
||||
|
||||
def validation2(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()
|
||||
@@ -454,7 +459,6 @@ class Audio2MeshARModel(Base):
|
||||
|
||||
return loss, loss_dict
|
||||
|
||||
|
||||
def save_reconstruct(self, samples_pt, path_audio, path_save, suffix=""):
|
||||
# samples_pt, [B x N x dim_motion]
|
||||
|
||||
@@ -489,7 +493,6 @@ class Audio2MeshARModel(Base):
|
||||
# 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]
|
||||
|
||||
@@ -0,0 +1,578 @@
|
||||
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, flame_mouth_upper_idx, flame_mouth_lower_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 Audio2MeshSSModel(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("./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")
|
||||
path_deca_mean = self.opt.DATASET.path_mean_dict
|
||||
self.mean_dict = np.load(path_deca_mean, allow_pickle=True).item()
|
||||
print(f"load mean deca coeff from > {path_deca_mean}, \nkeys = {self.mean_dict.keys()}")
|
||||
|
||||
# get template
|
||||
self.template_verts = self.get_template_vertices() # 1 x 1 x 5023 x 3
|
||||
self.template_verts_specific = self.get_template_vertices(self.mean_dict) # 1 x 1 x 5023 x 3
|
||||
|
||||
# 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
|
||||
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']
|
||||
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)
|
||||
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
|
||||
self.cond = 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)
|
||||
self.cond = output.last_hidden_state
|
||||
# self.cond = 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 = {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 speech data
|
||||
self.cond = self.cond.unfold(dimension=1, size=16, step=1) # (B, nseqs, nc_speech, 16)
|
||||
self.cond = self.cond.permute(0, 1, 3, 2) # (B, nseqs, 16, nc_speech)
|
||||
self.cond_code = self.cond[:, :, 7, :] # (B, nseqs, nc_speech), the 7-th audio code
|
||||
|
||||
self.nseq = self.cond.size(1)
|
||||
self.data = self.data[:, 7:7+self.nseq, :] # (B, nseqs, nc_motion)
|
||||
self.data = self.get_vertices(self.data) # (B, nseqs, num_vertices, 3)
|
||||
|
||||
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}, cond_code = {self.cond_code.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.pred_code = self.netG(self.cond)
|
||||
self.pred += self.template_verts
|
||||
debug(self.opt, f"traing pred = {self.pred.shape}", verbose=False)
|
||||
|
||||
# loss
|
||||
loss, self.loss_dict = self.eval_losses(self.pred, self.data, self.pred_code, self.cond_code)
|
||||
|
||||
# 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.pred_code = self.netG(self.cond)
|
||||
self.pred += self.template_verts
|
||||
|
||||
loss, self.loss_dict = self.eval_losses(self.pred, self.data, self.pred_code, self.cond_code)
|
||||
|
||||
return loss
|
||||
|
||||
|
||||
def infer(self, batch_cond, path_audio, suffix="", save_npy=True):
|
||||
self.eval()
|
||||
self.cond = batch_cond.float().to(self.device) # (nsteps, dim_cond)
|
||||
|
||||
with torch.no_grad():
|
||||
samples_pt, _ = self.netG(self.cond) # B x N x dim_motion
|
||||
samples_pt += self.template_verts # B x N x 5023 x 3
|
||||
|
||||
print(f"testing pt shape = {samples_pt.shape}")
|
||||
|
||||
# !! add specific when render & output !!
|
||||
samples_pt = samples_pt - self.template_verts + self.template_verts_specific
|
||||
|
||||
# render & and save
|
||||
self.save_reconstruct(samples_pt, path_audio,
|
||||
path_save=Path(self.opt.OUTPUT_DIR),
|
||||
suffix=suffix)
|
||||
|
||||
if 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
|
||||
self.set_input(batch_input)
|
||||
|
||||
with torch.no_grad():
|
||||
samples_pt, _ = self.netG(self.cond) # B x N x 5023 x 3
|
||||
samples_pt += self.template_verts # B x N x 5023 x 3
|
||||
|
||||
# !! add specific when render & output !!
|
||||
samples_pt = samples_pt - self.template_verts + self.template_verts_specific
|
||||
|
||||
print(f"testing pt shape = {samples_pt.shape}, gt shape = {self.data.shape}")
|
||||
self.save_reconstruct_with_gt(samples_pt, self.data,
|
||||
path_save=Path(self.opt.OUTPUT_DIR),
|
||||
suffix=f'sampled_{cur_epoch:05d}_{cur_batch:03d}')
|
||||
|
||||
|
||||
def get_template_vertices(self, mean_dict=None):
|
||||
|
||||
batch_exp = torch.zeros(1, 50).to(self.device)
|
||||
batch_pos = torch.zeros(1, 6).to(self.device)
|
||||
|
||||
if mean_dict is not None:
|
||||
batch_shape = self.mean_dict["shape"].reshape(1, 100)
|
||||
batch_shape = torch.from_numpy(batch_shape).float().to(self.device)
|
||||
else:
|
||||
batch_shape = torch.zeros(1, 100).to(self.device)
|
||||
|
||||
verts, _, _ = self.netR.get_vertices(batch_shape, batch_exp, batch_pos) # 1 x 5023 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.unsqueeze(dim=0) # 1 x 1 x 5023 x 3
|
||||
|
||||
|
||||
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, dim_motion)
|
||||
batch_pdt_geo, (nbatch, seqlen, num_vertices, 3)
|
||||
"""
|
||||
|
||||
# get mesh geometry
|
||||
batch_tgt_geo = self.get_vertices(batch_tgt_geo) # B x nseq x num_vertices x 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, dim_motion)
|
||||
batch_pdt_geo, (nbatch, seqlen, num_vertices, 3)
|
||||
"""
|
||||
loss = 0
|
||||
loss_dict = {}
|
||||
|
||||
# get mesh geometry
|
||||
batch_tgt_geo = self.get_vertices(batch_tgt_geo) # B x nseq x num_vertices x 3
|
||||
# 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, batch_pdt_code, batch_tgt_code):
|
||||
""" Computes the VAE loss function.
|
||||
pramas:
|
||||
batch_pdt_geo, (nbatch, seqlen, num_vertices, 3)
|
||||
batch_tgt_geo, (nbatch, seqlen, num_vertices, 3)
|
||||
|
||||
batch_pdt_code, (nbatch, seqlen, dim_speech)
|
||||
batch_tgt_code, (nbatch, seqlen, dim_speech)
|
||||
"""
|
||||
loss = 0
|
||||
loss_dict = {}
|
||||
|
||||
# synthesis geo rec
|
||||
loss = 0
|
||||
loss_rec_geo = self.loss_func_wing(batch_pdt_geo, batch_tgt_geo)
|
||||
loss_rec_geo2 = self.loss_func_wing(batch_pdt_geo, batch_tgt_geo, weight=self.vertices_weight)
|
||||
loss_dict["loss_rec_geo"] = loss_rec_geo.mean().detach()
|
||||
loss_dict["loss_rec_geo_w"] = loss_rec_geo2.mean().detach()
|
||||
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_vel_geo2 = self.loss_func_wing(diff_pdt_geo, diff_tgt_geo, weight=self.vertices_weight)
|
||||
loss_dict["loss_vel_geo"] = loss_vel_geo.mean().detach()
|
||||
loss_dict["loss_vel_geo_w"] = loss_vel_geo2.mean().detach()
|
||||
if self.opt.LOSS.lambda_vel_geo:
|
||||
loss += loss_vel_geo2.mean() * self.opt.LOSS.lambda_vel_geo
|
||||
|
||||
|
||||
# self-supervised loss
|
||||
loss_rec_code = self.loss_func_wing(batch_pdt_code, batch_tgt_code)
|
||||
loss_dict["loss_rec_code"] = loss_rec_code.mean().detach()
|
||||
if self.opt.LOSS.lambda_rec_code:
|
||||
loss += loss_rec_code.mean() * self.opt.LOSS.lambda_rec_code
|
||||
|
||||
# # closure loss
|
||||
# diff_pdf_closure = batch_pdt_geo[:,:,flame_mouth_upper_idx].sum(dim=[2,3]) / len(flame_mouth_upper_idx) \
|
||||
# - batch_pdt_geo[:,:,flame_mouth_lower_idx].sum(dim=[2,3]) / len(flame_mouth_upper_idx)
|
||||
|
||||
# diff_tgt_closure = batch_tgt_geo[:,:,flame_mouth_upper_idx].sum(dim=[2,3]) / len(flame_mouth_upper_idx) \
|
||||
# - batch_tgt_geo[:,:,flame_mouth_lower_idx].sum(dim=[2,3]) / len(flame_mouth_upper_idx)
|
||||
|
||||
# loss_closure = self.loss_func_wing(diff_pdf_closure, diff_tgt_closure)
|
||||
# loss_dict["loss_closure"] = loss_closure.mean().detach()
|
||||
|
||||
# if self.opt.LOSS.lambda_closure > 0:
|
||||
# loss += loss_closure.mean() * self.opt.LOSS.lambda_closure
|
||||
|
||||
# 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.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, 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_ss":
|
||||
from src.nn.audio2mesh_ss 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
|
||||
|
||||
|
||||
|
||||
@@ -322,12 +322,8 @@ def tensor2image(tensor):
|
||||
|
||||
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":
|
||||
|
||||
if opt.MODEL.name_netG == "audio2motion_voca":
|
||||
from src.nn.audio2motion_voca import Audio2MotionVOCA
|
||||
netG = Audio2MotionVOCA(opt)
|
||||
|
||||
|
||||
Reference in new issue
Block a user