add onnx export
This commit is contained in:
1 parent
e2e8d8baf8
commit
28810e9ed3
22 files changed
+835
-342
No files matched your search
+120
-86
@@ -1,10 +1,12 @@
|
||||
from collections import OrderedDict
|
||||
import sys
|
||||
|
||||
import numpy as np
|
||||
from collections import OrderedDict
|
||||
|
||||
import tempfile
|
||||
from scipy.io import wavfile
|
||||
|
||||
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
|
||||
@@ -16,8 +18,6 @@ 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
|
||||
@@ -41,7 +41,10 @@ class Audio2Mesh2Model(Base):
|
||||
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
|
||||
if isinstance(self.netG, torch.nn.DataParallel):
|
||||
self.netG.module.decoder_mesh.weight.data = init_exp_weight
|
||||
else:
|
||||
self.netG.decoder_mesh.weight.data = init_exp_weight
|
||||
print(f"init_exp_weight shape = {init_exp_weight.shape}")
|
||||
|
||||
# # print network parameters
|
||||
@@ -96,6 +99,7 @@ class Audio2Mesh2Model(Base):
|
||||
self.processor = Wav2Vec2FeatureExtractor.from_pretrained(path_ckpt_wav2vec)
|
||||
self.extractor = Wav2Vec2Model.from_pretrained(path_ckpt_wav2vec).to(self.device)
|
||||
|
||||
|
||||
def set_input(self, batch_input):
|
||||
|
||||
# motion data
|
||||
@@ -133,7 +137,7 @@ class Audio2Mesh2Model(Base):
|
||||
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 ' "
|
||||
|
||||
@@ -142,8 +146,8 @@ class Audio2Mesh2Model(Base):
|
||||
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)
|
||||
cond = cond.unfold(dimension=1, size=16, step=1) # (B, nseqs, nc_codit, 16)
|
||||
cond = cond.permute(0, 1, 3, 2) # (B, nseqs, 16, nc_condit)
|
||||
self.cond = cond
|
||||
|
||||
self.nseq = cond.size(1)
|
||||
@@ -155,6 +159,17 @@ class Audio2Mesh2Model(Base):
|
||||
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 forward(self, batch_input):
|
||||
self.set_input(batch_input)
|
||||
|
||||
# forward
|
||||
pred = self.netG(self.cond)
|
||||
debug(self.opt, f"traing pred = {pred.shape}", verbose=False)
|
||||
|
||||
return pred
|
||||
|
||||
|
||||
def training(self, batch_input):
|
||||
self.train() # set train model
|
||||
self.set_input(batch_input)
|
||||
@@ -193,12 +208,41 @@ class Audio2Mesh2Model(Base):
|
||||
return loss_dict
|
||||
|
||||
|
||||
def infer_with_gt(self, batch_cond, batch_data, audio_raw, suffix="", save_npy=True):
|
||||
self.eval()
|
||||
|
||||
cond = batch_cond.float().to(self.device) # (nsteps, dim_cond)
|
||||
data = batch_data.float().to(self.device) # (B, nframe, 53)
|
||||
vert, ldmk2d, ldmk3d = self.get_vertices(data)
|
||||
|
||||
|
||||
with torch.no_grad():
|
||||
batch_pdt_geo = self.netG(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
|
||||
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)
|
||||
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 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.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}")
|
||||
@@ -270,11 +314,11 @@ class Audio2Mesh2Model(Base):
|
||||
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_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_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():
|
||||
@@ -286,74 +330,6 @@ class Audio2Mesh2Model(Base):
|
||||
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:
|
||||
@@ -451,6 +427,7 @@ class Audio2Mesh2Model(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}")
|
||||
|
||||
# append each frame
|
||||
@@ -481,6 +458,64 @@ class Audio2Mesh2Model(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]
|
||||
# batch_tgt_geo, [1 x N x 5023 x 3]
|
||||
|
||||
B, N, *_ = batch_pdt_geo.shape
|
||||
|
||||
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")
|
||||
|
||||
v_render_pt = []
|
||||
v_render_gt = []
|
||||
nbatch_render = 10
|
||||
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_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))
|
||||
|
||||
# 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, ...]))
|
||||
|
||||
|
||||
# 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)}, 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()
|
||||
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]
|
||||
@@ -529,9 +564,8 @@ class Audio2Mesh2Model(Base):
|
||||
# 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')
|
||||
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))
|
||||
|
||||
# append each frame
|
||||
for m in range(nbatch_real):
|
||||
@@ -586,12 +620,12 @@ def define_netG(opt):
|
||||
|
||||
# to GPU
|
||||
netG.to(f"cuda:{opt.GPUS[0]}")
|
||||
netG = torch.nn.DataParallel(netG, opt.GPUS) # multi-GPUs
|
||||
if len(opt.GPUS) > 1:
|
||||
netG = torch.nn.DataParallel(netG, opt.GPUS) # multi-GPUs
|
||||
|
||||
return netG
|
||||
|
||||
|
||||
|
||||
def define_FLAME(opt, device):
|
||||
from src.nn.FLAME import FLAME
|
||||
|
||||
|
||||
Reference in new issue
Block a user