add audio2motion gan
This commit is contained in:
1 parent
7aed8b140a
commit
8b8b0de093
19 files changed
+1771
-202
No files matched your search
@@ -0,0 +1,81 @@
|
||||
# @package _global_
|
||||
# to execute this experiment run:
|
||||
# python train.py experiment=audio2mesh/train_audio2mesh_CN_20220425.yaml
|
||||
|
||||
defaults:
|
||||
- override /dataset: motion.yaml
|
||||
- override /model: model_audio2motion_gan.yaml
|
||||
- override /callbacks: callback_audio2render.yaml
|
||||
- override /logger: tensorboard.yaml
|
||||
- override /trainer: ddp.yaml
|
||||
|
||||
# all parameters below will be merged with parameters from default configurations set above
|
||||
# this allows you to overwrite only specified parameters
|
||||
|
||||
# name of the run determines folder name in logs
|
||||
name: "audio2motion"
|
||||
seed: 12345
|
||||
path_data: ${path_cwd}/data/Actor7
|
||||
specifict_folder: Actor7-raw-processing-2h
|
||||
|
||||
|
||||
trainer:
|
||||
gpus: [1]
|
||||
min_epochs: 100
|
||||
max_epochs: 300
|
||||
|
||||
# accumulate_grad_batches: 8
|
||||
gradient_clip_val: 0.5
|
||||
gradient_clip_algorithm: 'norm'
|
||||
# precision: 16
|
||||
|
||||
|
||||
num_sanity_val_steps: 1
|
||||
# check_val_every_n_epoch: 100
|
||||
val_check_interval: 0.25
|
||||
|
||||
enable_checkpointing: True
|
||||
log_every_n_steps: 10
|
||||
# resume_from_checkpoint: ${path_cwd}/logs/experiments/runs/audio2render/2022-05-30_14-29-24/checkpoints/last.ckpt
|
||||
|
||||
|
||||
model:
|
||||
_target_: src.models.module_audio2motion_gan.Audio2MotionGANModel
|
||||
|
||||
opt:
|
||||
dim_x: 53
|
||||
dim_c: 1024
|
||||
dim_z: 32
|
||||
path_mean_dict: ${path_data}/mean_deca_coeff_Actor7_processing.npy
|
||||
|
||||
pretrain: False
|
||||
pretrain_path: ${path_cwd}/logs/experiments/runs/ganrender/2022-06-07_13-08-41/checkpoints/epoch_000.ckpt
|
||||
|
||||
opt_optim:
|
||||
lr_G: 0.0005 # 0.00125
|
||||
lr_D: 0.0005 # 0.00125
|
||||
|
||||
opt_loss:
|
||||
lambda_rec_exp: 0.5
|
||||
lambda_rec_pos: 1
|
||||
lambda_rec_geo: 100
|
||||
lambda_vel_exp: 10
|
||||
lambda_vel_pos: 10
|
||||
lambda_vel_geo: 100
|
||||
|
||||
|
||||
dataset:
|
||||
batch_size_train: 1
|
||||
batch_size_test: 16
|
||||
num_workers: 4
|
||||
|
||||
dataset_train:
|
||||
path_data: ${path_data}/${specifict_folder}/data_train.npz
|
||||
|
||||
dataset_valid:
|
||||
path_data: ${path_data}/${specifict_folder}/data_valid.npz
|
||||
|
||||
dataset_test:
|
||||
path_data: ${path_data}/${specifict_folder}/data_test.npz
|
||||
|
||||
|
||||
@@ -0,0 +1,56 @@
|
||||
_target_: src.models.module_audio2motion_gan.Audio2RenderModel
|
||||
|
||||
opt:
|
||||
dim_x: 53
|
||||
dim_c: 1024
|
||||
dim_z: 32
|
||||
sr: 16000
|
||||
fps: 50
|
||||
num_vertices: 5023
|
||||
path_mean_dict: xxx/DECA_actor_mean.npy
|
||||
path_init_expression_basis: ${path_cwd}/checkpoints/init_expression_basis.npy
|
||||
|
||||
|
||||
opt_loss:
|
||||
lambda_rec_exp: 0.5
|
||||
lambda_rec_pos: 1
|
||||
lambda_rec_geo: 100
|
||||
lambda_vel_exp: 10
|
||||
lambda_vel_pos: 10
|
||||
lambda_vel_geo: 100
|
||||
|
||||
opt_optim:
|
||||
lr_G: 0.0025
|
||||
lr_D: 0.0025
|
||||
|
||||
|
||||
opt_netF:
|
||||
n_shape: 100
|
||||
n_exp: 50
|
||||
flame_model_path: ${path_cwd}/data/mesh/generic_model.pkl
|
||||
flame_lmk_embedding_path: ${path_cwd}/data/mesh/landmark_embedding.npy
|
||||
|
||||
# opt_netT:
|
||||
# tex_type: 'BFM'
|
||||
# tex_path: ${path_cwd}/data/mesh/FLAME_albedo_from_BFM.npz
|
||||
# n_tex: 50
|
||||
|
||||
|
||||
opt_netR:
|
||||
rasterizer_type: pytorch3d
|
||||
image_size: 512
|
||||
uv_size: 512 #256
|
||||
topology_path: ${path_cwd}/data/mesh/head_template.obj
|
||||
face_mask_path: ${path_cwd}/data/mesh/uv_face_mask.png
|
||||
face_eye_mask_path: ${path_cwd}/data/mesh/uv_face_eye_mask.png
|
||||
mean_tex_path: ${path_cwd}/data/mesh/mean_texture.jpg
|
||||
|
||||
|
||||
opt_netW:
|
||||
path_ckpt_wav2vec: ${path_cwd}/checkpoints/wav2vec2
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -1,14 +1,14 @@
|
||||
|
||||
import sys
|
||||
import numpy as np
|
||||
from collections import OrderedDict
|
||||
|
||||
import pickle
|
||||
|
||||
import torch
|
||||
import torch.nn as nn
|
||||
import torch.nn.functional as F
|
||||
from pathlib import Path
|
||||
|
||||
from src.models.info import flame_mouth_idx
|
||||
from src.models.info import idx_upper_mouth_68ldmk, idx_lower_mouth_68ldmk
|
||||
from src.models.info import idx_left_mouth_68ldmk, idx_right_mouth_68ldmk
|
||||
|
||||
from src.models import init_net
|
||||
from src.models.base import Base
|
||||
@@ -21,7 +21,7 @@ from common.debug import debug
|
||||
from common.losses import WingLoss
|
||||
|
||||
# disentangle model
|
||||
class Audio2MeshModel(Base):
|
||||
class Audio2MotionModel(Base):
|
||||
|
||||
def __init__(self, opt, logger):
|
||||
Base.__init__(self, opt, logger)
|
||||
@@ -34,16 +34,7 @@ class Audio2MeshModel(Base):
|
||||
self.netG = define_netG(opt)
|
||||
init_net(self.netG, init_type='kaiming', gpu_ids=opt.GPUS)
|
||||
|
||||
# init last layer
|
||||
init_exp_weight = np.load("./data/init_expression_basis.npy")
|
||||
init_exp_weight = torch.from_numpy(init_exp_weight).float().to(self.device)
|
||||
init_exp_weight = init_exp_weight[:, :50]
|
||||
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}")
|
||||
|
||||
# define FLAME & render
|
||||
self.netF = define_FLAME(opt, self.device)
|
||||
self.netR = define_render(opt, self.device)
|
||||
self.processor, self.extractor = define_extractor(opt, self.device)
|
||||
@@ -57,18 +48,24 @@ class Audio2MeshModel(Base):
|
||||
self.temp_verts, self.temp_ldmk2d, self.temp_ldmk3d \
|
||||
= self.get_template_vertices() # verts: (1 x 1 x 5023 x 3), ldmk: (1 x 1 x 68 x 3)
|
||||
|
||||
|
||||
self.temp_verts_specific, self.temp_ldmk2d_specific, self.temp_ldmk3d_specific \
|
||||
= self.get_template_vertices(self.mean_dict) # verts: (1 x 1 x 5023 x 3), ldmk: (1 x 1 x 68 x 3)
|
||||
|
||||
# self.temp_verts_specific = np.load("/ssdata1/lsen/CODE/audio-to-motion/data/Actor4/template_meiyan2.npy") # (5023, 3)
|
||||
# self.temp_verts_specific = self.temp_verts_specific.reshape(1, 1, 5023, 3)
|
||||
# self.temp_verts_specific = torch.from_numpy(self.temp_verts_specific).to(self.device)
|
||||
# save template mesh
|
||||
path_deca_mean = Path(path_deca_mean)
|
||||
path_temp_pkl = path_deca_mean.parent.joinpath(path_deca_mean.stem + "_data_template_mesh.pkl")
|
||||
if not path_temp_pkl.exists(): # load from cache
|
||||
self.logger.info(f"Load template mesh from raw 3DMM... (!NOT FOUND {path_temp_pkl}) ")
|
||||
template_mesh = self.temp_verts_specific.cpu().numpy() # verts: (1 x 1 x 5023 x 3)
|
||||
# save template data
|
||||
with open(str(path_temp_pkl), 'wb') as f:
|
||||
pickle.dump(template_mesh, f)
|
||||
|
||||
# save to
|
||||
|
||||
# loss function
|
||||
self.loss_func_wing = WingLoss(reduction="none") # return (B, )
|
||||
self.loss_func_l1 = nn.L1Loss(reduction="none")
|
||||
|
||||
self.loss_func_l1 = nn.L1Loss(reduction="mean")
|
||||
self.loss_func_wing = WingLoss(reduction="mean")
|
||||
self.names_loss = opt.LOSS.names
|
||||
|
||||
# define loss weight
|
||||
@@ -80,27 +77,29 @@ class Audio2MeshModel(Base):
|
||||
self.optimizer_G = get_optimizer(self.netG, opt)
|
||||
self.optimizers.append(self.optimizer_G)
|
||||
|
||||
# define scheduler
|
||||
self.scheduler_G = get_scheduler(self.optimizer_G, opt)
|
||||
self.schedulers.append(self.scheduler_G)
|
||||
|
||||
|
||||
@torch.no_grad()
|
||||
def set_input(self, batch_input):
|
||||
""" """
|
||||
|
||||
# motion data
|
||||
data = batch_input["data"].float().to(self.device) # (B, nsteps, nc_motion)
|
||||
self.data = batch_input["data"].float().to(self.device) # (B, nsteps, nc_motion)
|
||||
|
||||
self.batch_vid = batch_input['vid']
|
||||
self.batch_nframe = batch_input['nframe']
|
||||
self.batch_interv = batch_input['frame_interval']
|
||||
|
||||
debug(self.opt, f"data = {data.shape}, dtype={data.dtype}", verbose=False)
|
||||
debug(self.opt, f"data = {self.data.shape}, dtype={self.data.dtype}", verbose=False)
|
||||
debug(self.opt, f"batch_vid = {self.batch_vid[:2]}", verbose=False)
|
||||
debug(self.opt, f"batch_nframe = {self.batch_nframe[:2]}", verbose=False)
|
||||
debug(self.opt, f"batch_interv len={len(self.batch_interv)} len([0])={len(self.batch_interv[0])}, \
|
||||
beg={self.batch_interv[0][:4]}, end={self.batch_interv[1][:4]}", verbose=False)
|
||||
|
||||
|
||||
# speech data
|
||||
cond = None
|
||||
raw_speech = batch_input["cond"].numpy() # (B, nsegments)
|
||||
debug(self.opt, f"raw_speech = {raw_speech.shape}, dtype={raw_speech.dtype}", verbose=False)
|
||||
|
||||
@@ -114,47 +113,37 @@ class Audio2MeshModel(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) # (B, nseqs, nc_codit, 16)
|
||||
cond = cond.permute(0, 1, 3, 2) # (B, nseqs, 16, nc_condit)
|
||||
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)
|
||||
|
||||
# setup
|
||||
self.cond = cond
|
||||
self.cond = cond # (B, N, 16, nc_condit=1024)
|
||||
self.B, self.nsteps, self.nwind, self.dim_speech = cond.size()
|
||||
data = data[:, 7:7+self.nsteps, :]
|
||||
self.vert, self.ldmk2d, self.ldmk3d = self.get_vertices(data)
|
||||
|
||||
self.data = self.data[:, 7:7+self.nsteps, :] # (B, N, 53)
|
||||
self.vert, self.ldmk2d, self.ldmk3d = self.get_vertices(self.data) # (B, N, 5023, 3)
|
||||
|
||||
# cut audio clips
|
||||
idx_beg = int(7 * self.opt.DATASET.sr / self.opt.DATASET.fps + 0.5)
|
||||
idx_end = int((7 + self.nsteps) * self.opt.DATASET.sr / self.opt.DATASET.fps + 0.5)
|
||||
self.raw_speech = raw_speech[:, idx_beg: idx_end] # (B, nsteps * sr / fps)
|
||||
|
||||
debug(self.opt, f"[set_input] 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"[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, idx_epoch=0, idx_batch=0):
|
||||
self.train() # set train model
|
||||
self.set_input(batch_input)
|
||||
|
||||
# forward
|
||||
self.pred = self.netG(self.cond)
|
||||
self.pred += self.temp_verts
|
||||
debug(self.opt, f"traing pred = {self.pred.shape}", verbose=False)
|
||||
pred = self.netG(self.cond) # (B, N, 53)
|
||||
|
||||
# loss
|
||||
loss, loss_dict = self.eval_losses(self.pred, self.vert)
|
||||
loss, loss_dict = self.eval_losses(pred, self.data)
|
||||
|
||||
# backward
|
||||
self.optimizer_G.zero_grad()
|
||||
@@ -168,73 +157,30 @@ class Audio2MeshModel(Base):
|
||||
|
||||
return loss_dict
|
||||
|
||||
|
||||
def validation(self, batch_input, idx_epoch=0, idx_batch=0):
|
||||
def validation(self, batch_input):
|
||||
self.eval() # set eval model
|
||||
self.set_input(batch_input)
|
||||
|
||||
with torch.no_grad():
|
||||
pred = self.netG(self.cond)
|
||||
pred += self.temp_verts
|
||||
|
||||
loss, loss_dict = self.eval_losses(pred, self.vert)
|
||||
loss, loss_dict = self.eval_losses(pred, self.data)
|
||||
|
||||
return loss_dict
|
||||
|
||||
|
||||
def infer_with_gt(self, batch_cond, batch_data, batch_speech, 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)
|
||||
|
||||
# add a dimensions
|
||||
if batch_speech.dims == 1:
|
||||
batch_speech = batch_speech.unsqueeze(0) # (B, nsegmt)
|
||||
|
||||
|
||||
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
|
||||
|
||||
self.save_reconstruct(batch_pdt_geo, batch_speech,
|
||||
path_save=Path(self.opt.OUTPUT_DIR),
|
||||
suffix=suffix, vis_landmarks=False)
|
||||
|
||||
# render & and save
|
||||
print(f"testing pt shape = {batch_pdt_geo.shape}, gt shape = {vert.shape}")
|
||||
self.save_reconstruct_with_gt(batch_pdt_geo, vert, batch_speech,
|
||||
path_save=Path(self.opt.OUTPUT_DIR),
|
||||
suffix=suffix,vis_landmarks=False)
|
||||
|
||||
|
||||
if save_npy:
|
||||
# save result
|
||||
batch_pdt_geo = batch_pdt_geo.cpu().numpy()
|
||||
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, batch_speech, suffix="", save_npy=True):
|
||||
self.eval()
|
||||
self.cond = batch_cond.float().to(self.device) # (nsteps, dim_cond)
|
||||
|
||||
with torch.no_grad():
|
||||
batch_pdt_geo = self.netG(self.cond) # B x N x dim_motion
|
||||
batch_pdt_geo += self.temp_verts # B x N x 5023 x 3
|
||||
batch_pdt = self.netG(self.cond) # B x N x dim_motion
|
||||
print(f"testing pt shape = {batch_pdt.shape}")
|
||||
|
||||
print(f"testing pt shape = {batch_pdt_geo.shape}")
|
||||
# to geo
|
||||
batch_pdt_geo, *_ = self.get_vertices(batch_pdt) # B x N x 5023 x 3
|
||||
print(f"testing batch_pdt shape = {batch_pdt.shape}, batch_pdt_geo = {batch_pdt_geo.shape}")
|
||||
|
||||
# !! add specific when render & output !!
|
||||
batch_pdt_geo = batch_pdt_geo - self.temp_verts + self.temp_verts_specific
|
||||
|
||||
# render & and save
|
||||
self.save_reconstruct(batch_pdt_geo, batch_speech, path_save=Path(self.opt.OUTPUT_DIR),
|
||||
@@ -242,10 +188,11 @@ class Audio2MeshModel(Base):
|
||||
|
||||
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}")
|
||||
# batch_pdt_geo = batch_pdt_geo.cpu().numpy()
|
||||
batch_pdt = batch_pdt.cpu().numpy()
|
||||
path_save_npy = Path(self.opt.OUTPUT_DIR).joinpath(f"{suffix}_coeff.npy")
|
||||
np.save(path_save_npy, batch_pdt)
|
||||
print(f"save infer_result shape = {batch_pdt.shape} -> {path_save_npy}")
|
||||
|
||||
|
||||
def testing(self, batch_input, idx_epoch=0, idx_batch=0):
|
||||
@@ -253,13 +200,12 @@ class Audio2MeshModel(Base):
|
||||
self.set_input(batch_input)
|
||||
|
||||
with torch.no_grad():
|
||||
batch_pdt_geo = self.netG(self.cond) # B x N x 5023 x 3
|
||||
batch_pdt_geo += self.temp_verts # B x N x 5023 x 3
|
||||
batch_pdt = self.netG(self.cond) # B x N x dim_motion
|
||||
|
||||
batch_pdt_geo, *_ = self.get_vertices(batch_pdt) # B x N x 5023 x 3
|
||||
print(f"testing batch_pdt shape = {batch_pdt.shape}, batch_pdt_geo = {batch_pdt_geo.shape}")
|
||||
|
||||
# !! add specific when render & output !!
|
||||
batch_pdt_geo = batch_pdt_geo - self.temp_verts + self.temp_verts_specific
|
||||
|
||||
print(f"testing pt shape = {batch_pdt_geo.shape}, gt shape = {self.vert.shape}")
|
||||
self.save_reconstruct_with_gt(batch_pdt_geo, self.vert, self.raw_speech,
|
||||
path_save=Path(self.opt.OUTPUT_DIR),
|
||||
suffix=f'sampled_{idx_epoch:05d}_{idx_batch:03d}')
|
||||
@@ -313,78 +259,93 @@ class Audio2MeshModel(Base):
|
||||
return verts, ldmk2d, ldmk3d
|
||||
|
||||
|
||||
def eval_losses(self, batch_pdt_geo, batch_tgt_geo):
|
||||
""" Computes the loss function.
|
||||
def eval_losses(self, batch_pdt, batch_tgt):
|
||||
""" Computes the VAE loss function.
|
||||
pramas:
|
||||
batch_tgt_geo, (nbatch, seqlen, num_vertices, 3)
|
||||
batch_pdt_geo, (nbatch, seqlen, num_vertices, 3)
|
||||
batch_pred, (nbatch, seqlen, dim_motion)
|
||||
batch_targt, (nbatch, seqlen, dim_motion)
|
||||
"""
|
||||
loss = 0
|
||||
loss_dict = OrderedDict()
|
||||
loss_dict = {}
|
||||
|
||||
# synthesis geo rec
|
||||
batch_pdt_exp = batch_pdt[..., :50]
|
||||
batch_pdt_pos = batch_pdt[..., 50:]
|
||||
|
||||
batch_tgt_exp = batch_tgt[..., :50]
|
||||
batch_tgt_pos = batch_tgt[..., 50:]
|
||||
|
||||
# get reconstruction
|
||||
batch_pdt_geo, *_ = self.get_vertices(batch_pdt) # B x nseq x num_vertices x 3
|
||||
batch_tgt_geo, *_ = self.get_vertices(batch_tgt) # B x nseq x num_vertices x 3
|
||||
|
||||
# rec loss
|
||||
loss = 0
|
||||
loss_rec_geo = self.loss_func_wing(batch_pdt_geo, batch_tgt_geo)
|
||||
loss_dict["rec_geo"] = loss_rec_geo.mean().detach()
|
||||
loss_rec_exp = self.loss_func_wing(batch_pdt_exp, batch_tgt_exp).mean()
|
||||
loss_dict["rec_exp"] = loss_rec_exp.detach()
|
||||
|
||||
loss_rec_pos = self.loss_func_wing(batch_pdt_pos, batch_tgt_pos).mean()
|
||||
loss_dict["rec_pos"] = loss_rec_pos.detach()
|
||||
|
||||
loss += loss_rec_exp * self.opt.LOSS.lambda_rec_exp
|
||||
loss += loss_rec_pos * self.opt.LOSS.lambda_rec_pos
|
||||
|
||||
# rec smooth
|
||||
diff_pdt_exp = batch_pdt_exp[:, 1:, :] - batch_pdt_exp[:, :-1, :]
|
||||
diff_tgt_exp = batch_tgt_exp[:, 1:, :] - batch_tgt_exp[:, :-1, :]
|
||||
loss_vel_exp = self.loss_func_wing(diff_pdt_exp, diff_tgt_exp).mean()
|
||||
loss_dict["vel_exp"] = loss_vel_exp.detach()
|
||||
|
||||
|
||||
diff_pdt_pos = batch_pdt_pos[:, 1:, :] - batch_pdt_pos[:, :-1, :]
|
||||
diff_tgt_pos = batch_tgt_pos[:, 1:, :] - batch_tgt_pos[:, :-1, :]
|
||||
loss_vel_pos = self.loss_func_wing(diff_pdt_pos, diff_tgt_pos).mean()
|
||||
loss_dict["vel_pos"] = loss_vel_pos.detach()
|
||||
|
||||
loss += loss_vel_exp * self.opt.LOSS.lambda_vel_exp
|
||||
loss += loss_vel_pos * self.opt.LOSS.lambda_vel_pos
|
||||
|
||||
# geo rec
|
||||
loss_rec_geo = self.loss_func_wing(batch_pdt_geo, batch_tgt_geo).mean()
|
||||
loss_dict["rec_geo"] = loss_rec_geo.detach()
|
||||
|
||||
loss_rec_geo2 = self.loss_func_wing(batch_pdt_geo, batch_tgt_geo, weight=self.vertices_weight)
|
||||
# loss_dict["rec_geo_w"] = loss_rec_geo2.mean().detach()
|
||||
# loss += loss_rec_geo.mean() * self.opt.LOSS.lambda_rec_geo
|
||||
loss += loss_rec_geo2.mean() * self.opt.LOSS.lambda_rec_geo
|
||||
loss += loss_rec_geo2 * self.opt.LOSS.lambda_rec_geo
|
||||
|
||||
# synthesis geo volocity
|
||||
# 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).mean()
|
||||
loss_dict["vel_geo"] = loss_vel_geo.detach()
|
||||
|
||||
loss_vel_geo = self.loss_func_wing(diff_pdt_geo, diff_tgt_geo)
|
||||
loss_dict["vel_geo"] = loss_vel_geo.mean().detach()
|
||||
|
||||
loss_vel_geo2 = self.loss_func_wing(diff_pdt_geo, diff_tgt_geo, weight=self.vertices_weight)
|
||||
# loss_dict["vel_geo_w"] = loss_vel_geo2.mean().detach()
|
||||
# loss += loss_vel_geo.mean() * self.opt.LOSS.lambda_vel_geo
|
||||
|
||||
if self.opt.LOSS.lambda_vel_geo > 0:
|
||||
loss += loss_vel_geo2.mean() * self.opt.LOSS.lambda_vel_geo
|
||||
|
||||
# landmarks loss
|
||||
ldmk3d_pdt = self.netF.seletec_3d68(batch_pdt_geo.reshape(-1, self.opt.MODEL.num_vertices, 3)) # (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()
|
||||
|
||||
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
|
||||
|
||||
loss_vel_geo2 = self.loss_func_wing(diff_pdt_geo, diff_tgt_geo, weight=self.vertices_weight).mean()
|
||||
loss += loss_vel_geo2 * self.opt.LOSS.lambda_vel_geo
|
||||
|
||||
# total loss
|
||||
loss_dict["all"] = loss.detach()
|
||||
loss_dict['all'] = loss.detach()
|
||||
|
||||
return loss, loss_dict
|
||||
|
||||
|
||||
@torch.no_grad()
|
||||
def render_geometry(self, verts, cam=None, device=None):
|
||||
"""
|
||||
verts: [N x 5023 x 3]
|
||||
"""
|
||||
batch_size = verts.size(0)
|
||||
|
||||
if cam is None:
|
||||
cam = torch.zeros(batch_size, 3).to(device) # (batch_size, 3)
|
||||
|
||||
# orth_proj
|
||||
verts_proj = util.batch_orth_proj(verts, cam);
|
||||
verts_proj[:,:,1:] = -verts_proj[:,:,1:]
|
||||
|
||||
# render
|
||||
images = self.netR.render_shape(verts, verts_proj) # (batch_size, 3, 512, 512)
|
||||
|
||||
return images
|
||||
|
||||
|
||||
def save_reconstruct(self, batch_pdt_geo, batch_speech, path_save, suffix="", vis_landmarks=False):
|
||||
# batch_pdt_pos, [B x N x dim_motion]
|
||||
# batch_speech, [B x N*sr/fps ]
|
||||
@@ -425,30 +386,10 @@ class Audio2MeshModel(Base):
|
||||
|
||||
# write video
|
||||
ipath_save = path_save.joinpath(f"{suffix}_{i:02d}_pt.mp4")
|
||||
write_video(v_render_pt, batch_speech, ipath_save, fps=50)
|
||||
write_video(v_render_pt, batch_speech[i], ipath_save, fps=50)
|
||||
self.logger.info(f"save video to -> {str(ipath_save)}")
|
||||
|
||||
|
||||
@torch.no_grad()
|
||||
def render_geometry(self, verts, cam=None, device=None):
|
||||
"""
|
||||
verts: [N x 5023 x 3]
|
||||
"""
|
||||
batch_size = verts.size(0)
|
||||
|
||||
if cam is None:
|
||||
cam = torch.zeros(batch_size, 3).to(device) # (batch_size, 3)
|
||||
|
||||
# orth_proj
|
||||
verts_proj = util.batch_orth_proj(verts, cam);
|
||||
verts_proj[:,:,1:] = -verts_proj[:,:,1:]
|
||||
|
||||
# render
|
||||
images = self.netR.render_shape(verts, verts_proj) # (batch_size, 3, 512, 512)
|
||||
|
||||
return images
|
||||
|
||||
|
||||
@torch.no_grad()
|
||||
def save_reconstruct_with_gt(self, batch_pdt_geo, batch_tgt_geo, batch_speech, path_save, suffix="", vis_landmarks=True):
|
||||
# batch_pdt_geo, [B x N x 5023 x 3]
|
||||
@@ -511,41 +452,43 @@ class Audio2MeshModel(Base):
|
||||
|
||||
#########################################
|
||||
def tensor2image(tensor):
|
||||
# image = tensor.detach().cpu().numpy()
|
||||
image = tensor.numpy()
|
||||
image = tensor.detach().cpu().numpy()
|
||||
image = image*255.
|
||||
image = np.maximum(np.minimum(image, 255), 0)
|
||||
image = image.transpose(1,2,0)[:,:,[2,1,0]]
|
||||
|
||||
return image.astype(np.uint8).copy()
|
||||
|
||||
|
||||
def define_netG(opt):
|
||||
netG = None
|
||||
|
||||
if opt.MODEL.name_netG == "audio2mesh":
|
||||
from src.nn.audio2mesh import Audio2Mesh
|
||||
netG = Audio2Mesh(opt)
|
||||
if opt.MODEL.name_netG == "audio2motion_voca4":
|
||||
from src.nn.audio2motion_voca4 import Audio2MotionVOCA
|
||||
netG = Audio2MotionVOCA(opt)
|
||||
|
||||
elif opt.MODEL.name_netG == "audio2mesh_voca":
|
||||
from src.nn.audio2mesh_voca import Audio2Mesh
|
||||
netG = Audio2Mesh(opt)
|
||||
elif opt.MODEL.name_netG == "audio2motion_voca":
|
||||
from src.nn.audio2motion_voca import Audio2MotionVOCA
|
||||
netG = Audio2MotionVOCA(opt)
|
||||
|
||||
elif opt.MODEL.name_netG == "audio2mesh_resnet":
|
||||
from src.nn.audio2mesh_resnet import Audio2Mesh
|
||||
netG = Audio2Mesh(opt)
|
||||
elif opt.MODEL.name_netG == "audio2motion_voca33":
|
||||
from src.nn.audio2motion_voca33 import Audio2Motion
|
||||
netG = Audio2Motion(opt)
|
||||
|
||||
elif opt.MODEL.name_netG == "audio2motion":
|
||||
from src.nn.audio2motion import Audio2Motion
|
||||
netG = Audio2Motion(opt)
|
||||
|
||||
elif opt.MODEL.name_netG == "audio2motion2":
|
||||
from src.nn.audio2motion2 import Audio2Motion2
|
||||
netG = Audio2Motion2(opt)
|
||||
else:
|
||||
raise NameError(f"The model of opt.MODEL.name_netAE(={opt.MODEL.name_netG}) not existing!")
|
||||
|
||||
# to GPU
|
||||
netG.to(f"cuda:{opt.GPUS[0]}")
|
||||
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
|
||||
|
||||
@@ -579,3 +522,7 @@ def define_extractor(opt, device):
|
||||
extractor = Wav2Vec2Model.from_pretrained(path_ckpt_wav2vec).to(device)
|
||||
|
||||
return processor, extractor
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,562 @@
|
||||
from typing import Any, List
|
||||
from omegaconf import DictConfig
|
||||
import numpy as np
|
||||
from pathlib import Path
|
||||
|
||||
import kornia
|
||||
from kornia import morphology, filters
|
||||
|
||||
import os
|
||||
import cv2
|
||||
from skimage import transform
|
||||
|
||||
import torchvision
|
||||
|
||||
import torch
|
||||
import torch.nn.functional as F
|
||||
|
||||
from pytorch_lightning import LightningModule
|
||||
from torchmetrics import MeanMetric, MinMetric
|
||||
import logging
|
||||
|
||||
from src.loss.loss_feat2face import VGGLoss
|
||||
from src.loss.common import adversarial_loss
|
||||
|
||||
from .components.networks_mesh2face import Generator, Discriminator
|
||||
from . import init_weights
|
||||
|
||||
class GANRenderModel(LightningModule):
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
opt: DictConfig = None,
|
||||
opt_loss: DictConfig = None,
|
||||
opt_optim: DictConfig = None,
|
||||
):
|
||||
super().__init__()
|
||||
logging.info(f"[__init__] self.device = {self.device}")
|
||||
self.opt = opt
|
||||
self.opt_loss = opt_loss
|
||||
self.opt_optim = opt_optim
|
||||
|
||||
mapping_kwargs=dict(num_layers = opt.num_layers)
|
||||
|
||||
|
||||
# load networks
|
||||
self.netG = Generator(
|
||||
z_dim =opt.z_dim, # Input latent (Z) dimensionality.
|
||||
c_dim =opt.c_dim, # Conditioning label (C) dimensionality.
|
||||
w_dim =opt.w_dim, # Intermediate latent (W) dimensionality.
|
||||
img_resolution =opt.img_resolution, # Output resolution.
|
||||
img_channels =opt.img_channels, # Number of output color channels.
|
||||
mapping_kwargs = mapping_kwargs,
|
||||
)
|
||||
|
||||
self.netD = Discriminator(
|
||||
c_dim =opt.c_dim, # Conditioning label (C) dimensionality.
|
||||
img_resolution =opt.img_resolution, # Input resolution.
|
||||
img_channels =opt.img_channels, # Number of input color channels.
|
||||
mapping_kwargs =mapping_kwargs,
|
||||
)
|
||||
|
||||
# init by default
|
||||
init_weights(self.netG, init_type='kaiming')
|
||||
init_weights(self.netD, init_type='kaiming')
|
||||
|
||||
# load form ckp
|
||||
if opt.pretrain:
|
||||
logging.info(f"\n [init] load stat for netG, netD, from = {opt.pretrain_path}")
|
||||
self.load_pretrain_model(opt.pretrain_path)
|
||||
|
||||
# use separate metric instance for train, val and test step
|
||||
# to ensure a proper reduction over the epoch
|
||||
self.train_best, self.valid_best = MinMetric(), MinMetric()
|
||||
self.train_rec, self.valid_rec = MeanMetric(), MeanMetric()
|
||||
|
||||
# for logging best so far validation accuracy
|
||||
self.criterionL1 = torch.nn.L1Loss()
|
||||
self.criterionVGG = VGGLoss()
|
||||
|
||||
|
||||
def load_pretrain_model(self, pretrain_path):
|
||||
state_dict = torch.load(pretrain_path, map_location=self.device)["state_dict"]
|
||||
|
||||
# for netG
|
||||
state_dict_netG = {k[5:]:v for k, v in state_dict.items() if (k[:4] == "netG" and k[5:] in self.netG.state_dict().keys())}
|
||||
state_dict_netD = {k[5:]:v for k, v in state_dict.items() if (k[:4] == "netD" and k[5:] in self.netD.state_dict().keys())}
|
||||
|
||||
# print(f"\nself.netG state \n: {self.netG.state_dict().keys()}, \n\n state_dict_netG = {state_dict_netG.keys()}")
|
||||
# print(f"\nself.netD state \n: {self.netD.state_dict().keys()}, \n\n state_dict_netD = {state_dict_netD.keys()}")
|
||||
|
||||
# 看看哪些参数没有初始化
|
||||
diff_G = set(self.netG.state_dict().keys()).difference(set(state_dict_netG.keys())) # 在netG.keys()中,但不在state_dict_netG中
|
||||
diff_D = set(self.netD.state_dict().keys()).difference(set(state_dict_netD.keys())) # 在netG.keys()中,但不在state_dict_netG中
|
||||
print(f"\nself.netG, not init keys from pretrained model: \n {diff_G}")
|
||||
print(f"\nself.netD, not init keys from pretrained model: \n {diff_D}")
|
||||
|
||||
# update
|
||||
self.netG.load_state_dict(state_dict_netG, strict=False)
|
||||
self.netD.load_state_dict(state_dict_netD, strict=False)
|
||||
|
||||
|
||||
|
||||
def configure_optimizers(self):
|
||||
"""Choose what optimizers and learning-rate schedulers to use in your optimization.
|
||||
Normally you'd need one. But in the case of GANs or similar you might have multiple.
|
||||
"""
|
||||
|
||||
lr_G = self.opt_optim.lr_G
|
||||
lr_D = self.opt_optim.lr_D
|
||||
optim_G = torch.optim.Adam(self.netG.parameters(), lr=lr_G, betas=(0, 0.99), eps=1e-8)
|
||||
optim_D = torch.optim.Adam(self.netD.parameters(), lr=lr_D, betas=(0, 0.99), eps=1e-8)
|
||||
|
||||
return [optim_D, optim_G], []
|
||||
|
||||
|
||||
@torch.no_grad()
|
||||
def set_input(self, batch:Any):
|
||||
# data info
|
||||
data_info = {
|
||||
"vid": batch['vid'],
|
||||
"path_data": batch["path_data"],
|
||||
"frame_interval": batch['frame_interval'],
|
||||
}
|
||||
|
||||
# get verties
|
||||
# batch_idn = self.mean_shape.expand(B, N, -1)
|
||||
# batch_lmk = data_ldmk[:, :, 0:17, :] # (B, N, 17, 2)
|
||||
# dim of shape = 100, tex = 50, exp = 50, pose = 6, cam = 3, light = 27
|
||||
data_deca = batch["data_coeff"] # (B, N, 236)
|
||||
batch_exp = data_deca[:, :, 150:200]
|
||||
batch_pos = data_deca[:, :, 200:206]
|
||||
batch_cam = data_deca[:, :, 206:209]
|
||||
batch_lit = data_deca[:, :, 209:236]
|
||||
|
||||
# batch_lmk = batch_lmk.reshape(batch_lmk.shape[0], batch_lmk.shape[1], -1) # (B, N, 34)
|
||||
# coeff = torch.cat([batch_exp, batch_pos, batch_lmk], dim=2) # (B, N, nc_codit= 56+34)
|
||||
coeff = torch.cat([batch_exp, batch_pos, batch_cam, batch_lit], dim=2) # (B, N, nc_codit=59)
|
||||
|
||||
# coeff = torch.cat([batch_exp, batch_cam, batch_pos], dim=2) # (B, N, nc_codit=59)
|
||||
# logging.info(f"[set_input] cat coeff = {coeff.shape}, dtype={coeff.dtype}, device={coeff.device}")
|
||||
|
||||
# 0=[0,1,2,(3),4, 5, 6], 1=[1,2,3,(4), 5, 6,7], ...
|
||||
coeff = coeff.unfold(dimension=1, size=7, step=1) # (B, N', nc_codit, 7)
|
||||
# logging.info(f"[set_input] unfold coeff = {coeff.shape}, dtype={coeff.dtype}, device={coeff.device}")
|
||||
|
||||
# update N
|
||||
B, N = coeff.size(0), coeff.size(1)
|
||||
|
||||
# get other GT & align to coeff
|
||||
image_tgt = batch["data_frame"][:, 3:3+N] # (B, N, 3, 256, 256)
|
||||
masks_tgt = batch["data_mask"][:, 3:3+N] # (B, N, 256, 256)
|
||||
ldmks_tgt = batch["data_ldmks"][:, 3:3+N, 0:17] # (B, N, 17, 2), only get chin margin landmarks
|
||||
|
||||
# get a reference image
|
||||
# assert B >= 2, f"the batch size(={B}) should >= 2!"
|
||||
|
||||
# idx_select = np.random.randint(low=0, high=N, size=B)
|
||||
image_ref = batch["data_frame"][:, 0:1] # (B, 1, 3, 256, 256)
|
||||
# image_ref = image_ref.roll(shifts=1, dims=0) # (B, 1, 3, 256, 256) , roll along B
|
||||
image_ref = image_ref.expand(-1, N, -1, -1, -1) # (B, N, 3, 256, 256)
|
||||
|
||||
# reshape to input
|
||||
image_tgt = image_tgt.reshape(B*N, image_tgt.size(2), image_tgt.size(3), image_tgt.size(4)) # (B*N, 3, 256, 256)
|
||||
image_ref = image_ref.reshape(B*N, image_ref.size(2), image_ref.size(3), image_ref.size(4)) # (B*N, 3, 256, 256)
|
||||
|
||||
masks_tgt = masks_tgt.reshape(B*N, 1, masks_tgt.size(2), masks_tgt.size(3)) # (B*N, 1, 256, 256)
|
||||
ldmks_tgt = ldmks_tgt.reshape(B*N, ldmks_tgt.size(2), ldmks_tgt.size(3)) # (B*N, 17, 2)
|
||||
coeff = coeff.reshape(B*N, -1) # (B*N, 59*7)
|
||||
|
||||
# make mask
|
||||
# kernel = torch.ones(3, 3).to(self.device)
|
||||
# masks_tgt = morphology.erosion(masks_tgt, kernel)
|
||||
# masks_tgt = filters.gaussian_blur2d(masks_tgt, (3, 3), (1.5, 1.5))
|
||||
|
||||
# logging.info(f"[reshape] coeff = {coeff.shape}, dtype={coeff.dtype}, device={coeff.device}")
|
||||
# logging.info(f"[reshape] image_tgt = {image_tgt.shape}, dtype={image_tgt.dtype}, device={image_tgt.device}")
|
||||
# logging.info(f"[reshape] masks_tgt = {masks_tgt.shape}, dtype={masks_tgt.dtype}, device={masks_tgt.device}")
|
||||
|
||||
return B, N, coeff, image_tgt, masks_tgt, ldmks_tgt, data_info, image_ref
|
||||
|
||||
|
||||
def set_requires_grad(self, nets, requires_grad=False):
|
||||
"""Set requies_grad=Fasle for all the networks to avoid unnecessary computations
|
||||
Parameters:
|
||||
nets (network list) -- a list of networks
|
||||
requires_grad (bool) -- whether the networks require gradients or not
|
||||
"""
|
||||
if not isinstance(nets, list):
|
||||
nets = [nets]
|
||||
|
||||
for net in nets:
|
||||
if net is not None:
|
||||
for param in net.parameters():
|
||||
param.requires_grad = requires_grad
|
||||
|
||||
|
||||
# def forward(self, batch_z:torch.Tensor, batch_c:torch.Tensor):
|
||||
# return self.netG(batch_z, batch_c)
|
||||
def training_step(self, batch, batch_idx, optimizer_idx):
|
||||
|
||||
|
||||
B, N, batch_c, image_tgt, masks_tgt, ldmks_tgt, batch_info, image_ref = self.set_input(batch)
|
||||
|
||||
# get noize input z
|
||||
batch_z = torch.randn(B*N, self.opt.z_dim).type_as(image_tgt) # (BN, dim_latent)
|
||||
# logging.info(f"[training_step] batch_c = {batch_c.shape}, dtype={batch_c.dtype}, device={batch_c.device}")
|
||||
# logging.info(f"[training_step] batch_z = {batch_z.shape}, dtype={batch_z.dtype}, device={batch_z.device}")
|
||||
|
||||
# forward
|
||||
# batch_img = torch.cat([image_ref, masks_tgt], dim=1) # (B*N, 4, 256, 256)
|
||||
image_pdt = self.netG(batch_z, batch_c) # (B*N, 3, 256, 256)
|
||||
# logging.info(f"[discriminator] image_pdt = {image_pdt.shape}, dtype={image_pdt.dtype}, device={image_pdt.device}")
|
||||
|
||||
# image_pdt_masked = image_pdt * masks_tgt # use pdt mask for masked pdt image
|
||||
image_pdt_masked = image_pdt * masks_tgt # use pdt mask for masked pdt image
|
||||
image_tgt_masked = image_tgt * masks_tgt # use tgt mask for masked tgt image
|
||||
|
||||
# return
|
||||
image_pdt_weighted = kornia.enhance.add_weighted(image_pdt * masks_tgt.expand(-1, 3, -1, -1), 0.4, image_pdt, 0.6, 0.0).detach()
|
||||
image_tgt_weighted = kornia.enhance.add_weighted(image_tgt * masks_tgt.expand(-1, 3, -1, -1), 0.4, image_tgt, 0.6, 0.0).detach()
|
||||
|
||||
|
||||
##################################################
|
||||
######### Optimize Discriminator #########
|
||||
##################################################
|
||||
if optimizer_idx == 0:
|
||||
|
||||
# GT label
|
||||
pred_real = self.netD(image_tgt_masked, batch_c)
|
||||
loss_D_real = adversarial_loss(pred_real, target_is_real=True, loss_mode="lsgan")
|
||||
|
||||
# PT label
|
||||
pred_fake = self.netD(image_pdt_masked.detach(), batch_c)
|
||||
loss_D_fake = adversarial_loss(pred_fake, target_is_real=False, loss_mode="lsgan")
|
||||
|
||||
# discriminator loss is the average of these
|
||||
d_loss = (loss_D_real + loss_D_fake) / 2
|
||||
|
||||
# logging
|
||||
self.log("train/D_real", loss_D_real, logger=False, on_step=True, on_epoch=False, prog_bar=True)
|
||||
self.log("train/D_fake", loss_D_fake, logger=False, on_step=True, on_epoch=False, prog_bar=True)
|
||||
self.logger.experiment[0].add_scalar("train/D_real", loss_D_real, self.global_step)
|
||||
self.logger.experiment[0].add_scalar("train/D_fake", loss_D_fake, self.global_step)
|
||||
|
||||
return {"loss": d_loss, "image_pdt": image_pdt_weighted, "image_tgt": image_tgt_weighted }
|
||||
|
||||
|
||||
|
||||
##################################################
|
||||
######### Optimize Generator #########
|
||||
##################################################
|
||||
if optimizer_idx == 1:
|
||||
# adversarial loss for each frames
|
||||
pred_fake = self.netD(image_pdt_masked, batch_c)
|
||||
loss_G = adversarial_loss(pred_fake, target_is_real=True, loss_mode="lsgan")
|
||||
|
||||
# L1-loss
|
||||
loss_rec = self.criterionL1(image_pdt_masked, image_tgt_masked)
|
||||
# loss_maskL1 = self.criterionMaskL1(image_pdt, image_tgt, self.mouth_mask * self.opt.lambda_mask)
|
||||
|
||||
# VGG & Style loss
|
||||
loss_vgg, loss_style = self.criterionVGG(image_pdt_masked, image_tgt_masked, style=True)
|
||||
loss_vgg = loss_vgg.mean()
|
||||
loss_style = loss_style.mean()
|
||||
|
||||
# # feature match loss
|
||||
# pred_real = self.netD(image_tgt, batch_c)
|
||||
# pred_fake = self.netD(image_pdt, batch_c)
|
||||
# loss_FM = self.compute_FeatureMatching_loss(pred_fake, pred_real)
|
||||
|
||||
# total loss
|
||||
g_loss = loss_G + loss_rec * self.opt_loss.lambda_rec \
|
||||
+ loss_vgg * self.opt_loss.lambda_vgg \
|
||||
+ loss_style * self.opt_loss.lambda_style \
|
||||
|
||||
|
||||
# logging
|
||||
self.log("train/G", loss_G, logger=False, on_step=True, on_epoch=False, prog_bar=True)
|
||||
self.log("train/rec", loss_rec, logger=False, on_step=True, on_epoch=False, prog_bar=True)
|
||||
self.log("train/vgg", loss_vgg, logger=False, on_step=True, on_epoch=False, prog_bar=True)
|
||||
self.log("train/style", loss_style, logger=False, on_step=True, on_epoch=False, prog_bar=True)
|
||||
self.logger.experiment[0].add_scalar("train/G", loss_G, self.global_step)
|
||||
self.logger.experiment[0].add_scalar("train/rec", loss_rec, self.global_step)
|
||||
self.logger.experiment[0].add_scalar("train/vgg", loss_vgg, self.global_step)
|
||||
self.logger.experiment[0].add_scalar("train/style", loss_style, self.global_step)
|
||||
|
||||
# # # show metric
|
||||
self.train_rec(loss_rec)
|
||||
self.train_best(g_loss)
|
||||
|
||||
return {"loss": g_loss, "image_pdt": image_pdt_weighted, "image_tgt": image_tgt_weighted }
|
||||
|
||||
|
||||
def on_train_batch_end(self, outputs, batch, batch_idx):
|
||||
|
||||
if not (self.global_step % 100 == 0 and self.global_rank == 0):
|
||||
return super().on_train_batch_end(outputs, batch, batch_idx)
|
||||
# print(f"outputs len={len(outputs)}, outputs = {outputs}")
|
||||
|
||||
image_pdt = outputs[0]["image_pdt"][:4]
|
||||
image_tgt = outputs[0]["image_tgt"][:4]
|
||||
grid_pdt = torchvision.utils.make_grid(image_pdt)
|
||||
grid_tgt = torchvision.utils.make_grid(image_tgt)
|
||||
# logging.info(f"[on] grid_pdt shape={grid_pdt.shape}, grid_tgt={grid_tgt.shape}, device={grid_tgt.device}")
|
||||
# logging.info(f"[on] self.logger.experiment len ={len(self.logger.experiment)}")
|
||||
# logging.info(f"[on] self.logger.experiment ={self.logger.experiment}")
|
||||
self.logger.experiment[0].add_image("image_pdt", grid_pdt, self.global_step)
|
||||
self.logger.experiment[0].add_image("image_tgt", grid_tgt, self.global_step)
|
||||
|
||||
|
||||
def on_train_epoch_end(self):
|
||||
|
||||
metric_rec = self.train_rec.compute()
|
||||
metric_best = self.train_best.compute()
|
||||
|
||||
self.log("metric/train/rec", metric_rec, logger=False, on_step=False, on_epoch=True, prog_bar=True)
|
||||
self.log("metric/train/best", metric_best, logger=False, on_step=False, on_epoch=True, prog_bar=True)
|
||||
self.logger.experiment[0].add_scalar("metric/train/rec", metric_rec, self.global_step)
|
||||
self.logger.experiment[0].add_scalar("metric/train/best", metric_best, self.global_step)
|
||||
|
||||
|
||||
def validation_step(self, batch, batch_idx):
|
||||
B, N, batch_c, image_tgt, masks_tgt, ldmks_tgt, batch_info, image_ref = self.set_input(batch)
|
||||
|
||||
# get noize input z
|
||||
batch_z = torch.randn(B*N, self.opt.z_dim).type_as(image_tgt) # (BN, dim_latent)
|
||||
# logging.info(f"[training_step] batch_c = {batch_c.shape}, dtype={batch_c.dtype}, device={batch_c.device}")
|
||||
# logging.info(f"[training_step] batch_z = {batch_z.shape}, dtype={batch_z.dtype}, device={batch_z.device}")
|
||||
|
||||
# forward
|
||||
# batch_img = torch.cat([image_ref, masks_tgt], dim=1) # (B*N, 4, 256, 256)
|
||||
image_pdt = self.netG(batch_z, batch_c) # (B*N, 4, 256, 256)
|
||||
|
||||
# add mask
|
||||
image_pdt_masked = image_pdt * masks_tgt # use pdt mask for masked pdt image
|
||||
image_tgt_masked = image_tgt * masks_tgt # use tgt mask for masked tgt image
|
||||
|
||||
|
||||
# adversarial loss
|
||||
pred_fake = self.netD(image_pdt_masked, batch_c)
|
||||
loss_G = adversarial_loss(pred_fake, target_is_real=True)
|
||||
|
||||
# L1-loss
|
||||
loss_rec = self.criterionL1(image_pdt_masked, image_tgt_masked)
|
||||
# loss_maskL1 = self.criterionMaskL1(image_pdt, image_tgt, self.mouth_mask * self.opt.lambda_mask)
|
||||
|
||||
# VGG & Style loss
|
||||
loss_vgg, loss_style = self.criterionVGG(image_pdt_masked, image_tgt_masked, style=True)
|
||||
loss_vgg = loss_vgg.mean()
|
||||
loss_style = loss_style.mean()
|
||||
|
||||
|
||||
self.log("valid/G", loss_G, logger=False, on_step=True, on_epoch=False, prog_bar=True)
|
||||
self.log("valid/rec", loss_rec, logger=False, on_step=True, on_epoch=False, prog_bar=True)
|
||||
self.log("valid/vgg", loss_vgg, logger=False, on_step=True, on_epoch=False, prog_bar=True)
|
||||
self.log("valid/style", loss_style, logger=False, on_step=True, on_epoch=False, prog_bar=True)
|
||||
|
||||
self.logger.experiment[0].add_scalar("valid/G", loss_G, self.global_step)
|
||||
self.logger.experiment[0].add_scalar("valid/rec", loss_rec, self.global_step)
|
||||
self.logger.experiment[0].add_scalar("valid/vgg", loss_vgg, self.global_step)
|
||||
self.logger.experiment[0].add_scalar("valid/style", loss_style, self.global_step)
|
||||
|
||||
loss = loss_G + loss_rec * self.opt_loss.lambda_rec \
|
||||
+ loss_vgg * self.opt_loss.lambda_vgg \
|
||||
+ loss_style * self.opt_loss.lambda_style
|
||||
|
||||
# add to logger
|
||||
pred_real = self.netD(image_tgt_masked, batch_c)
|
||||
loss_D_real = adversarial_loss(pred_real, target_is_real=True, loss_mode="lsgan")
|
||||
|
||||
pred_fake = self.netD(image_pdt_masked.detach(), batch_c)
|
||||
loss_D_fake = adversarial_loss(pred_fake, target_is_real=False, loss_mode="lsgan")
|
||||
|
||||
self.log("valid/D_real", loss_D_real, logger=False, on_step=True, on_epoch=False, prog_bar=True)
|
||||
self.log("valid/D_fake", loss_D_fake, logger=False, on_step=True, on_epoch=False, prog_bar=True)
|
||||
self.logger.experiment[0].add_scalar("valid/D_real", loss_D_real, self.global_step)
|
||||
self.logger.experiment[0].add_scalar("valid/D_fake", loss_D_fake, self.global_step)
|
||||
|
||||
# # # show metric
|
||||
self.valid_rec(loss_rec)
|
||||
self.valid_best(loss)
|
||||
|
||||
return {"loss": loss }
|
||||
|
||||
|
||||
def validation_epoch_end(self, outputs: List[Any]):
|
||||
"""
|
||||
`outputs` is a list of dicts returned from `validation_step()`
|
||||
"""
|
||||
metric_rec = self.valid_rec.compute()
|
||||
metric_best = self.valid_best.compute()
|
||||
|
||||
self.log("metric/valid/rec", metric_rec, logger=False, on_step=False, on_epoch=True, prog_bar=True)
|
||||
self.log("metric/valid/best", metric_best, logger=False, on_step=False, on_epoch=True, prog_bar=True)
|
||||
self.logger.experiment[0].add_scalar("metric/valid/rec", metric_rec, self.global_step)
|
||||
self.logger.experiment[0].add_scalar("metric/valid/best", metric_best, self.global_step)
|
||||
|
||||
|
||||
def test_step(self, batch, batch_idx):
|
||||
|
||||
B, N, batch_c, image_tgt, masks_tgt, ldmks_tgt, batch_info, image_ref = self.set_input(batch)
|
||||
|
||||
assert B == 1, f"B should == 1 in this test steps"
|
||||
# return {"loss": 0, "path_data":batch_info["path_data"][0]}
|
||||
|
||||
frame_beg = batch_info["frame_interval"][0].cpu().numpy()[0]
|
||||
frame_end = batch_info["frame_interval"][1].cpu().numpy()[0]
|
||||
|
||||
# for windws input & cut
|
||||
frame_beg = batch_info["frame_interval"][0].cpu().numpy()[0] + 3
|
||||
frame_end = frame_beg + N
|
||||
# frame_end = batch_info["frame_interval"][1].cpu().numpy()[0]
|
||||
|
||||
if frame_beg > 2000:
|
||||
return {"loss": 0, "path_data":batch_info["path_data"][0]}
|
||||
|
||||
|
||||
batch_z = torch.randn(B*N, self.opt.z_dim).type_as(image_tgt) # (BN, dim_latent)
|
||||
# logging.info(f"[training_step] batch_c = {batch_c.shape}, dtype={batch_c.dtype}, device={batch_c.device}")
|
||||
# logging.info(f"[training_step] batch_z = {batch_z.shape}, dtype={batch_z.dtype}, device={batch_z.device}")
|
||||
|
||||
# forward
|
||||
batch_img = torch.cat([image_ref, masks_tgt], dim=1) # (B*N, 4, 256, 256)
|
||||
image_pdt = self.netG(batch_z, batch_c, batch_img).detach() # (B*N, 3, 256, 256)
|
||||
|
||||
# add to logger
|
||||
# save to
|
||||
path_frame = Path(batch_info["path_data"][0]).joinpath("frames")
|
||||
path_tfrom = Path(batch_info["path_data"][0]).joinpath("frames_crop_tform_512")
|
||||
|
||||
|
||||
path_save_concat = Path(batch_info["path_data"][0]).joinpath(f"test_concat_epoch{self.current_epoch}")
|
||||
path_save_merged = Path(batch_info["path_data"][0]).joinpath(f"test_merged_epoch{self.current_epoch}")
|
||||
path_save_concat.mkdir(parents=True, exist_ok=True)
|
||||
path_save_merged.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
|
||||
# generate masks_tgt
|
||||
dilate_size = 11
|
||||
# kernel = torch.ones(dilate_size, dilate_size).to(self.device)
|
||||
# masks_tgt = morphology.dilation(masks_tgt, kernel)
|
||||
|
||||
kernel = torch.ones(dilate_size // 2, dilate_size // 2).to(self.device)
|
||||
masks_tgt = morphology.erosion(masks_tgt, kernel)
|
||||
masks_tgt = filters.gaussian_blur2d(masks_tgt, (dilate_size // 2, dilate_size // 2), (1.5, 1.5))
|
||||
|
||||
|
||||
# concate tgt & pdt
|
||||
# image_masked = masks_tgt * image_pdt + (1-masks_tgt) * image_tgt # (B, 3, 256, 256)
|
||||
image_masked = masks_tgt * image_pdt + (1-masks_tgt) * image_tgt # (B, 3, 256, 256)
|
||||
image_pdt_weighted = kornia.enhance.add_weighted(image_pdt * masks_tgt.expand(-1, 3, -1, -1), 0.4, image_pdt, 0.6, 0.0)
|
||||
image_tgt_weighted = kornia.enhance.add_weighted(image_tgt * masks_tgt.expand(-1, 3, -1, -1), 0.4, image_tgt, 0.6, 0.0)
|
||||
|
||||
image_concat = torch.cat([image_pdt_weighted, image_masked, image_tgt_weighted], dim=3).cpu().numpy() # (B, 3, 256, 256*3)
|
||||
image_masked = image_masked.cpu().numpy() # (B, 3, 256, 256)
|
||||
|
||||
logging.info(f'frame_beg {frame_beg}, {frame_end}, {image_concat.shape}, {image_concat.dtype}, mean={image_concat.mean()}')
|
||||
for i, idx in enumerate(range(frame_beg, frame_end)):
|
||||
if i > 1999: continue
|
||||
|
||||
jpath_save_concat = path_save_concat.joinpath(f"frame-{idx:06d}.jpg")
|
||||
# jpath_save_masked = path_save_masked.joinpath(f"frame-{idx:06d}.jpg")
|
||||
jpath_save_merged = path_save_merged.joinpath(f"frame-{idx:06d}.jpg")
|
||||
|
||||
jpath_image = path_frame.joinpath(f"frame-{idx:06d}.jpg")
|
||||
jpath_tform = path_tfrom.joinpath(f"frame-{idx:06d}.npy")
|
||||
|
||||
#
|
||||
jimage_concat = self.tensor2image(image_concat[i]) # (256, 256, 3)
|
||||
jimage_masked = self.tensor2image(image_masked[i]) # (256, 256, 3)
|
||||
|
||||
# load image
|
||||
image = cv2.imread(str(jpath_image)) # (H=1080, W=1920, 3)
|
||||
tform_param = np.load(str(jpath_tform)) # (3,3)
|
||||
# print(f"orignal image shape = {image.shape}, tform_param = {tform_param.shape}")
|
||||
|
||||
# get bbox
|
||||
tform = transform.SimilarityTransform(tform_param)
|
||||
DST_PTS = np.array([[0, 0], [0, 512 - 1], [512 - 1, 0]])
|
||||
src_pts = tform.inverse(DST_PTS)
|
||||
left, right = int(src_pts[0][0]), int(src_pts[2][0])
|
||||
top, bottom = int(src_pts[0][1]), int(src_pts[1][1])
|
||||
osize = min(right-left, bottom-top)
|
||||
# print(f"(left,top)=({left},{top}), (right, bottom)=({right},{bottom}), osize= {osize}")
|
||||
|
||||
# resize to osize
|
||||
iimage_masked_resize = cv2.resize(jimage_masked, dsize=(osize, osize), interpolation=cv2.INTER_LINEAR)
|
||||
|
||||
# paseter to orignial data
|
||||
image[top:top+osize, left:left+osize, :] = iimage_masked_resize
|
||||
|
||||
# save to image
|
||||
cv2.imwrite(str(jpath_save_concat), jimage_concat)
|
||||
# cv2.imwrite(str(jpath_save_masked), jimage_masked)
|
||||
cv2.imwrite(str(jpath_save_merged), image)
|
||||
|
||||
return {"loss": 0, "path_data":batch_info["path_data"][0]}
|
||||
|
||||
|
||||
def test_epoch_end(self, outputs: List[Any]):
|
||||
"""
|
||||
`outputs` is a list of dicts returned from `test_step()`
|
||||
"""
|
||||
|
||||
# concate video and add audio
|
||||
path_data = Path(outputs[0]["path_data"])
|
||||
logging.info(f"[test_epoch_end] path_data={path_data}")
|
||||
|
||||
path_save_concat = path_data.joinpath(f"test_concat_epoch{self.current_epoch}")
|
||||
path_save_merged = path_data.joinpath(f"test_merged_epoch{self.current_epoch}")
|
||||
|
||||
# save merged video
|
||||
ipath_frames = f"{str(path_save_merged)}/frame-%06d.jpg"
|
||||
ipath_audios = f"{str(path_data)}/audio/audio_trim.wav"
|
||||
ipath_output = f"{str(path_data)}/video/test_merged_epoch{self.current_epoch}.mp4"
|
||||
cmd = f"ffmpeg -y -r 50 -f image2 -i {ipath_frames} -i {ipath_audios} -vcodec libx264 -pix_fmt yuv420p -map 0:v -map 1:a -shortest {ipath_output}"
|
||||
logging.info(f"RUN: cmd")
|
||||
os.system(cmd)
|
||||
|
||||
# save concat video
|
||||
ipath_frames = f"{str(path_save_concat)}/frame-%06d.jpg"
|
||||
ipath_audios = f"{str(path_data)}/audio/audio_trim.wav"
|
||||
ipath_output = f"{str(path_data)}/video/test_concat_epoch{self.current_epoch}.mp4"
|
||||
cmd = f"ffmpeg -y -r 50 -f image2 -i {ipath_frames} -i {ipath_audios} -vcodec libx264 -pix_fmt yuv420p -map 0:v -map 1:a -shortest {ipath_output}"
|
||||
logging.info(f"RUN: cmd")
|
||||
os.system(cmd)
|
||||
|
||||
# cmd = "ffmpeg -y -r 50 -f image2 -i test_merged_epoch22/frame-%06d.jpg -i audio/audio_trim.wav -vcodec libx264 -pix_fmt yuv420p -map 0:v -map 1:a -shortest test_merged_epoch22.mp4"
|
||||
# cmd = "ffmpeg -y -r 50 -f image2 -i test_concat_epoch22/frame-%06d.jpg -i audio/audio_trim.wav -vcodec libx264 -pix_fmt yuv420p -map 0:v -map 1:a -shortest test_concat_epoch22.mp4"
|
||||
|
||||
# ffmpeg -i gan_model_epoch22.mp4 -i audio/audio_trim.wav -map 0:v -map 1:a -c:v copy -shortest gan_model_epoch22_audio.mp4
|
||||
|
||||
# cmd = "ffmpeg -y -r 50 -f image2 -i test_gan_model_epoch23/frame-%06d.jpg -vcodec libx264 -pix_fmt yuv420p gan_model_concat_epoch22.mp4"
|
||||
# ffmpeg -i gan_model_concat_epoch22.mp4 -i audio/audio_trim.wav -map 0:v -map 1:a -c:v copy -shortest gan_model_concat_epoch22_audio.mp4
|
||||
|
||||
|
||||
def on_epoch_end(self):
|
||||
# reset metrics at the end of every epoch
|
||||
self.train_rec.reset()
|
||||
self.valid_rec.reset()
|
||||
|
||||
|
||||
def get_progress_bar_dict(self):
|
||||
# don't show the version number
|
||||
items = super().get_progress_bar_dict() # "v_num", "loss"
|
||||
items.pop("v_num", None)
|
||||
# logging.info(items)
|
||||
# items["loss"] = '{:0.4f}'.format(float(items["loss"]))
|
||||
|
||||
return items
|
||||
|
||||
|
||||
def tensor2image(self, image):
|
||||
# image = tensor.detach().cpu().numpy()
|
||||
# image = tensor.numpy()
|
||||
|
||||
image = image*255.
|
||||
image = np.maximum(np.minimum(image, 255), 0)
|
||||
image = image.transpose(1,2,0)[:,:,[2,1,0]]
|
||||
|
||||
return image.astype(np.uint8).copy()
|
||||
|
||||
File renamed without changes.
File renamed without changes.
File renamed without changes.
@@ -0,0 +1,28 @@
|
||||
import torch
|
||||
import torch.nn.functional as F
|
||||
|
||||
|
||||
def adversarial_loss(pred, target_is_real=True, loss_mode="vanilla"):
|
||||
if loss_mode == "vanilla":
|
||||
if target_is_real:
|
||||
target = torch.ones_like(pred)
|
||||
else:
|
||||
target = torch.zeros_like(pred)
|
||||
return F.binary_cross_entropy_with_logits(pred, target)
|
||||
|
||||
elif loss_mode == "lsgan":
|
||||
if target_is_real:
|
||||
target = torch.ones_like(pred)
|
||||
else:
|
||||
target = torch.zeros_like(pred)
|
||||
return F.mse_loss(pred, target)
|
||||
|
||||
elif loss_mode == "hinge":
|
||||
if target_is_real:
|
||||
loss = torch.maximum(1-pred, torch.ones_like(pred)).mean()
|
||||
else:
|
||||
loss = torch.maximum(1+pred, torch.zeros_like(pred)).mean()
|
||||
return loss
|
||||
|
||||
else:
|
||||
raise NotImplementedError
|
||||
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
@@ -0,0 +1,190 @@
|
||||
import torch
|
||||
import torch.nn as nn
|
||||
import logging
|
||||
|
||||
class Generator(nn.Module):
|
||||
|
||||
def __init__(self, dim_x, dim_c, dim_z):
|
||||
super(Generator, self).__init__()
|
||||
|
||||
nc_input = dim_z + dim_c
|
||||
|
||||
# creat model
|
||||
self.encoder = nn.Sequential( # (nbatch, nchannel=1024 H=16, W=1)
|
||||
nn.BatchNorm2d(nc_input),
|
||||
|
||||
# block 1
|
||||
nn.Conv2d(nc_input, 512, kernel_size=(3,1), stride=(2,1), padding=(1,0), bias=True), # 32 x 8 x 1
|
||||
nn.LeakyReLU(0.02, True),
|
||||
nn.Conv2d(512, 512, kernel_size=(3,1), stride=(1,1), padding=(1,0), bias=True), # 32 x 8 x 1
|
||||
nn.LeakyReLU(0.02, True),
|
||||
|
||||
|
||||
nn.Conv2d(512, 512, kernel_size=(3,1), stride=(2,1), padding=(1,0), bias=True), # 32 x 4 x 1
|
||||
nn.LeakyReLU(0.02, True),
|
||||
nn.Conv2d(512, 512, kernel_size=(3,1), stride=(1,1), padding=(1,0), bias=True), # 32 x 8 x 1
|
||||
nn.LeakyReLU(0.02, True),
|
||||
|
||||
|
||||
nn.Conv2d(512, 256, kernel_size=(3,1), stride=(2,1), padding=(1,0), bias=True), # 64 x 2 x 1
|
||||
nn.LeakyReLU(0.02, True),
|
||||
nn.Conv2d(256, 256, kernel_size=(3,1), stride=(1,1), padding=(1,0), bias=True), # 32 x 8 x 1
|
||||
nn.LeakyReLU(0.02, True),
|
||||
|
||||
|
||||
nn.Conv2d(256, 256, kernel_size=(3,1), stride=(2,1), padding=(1,0), bias=True), # 64 x 1 x 1
|
||||
nn.LeakyReLU(0.02, True),
|
||||
nn.Conv2d(256, 256, kernel_size=(3,1), stride=(1,1), padding=(1,0), bias=True), # 32 x 8 x 1
|
||||
nn.LeakyReLU(0.02, True),
|
||||
|
||||
nn.Conv2d(256, 128, kernel_size=(3,1), stride=(2,1), padding=(1,0), bias=True), # 128 x 1 x 1
|
||||
nn.LeakyReLU(0.02, True),
|
||||
|
||||
nn.Flatten(), # 128,
|
||||
)
|
||||
|
||||
|
||||
|
||||
# output
|
||||
self.decoder = nn.Sequential(
|
||||
nn.Linear(in_features=128 + dim_z, out_features=2048), # 2048,
|
||||
nn.LeakyReLU(0.02, True),
|
||||
|
||||
nn.Linear(in_features=2048, out_features=128), # 128,
|
||||
nn.LeakyReLU(0.02, True),
|
||||
|
||||
nn.Linear(in_features=128, out_features=dim_x), # dim_x
|
||||
)
|
||||
|
||||
|
||||
def forward(self, c, z):
|
||||
""" forward function
|
||||
Args:
|
||||
c, motion data, (B, nseqs, 16, dim_c=1024)
|
||||
z, randon noise, (B, dim_z=32)
|
||||
return:
|
||||
(B x dim_x)
|
||||
"""
|
||||
logging.debug(f"[forward] input x shape = {c.shape}")
|
||||
|
||||
# remember high dimenstion
|
||||
shape_dims = c.shape
|
||||
if len(shape_dims) > 3:
|
||||
c = c.reshape(-1, c.shape[-2], c.shape[-1]) # (BN, nwind, dim_c)
|
||||
|
||||
# add noise
|
||||
z_expand = z.unsqueeze(dim=1).repeat([shape_dims[1], shape_dims[2], 1]) # (BN, nwind, dim_z)
|
||||
c = torch.cat([c, z_expand], dim=2) # (BN, nwind, dim_z + nc_c)
|
||||
|
||||
# preprocessing data
|
||||
c = c.unsqueeze(dim=1).transpose(1,3) # (B, 1, W, dim_x) --> (B, dim_x, W, 1)
|
||||
logging.debug(f"[forward] transpose c shape = {c.shape}")
|
||||
|
||||
feat = self.encoder(c) # (B, 50)
|
||||
logging.debug(f"[forward] encoder shape = {feat.shape}")
|
||||
|
||||
|
||||
# add noise again
|
||||
feat = torch.cat([feat, z], dim=1) # (B, 128 + dim_z)
|
||||
logging.debug(f"[forward] decoder shape = {pred.shape}")
|
||||
|
||||
pred = self.decoder(feat) # (B, dim_x)
|
||||
logging.debug(f"[forward] decoder shape = {pred.shape}")
|
||||
|
||||
|
||||
# recover high dimension
|
||||
if len(shape_dims) > 3:
|
||||
pred = pred.reshape(list(shape_dims[:-2]) + list(pred.shape[1:]))
|
||||
|
||||
logging.debug(f"[forward] reshape shape = {pred.shape}")
|
||||
|
||||
return pred
|
||||
|
||||
|
||||
|
||||
class Discriminator(torch.nn.Module):
|
||||
|
||||
def __init__(self, dim_x, dim_c):
|
||||
super(Discriminator, self).__init__()
|
||||
|
||||
|
||||
|
||||
# creat model
|
||||
self.encoder = nn.Sequential( # (nbatch, nchannel=1024 H=16, W=1)
|
||||
nn.BatchNorm2d(dim_c),
|
||||
|
||||
# block 1
|
||||
nn.Conv2d(dim_c, 512, kernel_size=(3,1), stride=(2,1), padding=(1,0), bias=True), # 32 x 8 x 1
|
||||
nn.LeakyReLU(0.02, True),
|
||||
nn.Conv2d(512, 512, kernel_size=(3,1), stride=(1,1), padding=(1,0), bias=True), # 32 x 8 x 1
|
||||
nn.LeakyReLU(0.02, True),
|
||||
|
||||
|
||||
nn.Conv2d(512, 512, kernel_size=(3,1), stride=(2,1), padding=(1,0), bias=True), # 32 x 4 x 1
|
||||
nn.LeakyReLU(0.02, True),
|
||||
nn.Conv2d(512, 512, kernel_size=(3,1), stride=(1,1), padding=(1,0), bias=True), # 32 x 8 x 1
|
||||
nn.LeakyReLU(0.02, True),
|
||||
|
||||
|
||||
nn.Conv2d(512, 256, kernel_size=(3,1), stride=(2,1), padding=(1,0), bias=True), # 64 x 2 x 1
|
||||
nn.LeakyReLU(0.02, True),
|
||||
nn.Conv2d(256, 256, kernel_size=(3,1), stride=(1,1), padding=(1,0), bias=True), # 32 x 8 x 1
|
||||
nn.LeakyReLU(0.02, True),
|
||||
|
||||
|
||||
nn.Conv2d(256, 256, kernel_size=(3,1), stride=(2,1), padding=(1,0), bias=True), # 64 x 1 x 1
|
||||
nn.LeakyReLU(0.02, True),
|
||||
nn.Conv2d(256, 256, kernel_size=(3,1), stride=(1,1), padding=(1,0), bias=True), # 32 x 8 x 1
|
||||
nn.LeakyReLU(0.02, True),
|
||||
|
||||
nn.Conv2d(256, 128, kernel_size=(3,1), stride=(2,1), padding=(1,0), bias=True), # 128 x 1 x 1
|
||||
nn.LeakyReLU(0.02, True),
|
||||
|
||||
nn.Flatten(), # 128,
|
||||
)
|
||||
|
||||
|
||||
# output
|
||||
self.decoder = nn.Sequential(
|
||||
nn.Linear(in_features=128 + dim_x, out_features=2048), # 2048,
|
||||
nn.LeakyReLU(0.02, True),
|
||||
|
||||
nn.Linear(in_features=2048, out_features=128), # 128,
|
||||
nn.LeakyReLU(0.02, True),
|
||||
|
||||
nn.Linear(in_features=128, out_features=16), # 16
|
||||
)
|
||||
|
||||
|
||||
|
||||
def forward(self, x, c):
|
||||
"""
|
||||
x, (B, N, dim_x=53)
|
||||
c, (B, N, 16, dim_c=1024)
|
||||
"""
|
||||
|
||||
""" forward function
|
||||
Args:
|
||||
x, motion data, (B, N, W, dim_c=1024)
|
||||
z, randon noise, (B, dim_z=32)
|
||||
return:
|
||||
(B x dim_x)
|
||||
"""
|
||||
logging.debug(f"[forward] input x shape = {x.shape}")
|
||||
|
||||
|
||||
# remember high dimenstion
|
||||
c = c.reshape(-1, c.shape[-2], c.shape[-1]) # (BN, W, dim_c)
|
||||
|
||||
# preprocessing data
|
||||
c = c.unsqueeze(dim=1).transpose(1,3) # (BN, 1, W, dim_x) --> (B, dim_x, W, 1)
|
||||
feat = self.encoder(x) # (BN, 128)
|
||||
logging.debug(f"[forward] encoder shape = {feat.shape}")
|
||||
|
||||
# add noise again
|
||||
feat = torch.cat([feat, x], dim=1) # (BN, 128 + dim_x)
|
||||
pred = self.decoder(feat) # (BN, 16)
|
||||
logging.debug(f"[forward] decoder shape = {pred.shape}")
|
||||
|
||||
|
||||
return pred
|
||||
@@ -8,7 +8,7 @@ from pytorch_lightning import LightningModule
|
||||
from torchmetrics import MaxMetric, MeanMetric, MinMetric
|
||||
import logging
|
||||
|
||||
from src.losses import WingLoss
|
||||
from src.loss import WingLoss
|
||||
from src.models import init_weights
|
||||
|
||||
from src.models.components import flame_mouth_idx
|
||||
|
||||
@@ -7,7 +7,7 @@ from pytorch_lightning import LightningModule
|
||||
from torchmetrics import MaxMetric, MeanMetric, MinMetric
|
||||
import logging
|
||||
|
||||
from src.losses import WingLoss
|
||||
from src.loss import WingLoss
|
||||
from src.utils.debug import debug
|
||||
from src.models import init_weights
|
||||
|
||||
@@ -19,7 +19,8 @@ from src.mesh import util
|
||||
from src.utils.animation import write_video, write_video_with_gt
|
||||
|
||||
|
||||
class Audio2CoeffModel(LightningModule):
|
||||
|
||||
class Audio2MotionModel(LightningModule):
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
@@ -0,0 +1,704 @@
|
||||
from typing import Any, List
|
||||
from omegaconf import DictConfig
|
||||
import numpy as np
|
||||
|
||||
import torch
|
||||
import torchvision
|
||||
from pytorch_lightning import LightningModule
|
||||
from torchmetrics import MeanMetric, MinMetric
|
||||
import logging
|
||||
|
||||
from src.utils.debug import debug
|
||||
from src.models import init_weights
|
||||
|
||||
from src.mesh import util
|
||||
from src.utils.animation import write_video, write_video_with_gt
|
||||
|
||||
from src.loss import WingLoss
|
||||
from src.loss.common import adversarial_loss
|
||||
|
||||
from src.models.components import flame_mouth_idx
|
||||
from .components.networks_audio2motion_gan import Generator, Discriminator
|
||||
from . import init_weights
|
||||
|
||||
class Audio2MotionGANModel(LightningModule):
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
opt: DictConfig = None,
|
||||
opt_loss: DictConfig = None,
|
||||
opt_optim: DictConfig = None,
|
||||
opt_netF: DictConfig = None,
|
||||
opt_netR: DictConfig = None,
|
||||
opt_netW: DictConfig = None,
|
||||
|
||||
):
|
||||
super().__init__()
|
||||
logging.info(f"[__init__] self.device = {self.device}")
|
||||
|
||||
|
||||
self.opt = opt
|
||||
self.opt_loss = opt_loss
|
||||
self.opt_optim = opt_optim
|
||||
|
||||
self.netG = Generator(
|
||||
dim_x = opt.dim_x, # data motion dimensionality = 53
|
||||
dim_c = opt.dim_c, # speech conditional data dimensionality = 1024
|
||||
dim_z = opt.dim_z, # Input latent (Z) dimensionality = 32
|
||||
)
|
||||
|
||||
self.netD = Discriminator(
|
||||
dim_x = opt.dim_x, # data motion dimensionality = 53
|
||||
dim_c = opt.dim_c, # speech conditional data dimensionality = 1024
|
||||
)
|
||||
|
||||
|
||||
self.netF = self._load_netF(opt_netF) # load FLAME model
|
||||
self.netR = self._load_netR(opt_netR) # load Render model
|
||||
self.processor, self.netW = self._load_netW(opt_netW) # load wav2vec model
|
||||
|
||||
|
||||
# load form ckp
|
||||
if opt.pretrain:
|
||||
logging.info(f"\n [init] load stat for netG, netD, from = {opt.pretrain_path}")
|
||||
self.load_pretrain_model(opt.pretrain_path)
|
||||
else:
|
||||
# init by default
|
||||
init_weights(self.netG, init_type='kaiming')
|
||||
init_weights(self.netD, init_type='kaiming')
|
||||
|
||||
# init last layer
|
||||
init_exp_weight = np.load(opt.path_init_expression_basis)
|
||||
init_exp_weight = torch.from_numpy(init_exp_weight).float() #.to(self.device)
|
||||
init_exp_weight = init_exp_weight[:, :50]
|
||||
self.netG.decoder_mesh.weight.data = init_exp_weight
|
||||
logging.info(f"init_exp_weight shape = {init_exp_weight.shape}")
|
||||
|
||||
|
||||
# load mean
|
||||
path_deca_mean = self.opt.path_mean_dict
|
||||
self.mean_dict = np.load(path_deca_mean, allow_pickle=True).item()
|
||||
|
||||
# get template (with specific avator)
|
||||
temp_verts, temp_ldmk2d, temp_ldmk3d = self.get_template_vertices() # verts: (1 x 1 x 5023 x 3), ldmk: (1 x 1 x 68 x 3)
|
||||
temp_verts_specific, temp_ldmk2d_specific, 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.register_buffer("temp_verts", temp_verts)
|
||||
self.register_buffer("temp_verts_specific", temp_verts_specific)
|
||||
|
||||
# define
|
||||
vertices_weight = torch.ones((1, 1, self.opt.num_vertices, 3)).to(self.device)
|
||||
vertices_weight[:, :, flame_mouth_idx, :] = 10
|
||||
self.register_buffer("vertices_weight", vertices_weight)
|
||||
|
||||
|
||||
# loss function
|
||||
self.loss_func_wing = WingLoss(reduction="none") # return (B, )
|
||||
|
||||
# use separate metric instance for train, val and test step
|
||||
# to ensure a proper reduction over the epoch
|
||||
self.train_rec, self.train_vel = MeanMetric(), MeanMetric()
|
||||
self.valid_rec, self.valid_vel = MeanMetric(), MeanMetric()
|
||||
self.test_rec, self.test_vel = MeanMetric(), MeanMetric()
|
||||
|
||||
# for logging best so far validation accuracy
|
||||
self.val_best = MinMetric()
|
||||
|
||||
|
||||
def _load_netF(self, opt_netF):
|
||||
from src.mesh.FLAME import FLAME
|
||||
|
||||
logging.info("_load_netF, FLAME ...")
|
||||
|
||||
model = FLAME(opt_netF)
|
||||
|
||||
# set to freeze
|
||||
for param in model.parameters():
|
||||
param.requires_grad = False
|
||||
|
||||
return model.eval()
|
||||
|
||||
|
||||
def _load_netR(self, opt_netR):
|
||||
from src.mesh.renderer import SRenderY, set_rasterizer
|
||||
|
||||
logging.info("_load_netR, Render ...")
|
||||
opt_netR.rasterizer_type = opt_netR.rasterizer_type # standard
|
||||
opt_netR.uv_size = opt_netR.uv_size
|
||||
opt_netR.image_size = opt_netR.image_size
|
||||
set_rasterizer(opt_netR.rasterizer_type)
|
||||
|
||||
model = SRenderY(opt_netR.image_size,
|
||||
obj_filename=opt_netR.topology_path,
|
||||
uv_size=opt_netR.uv_size,
|
||||
rasterizer_type=opt_netR.rasterizer_type
|
||||
)
|
||||
|
||||
# set to freeze
|
||||
for param in model.parameters():
|
||||
param.requires_grad = False
|
||||
|
||||
|
||||
return model.eval()
|
||||
|
||||
|
||||
def _load_netW(self, opt_netW):
|
||||
from transformers import Wav2Vec2FeatureExtractor, Wav2Vec2Model
|
||||
|
||||
logging.info("_load_netW, Wav2Vec2Model ...")
|
||||
# MODEL_ID = "jonatasgrosman/wav2vec2-large-xlsr-53-chinese-zh-cn"
|
||||
# path_ckpt_wav2vec = "./checkpoints/wav2vec2"
|
||||
processor = Wav2Vec2FeatureExtractor.from_pretrained(opt_netW.path_ckpt_wav2vec)
|
||||
extractor = Wav2Vec2Model.from_pretrained(opt_netW.path_ckpt_wav2vec)
|
||||
|
||||
# set to freeze
|
||||
for param in extractor.parameters():
|
||||
param.requires_grad = False
|
||||
|
||||
return processor, extractor.eval()
|
||||
|
||||
|
||||
def configure_optimizers(self):
|
||||
"""Choose what optimizers and learning-rate schedulers to use in your optimization.
|
||||
Normally you'd need one. But in the case of GANs or similar you might have multiple.
|
||||
|
||||
See examples here:
|
||||
https://pytorch-lightning.readthedocs.io/en/latest/common/lightning_module.html#configure-optimizers
|
||||
"""
|
||||
|
||||
lr_G = self.opt_optim.lr_G
|
||||
lr_D = self.opt_optim.lr_D
|
||||
optim_G = torch.optim.Adam(self.netG.parameters(), lr=lr_G, betas=(0, 0.99), eps=1e-8)
|
||||
optim_D = torch.optim.Adam(self.netD.parameters(), lr=lr_D, betas=(0, 0.99), eps=1e-8)
|
||||
|
||||
return [optim_D, optim_G], []
|
||||
|
||||
|
||||
@torch.no_grad()
|
||||
def set_input(self, batch:Any):
|
||||
|
||||
# logging.info(f"\n[set_input] self.device = {self.device}")
|
||||
|
||||
# batch information
|
||||
batch_info = {
|
||||
"vid": batch['vid'],
|
||||
"nframe": batch['nframe'],
|
||||
"interv": batch['frame_interval']
|
||||
}
|
||||
|
||||
# speech data
|
||||
cond = None
|
||||
raw_speech = batch["cond"].cpu().numpy() # (B, nsegments)
|
||||
debug(f"raw_speech = {raw_speech.shape}, dtype={raw_speech.dtype}", verbose=False)
|
||||
|
||||
# padding half frame length for bed and end
|
||||
npad = int(0.5 * self.opt.sr * ( 1 / self.opt.fps) + 0.5)
|
||||
raw_speech = np.pad(raw_speech, pad_width=((0,0), (npad, npad)), mode="edge")
|
||||
debug(f"after padding raw_speech = {raw_speech.shape}, dtype={raw_speech.dtype}", verbose=False)
|
||||
|
||||
inputs = self.processor(list(raw_speech), sampling_rate=16000, return_tensors="pt")
|
||||
cond = self.netW(**inputs.to(self.device)).last_hidden_state # B x nsteps x nc_feat
|
||||
debug(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)
|
||||
|
||||
# setup
|
||||
B, N = cond.size(0), cond.size(1)
|
||||
|
||||
# motion data
|
||||
data = batch["data"].float() # (B, nsteps, nc_motion)
|
||||
debug(f"data = {data.shape}, dtype={data.dtype}", verbose=False)
|
||||
data = data[:, 7:7+N, :] # (B, nseqs, nc_motion)
|
||||
|
||||
# self.vert, self.ldmk2d, self.ldmk3d = self.get_vertices(data)
|
||||
|
||||
# cut audio clips
|
||||
idx_beg = int(7 * self.opt.sr / self.opt.fps + 0.5)
|
||||
idx_end = int((7 + N) * self.opt.sr / self.opt.fps + 0.5)
|
||||
batch_info["raw_speech"] = raw_speech[:, idx_beg: idx_end] # (B, nsteps * sr / fps)
|
||||
|
||||
# debug(f"[set_input] vert = {self.vert.shape}, dtype={self.vert.dtype}, device={self.vert.device}", verbose=False)
|
||||
debug(f"[set_input] cond = {cond.shape}, dtype={cond.dtype}, device={cond.device}", verbose=False)
|
||||
debug(f"[set_input] ldmk2d = {self.ldmk2d.shape}, dtype={self.ldmk2d.dtype}, device={self.ldmk2d.device}", verbose=False)
|
||||
debug(f"[set_input] ldmk3d = {self.ldmk3d.shape}, dtype={self.ldmk3d.dtype}, device={self.ldmk3d.device}", verbose=False)
|
||||
|
||||
|
||||
return B, N, cond, data, batch_info
|
||||
|
||||
|
||||
def training_step(self, batch, batch_idx, optimizer_idx):
|
||||
|
||||
B, N, batch_c, batch_tgt, batch_info = self.set_input(batch)
|
||||
|
||||
# get noise input z
|
||||
batch_z = torch.randn(B, N, self.opt.z_dim).type_as(batch_c) # (B, N, dim_latent)
|
||||
|
||||
batch_pdt = self.netG(batch_z, batch_c) #(B, N, nc_motion)
|
||||
|
||||
# visulize
|
||||
self.training_batch_visulize(batch_pdt, batch_tgt, every_step=100)
|
||||
|
||||
##################################################
|
||||
######### Optimize Discriminator #########
|
||||
##################################################
|
||||
if optimizer_idx == 0:
|
||||
|
||||
# GT label
|
||||
pred_real = self.netD(batch_pdt, batch_c)
|
||||
loss_D_real = adversarial_loss(pred_real, target_is_real=True, loss_mode="lsgan")
|
||||
|
||||
# PT label
|
||||
pred_fake = self.netD(batch_pdt.detach(), batch_c)
|
||||
loss_D_fake = adversarial_loss(pred_fake, target_is_real=False, loss_mode="lsgan")
|
||||
|
||||
# discriminator loss is the average of these
|
||||
d_loss = (loss_D_real + loss_D_fake) / 2
|
||||
|
||||
# logging
|
||||
self.log("train/D_real", loss_D_real, logger=False, on_step=True, on_epoch=False, prog_bar=True)
|
||||
self.log("train/D_fake", loss_D_fake, logger=False, on_step=True, on_epoch=False, prog_bar=True)
|
||||
self.logger.experiment[0].add_scalar("train/D_real", loss_D_real, self.global_step)
|
||||
self.logger.experiment[0].add_scalar("train/D_fake", loss_D_fake, self.global_step)
|
||||
|
||||
return {"loss": d_loss}
|
||||
|
||||
##################################################
|
||||
######### Optimize Generator #########
|
||||
##################################################
|
||||
if optimizer_idx == 1:
|
||||
pred_fake = self.netD(batch_pdt, batch_c)
|
||||
loss_G = adversarial_loss(pred_fake, target_is_real=True, loss_mode="lsgan")
|
||||
|
||||
# supervised loss
|
||||
loss_e, loss_dict = self.eval_losses(batch_pdt, batch_tgt)
|
||||
|
||||
g_loss = loss_G + loss_e
|
||||
|
||||
# logging
|
||||
self.log("train/G", loss_G, logger=False, on_step=True, on_epoch=False, prog_bar=True)
|
||||
self.log("train/rec_geo", loss_dict["rec_geo"], logger=False, on_step=True, on_epoch=False, prog_bar=True)
|
||||
self.log("train/vel_geo", loss_dict["vel_geo"], logger=False, on_step=True, on_epoch=False, prog_bar=True)
|
||||
self.log("train/rec_exp", loss_dict["rec_exp"], logger=False, on_step=True, on_epoch=False, prog_bar=True)
|
||||
self.log("train/rec_pos", loss_dict["rec_pos"], logger=False, on_step=True, on_epoch=False, prog_bar=True)
|
||||
|
||||
self.logger.experiment[0].add_scalar("train/G", loss_G, self.global_step)
|
||||
self.logger.experiment[0].add_scalar("train/rec_geo", loss_dict["rec_geo"], self.global_step)
|
||||
self.logger.experiment[0].add_scalar("train/vel_geo", loss_dict["vel_geo"], self.global_step)
|
||||
self.logger.experiment[0].add_scalar("train/rec_exp", loss_dict["rec_exp"], self.global_step)
|
||||
self.logger.experiment[0].add_scalar("train/rec_pos", loss_dict["rec_pos"], self.global_step)
|
||||
|
||||
# # # show metric
|
||||
self.train_rec(loss_dict["rec_geo"])
|
||||
self.train_vel(loss_dict["vel_geo"])
|
||||
self.train_best(loss_e)
|
||||
|
||||
return {"loss": g_loss}
|
||||
|
||||
|
||||
def on_train_epoch_end(self):
|
||||
|
||||
metric_rec = self.train_rec.compute()
|
||||
metric_vel = self.train_vel.compute()
|
||||
metric_best = self.train_best.compute()
|
||||
|
||||
self.log("metric/train/rec", metric_rec, logger=False, on_step=False, on_epoch=True, prog_bar=True)
|
||||
self.log("metric/train/vel", metric_vel, logger=False, on_step=False, on_epoch=True, prog_bar=True)
|
||||
self.log("metric/train/best", metric_best, logger=False, on_step=False, on_epoch=True, prog_bar=True)
|
||||
self.logger.experiment[0].add_scalar("metric/train/rec", metric_rec, self.global_step)
|
||||
self.logger.experiment[0].add_scalar("metric/train/vel", metric_vel, self.global_step)
|
||||
self.logger.experiment[0].add_scalar("metric/train/best", metric_best, self.global_step)
|
||||
|
||||
|
||||
def training_batch_visulize(self, batch_pdt, batch_tgt, every_step=100):
|
||||
if not (self.global_step % every_step == 0 and self.global_rank == 0):
|
||||
return
|
||||
|
||||
batch_pdt = batch_pdt[0, ::3] # (N//3, nc_motion)
|
||||
batch_tgt = batch_tgt[0, ::3] # (N//3, nc_motion)
|
||||
|
||||
# get mesh
|
||||
batch_pdt_geo, *_ = self.get_vertices(batch_pdt[:4]) # 4 x 5023 x 3
|
||||
batch_tgt_geo, *_ = self.get_vertices(batch_tgt[:4]) # 4 x 5023 x 3
|
||||
|
||||
# render image
|
||||
cam = torch.tensor([5, 0, 0], device=self.device).repeat(4, 1) # (4, 3)
|
||||
render_pt = self.render_geometry(batch_pdt_geo, cam, self.device) # (4, 3, 512, 512)
|
||||
render_gt = self.render_geometry(batch_tgt_geo, cam, self.device) # (4, 3, 512, 512)
|
||||
|
||||
# vislandmarks
|
||||
ldmk3d_pt = self.netF.seletec_3d68(batch_pdt_geo) # [nbatch_real x 68 x 3]
|
||||
ldmk3d_gt = self.netF.seletec_3d68(batch_tgt_geo) # [nbatch_real x 68 x 3]
|
||||
|
||||
ldmk3d_pt = util.batch_orth_proj(ldmk3d_pt, cam);
|
||||
ldmk3d_pt[:,:,1:] = -ldmk3d_pt[:,:,1:];
|
||||
|
||||
ldmk3d_gt = util.batch_orth_proj(ldmk3d_gt, cam);
|
||||
ldmk3d_gt[:,:,1:] = -ldmk3d_gt[:,:,1:];
|
||||
|
||||
render_pt = util.tensor_vis_landmarks(render_pt, ldmk3d_pt, gt_landmarks=ldmk3d_gt, isScale=True, color = (255, 0, 0), color_gt=(0, 255, 0))
|
||||
render_gt = util.tensor_vis_landmarks(render_gt, ldmk3d_gt, isScale=True, color = (0, 255, 0))
|
||||
print(f"render_pt ={render_pt.shape}, render_gt={render_gt.shape}")
|
||||
|
||||
|
||||
grid_pdt = torchvision.utils.make_grid(render_pt)
|
||||
grid_tgt = torchvision.utils.make_grid(render_gt)
|
||||
|
||||
self.logger.experiment[0].add_image("image_pdt", grid_pdt, self.global_step)
|
||||
self.logger.experiment[0].add_image("image_tgt", grid_tgt, self.global_step)
|
||||
|
||||
|
||||
def validation_step(self, batch, batch_idx):
|
||||
B, N, batch_c, batch_tgt, batch_info = self.set_input(batch)
|
||||
|
||||
|
||||
# get noise input z
|
||||
batch_z = torch.randn(B, N, self.opt.z_dim).type_as(batch_c) # (B, N, dim_latent)
|
||||
batch_pdt = self.netG(batch_z, batch_c) #(B, N, nc_motion)
|
||||
|
||||
|
||||
##################################################
|
||||
######### Discriminator #########
|
||||
# GT label
|
||||
pred_real = self.netD(batch_pdt, batch_c)
|
||||
loss_D_real = adversarial_loss(pred_real, target_is_real=True, loss_mode="lsgan")
|
||||
|
||||
# PT label
|
||||
pred_fake = self.netD(batch_pdt.detach(), batch_c)
|
||||
loss_D_fake = adversarial_loss(pred_fake, target_is_real=False, loss_mode="lsgan")
|
||||
|
||||
# logging
|
||||
self.log("valid/D_real", loss_D_real, logger=False, on_step=True, on_epoch=False, prog_bar=True)
|
||||
self.log("valid/D_fake", loss_D_fake, logger=False, on_step=True, on_epoch=False, prog_bar=True)
|
||||
self.logger.experiment[0].add_scalar("valid/D_real", loss_D_real, self.global_step)
|
||||
self.logger.experiment[0].add_scalar("valid/D_fake", loss_D_fake, self.global_step)
|
||||
|
||||
##################################################
|
||||
######### Generator #########
|
||||
pred_fake = self.netD(batch_pdt, batch_c)
|
||||
loss_G = adversarial_loss(pred_fake, target_is_real=True, loss_mode="lsgan")
|
||||
|
||||
# supervised loss
|
||||
loss_e, loss_dict = self.eval_losses(batch_pdt, batch_tgt)
|
||||
|
||||
g_loss = loss_G + loss_e
|
||||
|
||||
# logging
|
||||
self.log("valid/G", loss_G, logger=False, on_step=True, on_epoch=False, prog_bar=True)
|
||||
self.log("valid/rec_geo", loss_dict["rec_geo"], logger=False, on_step=True, on_epoch=False, prog_bar=True)
|
||||
self.log("valid/vel_geo", loss_dict["vel_geo"], logger=False, on_step=True, on_epoch=False, prog_bar=True)
|
||||
self.log("valid/rec_exp", loss_dict["rec_exp"], logger=False, on_step=True, on_epoch=False, prog_bar=True)
|
||||
self.log("valid/rec_pos", loss_dict["rec_pos"], logger=False, on_step=True, on_epoch=False, prog_bar=True)
|
||||
self.logger.experiment[0].add_scalar("valid/G", loss_G, self.global_step)
|
||||
self.logger.experiment[0].add_scalar("valid/rec_geo", loss_dict["rec_geo"], self.global_step)
|
||||
self.logger.experiment[0].add_scalar("valid/vel_geo", loss_dict["vel_geo"], self.global_step)
|
||||
self.logger.experiment[0].add_scalar("valid/rec_exp", loss_dict["rec_exp"], self.global_step)
|
||||
self.logger.experiment[0].add_scalar("valid/rec_pos", loss_dict["rec_pos"], self.global_step)
|
||||
|
||||
|
||||
# # # show metric
|
||||
self.valid_rec(loss_dict["rec_geo"])
|
||||
self.valid_vel(loss_dict["vel_geo"])
|
||||
self.valid_best(loss_e)
|
||||
|
||||
return {"loss": g_loss }
|
||||
|
||||
|
||||
|
||||
def validation_epoch_end(self, outputs: List[Any]):
|
||||
"""
|
||||
`outputs` is a list of dicts returned from `validation_step()`
|
||||
"""
|
||||
metric_rec = self.valid_rec.compute()
|
||||
metric_vel = self.valid_vel.compute()
|
||||
metric_best = self.valid_best.compute()
|
||||
|
||||
self.log("metric/valid/rec", metric_rec, logger=False, on_step=False, on_epoch=True, prog_bar=True)
|
||||
self.log("metric/valid/vel", metric_vel, logger=False, on_step=False, on_epoch=True, prog_bar=True)
|
||||
self.log("metric/valid/best", metric_best, logger=False, on_step=False, on_epoch=True, prog_bar=True)
|
||||
|
||||
self.logger.experiment[0].add_scalar("metric/valid/rec", metric_rec, self.global_step)
|
||||
self.logger.experiment[0].add_scalar("metric/valid/vel", metric_vel, self.global_step)
|
||||
self.logger.experiment[0].add_scalar("metric/valid/best", metric_best, self.global_step)
|
||||
|
||||
|
||||
def test_step(self, batch, batch_idx):
|
||||
pass
|
||||
|
||||
|
||||
def test_epoch_end(self, outputs: List[Any]):
|
||||
pass
|
||||
|
||||
|
||||
def on_epoch_end(self):
|
||||
# reset metrics at the end of every epoch
|
||||
self.train_rec.reset(), self.train_vel.reset()
|
||||
self.valid_rec.reset(), self.valid_vel.reset()
|
||||
self.test_rec.reset(), self.test_vel.reset()
|
||||
|
||||
|
||||
def eval_losses(self, batch_pdt, batch_tgt):
|
||||
""" Computes the loss function.
|
||||
pramas:
|
||||
batch_tgt, (nbatch, seqlen, dim_motion)
|
||||
batch_pdt, (nbatch, seqlen, dim_motion)
|
||||
"""
|
||||
loss = 0
|
||||
loss_dict = {}
|
||||
|
||||
batch_pdt_exp = batch_pdt[..., :50]
|
||||
batch_pdt_pos = batch_pdt[..., 50:]
|
||||
|
||||
batch_tgt_exp = batch_tgt[..., :50]
|
||||
batch_tgt_pos = batch_tgt[..., 50:]
|
||||
|
||||
# get reconstruction
|
||||
batch_pdt_geo, *_ = self.get_vertices(batch_pdt) # B x nseq x num_vertices x 3
|
||||
batch_tgt_geo, *_ = self.get_vertices(batch_tgt) # B x nseq x num_vertices x 3
|
||||
|
||||
# rec loss
|
||||
loss_rec_exp = self.loss_func_wing(batch_pdt_exp, batch_tgt_exp).mean()
|
||||
loss_dict["rec_exp"] = loss_rec_exp.detach()
|
||||
|
||||
loss_rec_pos = self.loss_func_wing(batch_pdt_pos, batch_tgt_pos).mean()
|
||||
loss_dict["rec_pos"] = loss_rec_pos.detach()
|
||||
|
||||
loss += loss_rec_exp * self.opt_loss.lambda_rec_exp
|
||||
loss += loss_rec_pos * self.opt_loss.lambda_rec_pos
|
||||
|
||||
# rec smooth
|
||||
diff_pdt_exp = batch_pdt_exp[:, 1:, :] - batch_pdt_exp[:, :-1, :]
|
||||
diff_tgt_exp = batch_tgt_exp[:, 1:, :] - batch_tgt_exp[:, :-1, :]
|
||||
loss_vel_exp = self.loss_func_wing(diff_pdt_exp, diff_tgt_exp).mean()
|
||||
loss_dict["vel_exp"] = loss_vel_exp.detach()
|
||||
|
||||
|
||||
diff_pdt_pos = batch_pdt_pos[:, 1:, :] - batch_pdt_pos[:, :-1, :]
|
||||
diff_tgt_pos = batch_tgt_pos[:, 1:, :] - batch_tgt_pos[:, :-1, :]
|
||||
loss_vel_pos = self.loss_func_wing(diff_pdt_pos, diff_tgt_pos).mean()
|
||||
loss_dict["vel_pos"] = loss_vel_pos.detach()
|
||||
|
||||
loss += loss_vel_exp * self.opt_loss.lambda_vel_exp
|
||||
loss += loss_vel_pos * self.opt_loss.lambda_vel_pos
|
||||
|
||||
# geo rec
|
||||
loss_rec_geo = self.loss_func_wing(batch_pdt_geo, batch_tgt_geo).mean()
|
||||
loss_dict["rec_geo"] = loss_rec_geo.detach()
|
||||
|
||||
loss_rec_geo2 = self.loss_func_wing(batch_pdt_geo, batch_tgt_geo, weight=self.vertices_weight)
|
||||
loss += loss_rec_geo2 * self.opt_loss.lambda_rec_geo
|
||||
|
||||
# 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).mean()
|
||||
loss_dict["vel_geo"] = loss_vel_geo.detach()
|
||||
|
||||
loss_vel_geo2 = self.loss_func_wing(diff_pdt_geo, diff_tgt_geo, weight=self.vertices_weight).mean()
|
||||
loss += loss_vel_geo2 * self.opt_loss.lambda_vel_geo
|
||||
|
||||
# total loss
|
||||
loss_dict['all'] = loss.detach()
|
||||
|
||||
return loss, loss_dict
|
||||
|
||||
|
||||
|
||||
@torch.no_grad()
|
||||
def get_template_vertices(self, mean_dict=None):
|
||||
|
||||
batch_exp = torch.zeros(1, 50).to(self.device)
|
||||
batch_pose = torch.zeros(1, 6).to(self.device)
|
||||
|
||||
if mean_dict is not None:
|
||||
batch_shape = self.mean_dict["shape"].reshape(1, 100)
|
||||
batch_shape = torch.from_numpy(batch_shape).float().to(self.device)
|
||||
else:
|
||||
batch_shape = torch.zeros(1, 100).to(self.device)
|
||||
|
||||
# predict with netF
|
||||
# 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
|
||||
logging.info(f"template verts reshape = {verts.shape}")
|
||||
|
||||
return verts, ldmk2d, ldmk3d
|
||||
|
||||
|
||||
@torch.no_grad()
|
||||
def get_vertices(self, batch_motion):
|
||||
"""
|
||||
batch_motion, (nbatch, seqlen, 53)
|
||||
"""
|
||||
batch_exp = batch_motion[..., :50]
|
||||
batch_pos_mouth = batch_motion[..., 50:]
|
||||
nbatch, seqlen = batch_exp.size(0), batch_exp.size(1)
|
||||
|
||||
batch_exp = batch_exp.reshape(nbatch * seqlen, -1) # nbatch * seqlen x 50
|
||||
batch_pos_mouth = batch_pos_mouth.reshape(nbatch * seqlen, -1) # nbatch * seqlen x 3
|
||||
|
||||
batch_shape= torch.zeros(nbatch * seqlen, 100).to(self.device) # nbatch * seqlen x 50
|
||||
batch_pose = torch.zeros(nbatch * seqlen, 6).to(self.device) # nbatch * seqlen x 6
|
||||
batch_pose[:, 3:6] = batch_pos_mouth
|
||||
|
||||
# predict with netF
|
||||
verts, ldmk2d, ldmk3d = self.netF(batch_shape, batch_exp, batch_pose) # nbatch * seqlen x 5023 x 3
|
||||
verts = verts.reshape(nbatch, seqlen, -1, 3) # nbatch x seqlen x 5023 x 3
|
||||
ldmk2d = ldmk2d.reshape(nbatch, seqlen, -1, 3) # nbatch x seqlen x 5023 x 3
|
||||
ldmk3d = ldmk3d.reshape(nbatch, seqlen, -1, 3) # nbatch x seqlen x 5023 x 3
|
||||
|
||||
return verts, ldmk2d, ldmk3d
|
||||
|
||||
|
||||
@torch.no_grad()
|
||||
def render_geometry(self, verts, cam=None, device=None):
|
||||
"""
|
||||
verts: [N x 5023 x 3]
|
||||
"""
|
||||
batch_size = verts.size(0)
|
||||
|
||||
if cam is None:
|
||||
cam = torch.zeros(batch_size, 3).to(device) # (batch_size, 3)
|
||||
|
||||
# orth_proj
|
||||
verts_proj = util.batch_orth_proj(verts, cam);
|
||||
verts_proj[:,:,1:] = -verts_proj[:,:,1:]
|
||||
|
||||
# render
|
||||
images = self.netR.render_shape(verts, verts_proj) # (batch_size, 3, 512, 512)
|
||||
|
||||
return images
|
||||
|
||||
|
||||
def save_reconstruct(self, batch_pdt_geo, batch_speech, path_save, suffix="", vis_landmarks=False):
|
||||
# batch_pdt_pos, [B x N x dim_motion]
|
||||
# batch_speech, [B x N*sr/fps ]
|
||||
|
||||
B, N, *_ = batch_pdt_geo.shape
|
||||
nbatch_render = 10
|
||||
|
||||
# for each batch
|
||||
for i in range(B):
|
||||
igeo_pt = batch_pdt_geo[i, ...]
|
||||
|
||||
v_render_pt = []
|
||||
for k in range(0, N, nbatch_render):
|
||||
# split
|
||||
kgeo_pt = igeo_pt[k:k+nbatch_render, ...] # [nbatch_real x 5023 x 3]
|
||||
nbatch_real = kgeo_pt.size(0)
|
||||
|
||||
# cam
|
||||
cam = torch.tensor([5, 0, 0], device=self.device) # (1, 3)
|
||||
cam = cam.repeat(nbatch_real, 1) # (nbatch_real, 3)
|
||||
# print(f"cam shape = {cam.shape}")
|
||||
|
||||
# render
|
||||
render_pt = self.render_geometry(kgeo_pt, cam, self.device) # (nbatch_real, 3, 512, 512)
|
||||
# print(f"render_pt ={render_pt.shape}, render_gt={render_gt.shape}")
|
||||
|
||||
if vis_landmarks:
|
||||
kldmk3d_pt = self.netF.seletec_3d68(kgeo_pt) # [nbatch_real x 68 x 3]
|
||||
kldmk3d_pt = util.batch_orth_proj(kldmk3d_pt, cam);
|
||||
kldmk3d_pt[:,:,1:] = -kldmk3d_pt[:,:,1:];
|
||||
render_pt = util.tensor_vis_landmarks(render_pt, kldmk3d_pt, isScale=True, color = (255, 0, 0))
|
||||
else:
|
||||
render_pt = render_pt.cpu()
|
||||
|
||||
# append each frame
|
||||
for m in range(nbatch_real):
|
||||
v_render_pt.append(tensor2image(render_pt[m, ...]))
|
||||
|
||||
# write video
|
||||
ipath_save = path_save.joinpath(f"{suffix}_{i:02d}_pt.mp4")
|
||||
write_video(v_render_pt, batch_speech[i], ipath_save, fps=50)
|
||||
self.logger.info(f"save video to -> {str(ipath_save)}")
|
||||
|
||||
|
||||
@torch.no_grad()
|
||||
def save_reconstruct_with_gt(self, batch_pdt_geo, batch_tgt_geo, batch_speech, path_save, suffix="", vis_landmarks=True):
|
||||
# batch_pdt_geo, [B x N x 5023 x 3]
|
||||
# batch_tgt_geo, [B x N x 5023 x 3]
|
||||
# batch_speech, [B x N*sr/fps ]
|
||||
|
||||
B, N, *_ = batch_pdt_geo.shape
|
||||
nbatch_render = 10
|
||||
|
||||
# for each batch
|
||||
for i in range(B):
|
||||
igeo_pt = batch_pdt_geo[i, ...] # [N x 5023 x 3]
|
||||
igeo_gt = batch_tgt_geo[i, ...] # [N x 5023 x 3]
|
||||
ipath_save = path_save.joinpath(f"{suffix}_{i:02d}.mp4")
|
||||
|
||||
v_render_pt = []
|
||||
v_render_gt = []
|
||||
|
||||
for k in range(0, N, nbatch_render):
|
||||
|
||||
# split
|
||||
kgeo_pt = igeo_pt[k:k+nbatch_render, ...] # [nbatch_real x 5023 x 3]
|
||||
kgeo_gt = igeo_gt[k:k+nbatch_render, ...] # [nbatch_real x 5023 x 3]
|
||||
|
||||
nbatch_real = kgeo_pt.size(0)
|
||||
|
||||
# cam
|
||||
cam = torch.tensor([5, 0, 0], device=self.device).repeat(nbatch_real, 1) # (nbatch_real, 3)
|
||||
# print(f"cam shape = {cam.shape}")
|
||||
|
||||
# render
|
||||
render_pt = self.render_geometry(kgeo_pt, cam, self.device) # (nbatch_real, 3, 512, 512)
|
||||
render_gt = self.render_geometry(kgeo_gt, cam, self.device) # (nbatch_real, 3, 512, 512)
|
||||
# print(f"render_pt ={render_pt.shape}, render_gt={render_gt.shape}")
|
||||
|
||||
if vis_landmarks:
|
||||
# landmarks 3d
|
||||
kldmk3d_pt = self.netF.seletec_3d68(kgeo_pt) # [nbatch_real x 68 x 3]
|
||||
kldmk3d_gt = self.netF.seletec_3d68(kgeo_gt) # [nbatch_real x 68 x 3]
|
||||
|
||||
kldmk3d_pt = util.batch_orth_proj(kldmk3d_pt, cam);
|
||||
kldmk3d_pt[:,:,1:] = -kldmk3d_pt[:,:,1:];
|
||||
|
||||
kldmk3d_gt = util.batch_orth_proj(kldmk3d_gt, cam);
|
||||
kldmk3d_gt[:,:,1:] = -kldmk3d_gt[:,:,1:];
|
||||
|
||||
render_pt = util.tensor_vis_landmarks(render_pt, kldmk3d_pt, gt_landmarks=kldmk3d_gt, isScale=True, color = (255, 0, 0), color_gt=(0, 255, 0))
|
||||
render_gt = util.tensor_vis_landmarks(render_gt, kldmk3d_gt, isScale=True, color = (0, 255, 0))
|
||||
else:
|
||||
render_pt = render_pt.cpu()
|
||||
render_gt = render_gt.cpu()
|
||||
|
||||
# append each frame
|
||||
for m in range(nbatch_real):
|
||||
v_render_pt.append(tensor2image(render_pt[m, ...]))
|
||||
v_render_gt.append(tensor2image(render_gt[m, ...]))
|
||||
|
||||
# save animation
|
||||
write_video_with_gt(v_render_pt, v_render_gt, batch_speech[i], ipath_save, fps=50, sr=16000)
|
||||
|
||||
|
||||
def tensor2image(self, tensor):
|
||||
# image = tensor.detach().cpu().numpy()
|
||||
image = tensor.numpy()
|
||||
image = image*255.
|
||||
image = np.maximum(np.minimum(image, 255), 0)
|
||||
image = image.transpose(1,2,0)[:,:,[2,1,0]]
|
||||
|
||||
return image.astype(np.uint8).copy()
|
||||
|
||||
|
||||
def get_progress_bar_dict(self):
|
||||
# don't show the version number
|
||||
items = super().get_progress_bar_dict() # "v_num", "loss"
|
||||
items.pop("v_num", None)
|
||||
|
||||
# logging.info(items)
|
||||
# return items
|
||||
|
||||
# items["test"] = '{:.6f}'.format(items["loss"])
|
||||
|
||||
|
||||
return items
|
||||
|
||||
@@ -9,10 +9,10 @@ from pytorch_lightning import LightningModule
|
||||
from torchmetrics import MaxMetric, MeanMetric, MinMetric
|
||||
import logging
|
||||
|
||||
from ..losses import lossfunc
|
||||
from ..loss import lossfunc
|
||||
|
||||
|
||||
from src.losses import WingLoss
|
||||
from src.loss import WingLoss
|
||||
from src.utils.debug import debug
|
||||
from src.models import init_weights
|
||||
|
||||
|
||||
Reference in new issue
Block a user