add audio2pose model, dataset, prepare data scrit

This commit is contained in:
Sen Liang committed 2022-04-13 23:45:24 +08:00
1 parent 91cdd0d678
commit c2797657f8
9 files changed
+1198 -502

No files matched your search

@@ -0,0 +1,90 @@
import os
import sys
import json
import librosa
import numpy as np
from pathlib import Path
if __name__ == "__main__":
path_data = Path('/mfs/lsen/DATA/LuoXData/processing2') # '../data/trinity/source'
v_dir_videos = sorted(path_data.glob("*"), reverse=True)
print(f"Have {len(v_dir_videos)} dir files")
# for each video
duration_frame, duration_coeff = 0, 0
for ipath_data in v_dir_videos:
ivideo_name = ipath_data.stem
print(f"\n processing {ivideo_name} ... ")
ipath_infors = ipath_data.joinpath("video/info.json")
ipath_coeff = ipath_data.joinpath("DECA_coeff")
ipath_frame = ipath_data.joinpath("frames")
ipath_save_pos = ipath_data.joinpath("audio/feat_DECA_pos_cam_trim.npy")
if ipath_save_pos.exists():
print(f"ipath_save_exp have already save > {ipath_save_pos}")
continue
if not ipath_infors.exists():
continue
# load video info
with open(str(ipath_infors), "r") as f:
info = json.load(f)
fps = info["fps"]
nframes = info["nframes"]
print(f"info = {info}, duration ={nframes / fps // 60}")
# check
vframe_frame = list(ipath_frame.glob("*.jpg"))
vframe_coeff = list(ipath_coeff.glob("*.npy"))
print(f"vframe_frame len = {len(vframe_frame)}, vframe_coeff={len(vframe_coeff)}")
duration_frame += len(vframe_frame) / 50 / 60
duration_coeff += len(vframe_coeff) / 50 / 60
print(f"add duration_frame = {duration_frame} min, duration_coeff={duration_coeff} min")
if len(vframe_frame) != nframes:
print(f"\n ERROR: nframe_real ={len(vframe_frame)} / nframe_info ={nframes}")
continue
if len(vframe_coeff)+1 < nframes:
print(f"\n ERROR: nframe_coeff ={len(vframe_coeff)} / nframe_info ={nframes}")
continue
feat_pos = []
feat_cam = []
for j in range(len(vframe_frame)):
jpath_coeff = ipath_coeff.joinpath(f"frame-{j:06d}.json.npy")
if j%1000 == 0: print(f"processing the {j}-th frame ... ")
if not jpath_coeff.exists():
print(f"\n ERROR: Path NOT FOUND! -> {jpath_coeff}")
break
data_coeff = np.load(jpath_coeff, allow_pickle=True).item()
feat_pos.append(data_coeff["pose"])
feat_cam.append(data_coeff["cam"])
# save
feat = np.concatenate([np.array(feat_pos), np.array(feat_cam)], axis=1) # (nframe_trim, 6+3)
# pad one
if nframes == feat.shape[0] + 1:
feat = np.pad(feat, ((0,1),(0,0)), mode="edge")
np.save(ipath_save_pos, feat)
print(f"SAVE OK! pos = {feat.shape}, nframe={nframes}\n save to -> {ipath_save_pos}") # (nframe, 9)
elif nframes == feat.shape[0]:
np.save(ipath_save_pos, feat)
print(f"SAVE OK! pos = {feat.shape}, nframe={nframes}\n save to -> {ipath_save_pos}") # (nframe, 9)
else:
print("ERROR, skip! ")
@@ -0,0 +1,165 @@
import os
import sys
import json
import librosa
import numpy as np
from pathlib2 import Path
from scipy import interpolate
import torchaudio
def landmark_resample_fps(y, source_fps = 30, target_fps=25):
""" y, N x 136, with 30fps
"""
nsteps = y.shape[0]
x = np.arange(0, nsteps, 1)
# print("x:", x[::30], x[-10:])
func = interpolate.interp1d(x, y=y, axis=0)
x_new = np.arange(0, nsteps-1, 1.0*source_fps/target_fps)
# print("x_new", x_new[::30], x_new[-10:])
y_new = func(x_new)
if source_fps < target_fps:
y_new = np.concatenate([y_new, y[-1:]])
return y_new
if __name__ == "__main__":
path_data = Path('/mfs/lsen/DATA/LuoXData/processing2') # '../data/trinity/source'
path_save = Path('data/LuoXData/LuoXData-pose-16h') # processing
path_save.mkdir(parents=True, exist_ok=True)
v_dir_videos = sorted(path_data.glob("*/audio/feat_DECA_pos_cam_trim.npy"))
print(f"Have {len(v_dir_videos)} dir files")
v_dir_videos = [ipath.parent.parent for ipath in v_dir_videos]
vids = set([ipath.stem for ipath in v_dir_videos])
# print(f"vids total= {vids}")
vid_test = set(["2021-P09", "2021-P22"])
vid_valid = set(["2021-P14", "2021-P20"])
vid_train = vids - vid_test - vid_valid
# vids = set(["2021-P09", "2021-P14", "2021-P22"])
# vid_test = set(["2021-P09" ])
# vid_valid = set(["2021-P14" ])
# vid_train = set(["2021-P22" ])
print(f"vid test= {vid_test} \nvalid= {vid_valid}")
print(f"vid train= {vid_train}")
# for each video
data_train, data_valid, data_test = {}, {}, {}
durations_train, durations_valid, durations_test = 0, 0, 0
for i, ipath_data in enumerate(v_dir_videos):
vid = ipath_data.stem
if vid not in vids: continue
# if vid in vid_test: continue
# if vid in vid_valid:continue
print(f"\n processing the {i}-th video {vid} ... ")
ipath_info = ipath_data.joinpath("video/info.json")
ipath_feat_exp = ipath_data.joinpath("audio/feat_DECA_exp_trim.npy")
ipath_feat_pos = ipath_data.joinpath("audio/feat_DECA_pos_cam_trim.npy")
ipath_feat_idn = ipath_data.joinpath("audio/feat_DECA_idn_trim.npy")
ipath_speech = ipath_data.joinpath("audio/audio_trim.wav")
# check existing
if not ipath_speech.exists():
print(f"NOT existing {ipath_speech}")
continue
if not ipath_feat_exp.exists():
print(f"NOT existing {ipath_feat_exp}")
continue
# load video info
with open(str(ipath_info), "r") as f:
info = json.load(f)
fps = info["fps"]
nframes = info['nframes']
print(f"info={info}, duration = {nframes/fps}")
assert fps == 50, "fps should be 50"
# laod motion
data_exp = np.load(ipath_feat_exp) # (nframe, 50)
data_pos = np.load(ipath_feat_pos) # (nframe, 9)
data_idn = np.load(ipath_feat_idn) # (nframe, 100)
assert data_exp.shape[0] == data_pos.shape[0], f"data_exp shape={data_exp.shape}, data_pos shape={data_pos.shape}"
assert data_exp.shape[0] == data_idn.shape[0], f"data_exp shape={data_exp.shape}, data_idn shape={data_idn.shape}"
# load raw audio
audio_raw, sample_rate = torchaudio.load(ipath_speech)
print(f"audio_raw shape = {audio_raw.shape}, sr = {sample_rate}, duration = {(len(audio_raw[0])/sample_rate)}")
if len(audio_raw.shape) == 2:
audio_raw = audio_raw[0]
if sample_rate != 16000:
resampler = torchaudio.transforms.Resample(sample_rate, 16_000)
audio_raw = resampler(audio_raw).squeeze().numpy()
print(f"audio_raw shape = {audio_raw.shape}, sr = {16000}, duration = {(len(audio_raw)/16000)}")
if vid in vid_train:
durations_train += nframes/fps
data_train[vid] = {
"fps": info["fps"],
"sr": 16000,
"nframe": nframes,
"data_exp": data_exp,
"data_idn": data_idn,
"data_pos": data_pos,
"data_speech": audio_raw,
}
# if durations_train / 3600 > 16:
# break
if vid in vid_valid:
durations_valid += nframes/fps
data_valid[vid] = {
"fps": info["fps"],
"sr": 16000,
"nframe": nframes,
"data_exp": data_exp,
"data_idn": data_idn,
"data_pos": data_pos,
"data_speech": audio_raw,
}
if vid in vid_test:
durations_test += nframes/fps
data_test[vid] = {
"fps": info["fps"],
"sr": 16000,
"nframe": nframes,
"data_exp": data_exp,
"data_idn": data_idn,
"data_pos": data_pos,
"data_speech": audio_raw,
}
print(f"frames: data_train ({durations_train / 60 } min) ({durations_train / 3600 } h) , ids = ({len(data_train)})")
print(f"frames: data_valid ({durations_valid / 60 } min) ({durations_valid / 3600 } h) , ids = ({len(data_valid)})")
print(f"frames: data_test ({durations_test / 60 } min) ({durations_test / 3600 } h) , ids = ({len(data_test)})")
np.savez(path_save.joinpath("data_train.npz"), data=data_train)
np.savez(path_save.joinpath("data_valid.npz"), data=data_valid)
np.savez(path_save.joinpath("data_test.npz"), data=data_test)
print(f"Total frames: data_train ({durations_train / 60 } min) ({durations_train / 3600 } h) , ids = ({len(data_train)})")
print(f"Total frames: data_valid ({durations_valid / 60 } min) ({durations_valid / 3600 } h) , ids = ({len(data_valid)})")
print(f"Total frames: data_test ({durations_test / 60 } min) ({durations_test / 3600 } h) , ids = ({len(data_test)})")
print(f"--> {path_save}")
@@ -0,0 +1,91 @@
import os
import sys
import json
import librosa
import numpy as np
from pathlib import Path
if __name__ == "__main__":
path_data = Path('/mfs/lsen/DATA/Obama/processing') # '../data/trinity/source'
v_dir_videos = sorted(path_data.glob("*"), reverse=True)
print(f"Have {len(v_dir_videos)} dir files")
# for each video
duration_frame, duration_coeff = 0, 0
for ipath_data in v_dir_videos:
ivideo_name = ipath_data.stem
print(f"\n processing {ivideo_name} ... ")
ipath_infors = ipath_data.joinpath("video/info.json")
ipath_coeff = ipath_data.joinpath("DECA_coeff")
ipath_frame = ipath_data.joinpath("frames")
ipath_save_pos = ipath_data.joinpath("audio/feat_DECA_pos_cam_trim.npy")
if ipath_save_pos.exists():
print(f"ipath_save_exp have already save > {ipath_save_pos}")
continue
if not ipath_infors.exists():
continue
# load video info
with open(str(ipath_infors), "r") as f:
info = json.load(f)
fps = info["fps"]
if len(info["active_frames"]) == 2:
ibeg = info["active_frames"][0]
iend = info["active_frames"][1]
nframe_trim = iend - ibeg
print(f"frame trim = {nframe_trim}, info['active_frames'] = {info['active_frames']}, duration ={nframe_trim / fps // 60}")
else:
print(f"ERROR: info['active_frames'] = {info['active_frames']}")
continue
# check
vframe_frame = list(ipath_frame.glob("*.jpg"))
vframe_coeff = list(ipath_coeff.glob("*.npy"))
print(f"vframe_frame len = {len(vframe_frame)}, vframe_coeff={len(vframe_coeff)}")
duration_frame += len(vframe_frame) / fps / 60
duration_coeff += len(vframe_coeff) / fps / 60
print(f"add duration_frame = {duration_frame} min, duration_coeff={duration_coeff} min")
if len(vframe_frame) != nframe_trim:
print(f"\n ERROR: nframe_real ={len(vframe_frame)} / nframe_info ={nframe_trim}")
continue
if len(vframe_coeff)+1 < nframe_trim:
print(f"\n ERROR: nframe_coeff ={len(vframe_coeff)} / nframe_info ={nframe_trim}")
continue
feat_pos = []
feat_cam = []
for j in range(ibeg, iend):
jpath_coeff = ipath_coeff.joinpath(f"frame-{j:05d}.json.npy")
if j%1000 == 0: print(f"processing the {j}-th frame ... ")
if not jpath_coeff.exists():
print(f"\n ERROR: Path NOT FOUND! -> {jpath_coeff}")
break
data_coeff = np.load(jpath_coeff, allow_pickle=True).item()
feat_pos.append(data_coeff["pose"])
feat_cam.append(data_coeff["cam"])
# save
feat = np.concatenate([np.array(feat_pos), np.array(feat_cam)], axis=1) # (nframe_trim, 6+3)
# pad one
if nframe_trim == feat.shape[0]:
np.save(ipath_save_pos, feat)
print(f"SAVE OK! pos = {feat.shape}, nframe={nframe_trim}\n save to -> {ipath_save_pos}") # (nframe, 9)
else:
print("ERROR, skip! ")
+163
View File
@@ -0,0 +1,163 @@
import imp
import numpy as np
import time
import random
from torch.utils.data import Dataset
from pathlib import Path
from scipy.signal import savgol_filter
# common
from common.resampling import resample_by_nsteps
class MotionPoseDataset(Dataset):
"""
Motion dataset.
Prepares conditioning information (previous poses + control signal) and the corresponding next poses"""
def __init__(self, opt, phase="train"):
"""
phase = "train | valid | test "
"""
super(MotionPoseDataset, self).__init__()
self.opt = opt
self.phase = phase
path_data= Path(opt.DATASET.root).joinpath(f"data_{phase}.npz")
self.nseqR = opt.MODEL.n_lookprevs # 5, number of previous sequence
self.nseqL = opt.MODEL.n_lookahead # 20, number of future sequence
print(f"[{self.phase}] load data ... --> {path_data}")
self.annodb = np.load(path_data, allow_pickle=True)['data'].item()
self.num_pid = len(self.annodb)
self.pids = list(self.annodb.keys())
self.fps = opt.DATASET.fps # 50
self.sr = opt.DATASET.sr # 16000
self.nwind = eval(f"opt.DATASET.nwind_second_{phase}")
self.nsteps_frame = self.nwind * self.fps
self.nsteps_segmt = self.nwind * self.sr
print(f'''len(annodb)={len(self.annodb)}\t'''
f'''nsteps_frame={self.nsteps_frame}\t'''
f'''nsteps_segmt={self.nsteps_segmt} ''')
def __len__(self):
if self.phase == "train":
return 20000
elif self.phase == "valid":
return 3000 #3000
else:
return 100
def __getitem__(self, idx):
"""
Returns poses and conditioning.
If data-dropout sould be applied, a random selection of the previous poses is masked.
The control is not masked
return:
motion: (nsteps, nc_motion), current frame's pose (15 joint, xyz position)
speech: (nsteps, nc_speech), conditional data = previous motion data + full windows contrl data
"""
np.random.seed(int(idx + time.time()))
vid = self.pids[idx % self.num_pid]
# random select idx
data = self.annodb[vid]
data_idn = data["data_idn"] # (nframes, nc_idn=100)
data_exp = data["data_exp"] # (nframes, nc_exp=50)
data_pos = data["data_pos"] # (nframes, nc_pos=9) pose=6, camera=3
data_aud = data["data_speech"] # (nsegemts, )
nframe = data_pos.shape[0]
nsegmt = data_aud.shape[0]
if self.phase == "train" and self.opt.DATASET.shifting_speed and random.random() < 0.3:
speed = random.sample({0.5, 0.7, 0.8, 0.9, 1.1, 1.2, 1.3, 1.4, 1.5},1)[0]
beg_frame = np.random.randint(nframe - int(self.nsteps_frame * speed) - 10) + 5 # select from (5:-5)
end_frame = beg_frame + int(self.nsteps_frame * speed)
beg_segmt = int((1.0 * beg_frame / nframe) * nsegmt)
end_segmt = beg_segmt + int(self.nsteps_segmt * speed)
data_idn = data_idn[beg_frame:end_frame] # (nteps, 100)
data_exp = data_exp[beg_frame:end_frame] # (nteps, 50)
data_pos = data_pos[beg_frame:end_frame] # (nteps, 9)
data_aud = data_aud[beg_segmt:end_segmt] # (nsegmt_steps, )
assert data_aud.shape[0] == int(self.nsteps_segmt * speed), f"data_aud shape={data_aud.shape}, int(self.nsteps_segmt * speed) = {int(self.nsteps_segmt * speed)}, vid={vid}"
assert data_pos.shape[0] == int(self.nsteps_frame * speed), f"data_pos shape={data_pos.shape}, vid={vid}"
# print(f"speed={speed}, data_aud shape={data_aud.shape} data_pos shape={data_pos.shape}")
# resample to same nsteps
data_idn = resample_by_nsteps(data_idn, nsteps_tgt=self.nsteps_frame)
data_exp = resample_by_nsteps(data_exp, nsteps_tgt=self.nsteps_frame)
data_pos = resample_by_nsteps(data_pos, nsteps_tgt=self.nsteps_frame)
data_aud = resample_by_nsteps(data_aud, nsteps_tgt=self.nsteps_segmt)
# print(f"resampling > data_aud shape={data_aud.shape} data_pos shape={data_pos.shape} \n")
else:
# random select beg:end frame
beg_frame = np.random.randint(nframe - self.nsteps_frame - 10) + 5 # select from (5:-5)
end_frame = beg_frame + self.nsteps_frame
beg_segmt = int((1.0 * beg_frame / nframe) * nsegmt)
end_segmt = beg_segmt + self.nsteps_segmt
# print(f"nframe-{self.nsteps_frame:04d} =[{beg_frame:04d},{end_frame:04d})\t nsegmet-{self.nsteps_segmt:04d}=[{beg_segmt:04d},{end_segmt:04d}), vid={vid}")
data_idn = data_idn[beg_frame:end_frame] # (nteps, 100)
data_exp = data_exp[beg_frame:end_frame] # (nteps, 50)
data_pos = data_pos[beg_frame:end_frame] # (nteps, 9)
data_aud = data_aud[beg_segmt:end_segmt] # (nsegmt_steps, )
assert data_aud.shape[0] == self.nsteps_segmt, f"data_aud shape={data_aud.shape}, vid={vid}, [{beg_segmt:04d},{end_segmt:04d})"
assert data_pos.shape[0] == self.nsteps_frame, f"data_pos shape={data_pos.shape}, vid={vid}"
# filter, explore doc: ./notebook/explore_pose.ipynb
if self.opt.DATASET.filter == "savgol":
# data_idn = savgol_filter(data_idn, window_length=5, polyorder=3, axis=0, mode='nearest')
data_exp = savgol_filter(data_exp, window_length=5, polyorder=3, axis=0, mode='nearest')
data_pos = savgol_filter(data_pos, window_length=5, polyorder=3, axis=0, mode='nearest')
# random augments: shuffle speed
result = {
"idn": data_idn, # (nsteps_frame, 100)
"exp": data_exp, # (nsteps_frame, 50)
"pos": data_pos, # (nsteps_frame, 9)
"aud": data_aud, # (nsteps_segmt,)
"vid": vid,
"nframe": nframe,
"frame_interval": [beg_frame, end_frame],
}
return result
def make_auguments_speed(self, data_pos, data_aud, p=0.5):
'''
parameters:
data_pos: (nsteps_motion, 53)
data_aud: (nsteps_speech, ), where nsteps_speech!= nsteps_motion
'''
if random.random() > p:
return data_pos, data_aud
nsteps_motion = data_pos.shape[0]
nsteps_speech = data_aud.shape[0]
speed = random.sample({0.5, 0.7, 0.8, 0.9, 1.1, 1.2, 1.3, 1.4, 1.5},1)[0]
if speed < 0:
data_pos = data_pos[:nsteps_motion*speed]
data_aud = data_aud[:nsteps_speech*speed]
return data_pos, data_aud
+2 -2
View File
@@ -21,8 +21,8 @@ class MotionRegressiveDataset(Dataset):
self.phase = phase self.phase = phase
self.path_data = Path(opt.DATASET.root) self.path_data = Path(opt.DATASET.root)
self.nseqR = opt.MODEL.n_lookprevs # 5, previous sequence, number of autoregressive body poses self.nseqR = opt.MODEL.n_lookprevs # 5, previous sequence, number of autoregressive body poses
self.nseqL = opt.MODEL.n_lookahead # 20, future sequence self.nseqL = opt.MODEL.n_lookahead # 20, future sequence
path_motion = self.path_data.joinpath(f"motion_{phase}.npz") path_motion = self.path_data.joinpath(f"motion_{phase}.npz")
path_speech = self.path_data.joinpath(f"speech_{phase}.npz") path_speech = self.path_data.joinpath(f"speech_{phase}.npz")
+294 -274
View File
@@ -1,23 +1,28 @@
import sys
import numpy as np import numpy as np
from collections import OrderedDict
import tempfile
from scipy.io import wavfile
import torch import torch
import torch.nn as nn import torch.nn as nn
import torch.nn.functional as F
from pathlib import Path from pathlib import Path
from src.models.info import flame_mouth_idx, flame_mouth_upper_idx, flame_mouth_lower_idx 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 import init_net
from src.models.base import Base from src.models.base import Base
from src.optims import get_optimizer, get_scheduler from src.optims import get_optimizer, get_scheduler
from src.losses.metrics import MeanDictMetric from src.utils import util
# common # common
from common.animation import save_animation_with_gt2, save_images_with_audio from common.animation import save_animation_with_gt2, save_images_with_audio
from common.debug import debug from common.debug import debug
from common.losses import WingLoss from common.losses import WingLoss
# disentangle model # disentangle model
class Audio2MeshModel(Base): class Audio2MeshModel(Base):
@@ -36,7 +41,10 @@ class Audio2MeshModel(Base):
init_exp_weight = np.load("./data/init_expression_basis.npy") 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 = torch.from_numpy(init_exp_weight).float().to(self.device)
init_exp_weight = init_exp_weight[:, :50] 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(f"init_exp_weight shape = {init_exp_weight.shape}")
# # print network parameters # # print network parameters
@@ -44,16 +52,22 @@ class Audio2MeshModel(Base):
# print(name, '\t\t', param.size()) # print(name, '\t\t', param.size())
# load mean lighting & shape # load mean lighting & shape
self.netR, self.flame = define_netR(device=self.device) # self.netR, self.flame = define_netR(device=self.device)
# self.netG.init_reconstruct_model(self.netR) # 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 path_deca_mean = self.opt.DATASET.path_mean_dict
self.mean_dict = np.load(path_deca_mean, allow_pickle=True).item() 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()}") print(f"load mean deca coeff from > {path_deca_mean}, \nkeys = {self.mean_dict.keys()}")
# get template # get template
self.template_verts = self.get_template_vertices() # 1 x 1 x 5023 x 3 self.temp_verts, self.temp_ldmk2d, self.temp_ldmk3d \
self.template_verts_specific = self.get_template_vertices(self.mean_dict) # 1 x 1 x 5023 x 3 = 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 filter outlier
# if self.opt.LOSS.filter_outlier: # if self.opt.LOSS.filter_outlier:
@@ -66,7 +80,6 @@ class Audio2MeshModel(Base):
self.vertices_weight = torch.ones((1, 1, self.opt.MODEL.num_vertices, 3)).to(self.device) self.vertices_weight = torch.ones((1, 1, self.opt.MODEL.num_vertices, 3)).to(self.device)
self.vertices_weight[:, :, flame_mouth_idx, :] = 10 self.vertices_weight[:, :, flame_mouth_idx, :] = 10
if self.isTrain: if self.isTrain:
# define optimizers # define optimizers
self.optimizer_G = get_optimizer(self.netG, opt) self.optimizer_G = get_optimizer(self.netG, opt)
@@ -75,33 +88,36 @@ class Audio2MeshModel(Base):
self.scheduler_G = get_scheduler(self.optimizer_G, opt) self.scheduler_G = get_scheduler(self.optimizer_G, opt)
self.schedulers.append(self.scheduler_G) self.schedulers.append(self.scheduler_G)
if self.opt.DATASET.speech_extractor == "wav2vec": if self.opt.DATASET.speech_extractor == "wav2vec":
from transformers import Wav2Vec2FeatureExtractor, Wav2Vec2Model from transformers import Wav2Vec2FeatureExtractor, Wav2Vec2Model
print("load Wav2Vec2Model ...") print("load Wav2Vec2Model ...")
MODEL_ID = "jonatasgrosman/wav2vec2-large-xlsr-53-chinese-zh-cn" # MODEL_ID = "jonatasgrosman/wav2vec2-large-xlsr-53-chinese-zh-cn"
self.processor = Wav2Vec2FeatureExtractor.from_pretrained(MODEL_ID) # self.processor = Wav2Vec2FeatureExtractor.from_pretrained(MODEL_ID)
self.extractor = Wav2Vec2Model.from_pretrained(MODEL_ID).to(self.device) # self.extractor = Wav2Vec2Model.from_pretrained(MODEL_ID).to(self.device)
path_ckpt_wav2vec = "./checkpoints/wav2vec2"
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): def set_input(self, batch_input):
# motion data # motion data
self.data = batch_input["data"].float().to(self.device) # (B, nsteps, nc_motion) data = batch_input["data"].float().to(self.device) # (B, nsteps, nc_motion)
self.batch_vid = batch_input['vid'] self.batch_vid = batch_input['vid']
self.batch_nframe = batch_input['nframe'] self.batch_nframe = batch_input['nframe']
self.batch_interv = batch_input['frame_interval'] self.batch_interv = batch_input['frame_interval']
self.B, self.nsteps = self.data.size(0), self.data.size(1) self.B, self.nsteps = data.size(0), data.size(1)
debug(self.opt, f"data = {self.data.shape}, dtype={self.data.dtype}", verbose=False) 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_vid = {self.batch_vid[:2]}", verbose=False)
debug(self.opt, f"batch_nframe = {self.batch_nframe[: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])}, \ 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) beg={self.batch_interv[0][:4]}, end={self.batch_interv[1][:4]}", verbose=False)
# speech data # speech data
self.cond = None cond = None
raw_speech = batch_input["cond"].numpy() # (B, nsegments) raw_speech = batch_input["cond"].numpy() # (B, nsegments)
debug(self.opt, f"raw_speech = {raw_speech.shape}, dtype={raw_speech.dtype}", verbose=False) debug(self.opt, f"raw_speech = {raw_speech.shape}, dtype={raw_speech.dtype}", verbose=False)
@@ -120,24 +136,38 @@ class Audio2MeshModel(Base):
with torch.no_grad(): with torch.no_grad():
output = self.extractor(**inputs) output = self.extractor(**inputs)
self.cond = output.last_hidden_state cond = output.last_hidden_state
# self.cond = output.extract_features
else: else:
assert 0, "opt.DATASET.speech_extractor should be 'wav2vec | deepspeech | mfcc ' " assert 0, "opt.DATASET.speech_extractor should be 'wav2vec | deepspeech | mfcc ' "
# B x nsteps x nc_feat # 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"data = {data.shape}, dtype={data.dtype}, device={data.device}", verbose=False)
debug(self.opt, f"cond = {self.cond.shape}, dtype={self.cond.dtype}, device={self.cond.device}", verbose=False) debug(self.opt, f"cond = {cond.shape}, dtype={cond.dtype}, device={cond.device}", verbose=False)
# unfold speech data # unfold speech data
self.cond = self.cond.unfold(dimension=1, size=16, step=1) # (nseqs, nc_motion, 16) cond = cond.unfold(dimension=1, size=16, step=1) # (B, nseqs, nc_codit, 16)
self.cond = self.cond.permute(0, 1, 3, 2) # (nseqs, 16, 53) cond = cond.permute(0, 1, 3, 2) # (B, nseqs, 16, nc_condit)
self.cond = cond
self.nseq = self.cond.size(1) self.nseq = cond.size(1)
self.data = self.data[:, 7:7+self.nseq, :] data = data[:, 7:7+self.nseq, :]
self.vert, self.ldmk2d, self.ldmk3d = self.get_vertices(data)
debug(self.opt, f"\n a data = {self.data.shape}, dtype={self.data.dtype}, device={self.data.device}", verbose=False) debug(self.opt, f"[set_input] vert = {self.vert.shape}, dtype={self.vert.dtype}, device={self.vert.device}", verbose=False)
debug(self.opt, f"a cond = {self.cond.shape}, dtype={self.cond.dtype}, device={self.cond.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 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): def training(self, batch_input):
@@ -146,11 +176,11 @@ class Audio2MeshModel(Base):
# forward # forward
self.pred = self.netG(self.cond) self.pred = self.netG(self.cond)
self.pred += self.template_verts self.pred += self.temp_verts
debug(self.opt, f"traing pred = {self.pred.shape}", verbose=False) debug(self.opt, f"traing pred = {self.pred.shape}", verbose=False)
# loss # loss
loss, self.loss_dict = self.eval_losses(self.pred, self.data) loss, loss_dict = self.eval_losses(self.pred, self.vert)
# backward # backward
self.optimizer_G.zero_grad() self.optimizer_G.zero_grad()
@@ -162,7 +192,7 @@ class Audio2MeshModel(Base):
self.optimizer_G.step() self.optimizer_G.step()
return loss return loss_dict
def validation(self, batch_input): def validation(self, batch_input):
@@ -170,38 +200,67 @@ class Audio2MeshModel(Base):
self.set_input(batch_input) self.set_input(batch_input)
with torch.no_grad(): with torch.no_grad():
self.pred = self.netG(self.cond) pred = self.netG(self.cond)
self.pred += self.template_verts pred += self.temp_verts
_, loss_dict = self.eval_losses(self.pred, self.data) loss, loss_dict = self.eval_losses(pred, self.vert)
return loss_dict 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): def infer(self, batch_cond, path_audio, suffix="", save_npy=True):
self.eval() self.eval()
self.cond = batch_cond.float().to(self.device) # (nsteps, dim_cond) self.cond = batch_cond.float().to(self.device) # (nsteps, dim_cond)
with torch.no_grad(): with torch.no_grad():
samples_pt = self.netG(self.cond) # B x N x dim_motion batch_pdt_geo = self.netG(self.cond) # B x N x dim_motion
samples_pt += self.template_verts # B x N x 5023 x 3 batch_pdt_geo += self.temp_verts # B x N x 5023 x 3
print(f"testing pt shape = {samples_pt.shape}") print(f"testing pt shape = {batch_pdt_geo.shape}")
# !! add specific when render & output !! # !! add specific when render & output !!
samples_pt = samples_pt - self.template_verts + self.template_verts_specific batch_pdt_geo = batch_pdt_geo - self.temp_verts + self.temp_verts_specific
# render & and save # render & and save
self.save_reconstruct(samples_pt, path_audio, self.save_reconstruct(batch_pdt_geo, path_audio,
path_save=Path(self.opt.OUTPUT_DIR), path_save=Path(self.opt.OUTPUT_DIR),
suffix=suffix) suffix=suffix)
if save_npy: if save_npy:
# save result # save result
samples_pt = samples_pt.cpu().numpy() batch_pdt_geo = batch_pdt_geo.cpu().numpy()
path_save_npy = Path(self.opt.OUTPUT_DIR).joinpath(f"{suffix}.npy") path_save_npy = Path(self.opt.OUTPUT_DIR).joinpath(f"{suffix}.npy")
np.save(path_save_npy, samples_pt) np.save(path_save_npy, batch_pdt_geo)
print(f"save infer_result shape = {samples_pt.shape} -> {path_save_npy}") 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, cur_epoch=0, cur_batch=0):
@@ -209,17 +268,14 @@ class Audio2MeshModel(Base):
self.set_input(batch_input) self.set_input(batch_input)
with torch.no_grad(): with torch.no_grad():
samples_pt = self.netG(self.cond) # B x N x 5023 x 3 batch_pdt_geo = self.netG(self.cond) # B x N x 5023 x 3
samples_pt += self.template_verts # B x N x 5023 x 3 batch_pdt_geo += self.temp_verts # B x N x 5023 x 3
samples_gt = self.get_vertices(self.data) # B x N x 5023 x 3
# samples_gt = samples_gt.cpu().numpy() # B x N x 5023 x 3
# !! add specific when render & output !! # !! add specific when render & output !!
samples_pt = samples_pt - self.template_verts + self.template_verts_specific batch_pdt_geo = batch_pdt_geo - self.temp_verts + self.temp_verts_specific
print(f"testing pt shape = {samples_pt.shape}, gt shape = {samples_gt.shape}") print(f"testing pt shape = {batch_pdt_geo.shape}, gt shape = {self.vert.shape}")
self.save_reconstruct_with_gt(samples_pt, samples_gt, self.save_reconstruct_with_gt(batch_pdt_geo, self.vert,
path_save=Path(self.opt.OUTPUT_DIR), path_save=Path(self.opt.OUTPUT_DIR),
suffix=f'sampled_{cur_epoch:05d}_{cur_batch:03d}') suffix=f'sampled_{cur_epoch:05d}_{cur_batch:03d}')
@@ -227,7 +283,7 @@ class Audio2MeshModel(Base):
def get_template_vertices(self, mean_dict=None): def get_template_vertices(self, mean_dict=None):
batch_exp = torch.zeros(1, 50).to(self.device) batch_exp = torch.zeros(1, 50).to(self.device)
batch_pos = torch.zeros(1, 6).to(self.device) batch_pose = torch.zeros(1, 6).to(self.device)
if mean_dict is not None: if mean_dict is not None:
batch_shape = self.mean_dict["shape"].reshape(1, 100) batch_shape = self.mean_dict["shape"].reshape(1, 100)
@@ -235,13 +291,19 @@ class Audio2MeshModel(Base):
else: else:
batch_shape = torch.zeros(1, 100).to(self.device) 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 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}") print(f"template verts reshape = {verts.shape}")
# np.save("./data/template.npy", verts.squeeze().cpu().numpy()) # np.save("./data/template.npy", verts.squeeze().cpu().numpy())
# print(f"save template.npy = {verts.squeeze().shape}") # print(f"save template.npy = {verts.squeeze().shape}")
# assert False # assert False
return verts.unsqueeze(dim=0) # 1 x 1 x 5023 x 3 return verts, ldmk2d, ldmk3d
def get_vertices(self, batch_motion): def get_vertices(self, batch_motion):
@@ -249,197 +311,41 @@ class Audio2MeshModel(Base):
batch_motion, (nbatch, seqlen, 53) batch_motion, (nbatch, seqlen, 53)
""" """
batch_exp = batch_motion[..., :50] batch_exp = batch_motion[..., :50]
batch_pos = batch_motion[..., 50:] batch_pos_mouth = batch_motion[..., 50:]
nbatch, seqlen = batch_exp.size(0), batch_exp.size(1) 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 = batch_pos.reshape(nbatch * seqlen, -1) # nbatch * seqlen x 3 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_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 = torch.zeros(nbatch * seqlen, 6).to(self.device) # nbatch * seqlen x 6
batch_pose[:, 3:6] = batch_pos batch_pose[:, 3:6] = batch_pos_mouth
verts, _, _ = self.netR.get_vertices(batch_shape, batch_exp, batch_pose) # nbatch * seqlen x 5023 x 3 with torch.no_grad():
verts = verts.reshape(nbatch, seqlen, -1, 3) # nbatch x seqlen x 5023 x 3 verts, ldmk2d, ldmk3d = self.netF(batch_shape, batch_exp, batch_pose) # nbatch * seqlen x 5023 x 3
# print(f"verts reshape = {verts.shape}") 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 return verts, ldmk2d, ldmk3d
def eval_losses_for_infer_loss(self, batch_pdt_geo, batch_tgt): def eval_losses(self, batch_pdt_geo, batch_tgt_geo):
""" Computes the VAE loss function. """ Computes the VAE loss function.
pramas: pramas:
batch_tgt, (nbatch, seqlen, dim_motion) batch_tgt_geo, (nbatch, seqlen, num_vertices, 3)
batch_pdt_geo, (nbatch, seqlen, num_vertices, 3)
"""
# 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) # 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):
""" Computes the VAE loss function.
pramas:
batch_tgt, (nbatch, seqlen, dim_motion)
batch_pdt_geo, (nbatch, seqlen, num_vertices, 3) batch_pdt_geo, (nbatch, seqlen, num_vertices, 3)
""" """
loss = 0 loss = 0
loss_dict = {} loss_dict = OrderedDict()
# get mesh geometry
batch_tgt_geo = self.get_vertices(batch_tgt) # 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 # synthesis geo rec
loss = 0 loss = 0
loss_rec_geo = self.loss_func_wing(batch_pdt_geo, batch_tgt_geo) # B
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["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["vel_geo"] = loss_vel_geo.mean().detach()
loss_vel_geo = self.loss_func_l1(diff_pdt_geo, diff_tgt_geo) # 1,
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
# 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["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["vel_geo_w"] = loss_vel_geo2.detach()
loss += loss_vel_geo2 * self.opt.LOSS.lambda_vel_geo
# total loss
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_rec_geo = self.loss_func_wing(batch_pdt_geo, batch_tgt_geo)
loss_dict["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_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_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:
batch_tgt, (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) # 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()
# loss += loss_rec_geo.mean() * self.opt.LOSS.lambda_rec_geo # loss += loss_rec_geo.mean() * self.opt.LOSS.lambda_rec_geo
loss += loss_rec_geo2.mean() * self.opt.LOSS.lambda_rec_geo loss += loss_rec_geo2.mean() * self.opt.LOSS.lambda_rec_geo
@@ -451,42 +357,61 @@ class Audio2MeshModel(Base):
loss_dict["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_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_dict["vel_geo_w"] = loss_vel_geo2.mean().detach()
# loss += loss_vel_geo.mean() * self.opt.LOSS.lambda_vel_geo # loss += loss_vel_geo.mean() * self.opt.LOSS.lambda_vel_geo
if 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 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)) # (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()
# closure loss if self.opt.LOSS.lambda_rec_ldmk > 0:
diff_pdf_closure = batch_pdt_geo[:,:,flame_mouth_upper_idx].sum(dim=[2,3]) / len(flame_mouth_upper_idx) \ loss += loss_rec_ldmk.mean() * self.opt.LOSS.lambda_rec_ldmk
- 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) \ # mouth closure_x loss (left/right mouth)
- batch_tgt_geo[:,:,flame_mouth_lower_idx].sum(dim=[2,3]) / len(flame_mouth_upper_idx) 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 = self.loss_func_wing(diff_pdf_closure, diff_tgt_closure) loss_closure_x = (diff_pdt_mouth_x - diff_tgt_mouth_x).abs().mean() # (B*N, 8) ==> (1,)
loss_dict["closure"] = loss_closure.mean().detach() 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 = 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()
if self.opt.LOSS.lambda_closure_y > 0:
loss += loss_closure_y.mean() * self.opt.LOSS.lambda_closure_y
if self.opt.LOSS.lambda_closure > 0:
loss += loss_closure.mean() * self.opt.LOSS.lambda_closure
# total loss # total loss
loss_dict["all"] = loss.clone().detach() loss_dict["all"] = loss.detach()
# return
return loss, loss_dict return loss, loss_dict
def save_reconstruct(self, samples_pt, path_audio, path_save, suffix=""): def save_reconstruct(self, batch_pdt_geo, path_audio, path_save, suffix=""):
# samples_pt, [B x N x dim_motion] # batch_pdt_geo, [B x N x dim_motion]
B, N, *_ = samples_pt.shape B, N, *_ = batch_pdt_geo.shape
nbatch_render = 10 nbatch_render = 10
# for each batch # for each batch
for i in range(B): for i in range(B):
igeo_pt = samples_pt[i, ...] igeo_pt = batch_pdt_geo[i, ...]
ipath_save = path_save.joinpath(f"{suffix}_{i:02d}.mp4") ipath_save = path_save.joinpath(f"{suffix}_{i:02d}.mp4")
v_render_pt = [] v_render_pt = []
@@ -501,7 +426,8 @@ class Audio2MeshModel(Base):
# print(f"cam shape = {cam.shape}") # print(f"cam shape = {cam.shape}")
# render # render
render_pt = self.netR.render_geometry(kgeo_pt, cam, self.device) # (nbatch_real, 3, 512, 512) 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}") # print(f"render_pt ={render_pt.shape}, render_gt={render_gt.shape}")
# append each frame # append each frame
@@ -513,16 +439,94 @@ class Audio2MeshModel(Base):
save_images_with_audio(v_render_pt, path_audio, ipath_save) save_images_with_audio(v_render_pt, path_audio, ipath_save)
def save_reconstruct_with_gt(self, samples_pt, samples_gt, path_save, suffix=""): @torch.no_grad()
# samples_pt, [B x N x 5023 x 3] def render_geometry(self, verts, cam=None, device=None):
# samples_gt, [B x N x 5023 x 3] """
B, N, *_ = samples_pt.shape 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_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]
# batch_tgt_geo, [B x N x 5023 x 3]
B, N, *_ = batch_pdt_geo.shape
nbatch_render = 10 nbatch_render = 10
# for each batch # for each batch
for i in range(B): for i in range(B):
igeo_pt = samples_pt[i, ...] # [N x 5023 x 3] igeo_pt = batch_pdt_geo[i, ...] # [N x 5023 x 3]
igeo_gt = samples_gt[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") ipath_save = path_save.joinpath(f"{suffix}_{i:02d}.mp4")
v_render_pt = [] v_render_pt = []
@@ -533,18 +537,36 @@ class Audio2MeshModel(Base):
# split # split
kgeo_pt = igeo_pt[k:k+nbatch_render, ...] # [nbatch_real x 5023 x 3] 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] kgeo_gt = igeo_gt[k:k+nbatch_render, ...] # [nbatch_real x 5023 x 3]
nbatch_real = kgeo_pt.size(0) nbatch_real = kgeo_pt.size(0)
# cam # cam
cam = torch.tensor([5, 0, 0], device=self.device) # (1, 3) cam = torch.tensor([5, 0, 0], device=self.device).repeat(nbatch_real, 1) # (nbatch_real, 3)
cam = cam.repeat(nbatch_real, 1) # (nbatch_real, 3)
# print(f"cam shape = {cam.shape}") # print(f"cam shape = {cam.shape}")
# render # render
render_pt = self.netR.render_geometry(kgeo_pt, cam, self.device) # (nbatch_real, 3, 512, 512) render_pt = self.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) 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}") # 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 = (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 # append each frame
for m in range(nbatch_real): for m in range(nbatch_real):
v_render_pt.append(tensor2image(render_pt[m, ...])) v_render_pt.append(tensor2image(render_pt[m, ...]))
@@ -569,10 +591,12 @@ class Audio2MeshModel(Base):
######################################### #########################################
def tensor2image(tensor): def tensor2image(tensor):
image = tensor.detach().cpu().numpy() # image = tensor.detach().cpu().numpy()
image = tensor.numpy()
image = image*255. image = image*255.
image = np.maximum(np.minimum(image, 255), 0) image = np.maximum(np.minimum(image, 255), 0)
image = image.transpose(1,2,0)[:,:,[2,1,0]] image = image.transpose(1,2,0)[:,:,[2,1,0]]
return image.astype(np.uint8).copy() return image.astype(np.uint8).copy()
@@ -596,35 +620,31 @@ def define_netG(opt):
# to GPU # to GPU
netG.to(f"cuda:{opt.GPUS[0]}") 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 return netG
def define_netR(device): def define_FLAME(opt, device):
# import
from src.nn.FLAME import FLAME from src.nn.FLAME import FLAME
sys.path.insert(0, "/ssdata1/lsen/CODE/DECA_old") model = FLAME(opt.FLAME).to(device)
from decalib.deca import DECA
from decalib.utils import util
from decalib.utils.config import cfg as deca_cfg
# use device return model
# 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 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
+1 -1
View File
@@ -261,8 +261,8 @@ class Audio2MeshARModel(Base):
# ibatch_y_pre = self.y_tgt[:, 0:1] # B x 1 x 5023 x 3 # ibatch_y_pre = self.y_tgt[:, 0:1] # B x 1 x 5023 x 3
ibatch_y_pre = self.template_verts.expand(B, -1, -1, -1) # B x 1 x 5023 x 3 ibatch_y_pre = self.template_verts.expand(B, -1, -1, -1) # B x 1 x 5023 x 3
for istep in range(1, self.nsteps_align):
for istep in range(1, self.nsteps_align):
ibatch_x = self.x[:, istep:istep+1] # B x 1 x nwind x nc_condit 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.netG(ibatch_x, ibatch_y_pre) # B x 1 x 5023 x 3
@@ -9,10 +9,6 @@ import torch
import torch.nn as nn import torch.nn as nn
from pathlib import Path 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 import init_net
from src.models.base import Base from src.models.base import Base
from src.optims import get_optimizer, get_scheduler from src.optims import get_optimizer, get_scheduler
@@ -23,8 +19,9 @@ from common.animation import save_animation_with_gt2, save_images_with_audio
from common.debug import debug from common.debug import debug
from common.losses import WingLoss from common.losses import WingLoss
# disentangle model # disentangle model
class Audio2Mesh2Model(Base): class Audio2PoseModel(Base):
def __init__(self, opt, logger): def __init__(self, opt, logger):
Base.__init__(self, opt, logger) Base.__init__(self, opt, logger)
@@ -33,30 +30,17 @@ class Audio2Mesh2Model(Base):
self.logger = logger self.logger = logger
self.names_model = ["G"] # G 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
# define networks # define networks
self.netG = define_netG(opt) self.netG = define_netG(opt)
init_net(self.netG, init_type='kaiming', gpu_ids=opt.GPUS) 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]
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
# 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.netF = define_FLAME(opt, self.device)
self.netR = define_render(opt, self.device) self.netR = define_render(opt, self.device)
self.processor, self.extractor = define_extractor(opt, self.device)
# path_deca_mean = Path("./data/DECA_obama_mean.npy") # path_deca_mean = Path("./data/DECA_obama_mean.npy")
path_deca_mean = self.opt.DATASET.path_mean_dict path_deca_mean = self.opt.DATASET.path_mean_dict
@@ -69,16 +53,11 @@ class Audio2Mesh2Model(Base):
self.temp_verts_specific, self.temp_ldmk2d_specific, self.temp_ldmk3d_specific \ 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) = 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 # loss function
# if self.opt.LOSS.filter_outlier:
self.loss_func_wing = WingLoss(reduction="none") # return (B, ) self.loss_func_wing = WingLoss(reduction="none") # return (B, )
self.loss_func_l1 = nn.L1Loss(reduction="none") self.loss_func_l1 = nn.L1Loss(reduction="none")
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: if self.isTrain:
# define optimizers # define optimizers
@@ -88,76 +67,48 @@ class Audio2Mesh2Model(Base):
self.scheduler_G = get_scheduler(self.optimizer_G, opt) self.scheduler_G = get_scheduler(self.optimizer_G, opt)
self.schedulers.append(self.scheduler_G) 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)
path_ckpt_wav2vec = "./checkpoints/wav2vec2"
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): def set_input(self, batch_input):
# motion data # motion data
data = batch_input["data"].float().to(self.device) # (B, nsteps, nc_motion) x = batch_input["pose"].float().to(self.device) # (B, nsteps, nc_motion)
self.batch_vid = batch_input['vid'] self.batch_vid = batch_input['vid']
self.batch_nframe = batch_input['nframe'] self.batch_nframe = batch_input['nframe']
self.batch_interv = batch_input['frame_interval'] 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"x = {x.shape}, dtype={x.dtype}", verbose=False)
debug(self.opt, f"batch_vid = {self.batch_vid[:2]}", 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_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])}, \ 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) beg={self.batch_interv[0][:4]}, end={self.batch_interv[1][:4]}", verbose=False)
# speech data # speech data
cond = None raw_speech = batch_input["aud"].numpy() # (B, nsegments)
raw_speech = batch_input["cond"].numpy() # (B, nsegments)
debug(self.opt, f"raw_speech = {raw_speech.shape}, dtype={raw_speech.dtype}", verbose=False) debug(self.opt, f"raw_speech = {raw_speech.shape}, dtype={raw_speech.dtype}", verbose=False)
if self.opt.DATASET.speech_extractor == "wav2vec": # padding half frame length for bed and end
# raw_speech = raw_speech.reshape(self.B * self.nsteps, -1) # (B*nsteps, nsegments) npad = int(0.5 * self.opt.DATASET.sr * ( 1 / self.opt.DATASET.fps) + 0.5)
# debug(self.opt, f"raw_speech = {raw_speech.shape}, dtype={raw_speech.dtype}", verbose=False) 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)
# padding half frame length for bed and end inputs = self.processor(list(raw_speech), sampling_rate=16000, return_tensors="pt")
npad = int(0.5 * self.opt.DATASET.sr * ( 1 / self.opt.DATASET.fps) + 0.5) with torch.no_grad():
raw_speech = np.pad(raw_speech, pad_width=((0,0), (npad, npad)), mode="edge") cond = self.extractor(**inputs.to(self.device)).last_hidden_state # B x nsteps x nc_feat
debug(self.opt, f"after padding raw_speech = {raw_speech.shape}, dtype={raw_speech.dtype}", verbose=False) debug(self.opt, f"cond = {cond.shape}, dtype={cond.dtype}, device={cond.device}", verbose=False)
raw_speech = list(raw_speech) # unfold speech data
inputs = self.processor(raw_speech, sampling_rate=16000, return_tensors="pt") cond = cond.unfold(dimension=1, size=16, step=1) # (B, nsteps, nc_codit, 16)
inputs = inputs.to(self.device) cond = cond.permute(0, 1, 3, 2) # (B, nsteps, 16, nc_speech)
with torch.no_grad(): # setup
output = self.extractor(**inputs) self.c = cond # (B, nsteps, 16, nc_speech)
cond = output.last_hidden_state self.B, self.nsteps, self.nwind, self.nc_speech = cond.size()
self.x = x[:, 7:7+self.nsteps, :] # (B, nsteps, nc_motion)
else: debug(self.opt, f"x = {self.x.shape}, dtype={self.x.dtype}, device={self.x.device}", verbose=False)
assert 0, "opt.DATASET.speech_extractor should be 'wav2vec | deepspeech | mfcc ' " debug(self.opt, f"c = {self.c.shape}, dtype={self.c.dtype}, device={self.c.device}", verbose=False)
# 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) # (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)
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 forward(self, batch_input): def forward(self, batch_input):
@@ -174,13 +125,16 @@ class Audio2Mesh2Model(Base):
self.train() # set train model self.train() # set train model
self.set_input(batch_input) 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 # forward
self.pred = self.netG(self.cond) batch_pt, batch_mu, batch_lv = self.netG(batch_x, batch_x_prev, batch_c) # [B*(nsteps-1), nc_motion]
self.pred += self.temp_verts debug(self.opt, f"traing batch_pt = {batch_pt.shape}, batch_gt = {batch_x.shape}")
debug(self.opt, f"traing pred = {self.pred.shape}", verbose=False)
# loss # loss
loss, loss_dict = self.eval_losses(self.pred, self.vert) loss, loss_dict = self.eval_losses(batch_pt, batch_x, batch_mu, batch_lv)
# backward # backward
self.optimizer_G.zero_grad() self.optimizer_G.zero_grad()
@@ -189,7 +143,6 @@ class Audio2Mesh2Model(Base):
if self.opt.TRAIN.grad_clip_norm: # operate grad 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_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) torch.nn.utils.clip_grad_norm_(self.netG.parameters(), self.opt.TRAIN.max_grad_norm)
self.optimizer_G.step() self.optimizer_G.step()
return loss_dict return loss_dict
@@ -200,48 +153,47 @@ class Audio2Mesh2Model(Base):
self.set_input(batch_input) self.set_input(batch_input)
with torch.no_grad(): with torch.no_grad():
pred = self.netG(self.cond) batch_pt = torch.zeros_like(self.x) # [B, nsteps, nc_motion]
pred += self.temp_verts batch_pt[:, 0] = self.x[:, 0] # assign first frame
loss, loss_dict = self.eval_losses(pred, self.vert) 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]
self.logger.info(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.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]
loss, loss_dict = self.eval_losses(batch_pt, batch_gt, batch_mu, batch_lv)
return loss_dict 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): def infer(self, batch_cond, path_audio, suffix="", save_npy=True):
self.eval() self.eval()
self.cond = batch_cond.float().to(self.device) # (nsteps, dim_cond) c = batch_cond.float().to(self.device) # (B, nsteps, 16, nc_speech)
nbtach, nstep, *_ = c.shape
with torch.no_grad(): 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 batch_pdt_geo += self.temp_verts # B x N x 5023 x 3
@@ -268,14 +220,26 @@ class Audio2Mesh2Model(Base):
self.set_input(batch_input) self.set_input(batch_input)
with torch.no_grad(): 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_pt = torch.zeros_like(self.x) # [B, nsteps, nc_motion]
batch_pdt_geo = batch_pdt_geo - self.temp_verts + self.temp_verts_specific batch_pt[:, 0] = self.x[:, 0] # assign first frame
print(f"testing pt shape = {batch_pdt_geo.shape}, gt shape = {self.vert.shape}") for istep in range(1, self.nsteps):
self.save_reconstruct_with_gt(batch_pdt_geo, self.vert, 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, *_ = self.netG(ibatch_x, ibatch_x_prev, ibatch_c) # [B, nc_motion]
self.logger.info(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}")
self.save_reconstruct_with_gt(batch_pt, self.x,
path_save=Path(self.opt.OUTPUT_DIR), path_save=Path(self.opt.OUTPUT_DIR),
suffix=f'sampled_{cur_epoch:05d}_{cur_batch:03d}') suffix=f'sampled_{cur_epoch:05d}_{cur_batch:03d}')
@@ -310,6 +274,7 @@ class Audio2Mesh2Model(Base):
""" """
batch_motion, (nbatch, seqlen, 53) batch_motion, (nbatch, seqlen, 53)
""" """
batch_exp = batch_motion[..., :50] batch_exp = batch_motion[..., :50]
batch_pos_mouth = batch_motion[..., 50:] batch_pos_mouth = batch_motion[..., 50:]
nbatch, seqlen = batch_exp.size(0), batch_exp.size(1) nbatch, seqlen = batch_exp.size(0), batch_exp.size(1)
@@ -330,71 +295,40 @@ class Audio2Mesh2Model(Base):
return verts, ldmk2d, ldmk3d return verts, ldmk2d, ldmk3d
def eval_losses(self, batch_pdt_geo, batch_tgt_geo): def eval_losses(self, batch_pt, batch_gt, batch_mu, batch_lv):
""" Computes the VAE loss function. """ Computes the VAE loss function.
pramas: pramas:
batch_tgt_geo, (nbatch, seqlen, num_vertices, 3) batch_pt, batch_gt: [B * nsteps, nc_motion]
batch_pdt_geo, (nbatch, seqlen, num_vertices, 3) batch_mu, batch_lv: [B * nsteps, nc_latent]
""" """
loss = 0
loss_dict = OrderedDict() loss_dict = OrderedDict()
# synthesis geo rec # recon loss
loss = 0 loss_rec = (batch_pt - batch_gt).pow(2).mean()
loss_rec_geo = self.loss_func_wing(batch_pdt_geo, batch_tgt_geo) loss_dict["rec"] = loss_rec.detach()
loss_dict["rec_geo"] = loss_rec_geo.mean().detach() loss = loss_rec
loss_rec_geo2 = self.loss_func_wing(batch_pdt_geo, batch_tgt_geo, weight=self.vertices_weight) # kl loss
# loss_dict["rec_geo_w"] = loss_rec_geo2.mean().detach() loss_kl = -0.5 * (1 + batch_lv - batch_mu.pow(2) - batch_lv.exp()).sum().clamp(max=0) # [B*nsteps, ]
# loss += loss_rec_geo.mean() * self.opt.LOSS.lambda_rec_geo loss_kl /= batch_lv.numel()
loss += loss_rec_geo2.mean() * self.opt.LOSS.lambda_rec_geo loss_dict["kl"] = loss_kl.detach()
# synthesis geo volocity if self.opt.LOSS.lambda_kl > 0:
diff_pdt_geo = batch_pdt_geo[:, 1:, :] - batch_pdt_geo[:, :-1, :] loss += loss_kl * self.opt.LOSS.lambda_kl
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) # velocity loss
# loss_dict["vel_geo_w"] = loss_vel_geo2.mean().detach() batch_pt = batch_pt.reshape(self.B, self.nsteps, self.nc_motion)
# loss += loss_vel_geo.mean() * self.opt.LOSS.lambda_vel_geo batch_gt = batch_gt.reshape(self.B, self.nsteps, self.nc_motion)
if self.opt.LOSS.lambda_vel_geo > 0: diff_pt = batch_pt[:, 1:, :] - batch_pt[:, :-1, :] # [B, nsteps-1, nc_motion]
loss += loss_vel_geo2.mean() * self.opt.LOSS.lambda_vel_geo diff_gt = batch_gt[:, 1:, :] - batch_gt[:, :-1, :] # (B, nsteps-1, nc_motion)
loss_vel_rec = (diff_pt - diff_gt).pow(2).mean()
loss_dict["vel_rec"] = loss_vel_rec.detach()
# landmarks loss if self.opt.LOSS.lambda_vel_rec > 0:
ldmk3d_pdt = self.netF.seletec_3d68(batch_pdt_geo.reshape(-1, self.opt.MODEL.num_vertices, 3)) # (B*N, 68, 3) loss += loss_vel_rec * self.opt.LOSS.lambda_vel_rec
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()
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 = 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()
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 = 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()
if self.opt.LOSS.lambda_closure_y > 0:
loss += loss_closure_y.mean() * self.opt.LOSS.lambda_closure_y
# total loss # total loss
@@ -411,14 +345,14 @@ class Audio2Mesh2Model(Base):
# for each batch # for each batch
for i in range(B): for i in range(B):
igeo_pt = batch_pdt_geo[i, ...] ipos_pt = batch_pdt_geo[i, ...]
ipath_save = path_save.joinpath(f"{suffix}_{i:02d}.mp4") ipath_save = path_save.joinpath(f"{suffix}_{i:02d}.mp4")
v_render_pt = [] v_render_pt = []
for k in range(0, N, nbatch_render): for k in range(0, N, nbatch_render):
# split # split
kgeo_pt = igeo_pt[k:k+nbatch_render, ...] # [nbatch_real x 5023 x 3] kpos_pt = ipos_pt[k:k+nbatch_render, ...] # [nbatch_real x 5023 x 3]
nbatch_real = kgeo_pt.size(0) nbatch_real = kpos_pt.size(0)
# cam # cam
cam = torch.tensor([5, 0, 0], device=self.device) # (1, 3) cam = torch.tensor([5, 0, 0], device=self.device) # (1, 3)
@@ -426,7 +360,7 @@ class Audio2Mesh2Model(Base):
# print(f"cam shape = {cam.shape}") # print(f"cam shape = {cam.shape}")
# render # render
render_pt = self.render_geometry(kgeo_pt, cam, self.device) # (nbatch_real, 3, 512, 512) render_pt = self.render_geometry(kpos_pt, cam, self.device) # (nbatch_real, 3, 512, 512)
render_pt = render_pt.cpu() render_pt = render_pt.cpu()
# print(f"render_pt ={render_pt.shape}, render_gt={render_gt.shape}") # print(f"render_pt ={render_pt.shape}, render_gt={render_gt.shape}")
@@ -465,8 +399,8 @@ class Audio2Mesh2Model(Base):
B, N, *_ = batch_pdt_geo.shape B, N, *_ = batch_pdt_geo.shape
igeo_pt = batch_pdt_geo[0, ...] # [N x 5023 x 3] ipos_pt = batch_pdt_geo[0, ...] # [N x 5023 x 3]
igeo_gt = batch_tgt_geo[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") ipath_save = path_save.joinpath(f"{suffix}_{0:02d}.mp4")
v_render_pt = [] v_render_pt = []
@@ -474,23 +408,23 @@ class Audio2Mesh2Model(Base):
nbatch_render = 10 nbatch_render = 10
for k in range(0, N, nbatch_render): for k in range(0, N, nbatch_render):
# split # split
kgeo_pt = igeo_pt[k:k+nbatch_render, ...] # [nbatch_real x 5023 x 3] kpos_pt = ipos_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] kpos_gt = ipos_gt[k:k+nbatch_render, ...] # [nbatch_real x 5023 x 3]
nbatch_real = kgeo_pt.size(0) nbatch_real = kpos_pt.size(0)
# cam # cam
cam = torch.tensor([5, 0, 0], device=self.device).repeat(nbatch_real, 1) # (nbatch_real, 3) cam = torch.tensor([5, 0, 0], device=self.device).repeat(nbatch_real, 1) # (nbatch_real, 3)
# print(f"cam shape = {cam.shape}") # print(f"cam shape = {cam.shape}")
# render # render
render_pt = self.render_geometry(kgeo_pt, cam, self.device) # (nbatch_real, 3, 512, 512) render_pt = self.render_geometry(kpos_pt, cam, self.device) # (nbatch_real, 3, 512, 512)
render_gt = self.render_geometry(kgeo_gt, cam, self.device) # (nbatch_real, 3, 512, 512) 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}") # print(f"render_pt ={render_pt.shape}, render_gt={render_gt.shape}")
# landmarks 3d # landmarks 3d
kldmk3d_pt = self.netF.seletec_3d68(kgeo_pt) # [nbatch_real x 68 x 3] kldmk3d_pt = self.netF.seletec_3d68(kpos_pt) # [nbatch_real x 68 x 3]
kldmk3d_gt = self.netF.seletec_3d68(kgeo_gt) # [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 = util.batch_orth_proj(kldmk3d_pt, cam);
kldmk3d_pt[:,:,1:] = -kldmk3d_pt[:,:,1:]; kldmk3d_pt[:,:,1:] = -kldmk3d_pt[:,:,1:];
@@ -517,73 +451,60 @@ class Audio2Mesh2Model(Base):
@torch.no_grad() @torch.no_grad()
def save_reconstruct_with_gt(self, batch_pdt_geo, batch_tgt_geo, path_save, suffix=""): def save_reconstruct_with_gt(self, batch_pdt_pos, batch_tgt_pos, path_save, suffix=""):
# batch_pdt_geo, [B x N x 5023 x 3] # batch_pdt_pos, [B x N x nc_motion=9]
# batch_tgt_geo, [B x N x 5023 x 3] # batch_pdt_pos, [B x N x nc_motion=9]
B, N, *_ = batch_pdt_geo.shape
B, N, *_ = batch_pdt_pos.shape
nbatch_render = 10 nbatch_render = 10
# for each batch # for each batch
for i in range(B): for i in range(B):
igeo_pt = batch_pdt_geo[i, ...] # [N x 5023 x 3] ipos_pt = batch_pdt_pos[i, ...] # [N x 9]
igeo_gt = batch_tgt_geo[i, ...] # [N x 5023 x 3] ipos_gt = batch_tgt_pos[i, ...] # [N x 9]
ipath_save = path_save.joinpath(f"{suffix}_{i:02d}.mp4") ipath_save = path_save.joinpath(f"{suffix}_{i:02d}.mp4")
v_render_pt = [] v_render_pt = []
v_render_gt = [] v_render_gt = []
for k in range(0, N, nbatch_render): for k in range(0, N, nbatch_render):
# split # split
kgeo_pt = igeo_pt[k:k+nbatch_render, ...] # [nbatch_real x 5023 x 3] kpos_pt = ipos_pt[k:k+nbatch_render, :6] # [nbatch_real x 6]
kgeo_gt = igeo_gt[k:k+nbatch_render, ...] # [nbatch_real x 5023 x 3] kpos_gt = ipos_gt[k:k+nbatch_render, :6] # [nbatch_real x 6]
nbatch_real = kgeo_pt.size(0) 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]
# cam kidn_gt = self.idn[k:k+nbatch_render, :] # [nbatch_real, 100]
cam = torch.tensor([5, 0, 0], device=self.device).repeat(nbatch_real, 1) # (nbatch_real, 3) kexp_gt = self.exp[k:k+nbatch_render, :] # [nbatch_real, 50]
# print(f"cam shape = {cam.shape}")
# render # get geometry
render_pt = self.render_geometry(kgeo_pt, cam, self.device) # (nbatch_real, 3, 512, 512) kgeo_pt = self.get_vertices(kidn_gt.clone(), kexp_gt.clone(), kpos_pt) # (nbatch_read, 5023, 3)
render_gt = self.render_geometry(kgeo_gt, cam, self.device) # (nbatch_real, 3, 512, 512) kgeo_gt = self.get_vertices(kidn_gt.clone(), kexp_gt.clone(), kpos_gt) # (nbatch_read, 5023, 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)
# print(f"render_pt ={render_pt.shape}, render_gt={render_gt.shape}") # 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 = (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 # append each frame
nbatch_real = kpos_pt.shape[0]
for m in range(nbatch_real): for m in range(nbatch_real):
v_render_pt.append(tensor2image(render_pt[m, ...])) v_render_pt.append(tensor2image(render_pt[m, ...]))
v_render_gt.append(tensor2image(render_gt[m, ...])) v_render_gt.append(tensor2image(render_gt[m, ...]))
# get audio # get audio
jvid = self.batch_vid[i] jvid = self.batch_vid[i]
jnframe = self.batch_nframe[i].numpy()
jstart_frame = self.batch_interv[0][i].numpy() jstart_frame = self.batch_interv[0][i].numpy()
jpath_audio = f"{self.opt.DATASET.root_raw}/{jvid}/audio/audio_trim.wav" 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 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 jend_time = (jstart_frame + 7 + self.nsteps) / self.opt.DATASET.fps # xxx.yyy min
# print(f"jvid={jvid}, jnfram={jnframe}, jstart_frame={jstart_frame}, jpath_audio={jpath_audio}") # print(f"jvid={jvid}, jnfram={jnframe}, jstart_frame={jstart_frame}, jpath_audio={jpath_audio}")
# print(f"jstart_time={jstart_time}, jend_time={jend_time}") # print(f"jstart_time={jstart_time}, jend_time={jend_time}")
# save animation # save animation
# print(f"testing v_render_pt = {len(v_render_pt)}, gt shape = {len(v_render_gt)}") # 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,\ save_animation_with_gt2(v_render_pt, v_render_gt, ipath_save, fps=self.opt.DATASET.fps,\
@@ -647,4 +568,18 @@ def define_render(opt, device):
return model return model
def define_extractor(opt, device):
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)
path_ckpt_wav2vec = "./checkpoints/wav2vec2"
processor = Wav2Vec2FeatureExtractor.from_pretrained(path_ckpt_wav2vec)
extractor = Wav2Vec2Model.from_pretrained(path_ckpt_wav2vec).to(device)
return processor, extractor
+232
View File
@@ -0,0 +1,232 @@
import torch
import torch.nn as nn
import torch.nn.functional as F
class PoseMixtureVAE(nn.Module):
def __init__(
self,
nc_motion,
latent_size,
nseqR,
nseqF,
num_experts,
):
super().__init__()
self.nc_motion = nc_motion
self.latent_size = latent_size
self.nseqR = nseqR
self.nseqF = nseqF
nc_speech = 1024
nc_feat_c = 128
hidden_size = 256
self.layer_cond = nn.Sequential( # (nbatch, nchannel=1024, H=16, W=1)
nn.BatchNorm2d(nc_speech),
nn.Conv2d(nc_speech, 512, kernel_size=(3,1), stride=(2,1), padding=(1,0), bias=True), # 512 x 8 x 1
nn.LeakyReLU(0.02, True),
nn.Conv2d(512, 512, kernel_size=(3,1), stride=(1,1), padding=(1,0), bias=True), # 512 x 8 x 1
nn.LeakyReLU(0.02, True),
nn.Conv2d(512, 512, kernel_size=(3,1), stride=(2,1), padding=(1,0), bias=True), # 512 x 4 x 1
nn.LeakyReLU(0.02, True),
nn.Conv2d(512, 512, kernel_size=(3,1), stride=(1,1), padding=(1,0), bias=True), # 512 x 4 x 1
nn.LeakyReLU(0.02, True),
nn.Conv2d(512, 256, kernel_size=(3,1), stride=(2,1), padding=(1,0), bias=True), # 256 x 2 x 1
nn.LeakyReLU(0.02, True),
nn.Conv2d(256, 256, kernel_size=(3,1), stride=(1,1), padding=(1,0), bias=True), # 256 x 2 x 1
nn.LeakyReLU(0.02, True),
nn.Conv2d(256, 256, kernel_size=(3,1), stride=(2,1), padding=(1,0), bias=True), # 256 x 1 x 1
nn.LeakyReLU(0.02, True),
nn.Conv2d(256, nc_feat_c, kernel_size=(3,1), stride=(1,1), padding=(1,0), bias=True), # nc_feat_c x 1 x 1
nn.LeakyReLU(0.02, True),
nn.Flatten() # nc_feat_c
)
self.encoder = Encoder(nc_motion, nc_feat_c, latent_size, hidden_size, nseqR, nseqF)
self.decoder = MixedDecoder(nc_motion, nc_feat_c, latent_size, hidden_size, nseqR, nseqF, num_experts)
def forward(self, x, x_prev, c):
""" forward function
parameters:
x : shape = (B x nc_motion)
x_pre: shape = (B x nc_motion)
c : shape = (B x nwind x nc_speech)
return:
y : shape = (B x nc_motion)
"""
# condition header
c = torch.unsqueeze(c, dim=1).transpose(c, 1, 3) # (B, 1, nwind, nc_speech) -> (B, nc_speech, nwind, 1)
feat_c = self.layer_cond(c) # (B, 64)
self.logger.info(f"[forward] transpose c shape = {c.shape}, feac_c shape = {feat_c.shape}")
# encoder
z, mu, logvar = self.encoder(x, x_prev, feat_c)
# decoder
pred = self.decoder(z, x_prev, feat_c)
return pred, mu, logvar
def sample(self, z, x_prev, c):
""" forward function
parameters:
z : shape = (B x nc_motion)
x_pre: shape = (B x nc_motion)
c : shape = (B x nwind x nc_speech)
return:
y : shape = (B x nc_motion)
"""
# condition header
c = torch.unsqueeze(c, dim=1).transpose(c, 1, 3) # (B, 1, nwind, nc_speech) -> (B, nc_speech, nwind, 1)
feat_c = self.layer_cond(c) # (B, nc_feat_c)
self.logger.info(f"[forward] transpose c shape = {c.shape}, feac_c shape = {feat_c.shape}")
pred = self.decoder(z, x_prev, feat_c)
return pred
class Encoder(nn.Module):
def __init__(self, nc_motion, nc_feat_c, latent_size, hidden_size, nseqR, nseqF):
super().__init__()
# Encoder
# Takes pose | condition (n * poses) as input
input_size = nc_motion * nseqF + nc_motion * nseqR + nc_feat_c
self.fc1 = nn.Linear(input_size, hidden_size)
self.fc2 = nn.Linear(nc_motion * nseqF + hidden_size, hidden_size)
self.fc_mu = nn.Linear(nc_motion * nseqF + hidden_size, latent_size)
self.fc_logvar = nn.Linear(nc_motion * nseqF + hidden_size, latent_size)
def reparameterize(self, mu, logvar):
std = torch.exp(0.5 * logvar)
eps = torch.randn_like(std)
return mu + eps * std
def forward(self, x, x_prev, feat_c):
"""
x shape = (B, nc_motion)
x_prev shape = (B, nc_motion)
feat_c shape = (B, nc_feat_c)
"""
feat_c = torch.cat((x_prev, feat_c), dim=1) # (B, nc_motion * nseqR + nc_feat_c)
h1 = F.elu(self.fc1(torch.cat((x, feat_c), dim=1))) # (B, hidden_size)
h2 = F.elu(self.fc2(torch.cat((x, h1), dim=1))) # (B, hidden_size)
s = torch.cat((x, h2), dim=1) # (B, nc_motion * nseqF + hidden_size)
mu = self.fc_mu(s) # (B, latent_size)
logvar = self.fc_logvar(s) # (B, latent_size)
z = self.reparameterize(mu, logvar) # (B, latent_size)
return z, mu, logvar
class Decoder(nn.Module):
def __init__(self, nc_motion, nc_feat_c, latent_size, hidden_size, nseqR, nseqF):
super().__init__()
# Decoder
# Takes latent | condition as input
input_size = latent_size + nc_motion * nseqR + nc_feat_c
output_size = nseqF * nc_motion
self.fc4 = nn.Linear(input_size, hidden_size)
self.fc5 = nn.Linear(latent_size + hidden_size, hidden_size)
self.out = nn.Linear(latent_size + hidden_size, output_size)
def forward(self, z, x_prev, feat_c):
"""
z shape = (B, latent_size)
x_prev shape = (B, nc_motion)
feat_c shape = (B, nc_feat_c)
"""
feat_c = torch.cat((x_prev, feat_c), dim=1) # (B, nc_motion * nseqR + nc_feat_c)
h4 = F.elu(self.fc4(torch.cat((z, feat_c), dim=1))) # (B, hidden_size)
h5 = F.elu(self.fc5(torch.cat((z, h4), dim=1))) # (B, hidden_size)
pred = self.out(torch.cat((z, h5), dim=1)) # (B, output_size)
return pred
class MixedDecoder(nn.Module):
def __init__(self, nc_motion, nc_feat_c, latent_size, hidden_size, nseqR, nseqF, num_experts):
super().__init__()
input_size = latent_size + nc_motion * nseqR + nc_feat_c
inter_size = latent_size + hidden_size
output_size = nseqF * nc_motion
self.decoder_layers = [(
nn.Parameter(torch.empty(num_experts, input_size, hidden_size)),
nn.Parameter(torch.empty(num_experts, hidden_size)),
F.elu,),(
nn.Parameter(torch.empty(num_experts, inter_size, hidden_size)),
nn.Parameter(torch.empty(num_experts, hidden_size)),
F.elu,),(
nn.Parameter(torch.empty(num_experts, inter_size, output_size)),
nn.Parameter(torch.empty(num_experts, output_size)),
None,),
]
# init layers
for index, (weight, bias, _) in enumerate(self.decoder_layers):
index = str(index)
torch.nn.init.kaiming_uniform_(weight)
bias.data.fill_(0.01)
self.register_parameter("w" + index, weight)
self.register_parameter("b" + index, bias)
# Gating network
gate_hsize = 64
self.gate = nn.Sequential(
nn.Linear(input_size, gate_hsize),
nn.ELU(),
nn.Linear(gate_hsize, gate_hsize),
nn.ELU(),
nn.Linear(gate_hsize, num_experts),
)
def forward(self, z, x_prev, feat_c):
"""
z shape = (B, latent_size)
x_prev shape = (B, nc_motion)
feat_c shape = (B, nc_feat_c)
"""
feat_c = torch.cat((x_prev, feat_c), dim=1) # (B, nc_motion + nc_feat_c)
coefficients = F.softmax(self.gate(torch.cat((z, feat_c), dim=1)), dim=1) # (B, num_experts)
feat_o = feat_c
for (weight, bias, activation) in self.decoder_layers:
flat_weight = weight.flatten(start_dim=1, end_dim=2)
mixed_weight = torch.matmul(coefficients, flat_weight)\
.view(coefficients.shape[0], *weight.shape[1:3])
input = torch.cat((z, feat_o), dim=1).unsqueeze(1)
mixed_bias = torch.matmul(coefficients, bias).unsqueeze(1)
out = torch.baddbmm(mixed_bias, input, mixed_weight).squeeze(1)
if activation is not None:
feat_o = activation(out) # (B, hidden_size)
else:
feat_o = out # (B, output_size)
return feat_o