initial commit
This commit is contained in:
commit
c7175dd7ff
127 files changed
+13949
No files matched your search
@@ -0,0 +1,187 @@
|
||||
"""This package contains modules related to objective functions, optimizations, and network architectures.
|
||||
|
||||
To add a custom model class called 'dummy', you need to add a file called 'dummy_model.py' and define a subclass DummyModel inherited from Base.
|
||||
You need to implement the following five functions:
|
||||
-- <__init__>: initialize the class; first call Base.__init__(self, opt).
|
||||
-- <set_input>: unpack data from dataset and apply preprocessing.
|
||||
-- <forward>: produce intermediate results.
|
||||
-- <optimize_parameters>: calculate loss, gradients, and update network weights.
|
||||
-- <modify_commandline_options>: (optionally) add model-specific options and set default options.
|
||||
|
||||
In the function <__init__>, you need to define four lists:
|
||||
-- self.names_loss (str list): specify the training losses that you want to plot and save.
|
||||
-- self.names_model (str list): define networks used in our training.
|
||||
-- self.names_visual (str list): specify the images that you want to display and save.
|
||||
-- self.optimizers (optimizer list): define and initialize optimizers. You can define one optimizer for each network. If two networks are updated at the same time, you can use itertools.chain to group them. See cycle_gan_model.py for an usage.
|
||||
|
||||
Now you can use the model class by specifying flag '--model dummy'.
|
||||
See our template model class 'template_model.py' for more details.
|
||||
"""
|
||||
import torch
|
||||
import torch.nn as nn
|
||||
import functools
|
||||
from torch.optim import lr_scheduler
|
||||
|
||||
import importlib
|
||||
from src.models.base import Base
|
||||
|
||||
def create_model(opt, logger):
|
||||
"""Create a model given the option.
|
||||
|
||||
This function warps the class CustomDatasetDataLoader.
|
||||
This is the main interface between this package and 'train.py'/'test.py'
|
||||
|
||||
Example:
|
||||
>>> from models import create_model
|
||||
>>> model = create_model(opt)
|
||||
"""
|
||||
model = find_model_using_name(opt.MODEL.name)
|
||||
instance = model(opt, logger)
|
||||
|
||||
print("model [%s] was created" % type(instance).__name__)
|
||||
return instance
|
||||
|
||||
def find_model_using_name(model_name):
|
||||
"""Import the module "models/[model_name]_model.py".
|
||||
|
||||
In the file, the class called DatasetNameModel() will
|
||||
be instantiated. It has to be a subclass of Base,
|
||||
and it is case-insensitive.
|
||||
"""
|
||||
model_filename = f"src.models.model_{model_name}"
|
||||
modellib = importlib.import_module(model_filename)
|
||||
|
||||
model = None
|
||||
target_model_name = model_name.replace('_', '') + 'model'
|
||||
for name, cls in modellib.__dict__.items():
|
||||
if name.lower() == target_model_name.lower() and issubclass(cls, Base):
|
||||
model = cls
|
||||
|
||||
if model is None:
|
||||
print(f"In {model_filename}.py, there should be a subclass of Base with class name that matches {target_model_name} in lowercase.")
|
||||
raise("ERROR")
|
||||
|
||||
return model
|
||||
|
||||
|
||||
|
||||
def calculate_model_params(model):
|
||||
nparam = 0
|
||||
for iparam in model.parameters():
|
||||
nparam += iparam.numel()
|
||||
return nparam
|
||||
|
||||
def define_netGlow(opt):
|
||||
netG = None
|
||||
if opt.MODEL.name_netG == "MoGlow":
|
||||
from src.nn.moglow import MoGlow
|
||||
netG = MoGlow(opt)
|
||||
elif opt.MODEL.name_netG == "PiorGlow":
|
||||
from src.nn.piorglow import PiorGlow
|
||||
netG = PiorGlow(opt)
|
||||
elif opt.MODEL.name_netG == "MotionFlow":
|
||||
from src.nn.MotionFlow import MotionFlow
|
||||
netG = MotionFlow(opt)
|
||||
else:
|
||||
raise NameError(f"The model of opt.MODEL.name_netG(={opt.MODEL.name_netG}) not existing!")
|
||||
|
||||
return netG
|
||||
|
||||
def define_netG(opt):
|
||||
netG = None
|
||||
|
||||
if opt.MODEL.name_netAE == "VAE":
|
||||
from src.models.sequencial_vae import SequencialVAE
|
||||
netG = SequencialVAE(opt)
|
||||
|
||||
elif opt.MODEL.name_netAE == "MLP":
|
||||
from src.models.vae_vanilla import VanillaVAE
|
||||
netG = VanillaVAE(opt)
|
||||
|
||||
elif opt.MODEL.name_netAE == "ATC":
|
||||
from src.models.atcnet import ATCNet
|
||||
netG = ATCNet(opt)
|
||||
|
||||
elif opt.MODEL.name_netAE == "ATC_BIG":
|
||||
from src.models.atcnet_big import ATC_BIGNet
|
||||
netG = ATC_BIGNet(opt)
|
||||
|
||||
elif opt.MODEL.name_netAE == "ATC_REG":
|
||||
from src.models.atcnet_regression import ATC_REG_Net
|
||||
netG = ATC_REG_Net(opt)
|
||||
|
||||
elif opt.MODEL.name_netAE == "transformer-vae":
|
||||
from src.models.transformer_vae import TransformerVAE
|
||||
netG = TransformerVAE(opt)
|
||||
|
||||
elif opt.MODEL.name_netAE == "transformer":
|
||||
from src.models.transformer import Transformer
|
||||
netG = Transformer(opt)
|
||||
|
||||
elif opt.MODEL.name_netAE == "transformer-a2l":
|
||||
from src.models.transformer_a2l import TransformerA2L
|
||||
netG = TransformerA2L(opt)
|
||||
else:
|
||||
raise NameError(f"The model of opt.MODEL.name_netAE(={opt.MODEL.name_netAE}) not existing!")
|
||||
|
||||
|
||||
return netG
|
||||
|
||||
|
||||
|
||||
def init_weights(net, init_type='normal', init_gain=0.02):
|
||||
"""Initialize network weights.
|
||||
|
||||
Parameters:
|
||||
net (network) -- network to be initialized
|
||||
init_type (str) -- the name of an initialization method: normal | xavier | kaiming | orthogonal
|
||||
init_gain (float) -- scaling factor for normal, xavier and orthogonal.
|
||||
|
||||
We use 'normal' in the original pix2pix and CycleGAN paper. But xavier and kaiming might
|
||||
work better for some applications. Feel free to try yourself.
|
||||
"""
|
||||
def init_func(m): # define the initialization function
|
||||
classname = m.__class__.__name__
|
||||
#print(classname, hasattr(m, 'weight'),)
|
||||
if hasattr(m, 'weight') and (classname.find('Conv') != -1 or classname.find('Linear') != -1):
|
||||
if init_type == 'normal':
|
||||
nn.init.normal_(m.weight.data, 0.0, init_gain)
|
||||
elif init_type == 'xavier':
|
||||
nn.init.xavier_normal_(m.weight.data, gain=init_gain)
|
||||
elif init_type == 'kaiming':
|
||||
nn.init.kaiming_normal_(m.weight.data, a=0, mode='fan_in')
|
||||
elif init_type == 'orthogonal':
|
||||
nn.init.orthogonal_(m.weight.data, gain=init_gain)
|
||||
else:
|
||||
raise NotImplementedError('initialization method [%s] is not implemented' % init_type)
|
||||
|
||||
if hasattr(m, 'bias') and m.bias is not None:
|
||||
nn.init.constant_(m.bias.data, 0.0)
|
||||
|
||||
elif classname.find('BatchNorm2d') != -1: # BatchNorm Layer's weight is not a matrix; only normal distribution applies.
|
||||
nn.init.normal_(m.weight.data, 1.0, init_gain)
|
||||
nn.init.constant_(m.bias.data, 0.0)
|
||||
|
||||
print('initialize network with %s' % init_type)
|
||||
net.apply(init_func) # apply the initialization function <init_func>
|
||||
|
||||
|
||||
def init_net(net, init_type='normal', init_gain=0.02, gpu_ids=[]):
|
||||
"""Initialize a network: 1. register CPU/GPU device (with multi-GPU support); 2. initialize the network weights
|
||||
Parameters:
|
||||
net (network) -- the network to be initialized
|
||||
init_type (str) -- the name of an initialization method: normal | xavier | kaiming | orthogonal
|
||||
gain (float) -- scaling factor for normal, xavier and orthogonal.
|
||||
gpu_ids (int list) -- which GPUs the network runs on: e.g., 0,1,2
|
||||
|
||||
Return an initialized network.
|
||||
"""
|
||||
|
||||
if len(gpu_ids) > 0:
|
||||
assert(torch.cuda.is_available())
|
||||
net.to(f"cuda:{gpu_ids[0]}")
|
||||
net = torch.nn.DataParallel(net, gpu_ids) # multi-GPUs
|
||||
|
||||
init_weights(net, init_type, init_gain=init_gain)
|
||||
|
||||
return net
|
||||
@@ -0,0 +1,324 @@
|
||||
import os
|
||||
import torch
|
||||
from collections import OrderedDict
|
||||
from abc import ABCMeta, abstractmethod
|
||||
|
||||
from pathlib import Path
|
||||
|
||||
class Base():
|
||||
__metaclass__ = ABCMeta
|
||||
"""This class is an abstract base class (ABC) for models.
|
||||
To create a subclass, you need to implement the following five functions:
|
||||
-- <__init__>: initialize the class; first call Base.__init__(self, opt).
|
||||
-- <set_input>: unpack data from dataset and apply preprocessing.
|
||||
-- <forward>: produce intermediate results.
|
||||
-- <optimize>: calculate losses, gradients, and update network weights.
|
||||
-- <modify_commandline_options>: (optionally) add model-specific options and set default options.
|
||||
"""
|
||||
|
||||
def __init__(self, opt, logger):
|
||||
"""Initialize the Base class.
|
||||
|
||||
Parameters:
|
||||
opt (Option class)-- stores all the experiment flags; needs to be a subclass of BaseOptions
|
||||
|
||||
When creating your custom class, you need to implement your own initialization.
|
||||
In this fucntion, you should first call <Base.__init__(self, opt)>
|
||||
Then, you need to define four lists:
|
||||
-- self.names_loss (str list): specify the training losses that you want to plot and save.
|
||||
-- self.names_model (str list): specify the images that you want to display and save.
|
||||
-- self.names_visual (str list): define networks used in our training.
|
||||
-- self.optimizers (optimizer list): define and initialize optimizers. You can define one optimizer for each network. If two networks are updated at the same time, you can use itertools.chain to group them. See cycle_gan_model.py for an example.
|
||||
"""
|
||||
self.opt = opt
|
||||
self.logger = logger
|
||||
|
||||
self.gpu_ids = opt.GPUS
|
||||
self.isTrain = opt.isTrain
|
||||
|
||||
self.device = torch.device(f'cuda:{self.gpu_ids[0]}') if self.gpu_ids else torch.device('cpu') # get device name: CPU or GPU
|
||||
|
||||
self.path_save = Path(opt.OUTPUT_DIR) # save all the checkpoints to path_save
|
||||
self.path_save.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
self.names_loss = []
|
||||
self.names_model = []
|
||||
self.names_visual = []
|
||||
|
||||
self.loss_dict = OrderedDict()
|
||||
self.data_dict = OrderedDict()
|
||||
|
||||
self.schedulers = []
|
||||
self.optimizers = []
|
||||
|
||||
self.logger.info(f"device set to {self.device}")
|
||||
|
||||
def eval(self):
|
||||
"""Make models eval mode during test time"""
|
||||
for name in self.names_model:
|
||||
net = getattr(self, 'net' + name)
|
||||
net.eval()
|
||||
|
||||
def train(self):
|
||||
"""Make models train mode during train time"""
|
||||
for name in self.names_model:
|
||||
net = getattr(self, 'net' + name)
|
||||
net.train()
|
||||
|
||||
@abstractmethod
|
||||
def set_input(self, input):
|
||||
"""Unpack input data from the dataloader and perform necessary pre-processing steps.
|
||||
|
||||
Parameters:
|
||||
input (dict): includes the data itself and its metadata information.
|
||||
"""
|
||||
pass
|
||||
|
||||
@abstractmethod
|
||||
def forward(self):
|
||||
"""Run forward pass; called by both functions <optimize> and <test>."""
|
||||
pass
|
||||
|
||||
@abstractmethod
|
||||
def training(self):
|
||||
"""Calculate losses, gradients, and update network weights; called in every training iteration"""
|
||||
pass
|
||||
|
||||
|
||||
def testing(self):
|
||||
"""Forward function used in test time.
|
||||
|
||||
This function wraps <forward> function in no_grad() so we don't save intermediate steps for backprop
|
||||
It also calls <compute_visuals> to produce additional visualization results
|
||||
"""
|
||||
with torch.no_grad():
|
||||
self.forward()
|
||||
self.compute_visuals()
|
||||
|
||||
def validation(self):
|
||||
"""Forward function used in validation time. """
|
||||
pass
|
||||
|
||||
|
||||
def setup(self, opt):
|
||||
"""Load and print networks;
|
||||
Parameters:
|
||||
opt (Option class) -- stores all the experiment flags
|
||||
"""
|
||||
# if train
|
||||
if self.isTrain:
|
||||
|
||||
# load model for resume
|
||||
if opt.TRAIN.resume:
|
||||
self.logger.info("SETUP: resume network training")
|
||||
load_suffix = f'iter_{opt.TRAIN.load_iter}' if opt.TRAIN.load_iter > 0 else opt.TRAIN.epoch_begin
|
||||
self.load_networks(load_suffix, self.path_save, load_info=True)
|
||||
|
||||
# load model for pretrain
|
||||
elif opt.MODEL.pretrain:
|
||||
self.logger.info("SETUP: load pretrain network")
|
||||
load_suffix = f'iter_{opt.TRAIN.load_iter}'if opt.TRAIN.load_iter > 0 else opt.MODEL.load_epoch
|
||||
path_chekpoints = Path(opt.MODEL.path_checkpoint)
|
||||
self.load_networks(load_suffix, path_chekpoints, load_info=False)
|
||||
|
||||
# init
|
||||
else:
|
||||
self.logger.info("SETUP: Init by each network")
|
||||
|
||||
# if test or infer
|
||||
else:
|
||||
self.logger.info("SETUP: TEST or INFER, load pretrain network")
|
||||
load_suffix = f'iter_{opt.TRAIN.load_iter}' if opt.TRAIN.load_iter > 0 else opt.MODEL.load_epoch
|
||||
path_chekpoints = Path(opt.MODEL.path_checkpoint)
|
||||
self.load_networks(load_suffix, path_chekpoints, load_info=False)
|
||||
|
||||
# printer networks
|
||||
self.print_networks(opt.verbose)
|
||||
|
||||
|
||||
def update_parameters(self, epoch):
|
||||
pass
|
||||
|
||||
def update_learning_rate(self, cur_loss=None):
|
||||
"""Update learning rates for all the networks; called at the end of every epoch
|
||||
`cur_loss` used for learning rate policy 'plateau'
|
||||
"""
|
||||
for scheduler in self.schedulers:
|
||||
if self.opt.TRAIN.lr_policy == 'plateau':
|
||||
scheduler.step(cur_loss)
|
||||
else:
|
||||
scheduler.step()
|
||||
|
||||
msg = ""
|
||||
for i, optimize in enumerate(self.optimizers):
|
||||
lr = optimize.param_groups[0]['lr']
|
||||
msg += f"net{self.names_model[i]}={lr:.7f} "
|
||||
|
||||
self.logger.info(f"\t[UPDATE] learning rate:" + msg)
|
||||
|
||||
return lr
|
||||
|
||||
|
||||
def get_test_visuals(self):
|
||||
"""Return visualization images. train.py will display these images with
|
||||
visdom, and save the images to a HTML"""
|
||||
pass
|
||||
|
||||
|
||||
def get_train_visuals(self):
|
||||
"""Return visualization images. train.py will display these images with
|
||||
visdom, and save the images to a HTML"""
|
||||
|
||||
visual_ret = OrderedDict()
|
||||
for name in self.names_visual:
|
||||
visual_ret[name] = getattr(self, name)
|
||||
# get the data from a variable
|
||||
if isinstance(visual_ret[name], torch.Tensor):
|
||||
visual_ret[name] = visual_ret[name].detach().cpu().numpy()
|
||||
|
||||
return visual_ret
|
||||
|
||||
def get_current_losses(self):
|
||||
"""Return traning losses / errors.
|
||||
train.py will print out these errors on console, and save them to a file"""
|
||||
|
||||
errors_ret = OrderedDict()
|
||||
for name in self.names_loss:
|
||||
# print(f"name = ",name)
|
||||
# errors_ret[name] = self.loss_dict["loss_" + name ].detach().float().cpu() # float(...) works for both scalar tensor and float number
|
||||
errors_ret[name] = self.loss_dict["loss_" + name ].float().cpu() # float(...) works for both scalar tensor and float number
|
||||
|
||||
return errors_ret
|
||||
|
||||
def save_networks(self, epoch):
|
||||
"""Save all the networks to the disk.
|
||||
|
||||
Parameters:
|
||||
epoch (int) -- current epoch; used in the file name '%s_net_%s.pth' % (epoch, name)
|
||||
"""
|
||||
|
||||
# save parameters
|
||||
for name in self.names_model:
|
||||
|
||||
save_path = self.path_save.joinpath("checkpoints", f'{epoch}_net_{name}.pth')
|
||||
save_path.parent.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
net = getattr(self, 'net' + name)
|
||||
if isinstance(net, torch.nn.DataParallel):
|
||||
torch.save(net.module.state_dict(), save_path)
|
||||
else:
|
||||
torch.save(net.state_dict(), save_path)
|
||||
|
||||
# save training information
|
||||
save_path = self.path_save.joinpath("checkpoints", f'{epoch}_net_train_state.pth')
|
||||
save_path.parent.mkdir(parents=True, exist_ok=True)
|
||||
state = {
|
||||
"epoch": epoch,
|
||||
"losses":{},
|
||||
"optimizers": {},
|
||||
"schedulers": {}
|
||||
}
|
||||
|
||||
for name in self.names_model:
|
||||
optimizer_ = getattr(self, 'optimizer_' + name)
|
||||
scheduler_ = getattr(self, 'scheduler_' + name)
|
||||
state['optimizers']['optimizer_' + name] = optimizer_.state_dict()
|
||||
state['schedulers']['scheduler_' + name] = scheduler_.state_dict()
|
||||
|
||||
for name in self.names_loss:
|
||||
state["losses"][name] = self.loss_dict["loss_"+name]
|
||||
|
||||
torch.save(state, save_path)
|
||||
|
||||
|
||||
def load_networks(self, load_suffix, load_path, load_info=False):
|
||||
"""Load all the networks from the disk.
|
||||
"""
|
||||
|
||||
# load parameters
|
||||
for name in self.names_model:
|
||||
path_checkpoint = load_path.joinpath("checkpoints", f'{load_suffix}_net_{name}.pth')
|
||||
load_state = torch.load(str(path_checkpoint), map_location=str(self.device))
|
||||
|
||||
net = getattr(self, 'net' + name)
|
||||
|
||||
# net = net.module if isinstance(net, torch.nn.DataParallel) else net
|
||||
# mm = ["encoder_xt", "encoder_xp"]
|
||||
if isinstance(net, torch.nn.DataParallel):
|
||||
model_state = net.module.state_dict()
|
||||
|
||||
# state_dict = {}
|
||||
# for k,v in load_state.items():
|
||||
# if k in model_state.keys():
|
||||
# print(k, k.split("."))
|
||||
# if k.split(".")[0] not in mm:
|
||||
# state_dict[k] = v
|
||||
# state_dict = {k:v for k,v in load_state.items() if (k in model_state.keys() and k.split(".")[0] not in mm)}
|
||||
state_dict = {k:v for k,v in load_state.items() if (k in model_state.keys())}
|
||||
|
||||
# print(state_dict.keys())
|
||||
|
||||
model_state.update(state_dict)
|
||||
net.module.load_state_dict(model_state)
|
||||
|
||||
else:
|
||||
model_state = net.state_dict()
|
||||
# state_dict = {k:v for k,v in load_state.items() if (k in model_state.keys() and k.split(".")[0] not in mm)}
|
||||
state_dict = {k:v for k,v in load_state.items() if (k in model_state.keys())}
|
||||
|
||||
# print(state_dict.keys())
|
||||
|
||||
model_state.update(state_dict)
|
||||
net.load_state_dict(model_state)
|
||||
|
||||
self.logger.info('loading the model from %s' % path_checkpoint)
|
||||
|
||||
# net.module.set_actnorm_init(True) # set actnorm
|
||||
|
||||
if load_info:
|
||||
# load training state
|
||||
path_state = load_path.joinpath("checkpoints", f'{load_suffix}_net_train_state.pth')
|
||||
load_state = torch.load(str(path_state))
|
||||
|
||||
for name in self.names_model:
|
||||
optimizer_ = getattr(self, 'optimizer_' + name)
|
||||
scheduler_ = getattr(self, 'scheduler_' + name)
|
||||
optimizer_.load_state_dict(load_state['optimizers']['optimizer_' + name])
|
||||
scheduler_.load_state_dict(load_state['schedulers']['scheduler_' + name])
|
||||
|
||||
if self.opt.TRAIN.reset_lr:
|
||||
optimizer_.param_groups[0]['lr'] = self.opt.TRAIN.lr
|
||||
|
||||
def print_networks(self, verbose):
|
||||
"""Print the total number of parameters in the network and network architecture
|
||||
|
||||
Parameters:
|
||||
verbose (bool) -- if verbose: print the network architecture
|
||||
"""
|
||||
self.logger.info('---------- Networks initialized -------------')
|
||||
for name in self.names_model:
|
||||
net = getattr(self, 'net' + name)
|
||||
num_params = 0
|
||||
for param in net.parameters():
|
||||
num_params += param.numel()
|
||||
|
||||
if verbose:
|
||||
self.logger.info(net)
|
||||
|
||||
self.logger.info('[Network %s] Total number of parameters : %.3f M' % (name, num_params / 1e6))
|
||||
self.logger.info('-----------------------------------------------')
|
||||
|
||||
|
||||
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
|
||||
@@ -0,0 +1,319 @@
|
||||
import sys
|
||||
import numpy as np
|
||||
|
||||
import torch
|
||||
import torch.nn as nn
|
||||
from pathlib import Path
|
||||
|
||||
from src.models import init_net
|
||||
from src.models.base import Base
|
||||
from src.optims import get_optimizer, get_scheduler
|
||||
|
||||
# common
|
||||
from common.animation import save_animation_with_gt2, save_images_with_audio
|
||||
from common.debug import debug
|
||||
from common.losses import WingLoss
|
||||
|
||||
# disentangle model
|
||||
class Audio2motionModel(Base):
|
||||
|
||||
def __init__(self, opt, logger):
|
||||
Base.__init__(self, opt, logger)
|
||||
|
||||
self.opt = opt
|
||||
self.logger = logger
|
||||
self.names_model = ["G"] # G
|
||||
|
||||
|
||||
# define networks
|
||||
self.netG = define_netG(opt)
|
||||
self.netG.to()
|
||||
self.netG = torch.nn.DataParallel(self.netG, opt.GPUS) # multi-GPUs
|
||||
init_net(self.netG, init_type='kaiming', gpu_ids=opt.GPUS)
|
||||
|
||||
self.loss_func_l1 = nn.L1Loss(reduction="mean")
|
||||
self.loss_func_wing = WingLoss(reduction="mean")
|
||||
|
||||
if self.isTrain:
|
||||
self.names_loss = opt.LOSS.names
|
||||
|
||||
# define optimizers
|
||||
self.optimizer_G = get_optimizer(self.netG, opt)
|
||||
self.optimizers.append(self.optimizer_G)
|
||||
|
||||
self.scheduler_G = get_scheduler(self.optimizer_G, opt)
|
||||
self.schedulers.append(self.scheduler_G)
|
||||
|
||||
if self.opt.TRAIN.apply_testing or not self.isTrain:
|
||||
# load mean lighting & shape
|
||||
self.netR = define_netR(device=self.device)
|
||||
# self.netG.init_reconstruct_model(self.netR)
|
||||
|
||||
path_deca_mean = Path("./data/DECA_obama_mean.npy")
|
||||
self.mean_dict = np.load(path_deca_mean, allow_pickle=True).item()
|
||||
print(self.mean_dict.keys())
|
||||
|
||||
|
||||
def set_input(self, batch_input):
|
||||
|
||||
self.data = batch_input["data"].float().to(self.device) # (nsteps, dim_data)
|
||||
self.cond = batch_input["cond"].float().to(self.device) # (nsteps, dim_cond)
|
||||
|
||||
self.B = self.data.size(0)
|
||||
debug(self.opt, f"data = {self.data.shape}, cond = {self.cond.shape}, dtype={self.data.dtype}", verbose=False)
|
||||
|
||||
|
||||
def training(self, batch_input):
|
||||
self.train() # set train model
|
||||
self.set_input(batch_input)
|
||||
|
||||
# forward
|
||||
self.pred = self.netG(self.cond)
|
||||
|
||||
# loss
|
||||
loss, self.loss_dict = self.eval_losses(self.pred, self.data)
|
||||
|
||||
# backward
|
||||
self.optimizer_G.zero_grad()
|
||||
loss.backward()
|
||||
|
||||
if self.opt.TRAIN.grad_clip_norm: # operate grad
|
||||
torch.nn.utils.clip_grad_value_(self.netG.parameters(), self.opt.TRAIN.max_grad_clip)
|
||||
torch.nn.utils.clip_grad_norm_(self.netG.parameters(), self.opt.TRAIN.max_grad_norm)
|
||||
|
||||
self.optimizer_G.step()
|
||||
|
||||
return loss
|
||||
|
||||
|
||||
def validation(self, batch_input):
|
||||
self.eval() # set eval model
|
||||
self.set_input(batch_input)
|
||||
|
||||
with torch.no_grad():
|
||||
self.pred = self.netG(self.cond)
|
||||
loss, self.loss_dict = self.eval_losses(self.pred, self.data)
|
||||
|
||||
return loss
|
||||
|
||||
def infer(self, batch_cond, path_audio, suffix=""):
|
||||
self.eval()
|
||||
self.cond = batch_cond.float().to(self.device) # (nsteps, dim_cond)
|
||||
|
||||
with torch.no_grad():
|
||||
samples_pt = self.netG(self.cond).cpu().numpy() # B x N x dim_motion
|
||||
print(f"testing pt shape = {samples_pt.shape}")
|
||||
|
||||
self.save_reconstruct(samples_pt, path_audio,
|
||||
path_save=Path(self.opt.OUTPUT_DIR),
|
||||
suffix=suffix)
|
||||
|
||||
|
||||
def testing(self, batch_input, cur_epoch=0, cur_batch=0):
|
||||
self.eval() # set eval model
|
||||
self.set_input(batch_input)
|
||||
|
||||
with torch.no_grad():
|
||||
samples_pt = self.netG(self.cond).cpu().numpy() # B x N x dim_motion
|
||||
samples_gt = self.data.cpu().numpy() # B x N x dim_motion
|
||||
|
||||
print(f"testing pt shape = {samples_pt.shape}, gt shape = {samples_gt.shape}")
|
||||
|
||||
self.save_reconstruct_with_gt(samples_pt, samples_gt,
|
||||
path_save=Path(self.opt.OUTPUT_DIR),
|
||||
suffix=f'sampled_{cur_epoch:05d}_{cur_batch:03d}')
|
||||
|
||||
|
||||
def eval_losses(self, batch_pdt, batch_tgt):
|
||||
""" Computes the VAE loss function.
|
||||
pramas:
|
||||
batch_pred, (nbatch, seqlen, dim_motion)
|
||||
batch_targt, (nbatch, seqlen, dim_motion)
|
||||
"""
|
||||
loss = 0
|
||||
loss_dict = {}
|
||||
|
||||
# rec loss
|
||||
loss_rec = self.loss_func_wing(batch_pdt, batch_tgt)
|
||||
loss = loss_rec * self.opt.LOSS.lambda_rec
|
||||
loss_dict["loss_rec"] = loss_rec.detach()
|
||||
loss_dict["loss_rec_l1"] = self.loss_func_l1(batch_pdt, batch_tgt).detach()
|
||||
|
||||
# rec smooth
|
||||
diff_pdt = batch_pdt[:, 1:, :] - batch_pdt[:, :-1, :]
|
||||
diff_tgt = batch_tgt[:, 1:, :] - batch_tgt[:, :-1, :]
|
||||
loss_rec_smooth = self.loss_func_wing(diff_pdt, diff_tgt)
|
||||
loss += loss_rec_smooth * self.opt.LOSS.lambda_rec_smooth
|
||||
|
||||
loss_dict["loss_rec_smooth"] = loss_rec_smooth.detach()
|
||||
loss_dict["loss_rec_smooth_l1"] = self.loss_func_l1(diff_pdt, diff_tgt).detach()
|
||||
|
||||
# total loss
|
||||
loss_dict['loss_all'] = loss.detach()
|
||||
|
||||
return loss, loss_dict
|
||||
|
||||
|
||||
def save_reconstruct(self, samples_pt, path_audio, path_save, suffix=""):
|
||||
# samples_pt, [B x N x dim_motion]
|
||||
|
||||
B, N, _ = samples_pt.shape
|
||||
nbatch_render = 10
|
||||
|
||||
# for each batch
|
||||
for j in range(B):
|
||||
jcoeff_pt = samples_pt[j, :, :]
|
||||
jpath_save = path_save.joinpath(f"{suffix}_{j:02d}.mp4")
|
||||
|
||||
v_render_pt = []
|
||||
for k in range(0, N, nbatch_render):
|
||||
jcodedict_pt = {}
|
||||
|
||||
jcodedict_pt["exp"] = jcoeff_pt[k:k+nbatch_render, :50] # (nbatch_render, 50)
|
||||
nbatch_real = jcodedict_pt["exp"].shape[0]
|
||||
|
||||
# pose
|
||||
jcodedict_pt["pose"] = np.repeat([self.mean_dict["pose"]], nbatch_real, axis=0) # (nbatch_render, 6)
|
||||
jcodedict_pt["pose"][:, 3:6] = jcoeff_pt[k:k+nbatch_render, 50:53]
|
||||
|
||||
# others ==> to mean
|
||||
mean_cam = [[5,0,0]] # or [self.mean_dict["cam"]]
|
||||
jcodedict_pt["cam"] = np.repeat(mean_cam, nbatch_real, axis=0) # (nbatch_render, 3)
|
||||
jcodedict_pt["light"] = np.repeat([self.mean_dict["light"]], nbatch_real, axis=0) # (nbatch_render, 9, 3)
|
||||
jcodedict_pt["shape"] = np.repeat([self.mean_dict["shape"]], nbatch_real, axis=0) # (nbatch_render, 100)
|
||||
jcodedict_pt["detail"] = np.repeat([self.mean_dict["detail"]], nbatch_real, axis=0) # (nbatch_render, 128)
|
||||
|
||||
_, visdict_pt = self.netR.decode_one(jcodedict_pt, nbatch_real, self.device)
|
||||
|
||||
render_pt = visdict_pt["shape_images"] # (nbatch_render, 3, 224, 224)
|
||||
# print(f"render pt shape = {render_pt.shape}")
|
||||
|
||||
for m in range(nbatch_real):
|
||||
# cv2.imwrite(str(kpath_image), util.tensor2image(render_image[m, ...]))
|
||||
v_render_pt.append(tensor2image(render_pt[m, ...]))
|
||||
|
||||
# save animation
|
||||
# print(f"testing v_render_pt = {len(v_render_pt)}")
|
||||
save_images_with_audio(v_render_pt, path_audio, jpath_save)
|
||||
|
||||
|
||||
|
||||
def save_reconstruct_with_gt(self, samples_pt, samples_gt, path_save, suffix=""):
|
||||
# samples_pt, [B x N x dim_motion]
|
||||
# samples_gt, [B x N x dim_motion]
|
||||
B, N, _ = samples_pt.shape
|
||||
nbatch_render = 10
|
||||
|
||||
# for each batch
|
||||
for j in range(B):
|
||||
jcoeff_pt = samples_pt[j, :, :]
|
||||
jcoeff_gt = samples_gt[j, :, :]
|
||||
jpath_save = path_save.joinpath(f"{suffix}_{j:02d}.mp4")
|
||||
|
||||
v_render_pt = []
|
||||
v_render_gt = []
|
||||
|
||||
for k in range(0, N, nbatch_render):
|
||||
jcodedict_pt = {}
|
||||
jcodedict_gt = {}
|
||||
|
||||
# exp
|
||||
jcodedict_pt["exp"] = jcoeff_pt[k:k+nbatch_render, :50] # (nbatch_render, 50)
|
||||
jcodedict_gt["exp"] = jcoeff_gt[k:k+nbatch_render, :50] # (nbatch_render, 50)
|
||||
nbatch_real = jcodedict_pt["exp"].shape[0]
|
||||
|
||||
# pose
|
||||
jcodedict_pt["pose"] = np.repeat([self.mean_dict["pose"]], nbatch_real, axis=0) # (nbatch_render, 6)
|
||||
jcodedict_gt["pose"] = np.repeat([self.mean_dict["pose"]], nbatch_real, axis=0) # (nbatch_render, 6)
|
||||
jcodedict_pt["pose"][:, 3:6] = jcoeff_pt[k:k+nbatch_render, 50:53]
|
||||
jcodedict_gt["pose"][:, 3:6] = jcoeff_gt[k:k+nbatch_render, 50:53]
|
||||
|
||||
# others ==> to mean
|
||||
mean_cam = [[5,0,0]] # or [self.mean_dict["cam"]]
|
||||
jcodedict_pt["cam"] = np.repeat(mean_cam, nbatch_real, axis=0) # (nbatch_render, 3)
|
||||
jcodedict_pt["light"] = np.repeat([self.mean_dict["light"]], nbatch_real, axis=0) # (nbatch_render, 9, 3)
|
||||
jcodedict_pt["shape"] = np.repeat([self.mean_dict["shape"]], nbatch_real, axis=0) # (nbatch_render, 100)
|
||||
jcodedict_pt["detail"] = np.repeat([self.mean_dict["detail"]], nbatch_real, axis=0) # (nbatch_render, 128)
|
||||
|
||||
jcodedict_gt["cam"] = np.repeat(mean_cam, nbatch_real, axis=0) # (nbatch_render, 3)
|
||||
jcodedict_gt["light"] = np.repeat([self.mean_dict["light"]], nbatch_real, axis=0) # (nbatch_render, 9, 3)
|
||||
jcodedict_gt["shape"] = np.repeat([self.mean_dict["shape"]], nbatch_real, axis=0) # (nbatch_render, 100)
|
||||
jcodedict_gt["detail"] = np.repeat([self.mean_dict["detail"]], nbatch_real, axis=0) # (nbatch_render, 128)
|
||||
|
||||
_, visdict_pt = self.netR.decode_one(jcodedict_pt, nbatch_real, self.device)
|
||||
_, visdict_gt = self.netR.decode_one(jcodedict_gt, nbatch_real, self.device)
|
||||
|
||||
render_pt = visdict_pt["shape_images"] # (nbatch_render, 3, 224, 224)
|
||||
render_gt = visdict_gt["shape_images"] # (nbatch_render, 3, 224, 224)
|
||||
# print(f"render pt shape = {render_pt.shape}, gt {render_gt.shape}")
|
||||
|
||||
for m in range(nbatch_real):
|
||||
# cv2.imwrite(str(kpath_image), util.tensor2image(render_image[m, ...]))
|
||||
v_render_pt.append(tensor2image(render_pt[m, ...]))
|
||||
v_render_gt.append(tensor2image(render_gt[m, ...]))
|
||||
|
||||
# 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, jpath_save)
|
||||
|
||||
|
||||
|
||||
#########################################
|
||||
def tensor2image(tensor):
|
||||
image = tensor.detach().cpu().numpy()
|
||||
image = image*255.
|
||||
image = np.maximum(np.minimum(image, 255), 0)
|
||||
image = image.transpose(1,2,0)[:,:,[2,1,0]]
|
||||
return image.astype(np.uint8).copy()
|
||||
|
||||
|
||||
def define_netG(opt):
|
||||
netG = None
|
||||
|
||||
if opt.MODEL.name_netG == "audio2motion_conv_lstm":
|
||||
from src.nn.audio2motion_conv_lstm import Audio2MotionConvLSTM
|
||||
netG = Audio2MotionConvLSTM(opt)
|
||||
|
||||
elif opt.MODEL.name_netG == "audio2motion_voca":
|
||||
from src.nn.audio2motion_voca import Audio2MotionVOCA
|
||||
netG = Audio2MotionVOCA(opt)
|
||||
|
||||
elif opt.MODEL.name_netG == "audio2motion_voca2":
|
||||
from src.nn.audio2motion_voca2 import Audio2MotionVOCA2
|
||||
netG = Audio2MotionVOCA2(opt)
|
||||
|
||||
elif opt.MODEL.name_netG == "audio2motion_conv":
|
||||
from src.nn.audio2motion_conv import Audio2MotionConv
|
||||
netG = Audio2MotionConv(opt)
|
||||
|
||||
elif opt.MODEL.name_netG == "audio2motion":
|
||||
from src.nn.audio2motion import Audio2Motion
|
||||
netG = Audio2Motion(opt)
|
||||
|
||||
else:
|
||||
raise NameError(f"The model of opt.MODEL.name_netAE(={opt.MODEL.name_netG}) not existing!")
|
||||
|
||||
|
||||
return netG
|
||||
|
||||
|
||||
def define_netR(device):
|
||||
# import
|
||||
sys.path.insert(0, "/ssdata1/lsen/CODE/DECA_old")
|
||||
from decalib.deca import DECA
|
||||
from decalib.utils import util
|
||||
from decalib.utils.config import cfg as deca_cfg
|
||||
|
||||
# use device
|
||||
# device = "cuda:2"
|
||||
# whether to use FLAME texture model to generate uv texture map
|
||||
deca_cfg.model.use_tex = False
|
||||
deca_cfg.dataset.image_size = 512
|
||||
|
||||
# reconstruction model
|
||||
netR = DECA(config = deca_cfg, device=device)
|
||||
|
||||
return netR
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,352 @@
|
||||
import sys
|
||||
import numpy as np
|
||||
import tqdm
|
||||
|
||||
import torch
|
||||
import torch.nn as nn
|
||||
from pathlib import Path
|
||||
from collections import OrderedDict
|
||||
|
||||
from src.models import init_net
|
||||
from src.models.base import Base
|
||||
from src.optims import get_optimizer, get_scheduler
|
||||
|
||||
# common
|
||||
from common.animation import save_animation_with_gt2
|
||||
from common.debug import debug
|
||||
from common.losses import WingLoss
|
||||
|
||||
# disentangle model
|
||||
class Audio2motionRModel(Base):
|
||||
|
||||
def __init__(self, opt, logger):
|
||||
Base.__init__(self, opt, logger)
|
||||
|
||||
self.opt = opt
|
||||
self.logger = logger
|
||||
self.names_model = ["G"] # G
|
||||
|
||||
self.nseqR_m = opt.MODEL.n_lookprevs_motion # 3
|
||||
self.nseqR_s = opt.MODEL.n_lookprevs_speech # 3
|
||||
self.nseqL_s = opt.MODEL.n_lookahead_speech # 1
|
||||
|
||||
self.nc_motion = opt.MODEL.dim_motion # 53
|
||||
self.nc_speech = opt.MODEL.dim_speech # 27
|
||||
self.nc_condit = self.nc_motion * self.nseqR_m + self.nc_speech * (self.nseqR_s + 1 + self.nseqL_s)
|
||||
print(f"nc_condit={self.nc_condit}")
|
||||
|
||||
|
||||
# define networks
|
||||
self.netG = define_netG(opt)
|
||||
self.netG.to()
|
||||
self.netG = torch.nn.DataParallel(self.netG, opt.GPUS) # multi-GPUs
|
||||
init_net(self.netG, init_type='kaiming', gpu_ids=opt.GPUS)
|
||||
|
||||
self.loss_func_l1 = nn.L1Loss(reduction="mean")
|
||||
self.loss_func_wing = WingLoss(reduction="mean")
|
||||
|
||||
if self.isTrain:
|
||||
self.names_loss = opt.LOSS.names
|
||||
|
||||
# define optimizers
|
||||
self.optimizer_G = get_optimizer(self.netG, opt)
|
||||
self.optimizers.append(self.optimizer_G)
|
||||
|
||||
self.scheduler_G = get_scheduler(self.optimizer_G, opt)
|
||||
self.schedulers.append(self.scheduler_G)
|
||||
|
||||
if self.opt.TRAIN.apply_testing or not self.isTrain:
|
||||
# load mean lighting & shape
|
||||
self.netR = define_netR(device=self.device)
|
||||
# self.netG.init_reconstruct_model(self.netR)
|
||||
|
||||
path_deca_mean = Path("./data/DECA_obama_mean.npy")
|
||||
self.mean_dict = np.load(path_deca_mean, allow_pickle=True).item()
|
||||
print(self.mean_dict.keys())
|
||||
|
||||
|
||||
def set_input(self, batch_input):
|
||||
self.motion = batch_input["motion"].float().to(self.device) # (B, nstep, nc_motion)
|
||||
self.speech = batch_input["speech"].float().to(self.device) # (B, nstep, nc_speech)
|
||||
|
||||
self.B = self.motion.size(0)
|
||||
debug(self.opt, f"motion = {self.motion.shape}, speech = {self.speech.shape}, dtype={self.speech.dtype}", verbose=False)
|
||||
|
||||
|
||||
def training(self, batch_input):
|
||||
self.train() # set train model
|
||||
self.set_input(batch_input)
|
||||
|
||||
# motion
|
||||
# prepare data motion: nc_motion
|
||||
# prepare data condition: nseqR_m * nc_motion + (nseqR_s + 1 + nseqL_s) * nc_speech
|
||||
nstep = self.speech.shape[1]
|
||||
wsize = self.nseqR_s + 1 + self.nseqL_s
|
||||
nstep_new = nstep - self.nseqR_s - self.nseqL_s # nstep - wsize + 1
|
||||
|
||||
# unfold speech
|
||||
condit_s = self.speech.unfold(dimension=1, size=wsize, step=1) # (B, nwind_new, nc_speech, wsize)
|
||||
condit_s = condit_s.swapaxes_(3,2) # (B, nwind_new, wsize, nc_speech)
|
||||
condit_s = condit_s.reshape(self.B, nstep_new, -1) # (B, nwind_new, wsize * nc_speech)
|
||||
assert condit_s.shape[2] == wsize * self.nc_speech
|
||||
|
||||
# unfold motion
|
||||
condit_m = self.motion[:, self.nseqR_s-self.nseqR_m:, : ] # used when nseqR_m < nseqR_s
|
||||
condit_m = condit_m.unfold(dimension=1, size=self.nseqR_m, step=1) # (nwind - self.nseqR +1, nc_motion, wsize)
|
||||
condit_m = condit_m.swapaxes_(3,2) # (nwind_new, wsize, nc_speech)
|
||||
condit_m = condit_m.reshape(self.B, -1, self.nseqR_m * self.nc_motion) # (nwind - self.nseqR +1, self.nseqR * self.nc_motion)
|
||||
condit_m = condit_m[:, :nstep_new, ...] # (B, nstep_new, nc_motion * wsize), alignment
|
||||
assert condit_m.shape[2] == self.nseqR_m * self.nc_motion
|
||||
|
||||
# concate
|
||||
self.cond = torch.concat([condit_s, condit_m], dim=2)
|
||||
self.data = self.motion[:, self.nseqR_s:self.nseqR_s + nstep_new, :]
|
||||
assert self.cond.shape[1] == self.data.shape[1]
|
||||
assert self.cond.shape[2] == self.nc_condit
|
||||
|
||||
# forward
|
||||
self.pred = self.netG(self.cond)
|
||||
|
||||
# loss
|
||||
loss, self.loss_dict = self.eval_losses(self.pred, self.data)
|
||||
|
||||
# backward
|
||||
self.optimizer_G.zero_grad()
|
||||
loss.backward()
|
||||
|
||||
if self.opt.TRAIN.grad_clip_norm: # operate grad
|
||||
torch.nn.utils.clip_grad_value_(self.netG.parameters(), self.opt.TRAIN.max_grad_clip)
|
||||
torch.nn.utils.clip_grad_norm_(self.netG.parameters(), self.opt.TRAIN.max_grad_norm)
|
||||
|
||||
self.optimizer_G.step()
|
||||
|
||||
return loss
|
||||
|
||||
def validation(self, batch_input):
|
||||
self.eval() # set eval model
|
||||
self.set_input(batch_input)
|
||||
|
||||
# motion
|
||||
# prepare data motion: nc_motion
|
||||
# prepare data condition: nseqR_m * nc_motion + (nseqR_s + 1 + nseqL_s) * nc_speech
|
||||
nstep = self.speech.shape[1]
|
||||
wsize = self.nseqR_s + 1 + self.nseqL_s
|
||||
nstep_new = nstep - self.nseqR_s - self.nseqL_s # nstep - wsize + 1
|
||||
|
||||
# unfold speech
|
||||
condit_s = self.speech.unfold(dimension=1, size=wsize, step=1) # (B, nwind_new, nc_speech, wsize)
|
||||
condit_s = condit_s.swapaxes_(3,2) # (B, nwind_new, wsize, nc_speech)
|
||||
condit_s = condit_s.reshape(self.B, nstep_new, -1) # (B, nwind_new, wsize * nc_speech)
|
||||
assert condit_s.shape[2] == wsize * self.nc_speech
|
||||
|
||||
# unfold motion
|
||||
condit_m = self.motion[:, self.nseqR_s-self.nseqR_m:, : ] # used when nseqR_m < nseqR_s
|
||||
condit_m = condit_m.unfold(dimension=1, size=self.nseqR_m, step=1) # (nwind - self.nseqR +1, nc_motion, wsize)
|
||||
condit_m = condit_m.swapaxes_(3,2) # (nwind_new, wsize, nc_speech)
|
||||
condit_m = condit_m.reshape(self.B, -1, self.nseqR_m * self.nc_motion) # (nwind - self.nseqR +1, self.nseqR * self.nc_motion)
|
||||
condit_m = condit_m[:, :nstep_new, ...] # (B, nstep_new, nc_motion * wsize), alignment
|
||||
assert condit_m.shape[2] == self.nseqR_m * self.nc_motion
|
||||
|
||||
# concate
|
||||
self.cond = torch.concat([condit_s, condit_m], dim=2)
|
||||
self.data = self.motion[:, self.nseqR_s:self.nseqR_s + nstep_new, :]
|
||||
assert self.cond.shape[1] == self.data.shape[1]
|
||||
assert self.cond.shape[2] == self.nc_condit
|
||||
|
||||
with torch.no_grad():
|
||||
self.pred = self.netG(self.cond)
|
||||
|
||||
loss, self.loss_dict = self.eval_losses(self.pred, self.data)
|
||||
|
||||
return loss
|
||||
|
||||
|
||||
|
||||
def testing(self, batch_input, cur_epoch=0, cur_batch=0):
|
||||
self.eval() # set eval model
|
||||
self.set_input(batch_input)
|
||||
|
||||
# prepare data motion: nc_motion
|
||||
# prepare data condition: nseqR_m * nc_motion + (nseqR_s + 1 + nseqL_s) * nc_speech
|
||||
nstep = self.speech.shape[1]
|
||||
wsize = self.nseqR_s + 1 + self.nseqL_s
|
||||
nstep_new = nstep - self.nseqR_s - self.nseqL_s # nstep - wsize + 1
|
||||
|
||||
# unfold speech
|
||||
condit_s = self.speech.unfold(dimension=1, size=wsize, step=1) # (B, nwind_new, nc_speech, wsize)
|
||||
condit_s = condit_s.swapaxes_(3,2) # (B, nwind_new, wsize, nc_speech)
|
||||
condit_s = condit_s.reshape(self.B, nstep_new, -1) # (B, nwind_new, wsize * nc_speech)
|
||||
assert condit_s.shape[2] == wsize * self.nc_speech
|
||||
|
||||
|
||||
with torch.no_grad():
|
||||
|
||||
motion_pt = torch.zeros_like(self.motion) # B x nstep x nc_motion
|
||||
motion_pt[:, :self.nseqR_s, :] = self.motion[:, :self.nseqR_s, :] # copy first window frame
|
||||
motion_pt[:, -self.nseqL_s:, :] = self.motion[:, -self.nseqL_s:, :] # copy last window frame
|
||||
|
||||
for istep in range(nstep_new): # nstep
|
||||
# unfold motion
|
||||
condit_m = motion_pt[:, self.nseqR_s-self.nseqR_m:, : ] # used when nseqR_m < nseqR_s
|
||||
condit_m = condit_m.unfold(dimension=1, size=self.nseqR_m, step=1) # (nwind - self.nseqR +1, nc_motion, wsize)
|
||||
condit_m = condit_m.swapaxes_(3,2) # (nwind_new, wsize, nc_speech)
|
||||
condit_m = condit_m.reshape(self.B, -1, self.nseqR_m * self.nc_motion) # (nwind - self.nseqR +1, self.nseqR * self.nc_motion)
|
||||
condit_m = condit_m[:, :nstep_new, ...] # (B, nstep_new, nc_motion * wsize), alignment
|
||||
|
||||
# concate
|
||||
condit = torch.concat([condit_s, condit_m], dim=2)
|
||||
|
||||
pred = self.netG(condit) # (B, nstep, nc_motion)
|
||||
|
||||
# collection the predict motion
|
||||
motion_pt[:, self.nseqR_s+istep, :] = pred[:, istep, :] # append the last predict data
|
||||
|
||||
# convet to cpu & numpy
|
||||
motion_gt = self.motion.cpu().numpy()
|
||||
motion_pt = motion_pt.cpu().numpy()
|
||||
|
||||
# Trim head and last
|
||||
motion_gt = motion_gt[:,self.nseqR_s:-self.nseqL_s, :] # trim
|
||||
motion_pt = motion_pt[:,self.nseqR_s:-self.nseqL_s, :] # trim
|
||||
|
||||
self.save_reconstruct_with_gt(motion_pt, motion_gt,
|
||||
path_save=Path(self.opt.OUTPUT_DIR),
|
||||
suffix=f'sampled_{cur_epoch:05d}_{cur_batch:03d}')
|
||||
|
||||
|
||||
def eval_losses(self, batch_pdt, batch_tgt):
|
||||
""" Computes the VAE loss function.
|
||||
pramas:
|
||||
batch_pred, (nbatch, seqlen, nc_motion)
|
||||
batch_targt, (nbatch, seqlen, nc_motion)
|
||||
"""
|
||||
loss = 0
|
||||
loss_dict = {}
|
||||
|
||||
# rec loss
|
||||
loss_rec = self.loss_func_wing(batch_pdt, batch_tgt)
|
||||
loss = loss_rec * self.opt.LOSS.lambda_rec
|
||||
loss_dict["loss_rec"] = loss_rec.detach()
|
||||
loss_dict["loss_rec_l1"] = self.loss_func_l1(batch_pdt, batch_tgt).detach()
|
||||
|
||||
# rec smooth
|
||||
diff_pdt = batch_pdt[:, 1:, :] - batch_pdt[:, :-1, :]
|
||||
diff_tgt = batch_tgt[:, 1:, :] - batch_tgt[:, :-1, :]
|
||||
loss_rec_smooth = self.loss_func_wing(diff_pdt, diff_tgt)
|
||||
loss += loss_rec_smooth * self.opt.LOSS.lambda_rec_smooth
|
||||
|
||||
loss_dict["loss_rec_smooth"] = loss_rec_smooth.detach()
|
||||
loss_dict["loss_rec_smooth_l1"] = self.loss_func_l1(diff_pdt, diff_tgt).detach()
|
||||
|
||||
# total loss
|
||||
loss_dict['loss_all'] = loss.detach()
|
||||
|
||||
return loss, loss_dict
|
||||
|
||||
def save_reconstruct_with_gt(self, samples_pt, samples_gt, path_save, suffix=""):
|
||||
# samples_pt, [B x N x nc_motion]
|
||||
# samples_gt, [B x N x nc_motion]
|
||||
B, N, _ = samples_pt.shape
|
||||
nbatch_render = 10
|
||||
|
||||
# for each batch
|
||||
for j in range(B):
|
||||
jcoeff_pt = samples_pt[j, :, :]
|
||||
jcoeff_gt = samples_gt[j, :, :]
|
||||
jpath_save = path_save.joinpath(f"{suffix}_{j:02d}.mp4")
|
||||
|
||||
v_render_pt = []
|
||||
v_render_gt = []
|
||||
|
||||
for k in range(0, N, nbatch_render):
|
||||
jcodedict_pt = {}
|
||||
jcodedict_gt = {}
|
||||
|
||||
# exp
|
||||
jcodedict_pt["exp"] = jcoeff_pt[k:k+nbatch_render, :50] # (nbatch_render, 50)
|
||||
jcodedict_gt["exp"] = jcoeff_gt[k:k+nbatch_render, :50] # (nbatch_render, 50)
|
||||
nbatch_real = jcodedict_pt["exp"].shape[0]
|
||||
|
||||
# pose
|
||||
jcodedict_pt["pose"] = np.repeat([self.mean_dict["pose"]], nbatch_real, axis=0) # (nbatch_render, 6)
|
||||
jcodedict_gt["pose"] = np.repeat([self.mean_dict["pose"]], nbatch_real, axis=0) # (nbatch_render, 6)
|
||||
jcodedict_pt["pose"][:, 3:6] = jcoeff_pt[k:k+nbatch_render, 50:53]
|
||||
jcodedict_gt["pose"][:, 3:6] = jcoeff_gt[k:k+nbatch_render, 50:53]
|
||||
|
||||
# others ==> to mean
|
||||
mean_cam = [[5,0,0]] # or [self.mean_dict["cam"]]
|
||||
jcodedict_pt["cam"] = np.repeat(mean_cam, nbatch_real, axis=0) # (nbatch_render, 3)
|
||||
jcodedict_pt["light"] = np.repeat([self.mean_dict["light"]], nbatch_real, axis=0) # (nbatch_render, 9, 3)
|
||||
jcodedict_pt["shape"] = np.repeat([self.mean_dict["shape"]], nbatch_real, axis=0) # (nbatch_render, 100)
|
||||
jcodedict_pt["detail"] = np.repeat([self.mean_dict["detail"]], nbatch_real, axis=0) # (nbatch_render, 128)
|
||||
|
||||
jcodedict_gt["cam"] = np.repeat(mean_cam, nbatch_real, axis=0) # (nbatch_render, 3)
|
||||
jcodedict_gt["light"] = np.repeat([self.mean_dict["light"]], nbatch_real, axis=0) # (nbatch_render, 9, 3)
|
||||
jcodedict_gt["shape"] = np.repeat([self.mean_dict["shape"]], nbatch_real, axis=0) # (nbatch_render, 100)
|
||||
jcodedict_gt["detail"] = np.repeat([self.mean_dict["detail"]], nbatch_real, axis=0) # (nbatch_render, 128)
|
||||
|
||||
_, visdict_pt = self.netR.decode_one(jcodedict_pt, nbatch_real, self.device)
|
||||
_, visdict_gt = self.netR.decode_one(jcodedict_gt, nbatch_real, self.device)
|
||||
|
||||
render_pt = visdict_pt["shape_images"] # (nbatch_render, 3, 224, 224)
|
||||
render_gt = visdict_gt["shape_images"] # (nbatch_render, 3, 224, 224)
|
||||
# print("render image shape = ", render_image.shape)
|
||||
|
||||
|
||||
for m in range(nbatch_real):
|
||||
# cv2.imwrite(str(kpath_image), util.tensor2image(render_image[m, ...]))
|
||||
v_render_pt.append(tensor2image(render_pt[m, ...]))
|
||||
v_render_gt.append(tensor2image(render_gt[m, ...]))
|
||||
|
||||
# save animation
|
||||
save_animation_with_gt2(v_render_pt, v_render_gt, jpath_save)
|
||||
|
||||
|
||||
|
||||
#########################################
|
||||
def tensor2image(tensor):
|
||||
image = tensor.detach().cpu().numpy()
|
||||
image = image*255.
|
||||
image = np.maximum(np.minimum(image, 255), 0)
|
||||
image = image.transpose(1,2,0)[:,:,[2,1,0]]
|
||||
|
||||
return image.astype(np.uint8).copy()
|
||||
|
||||
|
||||
def define_netG(opt):
|
||||
netG = None
|
||||
|
||||
if opt.MODEL.name_netG == "audio2motionW":
|
||||
from src.nn.audio2motionW import Audio2MotionW
|
||||
netG = Audio2MotionW(opt)
|
||||
|
||||
elif opt.MODEL.name_netG == "audio2motion":
|
||||
from src.nn.audio2motion import Audio2Motion
|
||||
netG = Audio2Motion(opt)
|
||||
else:
|
||||
raise NameError(f"The model of opt.MODEL.({opt.MODEL.name_netG}) not existing!")
|
||||
|
||||
|
||||
return netG
|
||||
|
||||
|
||||
def define_netR(device):
|
||||
# import
|
||||
sys.path.insert(0, "/ssdata1/lsen/CODE/DECA_old")
|
||||
from decalib.deca import DECA
|
||||
from decalib.utils import util
|
||||
from decalib.utils.config import cfg as deca_cfg
|
||||
|
||||
# use device
|
||||
# device = "cuda:2"
|
||||
# whether to use FLAME texture model to generate uv texture map
|
||||
deca_cfg.model.use_tex = False
|
||||
deca_cfg.dataset.image_size = 512
|
||||
|
||||
# reconstruction model
|
||||
netR = DECA(config = deca_cfg, device=device)
|
||||
|
||||
return netR
|
||||
|
||||
|
||||
|
||||
Reference in new issue
Block a user