initial commit
This commit is contained in:
commit
c7175dd7ff
127 files changed
+13949
No files matched your search
Whitespace-only changes.
+310
@@ -0,0 +1,310 @@
|
||||
import os
|
||||
import yaml
|
||||
|
||||
import numpy as np
|
||||
from easydict import EasyDict as edict
|
||||
|
||||
config = edict()
|
||||
|
||||
config.OUTPUT_DIR = ''
|
||||
config.LOG_DIR = ''
|
||||
config.LOG_PREFIX = ''
|
||||
config.GPUS = '1'
|
||||
config.WORKERS = 8
|
||||
config.DEBUG = False
|
||||
|
||||
# pxxxx
|
||||
config.isTrain = True
|
||||
config.preprocess = ''
|
||||
config.verbose = True
|
||||
|
||||
# frequence
|
||||
config.FREQ = edict()
|
||||
config.FREQ.batch_save = 20
|
||||
config.FREQ.batch_print = 1
|
||||
config.FREQ.batch_display = 100
|
||||
config.FREQ.batch_test = 100000
|
||||
|
||||
config.FREQ.epoch_save = 1
|
||||
config.FREQ.epoch_print = 1
|
||||
config.FREQ.epoch_display = 10
|
||||
config.FREQ.epoch_valid = 1
|
||||
config.FREQ.epoch_test = 1
|
||||
|
||||
config.FREQ.update_html = 1
|
||||
|
||||
|
||||
# visual
|
||||
config.VISUAL = edict()
|
||||
config.VISUAL.use_HTML = True
|
||||
config.VISUAL.use_visdom = True
|
||||
|
||||
config.VISUAL.vsdm_id = 0
|
||||
config.VISUAL.vsdm_wsize = 256
|
||||
config.VISUAL.vsdm_port = 8098
|
||||
config.VISUAL.vsdm_ncol = 3
|
||||
config.VISUAL.vsdm_server = "http://localhost"
|
||||
config.VISUAL.vsdm_env = "main-2"
|
||||
|
||||
# cudnn related params
|
||||
config.CUDNN = edict()
|
||||
config.CUDNN.benchmark = True
|
||||
config.CUDNN.deterministic = True
|
||||
config.CUDNN.enable = True
|
||||
|
||||
|
||||
##########################
|
||||
# model related params
|
||||
config.MODEL = edict()
|
||||
config.MODEL.name = "LandmarkAE"
|
||||
config.MODEL.name_netG = "MLP"
|
||||
config.MODEL.dropout = 0.1
|
||||
|
||||
# load & init model
|
||||
config.MODEL.pretrain = False
|
||||
config.MODEL.path_pretrained = ""
|
||||
config.MODEL.path_checkpoint = ""
|
||||
config.MODEL.load_epoch = 0
|
||||
|
||||
# for MOGLOW
|
||||
config.MODEL.dim_motion = 0
|
||||
config.MODEL.dim_speech = 0
|
||||
config.MODEL.dim_hidden = 0
|
||||
|
||||
config.MODEL.n_lookprevs_motion = 3
|
||||
config.MODEL.n_lookprevs_speech = 3
|
||||
|
||||
config.MODEL.n_lookahead_motion = 7
|
||||
config.MODEL.n_lookahead_speech = 7
|
||||
|
||||
config.MODEL.n_layer_lstm = 2
|
||||
|
||||
|
||||
# # for wavenet
|
||||
# config.MODEL.n_early_every = 0
|
||||
# config.MODEL.n_early_size = 0
|
||||
# config.MODEL.n_layer_wave = 0
|
||||
# config.MODEL.kernel_size = 0
|
||||
|
||||
# # for transformer
|
||||
# config.MODEL.n_src_vocab = 0
|
||||
# config.MODEL.n_tgt_vocab = 0
|
||||
# config.MODEL.src_pad_idx = 0
|
||||
# config.MODEL.tgt_pad_idx = 0
|
||||
# config.MODEL.d_input = 68*2
|
||||
# config.MODEL.d_output = 68*2
|
||||
# config.MODEL.d_embed = 512
|
||||
# config.MODEL.d_model = 512
|
||||
# config.MODEL.d_latent = 256
|
||||
# config.MODEL.d_inner = 2048
|
||||
# config.MODEL.d_k = 64
|
||||
# config.MODEL.d_v = 64
|
||||
# config.MODEL.n_head = 8
|
||||
# config.MODEL.n_layers = 6
|
||||
# config.MODEL.max_position = 200
|
||||
|
||||
# In section 3.4 of paper "Attention Is All You Need", there is such detail:
|
||||
# "In our model, we share the same weight matrix between the two
|
||||
# embedding layers and the pre-softmax linear transformation...
|
||||
# In the embedding layers, we multiply those weights by \sqrt{d_model}".
|
||||
# Options here:
|
||||
# 'emb': multiply \sqrt{d_model} to embedding output
|
||||
# 'prj': multiply (\sqrt{d_model} ^ -1) to linear projection output
|
||||
# 'none': no multiplication
|
||||
# config.MODEL.scale_emb_or_prj = 'prj'
|
||||
# config.MODEL.scale_emb = False
|
||||
# config.MODEL.trg_emb_prj_weight_sharing = True
|
||||
# config.MODEL.emb_src_trg_weight_sharing = True
|
||||
|
||||
|
||||
##########################
|
||||
# dataset related params
|
||||
config.DATASET = edict()
|
||||
config.DATASET.name = 'ravdess'
|
||||
config.DATASET.type = '' # "clips" | "frame" | "none"
|
||||
config.DATASET.root = "../data/"
|
||||
|
||||
# from dataset iteratiion
|
||||
config.DATASET.nwind_second_train = 0
|
||||
config.DATASET.nwind_second_valid = 0
|
||||
config.DATASET.nwind_second_test = 0
|
||||
|
||||
# for data smooth
|
||||
config.DATASET.filter = '' # "gaussian" | "savgol"
|
||||
|
||||
# augmentation
|
||||
config.DATASET.flip = False
|
||||
|
||||
#############################
|
||||
# Trainning related parameter
|
||||
config.TRAIN = edict()
|
||||
|
||||
config.TRAIN.apply_validation = False
|
||||
config.TRAIN.apply_testing = False
|
||||
config.TRAIN.apply_update_parameters = False
|
||||
|
||||
config.TRAIN.lr = 0.001
|
||||
config.TRAIN.lr_step = [50, 100]
|
||||
config.TRAIN.lr_factor = 0.1
|
||||
config.TRAIN.beta1 = 0.5
|
||||
config.TRAIN.beta2 = 0.999
|
||||
config.TRAIN.lambda1 = 100
|
||||
config.TRAIN.lr_policy = ''
|
||||
config.TRAIN.lr_decay_iters = 0
|
||||
config.TRAIN.lr_milestones = [10,100,1000]
|
||||
config.TRAIN.grad_clip_norm = False
|
||||
config.TRAIN.max_grad_clip = 0
|
||||
config.TRAIN.max_grad_norm = 0
|
||||
|
||||
# for motionVAE
|
||||
config.TRAIN.p_use_pt = 0.5
|
||||
|
||||
config.TRAIN.reset_lr = False
|
||||
config.TRAIN.resume = False
|
||||
config.TRAIN.resume_suffix = ""
|
||||
config.TRAIN.checkpoints = ""
|
||||
config.TRAIN.batch_size = 24
|
||||
config.TRAIN.shuffle = True
|
||||
config.TRAIN.epoch_begin = 0
|
||||
config.TRAIN.epoch_end = 100
|
||||
config.TRAIN.niter = 0
|
||||
config.TRAIN.niter_decay = 100
|
||||
config.TRAIN.load_iter = 0
|
||||
config.TRAIN.epoch = 0
|
||||
|
||||
# for cyclical schedule
|
||||
config.TRAIN.n_cycle = 5
|
||||
config.TRAIN.ratio = 0.8
|
||||
config.TRAIN.beta_start= 0.0
|
||||
config.TRAIN.beta_stop = 1.0
|
||||
|
||||
config.TRAIN.optimizer = 'adam'
|
||||
config.TRAIN.momentum = 0.9
|
||||
config.TRAIN.weight_decay = 0.0001
|
||||
config.TRAIN.nesterov = False
|
||||
config.TRAIN.gamma1 = 0.99
|
||||
config.TRAIN.gamma2 = 0.0
|
||||
|
||||
###############################
|
||||
# loss related params
|
||||
config.LOSS = edict()
|
||||
config.LOSS.names = ["all", "L1"]
|
||||
config.LOSS.lambda_rec = 1
|
||||
config.LOSS.lambda_kld = 0
|
||||
config.LOSS.lambda_dif = 0
|
||||
config.LOSS.lambda_cyc = 0
|
||||
config.LOSS.lambda_trp = 0
|
||||
config.LOSS.lambda_geo = 0
|
||||
config.LOSS.lambda_rec_smooth = 0
|
||||
config.LOSS.lambda_geo_smooth = 0
|
||||
config.LOSS.lambda_logp = 0
|
||||
config.LOSS.lambda_logdet = 0
|
||||
|
||||
#############################
|
||||
# TEST related params
|
||||
config.TEST = edict()
|
||||
config.TEST.batch_size = 24
|
||||
config.TEST.path_input = ""
|
||||
config.TEST.path_save = ""
|
||||
|
||||
#############################
|
||||
# INFER related params
|
||||
config.INFER = edict()
|
||||
config.INFER.batch_size = 24
|
||||
config.INFER.path_input = ""
|
||||
config.INFER.path_save = ""
|
||||
|
||||
#############################
|
||||
# DEBUG related params
|
||||
config.DEBUG = edict()
|
||||
config.DEBUG.debug = False
|
||||
config.DEBUG.save_batch_image_gt = False
|
||||
config.DEBUG.save_batch_image_pred = False
|
||||
config.DEBUG.save_heatmaps_gt = False
|
||||
config.DEBUG.save_heatmaps_pred = False
|
||||
|
||||
|
||||
def update_index_exp(index_exp):
|
||||
# prepare index
|
||||
str_ids = index_exp.split(',')
|
||||
|
||||
result = []
|
||||
for i in range(int(len(str_ids) / 2)):
|
||||
start = int(str_ids[ 2*i])
|
||||
end = int(str_ids[2*i + 1])
|
||||
|
||||
if end > start:
|
||||
result += range(start, end)
|
||||
|
||||
# print('indexes', result)
|
||||
|
||||
return result
|
||||
|
||||
|
||||
def _update_dict(k, v):
|
||||
if k == 'DATASET':
|
||||
if 'MEAN' in v and v['MEAN']:
|
||||
v['MEAN'] = np.array([eval(x) if isinstance(x, str) else x for x in v['MEAN']])
|
||||
if 'STD' in v and v['STD']:
|
||||
v['STD'] = np.array([eval(x) if isinstance(x, str) else x for x in v['STD']])
|
||||
|
||||
# if "expression_indx" in v and v['expression_indx']:
|
||||
# v['expression_indx'] = update_index_exp(v['expression_indx'])
|
||||
|
||||
if k == 'MODEL':
|
||||
if 'EXTRA' in v and 'HEATMAP_SIZE' in v['EXTRA']:
|
||||
if isinstance(v['EXTRA']['HEATMAP_SIZE'], int):
|
||||
v['EXTRA']['HEATMAP_SIZE'] = np.array(
|
||||
[v['EXTRA']['HEATMAP_SIZE'], v['EXTRA']['HEATMAP_SIZE']])
|
||||
else:
|
||||
v['EXTRA']['HEATMAP_SIZE'] = np.array(v['EXTRA']['HEATMAP_SIZE'])
|
||||
|
||||
if 'IMAGE_SIZE' in v:
|
||||
if isinstance(v['IMAGE_SIZE'], int):
|
||||
v['IMAGE_SIZE'] = np.array([v['IMAGE_SIZE'], v['IMAGE_SIZE']])
|
||||
else:
|
||||
v['IMAGE_SIZE'] = np.array(v['IMAGE_SIZE'])
|
||||
|
||||
for vk, vv in v.items():
|
||||
if vk in config[k]:
|
||||
config[k][vk] = vv
|
||||
else:
|
||||
raise ValueError("{}.{} not exist in config.py".format(k, vk))
|
||||
|
||||
|
||||
def update_config(config_file):
|
||||
exp_config = None
|
||||
with open(config_file) as f:
|
||||
exp_config = edict(yaml.safe_load(f))
|
||||
|
||||
for k, v in exp_config.items():
|
||||
|
||||
if k in config:
|
||||
if isinstance(v, dict):
|
||||
_update_dict(k, v)
|
||||
else:
|
||||
if k == 'SCALES':
|
||||
config[k][0] = (tuple(v))
|
||||
else:
|
||||
config[k] = v
|
||||
else:
|
||||
raise ValueError("{} not exist in config.py".format(k))
|
||||
|
||||
# update some config item
|
||||
config.GPUS = [int(i) for i in config.GPUS.split(',')]
|
||||
|
||||
|
||||
def gen_config(config_file):
|
||||
cfg = dict(config)
|
||||
for k, v in cfg.items():
|
||||
if isinstance(v, edict):
|
||||
cfg[k] = dict(v)
|
||||
|
||||
with open(config_file, 'w') as f:
|
||||
yaml.dump(dict(cfg), f, default_flow_style=False)
|
||||
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
import sys
|
||||
gen_config(sys.argv[1])
|
||||
@@ -0,0 +1,35 @@
|
||||
import importlib
|
||||
|
||||
def create_dataset(opt, phase="train", logger=None):
|
||||
|
||||
dataset = find_dataset_by_name(opt.DATASET.name)
|
||||
|
||||
# instance
|
||||
dataset = dataset(opt, phase)
|
||||
print(f"dataset {type(dataset).__name__} was created!")
|
||||
|
||||
return dataset
|
||||
|
||||
|
||||
def find_dataset_by_name(dataset_name):
|
||||
"""
|
||||
Given the option --model [dataset_name], the file "src/dataset/dataset_name.py" will be imported
|
||||
"""
|
||||
path_dataset = f"src.datasets.{dataset_name}"
|
||||
# path_dataset = f"src.datasets.{dataset_name.lower()}"
|
||||
modellib = importlib.import_module(path_dataset)
|
||||
|
||||
# in the file, the calss called DATASET() will be instantiated.
|
||||
# it has to be a subclass of Dataset, and it is case-insensitive
|
||||
dataset = None
|
||||
target_name = dataset_name.replace('_', '') + 'Dataset'
|
||||
# target_name = dataset_name.upper() + "Dataset"
|
||||
for name, cls in modellib.__dict__.items():
|
||||
if name.lower() == target_name.lower():
|
||||
dataset = cls
|
||||
|
||||
if dataset is None:
|
||||
print(f"In {dataset_name}.py, there should be a class with name {target_name} in lowercase")
|
||||
exit(0)
|
||||
|
||||
return dataset
|
||||
@@ -0,0 +1,67 @@
|
||||
import numpy as np
|
||||
import torch
|
||||
from torch.utils.data import Dataset
|
||||
from pathlib import Path
|
||||
from scipy.signal import savgol_filter
|
||||
|
||||
from common.debug import debug
|
||||
|
||||
class MotionDataset(Dataset):
|
||||
"""
|
||||
Motion dataset.
|
||||
Prepares conditioning information (previous poses + control signal) and the corresponding next poses"""
|
||||
|
||||
def __init__(self, opt, phase="train"):
|
||||
"""
|
||||
phase = "train | valid | test "
|
||||
"""
|
||||
super(MotionDataset, self).__init__()
|
||||
|
||||
self.opt = opt
|
||||
self.phase = phase
|
||||
self.path_data = Path(opt.DATASET.root)
|
||||
|
||||
path_motion = self.path_data.joinpath(f"motion_{phase}.npz")
|
||||
path_speech = self.path_data.joinpath(f"speech_{phase}.npz")
|
||||
print(f"load data ... --> {path_motion} | {path_speech}")
|
||||
|
||||
self.data_motion = np.load(path_motion)['data'].astype(np.float32) # (N, nsteps, dim_motion)
|
||||
self.data_speech = np.load(path_speech)['data'].astype(np.float32) # (N, nsteps, dim_speech)
|
||||
print(f"motion data ={self.data_motion.shape}, output={self.data_speech.shape}")
|
||||
|
||||
if self.opt.DEBUG:
|
||||
self.data_motion = self.data_motion[:500, ...]
|
||||
self.data_speech = self.data_speech[:500, ...]
|
||||
|
||||
# filter, explore doc: ./notebook/explore_pose.ipynb
|
||||
if self.opt.DATASET.filter == "savgol":
|
||||
self.data_motion = savgol_filter(self.data_motion, window_length=5, polyorder=3, axis=1, mode='nearest')
|
||||
# self.data_speech = savgol_filter(self.data_speech, window_length=5, polyorder=3, axis=1, mode='nearest')
|
||||
|
||||
self.nc_motion = self.data_motion.shape[-1]
|
||||
self.nc_speech = self.data_speech.shape[-1]
|
||||
debug(opt, f"nc_motion={self.nc_motion}, nc_speech ={self.nc_speech }")
|
||||
|
||||
|
||||
def n_channels(self):
|
||||
return self.nc_motion, self.nc_speech
|
||||
|
||||
|
||||
def __len__(self):
|
||||
return self.data_motion.shape[0]
|
||||
|
||||
def __getitem__(self, idx):
|
||||
"""
|
||||
Returns poses and conditioning.
|
||||
If data-dropout sould be applied, a random selection of the previous poses is masked.
|
||||
The control is not masked
|
||||
return:
|
||||
motion: (nsteps, nc_motion), current frame's pose (15 joint, xyz position)
|
||||
speech: (nsteps, nc_speech), conditional data = previous motion data + full windows contrl data
|
||||
"""
|
||||
|
||||
sample = {'data': self.data_motion[idx], # (nwind, nc_motion)
|
||||
'cond': self.data_speech[idx] # (nwind, nc_speech)
|
||||
}
|
||||
|
||||
return sample
|
||||
@@ -0,0 +1,101 @@
|
||||
import numpy as np
|
||||
import torch
|
||||
from torch.utils.data import Dataset
|
||||
from pathlib import Path
|
||||
from scipy.signal import savgol_filter
|
||||
|
||||
from common.debug import debug
|
||||
|
||||
class MotionRegressiveDataset(Dataset):
|
||||
"""
|
||||
Motion dataset.
|
||||
Prepares conditioning information (previous poses + control signal) and the corresponding next poses"""
|
||||
|
||||
def __init__(self, opt, phase="train"):
|
||||
"""
|
||||
phase = "train | valid | test "
|
||||
"""
|
||||
super(MotionRegressiveDataset, self).__init__()
|
||||
|
||||
self.opt = opt
|
||||
self.phase = phase
|
||||
self.path_data = Path(opt.DATASET.root)
|
||||
|
||||
self.nseqR = opt.MODEL.n_lookprevs # 5, previous sequence, number of autoregressive body poses
|
||||
self.nseqL = opt.MODEL.n_lookahead # 20, future sequence
|
||||
|
||||
path_motion = self.path_data.joinpath(f"motion_{phase}.npz")
|
||||
path_speech = self.path_data.joinpath(f"speech_{phase}.npz")
|
||||
print(f"load data ... --> {path_motion}")
|
||||
|
||||
self.data_motion = np.load(path_motion)['data'].astype(np.float32) # (N, nsteps, dim_motion)
|
||||
self.data_speech = np.load(path_speech)['data'].astype(np.float32) # (N, nsteps, dim_speech)
|
||||
print(f"motion data ={self.data_motion.shape}, output={self.data_speech.shape}")
|
||||
|
||||
|
||||
self.nc_motion = self.data_motion.shape[2]
|
||||
self.nc_speech = self.data_speech.shape[2]
|
||||
self.nc_condit = (self.nseqR + 1 + self.nseqL) * self.nc_speech
|
||||
debug(opt, f"nc_motion={self.nc_motion}, nc_speech ={self.nc_speech } nc_condit={self.nc_condit}")
|
||||
|
||||
|
||||
def n_channels(self):
|
||||
return self.nc_motion, self.nc_condit
|
||||
|
||||
|
||||
|
||||
def __len__(self):
|
||||
return self.data_motion.shape[0]
|
||||
|
||||
def __getitem__(self, idx):
|
||||
"""
|
||||
Returns poses and conditioning.
|
||||
If data-dropout sould be applied, a random selection of the previous poses is masked.
|
||||
The control is not masked
|
||||
return:
|
||||
data: ( 45, 95), current frame's pose (15 joint, xyz position)
|
||||
cond: (927, 95), conditional data = previous motion data + full windows contrl data
|
||||
"""
|
||||
|
||||
idata_motion = self.data_motion[idx, :, :] # (nwind, nc_motion)
|
||||
idata_speech = self.data_speech[idx, :, :] # (nwind, nc_speech)
|
||||
|
||||
# filter, explore doc: ./notebook/explore_pose.ipynb
|
||||
if self.opt.DATASET.filter == "savgol":
|
||||
idata_motion = savgol_filter(idata_motion, window_length=5, polyorder=3, axis=0, mode='nearest')
|
||||
idata_speech = savgol_filter(idata_speech, window_length=5, polyorder=3, axis=0, mode='nearest')
|
||||
|
||||
# convert to torch
|
||||
idata_motion = torch.from_numpy(idata_motion) # (nwind, nc_motion)
|
||||
idata_speech = torch.from_numpy(idata_speech) # (nwind, nc_speech)
|
||||
|
||||
|
||||
# prepare data motion: nc_motion
|
||||
# prepare data condition: nseqR * nc_motion + (nseqR + 1 + nseqL) * nc_speech
|
||||
nwind = idata_motion.shape[0]
|
||||
nwind_new = nwind - self.nseqR - self.nseqL
|
||||
wsize_s = self.nseqR + 1 + self.nseqL
|
||||
|
||||
res_motion = idata_motion[self.nseqR:self.nseqR + nwind_new, :]
|
||||
|
||||
# unfold motion
|
||||
res_condit_m = idata_motion.unfold(dimension=0, size=self.nseqR, step=1) # (nwind - self.nseqR +1, nc_motion, wsize)
|
||||
res_condit_m = res_condit_m.swapaxes_(1,2) # (nwind_new, wsize, nc_speech)
|
||||
res_condit_m = res_condit_m.reshape(nwind - self.nseqR +1, -1) # (nwind - self.nseqR +1, self.nseqR * self.nc_motion)
|
||||
assert res_condit_m.shape[1] == self.nseqR * self.nc_motion
|
||||
|
||||
# unfold speech
|
||||
res_condit_s = idata_speech.unfold(dimension=0, size=wsize_s, step=1) # (nwind_new, nc_speech, wsize)
|
||||
res_condit_s = res_condit_s.swapaxes_(1,2) # (nwind_new, wsize, nc_speech)
|
||||
res_condit_s = res_condit_s.reshape(nwind_new, -1) # (nwind_new, wsize * nc_speech)
|
||||
assert res_condit_s.shape[1] == wsize_s * self.nc_speech
|
||||
|
||||
# concate
|
||||
res_condit = torch.concat([res_condit_s, res_condit_m], dim=1)
|
||||
assert res_condit.shape[1] == self.nc_condit
|
||||
|
||||
sample = {'data': res_motion, # (nwind, nc_motion)
|
||||
'cond': res_condit # (nwind, nc_condit)
|
||||
}
|
||||
|
||||
return sample
|
||||
@@ -0,0 +1,86 @@
|
||||
import numpy as np
|
||||
import torch
|
||||
from torch.utils.data import Dataset
|
||||
from pathlib import Path
|
||||
from scipy.signal import savgol_filter
|
||||
|
||||
from common.debug import debug
|
||||
|
||||
class MotionWindowDataset(Dataset):
|
||||
"""
|
||||
Motion dataset.
|
||||
Prepares conditioning information (previous poses + control signal) and the corresponding next poses
|
||||
"""
|
||||
|
||||
def __init__(self, opt, phase="train"):
|
||||
"""
|
||||
phase = "train | valid | test "
|
||||
"""
|
||||
super(MotionWindowDataset, self).__init__()
|
||||
|
||||
self.opt = opt
|
||||
self.phase = phase
|
||||
self.path_data = Path(opt.DATASET.root)
|
||||
|
||||
self.nseqR = opt.MODEL.n_lookprevs_speech # 5, previous sequence, number of autoregressive body poses
|
||||
self.nseqL = opt.MODEL.n_lookahead_speech # 20, future sequence
|
||||
|
||||
path_motion = self.path_data.joinpath(f"motion_{phase}.npz")
|
||||
path_speech = self.path_data.joinpath(f"speech_{phase}.npz")
|
||||
print(f"load data ... --> {path_motion}")
|
||||
|
||||
self.data_motion = np.load(path_motion)['data'].astype(np.float32) # (N, nsteps, dim_motion)
|
||||
self.data_speech = np.load(path_speech)['data'].astype(np.float32) # (N, nsteps, dim_speech)
|
||||
print(f"motion shape ={self.data_motion.shape}, speech shape ={self.data_speech.shape}")
|
||||
|
||||
if self.opt.DEBUG:
|
||||
self.data_motion = self.data_motion[:500, ...]
|
||||
self.data_speech = self.data_speech[:500, ...]
|
||||
|
||||
# filter, explore doc: ./notebook/explore_pose.ipynb
|
||||
if self.opt.DATASET.filter == "savgol":
|
||||
self.data_motion = savgol_filter(self.data_motion, window_length=5, polyorder=3, axis=1, mode='nearest')
|
||||
# self.data_speech = savgol_filter(self.data_speech, window_length=5, polyorder=3, axis=1, mode='nearest')
|
||||
|
||||
self.nc_motion = self.data_motion.shape[2]
|
||||
self.nc_speech = self.data_speech.shape[2]
|
||||
self.nc_condit = (self.nseqR + 1 + self.nseqL) * self.nc_speech
|
||||
debug(opt, f"nc_motion={self.nc_motion}, nc_speech ={self.nc_speech } nc_condit={self.nc_condit}")
|
||||
|
||||
def n_channels(self):
|
||||
return self.nc_motion, self.nc_condit
|
||||
|
||||
|
||||
def __len__(self):
|
||||
return self.data_motion.shape[0]
|
||||
|
||||
|
||||
def __getitem__(self, idx):
|
||||
"""
|
||||
Returns poses and conditioning.
|
||||
If data-dropout sould be applied, a random selection of the previous poses is masked.
|
||||
The control is not masked
|
||||
return:
|
||||
data: ( 45, 95), current frame's pose (15 joint, xyz position)
|
||||
cond: (927, 95), conditional data = previous motion data + full windows contrl data
|
||||
"""
|
||||
|
||||
idata_motion = torch.from_numpy(self.data_motion[idx, :, :]) # (nstep, nc_motion)
|
||||
idata_speech = torch.from_numpy(self.data_speech[idx, :, :]) # (nstep, nc_speech)
|
||||
|
||||
# prepare data motion: nc_motion
|
||||
# prepare data condition: nc_condit = (nseqR + 1 + nseqL) * nc_speech
|
||||
nstep = idata_motion.shape[0]
|
||||
nstep_new = nstep - self.nseqR - self.nseqL
|
||||
wsize = self.nseqR + 1 + self.nseqL
|
||||
|
||||
res_motion = idata_motion[self.nseqR:self.nseqR + nstep_new, :]
|
||||
res_condit = idata_speech.unfold(dimension=0, size=wsize, step=1) # (nstep_new, nc_speech, wsize)
|
||||
res_condit = res_condit.swapaxes_(1,2) # (nstep_new, wsize, nc_speech)
|
||||
res_condit = res_condit.reshape(nstep_new, self.nc_condit)
|
||||
|
||||
sample = {'data': res_motion, # (nstep_new, nc_motion)
|
||||
'cond': res_condit # (nstep_new, nc_condit)
|
||||
}
|
||||
|
||||
return sample
|
||||
@@ -0,0 +1,87 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
|
||||
import torch
|
||||
import torch.nn as nn
|
||||
from collections import OrderedDict
|
||||
|
||||
class MultiLossManager(nn.Module):
|
||||
"""Managment Multiple-Loss
|
||||
"""
|
||||
|
||||
def __init__(self, opt, autoWeight=False):
|
||||
super(MultiLossManager, self).__init__()
|
||||
|
||||
self.opt = opt
|
||||
self.autoWeight = autoWeight
|
||||
|
||||
self.weight = {}
|
||||
self.weigth_name = []
|
||||
|
||||
for iname in opt.LOSS.names:
|
||||
iname_full = f"lambda_{iname}"
|
||||
if iname_full in opt.LOSS.keys() and opt.LOSS[iname_full] > 0:
|
||||
self.weight[ "loss_"+iname ] = opt.LOSS[iname_full]
|
||||
self.weigth_name.append("loss_" + iname )
|
||||
|
||||
n_weight = len(self.weight)
|
||||
|
||||
print(f"WEIGHT of LOSS (n={n_weight}) = {self.weight}")
|
||||
|
||||
if autoWeight:
|
||||
self.weight = torch.ones(n_weight, requires_grad=True)
|
||||
self.weight = torch.nn.Parameter(self.weight)
|
||||
|
||||
|
||||
def forward(self, dict_loss):
|
||||
assert isinstance(dict_loss, OrderedDict), "dict_loss should be a OrderedDict"
|
||||
|
||||
loss_sum = 0
|
||||
i = 0
|
||||
for name in dict_loss.keys():
|
||||
if name not in self.weigth_name: continue
|
||||
|
||||
if self.autoWeight:
|
||||
loss_sum += 0.5 / (self.weight[i] ** 2) * dict_loss[name] + torch.log(1 + self.weight[i] ** 2)
|
||||
else:
|
||||
loss_sum += (self.weight[name] * dict_loss[name])
|
||||
|
||||
i += 1
|
||||
|
||||
# print(f"update WEIGHT of LOSS {self.weight}")
|
||||
|
||||
return loss_sum
|
||||
|
||||
|
||||
|
||||
class AutomaticWeightedLoss(nn.Module):
|
||||
"""automatically weighted multi-task loss
|
||||
Params:
|
||||
num: int,the number of loss
|
||||
x: multi-task loss
|
||||
Examples:
|
||||
loss1=1
|
||||
loss2=2
|
||||
awl = AutomaticWeightedLoss(2)
|
||||
loss_sum = awl(loss1, loss2)
|
||||
"""
|
||||
def __init__(self, num=2):
|
||||
super(AutomaticWeightedLoss, self).__init__()
|
||||
params = torch.ones(num, requires_grad=True)
|
||||
self.params = torch.nn.Parameter(params)
|
||||
|
||||
|
||||
def forward(self, dict_loss):
|
||||
|
||||
assert isinstance(dict_loss, OrderedDict), "dict_loss should be a OrderedDict"
|
||||
|
||||
loss_sum = 0
|
||||
for i, name in enumerate(dict_loss.keys()):
|
||||
|
||||
loss_sum += 0.5 / (self.params[i] ** 2) * dict_loss[name] + torch.log(1 + self.params[i] ** 2)
|
||||
|
||||
return loss_sum
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
awl = AutomaticWeightedLoss(2)
|
||||
print(awl.parameters())
|
||||
@@ -0,0 +1,12 @@
|
||||
from .wing import WingLoss
|
||||
from .smooth_l1_loss import SmoothL1Loss, L1Loss
|
||||
# from .landmarkloss import LandmarkPolygonLoss, LandmarkFocalLoss
|
||||
"""
|
||||
Source: https://github.com/open-mmlab/mmdetection/blob/master/mmdet/models/losses/__init__.py
|
||||
|
||||
"""
|
||||
|
||||
__all__ = [
|
||||
"WingLoss", "AdaptiveWingLoss", "LandmarkPolygonLoss", "LandmarkFocalLoss"
|
||||
]
|
||||
|
||||
Whitespace-only changes.
@@ -0,0 +1,115 @@
|
||||
import torch
|
||||
import torch.nn as nn
|
||||
import numpy as np
|
||||
|
||||
from shapely.geometry import Polygon
|
||||
|
||||
|
||||
class LandmarkPolygonLoss(nn.Module):
|
||||
def __init__(self, opt):
|
||||
super(LandmarkPolygonLoss, self).__init__()
|
||||
|
||||
self.opt = opt
|
||||
self.lmdk_indx = {
|
||||
"chin": list(range(0,17)),
|
||||
"eyebrow_lt": [17, 18, 19, 20, 21],
|
||||
"eyebrow_rt": [22, 23, 24, 25, 26],
|
||||
"nose": [27, 31, 32, 33, 34, 35],
|
||||
"eye_lt": [36, 37, 38, 39, 40, 41],
|
||||
"eye_rt": [42, 43, 44, 45, 46, 47],
|
||||
"mouth_out": list(range(48, 60)),
|
||||
"mouth_inn": list(range(60, 68)),
|
||||
}
|
||||
|
||||
def forward(self, pred, target):
|
||||
# predit, (nbatch, 68*2)
|
||||
# target, (nbatch, 68*2)
|
||||
|
||||
#print(f"pred shape = {predit.shape}, target shape = {target.shape}")
|
||||
pred = pred.reshape(-1, 68, 2) * 128
|
||||
target = target.reshape(-1, 68, 2) * 128
|
||||
|
||||
loss_chin = self.area_diff(pred, target, "chin")
|
||||
loss_nose = self.area_diff(pred, target, "nose")
|
||||
loss_eyebrow = self.area_diff(pred, target, "eyebrow_lt") \
|
||||
+ self.area_diff(pred, target, "eyebrow_rt")
|
||||
loss_eye = self.area_diff(pred, target, "eye_lt") \
|
||||
+ self.area_diff(pred, target, "eye_rt")
|
||||
loss_mouth = self.area_diff(pred, target, "mouth_out") \
|
||||
+ self.area_diff(pred, target, "mouth_inn")
|
||||
|
||||
loss = loss_chin + loss_nose + loss_eyebrow + loss_eye # + loss_mouth
|
||||
loss = torch.mean(loss)
|
||||
|
||||
return loss
|
||||
|
||||
|
||||
|
||||
def area_diff(self, pred, target, part):
|
||||
indx = self.lmdk_indx[part]
|
||||
|
||||
area_pt = self.PolygonArea(pred, indx)
|
||||
area_gt = self.PolygonArea(target, indx)
|
||||
|
||||
diff = torch.abs(area_pt - area_gt)
|
||||
return diff
|
||||
|
||||
|
||||
def PolygonArea(self, corners, indx):
|
||||
"""PolygonArea Function.
|
||||
Args:
|
||||
corners (torch.Tensor): the keypoints of corners, (nbatch, 68, 2)
|
||||
indx (list, int): the polygon index from the keypoints
|
||||
Return:
|
||||
area (torch.Tensor): (nbatch, )
|
||||
|
||||
"""
|
||||
area, n = 0, len(indx)
|
||||
for i in range(n):
|
||||
j = (i + 1) % n
|
||||
area += corners[:, i, 0] * corners[:, j, 1]
|
||||
area -= corners[:, j, 0] * corners[:, i, 1]
|
||||
|
||||
area = torch.abs(area) / 2.0
|
||||
return area
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
class LandmarkFocalLoss(nn.Module):
|
||||
def __init__(self, opt):
|
||||
super(LandmarkFocalLoss, self).__init__()
|
||||
self.opt = opt
|
||||
|
||||
|
||||
def forward(self, predit, target):
|
||||
|
||||
# predit, (nbatch, 68*2)
|
||||
# target, (nbatch, 68*2)
|
||||
|
||||
#print(f"pred shape = {predit.shape}, target shape = {target.shape}")
|
||||
predit = predit.reshape(-1, 68, 2)
|
||||
target = target.reshape(-1, 68, 2)
|
||||
|
||||
x = torch.abs(predit - target) # (nbatch, 68, 2)
|
||||
x = torch.sqrt(x[:,:,0] * x[:,:,0] + x[:,:,1] * x[:,:,1]) # (nbatch, 68)
|
||||
|
||||
#print(f"xsqrt = {x[0, :]}")
|
||||
|
||||
x = torch.torch.pow(1 + 1000*x, x) - 1 # (nbatch, 68)
|
||||
x = torch.clamp_max_(x, 10)
|
||||
|
||||
#print(f"xpow = {x[0, :]}")
|
||||
weight = torch.ones((68,), dtype=x.dtype, device=x.device)
|
||||
weight[48:68] = 10
|
||||
|
||||
|
||||
x = torch.mean(x, dim=0) # (68, )
|
||||
x = torch.mean(x * weight) # (1, )
|
||||
|
||||
return x
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,13 @@
|
||||
import torch
|
||||
import torch.nn as nn
|
||||
|
||||
from .utils import weighted_loss
|
||||
|
||||
@weighted_loss
|
||||
def pfld_loss(pred, target, euler_pt, euler_gt, attribute_gt):
|
||||
"""PFLD loss.
|
||||
Args:
|
||||
pred (torch.Tensor): The prediction landmark. (nbatch, 68*2)
|
||||
|
||||
|
||||
"""
|
||||
@@ -0,0 +1,101 @@
|
||||
import torch
|
||||
import torch.nn as nn
|
||||
|
||||
from .utils import weighted_loss
|
||||
|
||||
@weighted_loss
|
||||
def l1_loss(pred, target):
|
||||
""" L1 loss.
|
||||
Args:
|
||||
pred (torch.Tensor): The prediction.
|
||||
target(torch.Tensor): The ground truth of the prediction
|
||||
|
||||
Returns:
|
||||
torch.Tensor: loss
|
||||
"""
|
||||
|
||||
assert pred.size() == target.size() and target.numel() > 0
|
||||
|
||||
loss = torch.abs(pred - target)
|
||||
|
||||
return loss
|
||||
|
||||
@weighted_loss
|
||||
def smooth_l1_loss(pred, target, beta=1.0):
|
||||
"""Smooth L1 Loss.
|
||||
Args:
|
||||
pred (torch.Tensor): The prediction
|
||||
target (torch.Tensor): The GT of the prediction
|
||||
|
||||
Returns:
|
||||
torch.Tensor: loss
|
||||
"""
|
||||
|
||||
assert beta > 0
|
||||
assert pred.size() == target.size() and target.numel() > 0
|
||||
|
||||
diff = torch.abs(pred - target)
|
||||
loss = torch.where(diff < beta, 0.5 * diff * diff / beta, diff - 0.5 * beta)
|
||||
|
||||
return loss
|
||||
|
||||
|
||||
|
||||
class L1Loss(nn.Module):
|
||||
"""L1 Loss
|
||||
Args:
|
||||
reduction (str, optional): The method to reduce the loss, Options are `none|mean|sum`
|
||||
loss_weight (float, optional): The weight of loss.
|
||||
"""
|
||||
|
||||
def __init__(self, reduction='mean', loss_weight=1.0):
|
||||
super(L1Loss, self).__init__()
|
||||
|
||||
self.reduction = reduction
|
||||
self.loss_weight = loss_weight
|
||||
|
||||
|
||||
def forward(self, pred, target, weight=None, avg_factor=None):
|
||||
"""Forward function.
|
||||
|
||||
Args:
|
||||
pred (troch.Tensor): The prediction
|
||||
target (torch.Tensor): The GT of the prediction.
|
||||
weight (torch.Tensor, optional): The weight of loss for each prediction.
|
||||
avg_factor(int, optional): Average factor that is used to average the loss.
|
||||
"""
|
||||
|
||||
loss = l1_loss(pred, target, weight=weight, reduction=self.reduction, avg_factor=avg_factor)
|
||||
loss = self.loss_weight * loss
|
||||
|
||||
return loss
|
||||
|
||||
|
||||
class SmoothL1Loss(nn.Module):
|
||||
"""Smooth L1 Loss.
|
||||
Args:
|
||||
beta (float, optional): The threshold in the piecewise function. Default 1.0
|
||||
reduction (str, optional): The reduce loss method, options are `none|mean|sum`
|
||||
loss_weight (float, optional): The weight of loss
|
||||
Return:
|
||||
torch.Tensor: Loss
|
||||
"""
|
||||
|
||||
def __init__(self, beta=1.0, reduction="mean", loss_weight=1.0):
|
||||
super(SmoothL1Loss, self).__init__()
|
||||
self.beta = beta
|
||||
self.reduction = reduction
|
||||
self.loss_weight = loss_weight
|
||||
|
||||
def forward(self, pred, target, weight=None, avg_factor=None):
|
||||
"""Forward function.
|
||||
Args:
|
||||
pred (torch.Tensor): The prediction.
|
||||
target (torch.Tensor): The GT of the prediction
|
||||
weight (torch.Tensor, optional): The weigth of loss for each prediction. Default to None
|
||||
avg_factor (int, optional): Average factor that is used to average the loss.
|
||||
"""
|
||||
|
||||
loss = smooth_l1_loss(pred, target, beta=self.beta, weight=weight, avg_factor=avg_factor)
|
||||
loss = self.loss_weight * loss
|
||||
return loss
|
||||
@@ -0,0 +1,104 @@
|
||||
import functools
|
||||
|
||||
import torch.nn.functional as F
|
||||
|
||||
"""
|
||||
Source: https://github.com/open-mmlab/mmdetection/blob/master/mmdet/models/losses/utils.py
|
||||
"""
|
||||
|
||||
|
||||
def reduce_loss(loss, reduction):
|
||||
"""Reduce loss as specified.
|
||||
|
||||
Args:
|
||||
loss (Tensor): Elementwise loss tensor.
|
||||
reduction (str): Options are "none", "mean" and "sum".
|
||||
|
||||
Return:
|
||||
Tensor: Reduced loss tensor.
|
||||
"""
|
||||
reduction_enum = F._Reduction.get_enum(reduction)
|
||||
# none: 0, elementwise_mean:1, sum: 2
|
||||
if reduction_enum == 0:
|
||||
return loss
|
||||
elif reduction_enum == 1:
|
||||
return loss.mean()
|
||||
elif reduction_enum == 2:
|
||||
return loss.sum()
|
||||
|
||||
|
||||
def weight_reduce_loss(loss, weight=None, reduction='mean', avg_factor=None):
|
||||
"""Apply element-wise weight and reduce loss.
|
||||
|
||||
Args:
|
||||
loss (Tensor): Element-wise loss.
|
||||
weight (Tensor): Element-wise weights.
|
||||
reduction (str): Same as built-in losses of PyTorch.
|
||||
avg_factor (float): Avarage factor when computing the mean of losses.
|
||||
|
||||
Returns:
|
||||
Tensor: Processed loss values.
|
||||
"""
|
||||
# if weight is specified, apply element-wise weight
|
||||
if weight is not None:
|
||||
loss = loss * weight
|
||||
|
||||
# if avg_factor is not specified, just reduce the loss
|
||||
if avg_factor is None:
|
||||
loss = reduce_loss(loss, reduction)
|
||||
else:
|
||||
# if reduction is mean, then average the loss by avg_factor
|
||||
if reduction == 'mean':
|
||||
loss = loss.sum() / avg_factor
|
||||
# if reduction is 'none', then do nothing, otherwise raise an error
|
||||
elif reduction != 'none':
|
||||
raise ValueError('avg_factor can not be used with reduction="sum"')
|
||||
return loss
|
||||
|
||||
|
||||
def weighted_loss(loss_func):
|
||||
"""Create a weighted version of a given loss function.
|
||||
|
||||
To use this decorator, the loss function must have the signature like
|
||||
`loss_func(pred, target, **kwargs)`. The function only needs to compute
|
||||
element-wise loss without any reduction. This decorator will add weight
|
||||
and reduction arguments to the function. The decorated function will have
|
||||
the signature like `loss_func(pred, target, weight=None, reduction='mean',
|
||||
avg_factor=None, **kwargs)`.
|
||||
|
||||
:Example:
|
||||
|
||||
>>> import torch
|
||||
>>> @weighted_loss
|
||||
>>> def l1_loss(pred, target):
|
||||
>>> return (pred - target).abs()
|
||||
|
||||
>>> pred = torch.Tensor([0, 2, 3])
|
||||
>>> target = torch.Tensor([1, 1, 1])
|
||||
>>> weight = torch.Tensor([1, 0, 1])
|
||||
|
||||
>>> l1_loss(pred, target)
|
||||
tensor(1.3333)
|
||||
>>> l1_loss(pred, target, weight)
|
||||
tensor(1.)
|
||||
>>> l1_loss(pred, target, reduction='none')
|
||||
tensor([1., 1., 2.])
|
||||
>>> l1_loss(pred, target, weight, avg_factor=2)
|
||||
tensor(1.5000)
|
||||
"""
|
||||
|
||||
@functools.wraps(loss_func)
|
||||
def wrapper(pred,
|
||||
target,
|
||||
weight=None,
|
||||
reduction='mean',
|
||||
avg_factor=None,
|
||||
**kwargs):
|
||||
|
||||
# get element-wise loss
|
||||
loss = loss_func(pred, target, **kwargs)
|
||||
|
||||
loss = weight_reduce_loss(loss, weight, reduction, avg_factor)
|
||||
return loss
|
||||
|
||||
return wrapper
|
||||
@@ -0,0 +1,73 @@
|
||||
import math
|
||||
import torch
|
||||
from torch import nn
|
||||
|
||||
from .utils import weighted_loss
|
||||
|
||||
"""
|
||||
The Wing loss:
|
||||
|
||||
It has been proposed in `Wing Loss for Roubst Facial Landmark Localisation with
|
||||
Convolutional Neural Networks`. https://arxiv.org/abs/1711.06753
|
||||
|
||||
"""
|
||||
|
||||
|
||||
@weighted_loss
|
||||
def wing_loss(pred, target, w=5, epsilon=0.5):
|
||||
"""
|
||||
Source: https://github.com/BloodAxe/pytorch-toolbelt/blob/develop/pytorch_toolbelt/losses/functional.py
|
||||
|
||||
"""
|
||||
|
||||
diff = torch.abs(pred - target)
|
||||
C = w - w * math.log(1 + w / epsilon)
|
||||
loss = torch.where(diff < w, w * torch.log(1 + diff / epsilon), diff - C)
|
||||
|
||||
return loss
|
||||
|
||||
|
||||
|
||||
class WingLoss(nn.Module):
|
||||
|
||||
def __init__(self, w=10, epsilon=0.5, reduction='mean', loss_weight=1.0):
|
||||
super(WingLoss,self).__init__()
|
||||
|
||||
self.w = w
|
||||
self.epsilon = epsilon
|
||||
self.reduction = reduction
|
||||
self.loss_weight = loss_weight
|
||||
|
||||
def forward(self, pred, target, weight=None, avg_factor=None):
|
||||
"""Forward function.
|
||||
Args:
|
||||
pred (torch.Tensor, Bx68*2): The prediction
|
||||
target (torch.Tensor, Bx68*2): The GT of prediction
|
||||
weight (torch.Tensor, optional): The weight of each loss, default None
|
||||
avg_factor(int, optional): The average of the reduction loss
|
||||
"""
|
||||
|
||||
loss = wing_loss(pred, target, w=self.w, epsilon=self.epsilon, weight=weight, avg_factor=avg_factor)
|
||||
loss = self.loss_weight * loss
|
||||
|
||||
return loss
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
crieation = WingLoss()
|
||||
|
||||
GT = torch.zeros((2, 68, 64, 64))
|
||||
PT = torch.ones((2, 68, 64, 64))
|
||||
PT.requires_grad_(True)
|
||||
|
||||
loss = crieation(PT, GT)
|
||||
loss.backward()
|
||||
|
||||
print(loss)
|
||||
|
||||
|
||||
@@ -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
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,134 @@
|
||||
import numpy as np
|
||||
|
||||
import torch
|
||||
import torch.nn as nn
|
||||
import torch.nn.functional as F
|
||||
from collections import OrderedDict
|
||||
|
||||
from common.debug import debug
|
||||
from common.losses import WingLoss, L1Loss, SmoothL1Loss
|
||||
|
||||
|
||||
class ATCBase(nn.Module):
|
||||
|
||||
def __init__(self, opt):
|
||||
super(ATCBase, self).__init__()
|
||||
|
||||
self.opt = opt
|
||||
nseqR = opt.MODEL.n_lookprevs # 3
|
||||
nseqL = opt.MODEL.n_lookahead # 1
|
||||
|
||||
self.dim_motion = opt.MODEL.dim_motion
|
||||
self.dim_speech = opt.MODEL.dim_speech
|
||||
self.dim_hidden = opt.MODEL.dim_hidden
|
||||
|
||||
self.dim_condit = self.dim_motion * nseqR + self.dim_speech * (nseqR + 1 + nseqL) # 136 * 5 + 27 * (5 + 1 + 20) = 1382
|
||||
|
||||
print(f"dim_condit={self.dim_condit}")
|
||||
|
||||
|
||||
# encoder
|
||||
self.encoder = nn.Sequential( # nbatch x nsteps x dim_audio
|
||||
nn.Linear(self.dim_condit, 128),
|
||||
nn.ELU(),
|
||||
nn.Linear(128, 1024),
|
||||
nn.ELU(),
|
||||
nn.Linear(1024, 512),
|
||||
nn.ELU(),
|
||||
nn.Linear(512, self.dim_hidden),
|
||||
nn.ELU()
|
||||
)
|
||||
|
||||
# encoder lstm
|
||||
# self.encoder_lstm = nn.LSTM(256, hidden_size=256, num_layers=3, batch_first=True)
|
||||
|
||||
# fc output
|
||||
self.final_layer = nn.Sequential(
|
||||
nn.Linear(self.dim_hidden, out_features=self.dim_motion, bias=True),
|
||||
nn.Tanh()
|
||||
)
|
||||
|
||||
|
||||
# loss
|
||||
# self.loss_func_wing = SmoothL1Loss(reduction='mean')
|
||||
|
||||
self.loss_func_wing = WingLoss(reduction='none')
|
||||
self.loss_func_L1 = SmoothL1Loss(reduction='none')
|
||||
self.loss_sl1 = nn.SmoothL1Loss(reduction="none")
|
||||
|
||||
|
||||
|
||||
|
||||
def forward(self, c, x, x_idn=None):
|
||||
"""Forward function
|
||||
Args:
|
||||
c: [B x seqlen x dim_condit], audio feature, like mfcc
|
||||
x: [B x seqlen x dim_motion], expression coeff
|
||||
x_idn: [B x nsteps x dim_idn], identity coeff
|
||||
"""
|
||||
|
||||
B, nsteps, _ = x.size() # batch size
|
||||
self.target = x.detach() # B x N x dim_x
|
||||
debug(self.opt, f"[forward] c shape = {c.shape}, x shape = {x.shape}", verbose=False)
|
||||
|
||||
|
||||
# preprocessing data
|
||||
feat = self.encoder(c) # B x N x dim_h
|
||||
debug(self.opt, f"[forward] feat shape = {feat.shape}", verbose=False)
|
||||
|
||||
|
||||
self.pred = self.final_layer(feat) # B x N x dim_x
|
||||
debug(self.opt, f"[forward] final shape = {feat.shape}", verbose=False)
|
||||
|
||||
# keep target to calculate loss
|
||||
# self.pred = feat.detach() # B x N x dim_x
|
||||
|
||||
return self.pred
|
||||
|
||||
|
||||
def init_reconstruct_model(self, netR):
|
||||
"""
|
||||
init reconstruction model
|
||||
"""
|
||||
self.netR = netR
|
||||
|
||||
|
||||
def eval_losses(self):
|
||||
"""
|
||||
Warpping function for loss function
|
||||
"""
|
||||
return self.loss_function_(self.pred, self.target)
|
||||
|
||||
|
||||
def loss_function_(self, pred, target, **kwargs):
|
||||
""" Computes the VAE loss function.
|
||||
pramas:
|
||||
pred, torch.Tensor, (nbatch, seqlen, 79)
|
||||
target, torch.Tensor, (nbatch, seqlen, 79)
|
||||
|
||||
|
||||
"""
|
||||
loss = 0
|
||||
loss_dict = {}
|
||||
|
||||
# rec loss
|
||||
loss_rec = self.loss_func_wing(pred, target)
|
||||
loss = loss_rec * self.opt.LOSS.lambda_rec
|
||||
loss_dict["loss_rec"] = loss_rec.detach()
|
||||
|
||||
# rec smooth
|
||||
diff_pred = pred[:, 1:, :] - pred[:, :-1, :]
|
||||
diff_target = target[:, 1:, :] - target[:, :-1, :]
|
||||
loss_rec_smooth = self.loss_func_wing(diff_pred, diff_target)
|
||||
loss += loss_rec_smooth * self.opt.LOSS.lambda_rec_smooth
|
||||
loss_dict["loss_rec_smooth"] = loss_rec_smooth.detach()
|
||||
|
||||
loss_dict["loss_all"] = loss.detach()
|
||||
|
||||
return loss, loss_dict
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,183 @@
|
||||
import numpy as np
|
||||
|
||||
import torch
|
||||
import torch.nn as nn
|
||||
import torch.nn.functional as F
|
||||
|
||||
from .base import Base
|
||||
from ..losses import L1Loss, SmoothL1Loss
|
||||
|
||||
|
||||
class ATCNet(nn.Module):
|
||||
|
||||
def __init__(self, opt):
|
||||
super(ATCNet, self).__init__()
|
||||
|
||||
self.opt = opt
|
||||
self.dim_output = opt.MODEL.dim_output
|
||||
|
||||
# encoder
|
||||
self.encoder = nn.Sequential( # nbatch * seqlen x 12 x 28 x 1
|
||||
# block 1
|
||||
nn.Conv2d(12, 32, kernel_size=(3,1), stride=(1,1), padding=(1,0), bias=True), # 32 x 28 x 1
|
||||
nn.BatchNorm2d(32),
|
||||
nn.LeakyReLU(0.02, True),
|
||||
nn.Conv2d(32, 32, kernel_size=(3,1), stride=(1,1), padding=(1,0), bias=True), # 32 x 28 x 1
|
||||
nn.BatchNorm2d(32),
|
||||
nn.LeakyReLU(0.02, True),
|
||||
nn.MaxPool2d(kernel_size=(2, 1), stride=(2, 1)), # 32 x 14 x 1
|
||||
|
||||
# block 2
|
||||
nn.Conv2d(32, 64, kernel_size=(3,1), stride=(1,1), padding=(1,0), bias=True), # 64 x 14 x 1
|
||||
nn.BatchNorm2d(64),
|
||||
nn.LeakyReLU(0.02, True),
|
||||
nn.Conv2d(64, 64, kernel_size=(3,1), stride=(1,1), padding=(1,0), bias=True), # 64 x 14 x 1
|
||||
nn.BatchNorm2d(64),
|
||||
nn.LeakyReLU(0.02, True),
|
||||
nn.MaxPool2d(kernel_size=(2, 1), stride=(2, 1)), # 64 x 7 x 1
|
||||
|
||||
# block 3
|
||||
nn.Conv2d(64, 128, kernel_size=(3,1), stride=(1,1), padding=(1,0), bias=True), # 128 x 7 x 1
|
||||
nn.BatchNorm2d(128),
|
||||
nn.LeakyReLU(0.02, True),
|
||||
nn.Conv2d(128, 128, kernel_size=(3,1), stride=(1,1), padding=(1,0), bias=True), # 128 x 7 x 1
|
||||
nn.BatchNorm2d(128),
|
||||
nn.LeakyReLU(0.02, True),
|
||||
nn.Conv2d(128, 128, kernel_size=(3,1), stride=(1,1), padding=(1,0), bias=True), # 128 x 7 x 1
|
||||
nn.BatchNorm2d(128),
|
||||
nn.LeakyReLU(0.02, True),
|
||||
nn.MaxPool2d(kernel_size=(2, 1), stride=(2, 1)), # 128 x 4 x 1
|
||||
|
||||
# block 4
|
||||
nn.Conv2d(128, 256, kernel_size=(3,1), stride=(1,1), padding=(1,0), bias=True), # 256 x 4 x 1
|
||||
nn.BatchNorm2d(256),
|
||||
nn.LeakyReLU(0.02, True),
|
||||
nn.Conv2d(256, 256, kernel_size=(3,1), stride=(1,1), padding=(1,0), bias=True), # 256 x 4 x 1
|
||||
nn.BatchNorm2d(256),
|
||||
nn.LeakyReLU(0.02, True),
|
||||
nn.Conv2d(256, 256, kernel_size=(3,1), stride=(1,1), padding=(1,0), bias=True), # 256 x 4 x 1
|
||||
nn.BatchNorm2d(256),
|
||||
nn.LeakyReLU(0.02, True),
|
||||
nn.Conv2d(256, 256, kernel_size=(3,1), stride=(1,1), padding=(0,0), bias=True), # 256 x 1 x 1
|
||||
nn.BatchNorm2d(256),
|
||||
nn.LeakyReLU(0.02, True),
|
||||
)
|
||||
|
||||
# encoder lstm
|
||||
# self.encoder_lstm = nn.LSTM(256, hidden_size=256, num_layers=3, batch_first=True)
|
||||
|
||||
|
||||
# fc head
|
||||
self.fcNet = nn.Sequential( # nbatch x 512*12*2
|
||||
nn.Linear(in_features=256, out_features=256, bias=True), # nbatch x 1024
|
||||
nn.LeakyReLU(True),
|
||||
nn.Linear(in_features=256, out_features=128, bias=True), # nbatch x 128
|
||||
nn.LeakyReLU(True),
|
||||
)
|
||||
|
||||
# fc output
|
||||
self.final_layer = nn.Sequential(
|
||||
nn.Linear(128, out_features=self.dim_output, bias=True),
|
||||
nn.Tanh()
|
||||
)
|
||||
|
||||
# loss
|
||||
self.creationL1 = SmoothL1Loss(reduction='mean')
|
||||
|
||||
|
||||
|
||||
|
||||
def forward(self, x, target=None, target_idn=None):
|
||||
"""Forward function
|
||||
Args:
|
||||
x: torch.Tensor, [nbatch x seqlen x 28 x 12], the input
|
||||
target: torch.Tensor, [nbatch x seqlen x dim_ouput], the ground-truth of target data
|
||||
"""
|
||||
|
||||
(nbatch, seq_len, seglen, nfeat) = x.shape
|
||||
|
||||
# preprocessing data
|
||||
x = x.view(nbatch * seq_len, 1, 28, 12) # nbatch*seqlen x 1 x 28 x 12
|
||||
x = torch.transpose(x, 1, 3) # nbatch*seqlen x 12 x 28 x 1
|
||||
|
||||
x = self.encoder(x) # # nbatch*seqlen x 256 x 1 x 1
|
||||
x = x.view(nbatch, seq_len, -1) # nbatch x seqlen x 256
|
||||
# x, _ = self.encoder_lstm(x) # nbatch x seqlen x 256
|
||||
|
||||
x = self.fcNet(x) # nbatch x seqlen x 128
|
||||
y = self.final_layer(x) # nbatch x seqlen x 79
|
||||
|
||||
|
||||
# keep target to calculate loss
|
||||
self.pred = y
|
||||
self.target = target # nbatch x seqlen x dim_output
|
||||
self.target_idn = target_idn # nbatch x seqlen x 100
|
||||
|
||||
return self.pred
|
||||
|
||||
|
||||
def init_reconstruct_model(self, netR):
|
||||
"""
|
||||
init reconstruction model
|
||||
"""
|
||||
self.netR = netR
|
||||
|
||||
|
||||
def loss_function(self):
|
||||
"""
|
||||
Warpping function for loss function
|
||||
"""
|
||||
return self.loss_function_(self.pred, self.target)
|
||||
|
||||
|
||||
def loss_function_(self, pred, target, **kwargs):
|
||||
""" Computes the VAE loss function.
|
||||
pramas:
|
||||
pred, torch.Tensor, (nbatch, seqlen, 79)
|
||||
target, torch.Tensor, (nbatch, seqlen, 79)
|
||||
|
||||
|
||||
"""
|
||||
loss = 0
|
||||
loss_dict = {}
|
||||
|
||||
# reconstruction loss
|
||||
if self.opt.LOSS.lambda_rec > 0:
|
||||
loss_dict["loss_rec"] = self.creationL1(pred, target)
|
||||
loss += self.opt.LOSS.lambda_rec * loss_dict["loss_rec"]
|
||||
|
||||
|
||||
if self.opt.LOSS.lambda_smooth_rec > 0:
|
||||
diff_pred = pred[:, 1:, :] - pred[:, :-1, :]
|
||||
diff_target = target[:, 1:, :] - target[:, :-1, :]
|
||||
loss_dict["loss_smooth_rec"] = self.creationL1(diff_pred, diff_target)
|
||||
loss += self.opt.LOSS.lambda_smooth_rec * loss_dict["loss_smooth_rec"]
|
||||
|
||||
|
||||
# 3D Geometry loss
|
||||
if self.opt.LOSS.lambda_geo > 0:
|
||||
with torch.no_grad():
|
||||
coeff_idn = self.target_idn.reshape(-1, 100) # (nbatch x seqlen, 100)
|
||||
coeff_exp_gt = self.target.reshape(-1, 79) # (nbatch x seqlen, 79)
|
||||
coeff_exp_pt = self.pred.reshape(-1, 79) # (nbatch x seqlen, 79)
|
||||
|
||||
geo_gt = self.netR.eval_geo(coeff_idn, coeff_exp_gt) # (nbatch x seqlen, npoints, 3)
|
||||
geo_pt = self.netR.eval_geo(coeff_idn, coeff_exp_pt) # (nbatch x seqlen, npoints, 3)
|
||||
|
||||
loss_dict["loss_geo"] = self.creationL1(geo_pt, geo_gt)
|
||||
loss += self.opt.LOSS.lambda_rec * loss_dict["loss_geo"]
|
||||
|
||||
if self.opt.LOSS.lambda_smooth_geo > 0:
|
||||
diff_pred = geo_pt[:, 1:, :] - geo_pt[:, :-1, :]
|
||||
diff_target = geo_gt[:, 1:, :] - geo_gt[:, :-1, :]
|
||||
loss_dict["loss_smooth_geo"] = self.creationL1(diff_pred, diff_target)
|
||||
loss += self.opt.LOSS.lambda_smooth_geo * loss_dict["loss_smooth_geo"]
|
||||
|
||||
|
||||
return loss, loss_dict
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,93 @@
|
||||
import torch
|
||||
import torch.nn as nn
|
||||
from common.debug import debug
|
||||
|
||||
class Audio2Motion(nn.Module):
|
||||
|
||||
def __init__(self, opt):
|
||||
super(Audio2Motion, self).__init__()
|
||||
|
||||
self.opt = opt
|
||||
nseqR_m = opt.MODEL.n_lookprevs_motion # 3
|
||||
nseqR_s = opt.MODEL.n_lookprevs_speech # 3
|
||||
nseqL_s = opt.MODEL.n_lookahead_speech # 1
|
||||
|
||||
nLSTM = opt.MODEL.n_layer_lstm # 3
|
||||
|
||||
self.dim_motion = opt.MODEL.dim_motion # 53
|
||||
self.dim_speech = opt.MODEL.dim_speech # 27
|
||||
self.dim_hidden = opt.MODEL.dim_hidden # 256
|
||||
self.dim_condit = self.dim_motion * nseqR_m + self.dim_speech * (nseqR_s + 1 + nseqL_s)
|
||||
print(f"dim_condit={self.dim_condit}")
|
||||
|
||||
# encoder
|
||||
self.encoder = nn.Sequential( # nbatch x nseqlen x 27
|
||||
nn.Linear(in_features=self.dim_condit, out_features=self.dim_hidden),
|
||||
nn.LayerNorm(self.dim_hidden),
|
||||
nn.LeakyReLU(0.2),
|
||||
|
||||
nn.Linear(in_features=self.dim_hidden, out_features=4*self.dim_hidden),
|
||||
nn.LayerNorm(4*self.dim_hidden),
|
||||
nn.LeakyReLU(0.2),
|
||||
nn.Dropout(0.1),
|
||||
|
||||
nn.Linear(in_features=4*self.dim_hidden, out_features=self.dim_hidden),
|
||||
)
|
||||
|
||||
# lstm
|
||||
self.LSTM = nn.LSTM(
|
||||
input_size = self.dim_hidden,
|
||||
hidden_size = self.dim_hidden,
|
||||
num_layers= nLSTM,
|
||||
dropout = 0,
|
||||
bidirectional=False,
|
||||
batch_first = True
|
||||
)
|
||||
|
||||
# output
|
||||
self.decoder = nn.Sequential(
|
||||
nn.Linear(in_features=self.dim_hidden, out_features=4*self.dim_hidden),
|
||||
nn.LayerNorm(4*self.dim_hidden),
|
||||
nn.LeakyReLU(0.2),
|
||||
nn.Dropout(0.1),
|
||||
|
||||
nn.Linear(in_features=4*self.dim_hidden, out_features=4*self.dim_hidden),
|
||||
nn.LayerNorm(4*self.dim_hidden),
|
||||
nn.LeakyReLU(0.2),
|
||||
nn.Dropout(0.1),
|
||||
|
||||
nn.Linear(in_features=4*self.dim_hidden, out_features=self.dim_hidden),
|
||||
nn.LayerNorm(self.dim_hidden),
|
||||
nn.LeakyReLU(0.2),
|
||||
nn.Dropout(0.1),
|
||||
|
||||
nn.Linear(in_features=self.dim_hidden, out_features=self.dim_motion),
|
||||
nn.Tanh()
|
||||
)
|
||||
|
||||
def forward(self, x):
|
||||
""" forward function
|
||||
Args:
|
||||
x: torch.Tensor, [nbatch x seqlen x dim_condit]
|
||||
target: torch.Tensor, [nbatch x seqlen x dim_motion]
|
||||
return:
|
||||
pred: torch.Tensor, [nbatch x seqlen x dim_motion]
|
||||
"""
|
||||
|
||||
(nbatch, nseqlen, nfeat) = x.shape
|
||||
debug(self.opt, f"[forward] input x shape = {x.shape}", verbose=False)
|
||||
|
||||
feat = self.encoder(x) # [nbatch x nseqlen x dim_hidden]
|
||||
debug(self.opt, f"[forward] encoder shape = {feat.shape}", verbose=False)
|
||||
|
||||
|
||||
feat, _ = self.LSTM(feat) # [nbatch x nseqlen x dim_hidden]
|
||||
debug(self.opt, f"[forward] lstm shape = {feat.shape}", verbose=False)
|
||||
|
||||
|
||||
pred = self.decoder(feat) # [nbatch x nseqlen x dim_motion]
|
||||
debug(self.opt, f"[forward] decoder shape = {pred.shape}", verbose=False)
|
||||
|
||||
return pred
|
||||
|
||||
|
||||
@@ -0,0 +1,120 @@
|
||||
import torch
|
||||
import torch.nn as nn
|
||||
from common.debug import debug
|
||||
|
||||
class Audio2MotionConv(nn.Module):
|
||||
|
||||
def __init__(self, opt):
|
||||
super(Audio2MotionConv, self).__init__()
|
||||
|
||||
self.opt = opt
|
||||
self.dim_motion = opt.MODEL.dim_motion # 53
|
||||
self.dim_speech = opt.MODEL.dim_speech # 29
|
||||
self.dim_hidden = opt.MODEL.dim_hidden # 256
|
||||
|
||||
# encoder
|
||||
self.encoder = nn.Sequential( # (nbatch, nchannel=29, H=16, W=1)
|
||||
# block 1
|
||||
nn.Conv2d(self.dim_speech, 32, kernel_size=(3,1), stride=(1,1), padding=(1,0), bias=True), # 32 x 16 x 1
|
||||
nn.BatchNorm2d(32),
|
||||
nn.LeakyReLU(0.02, True),
|
||||
nn.Conv2d(32, 32, kernel_size=(3,1), stride=(1,1), padding=(1,0), bias=True), # 32 x 16 x 1
|
||||
nn.BatchNorm2d(32),
|
||||
nn.LeakyReLU(0.02, True),
|
||||
nn.Conv2d(32, 32, kernel_size=(3,1), stride=(1,1), padding=(1,0), bias=True), # 32 x 16 x 1
|
||||
nn.BatchNorm2d(32),
|
||||
nn.LeakyReLU(0.02, True),
|
||||
|
||||
# block 2
|
||||
nn.Conv2d(32, 128, kernel_size=(3,1), stride=(2,1), padding=(1,0), bias=True), # 128 x 8 x 1
|
||||
nn.BatchNorm2d(128),
|
||||
nn.LeakyReLU(0.02, True),
|
||||
nn.Conv2d(128, 128, kernel_size=(3,1), stride=(1,1), padding=(1,0), bias=True), # 128 x 8 x 1
|
||||
nn.BatchNorm2d(128),
|
||||
nn.LeakyReLU(0.02, True),
|
||||
nn.Conv2d(128, 128, kernel_size=(3,1), stride=(1,1), padding=(1,0), bias=True), # 128 x 8 x 1
|
||||
nn.BatchNorm2d(128),
|
||||
nn.LeakyReLU(0.02, True),
|
||||
nn.Conv2d(128, 128, kernel_size=(3,1), stride=(1,1), padding=(1,0), bias=True), # 128 x 8 x 1
|
||||
nn.BatchNorm2d(128),
|
||||
nn.LeakyReLU(0.02, True),
|
||||
|
||||
|
||||
# block 3
|
||||
nn.Conv2d(128, 256, kernel_size=(3,1), stride=(2,1), padding=(1,0), bias=True), # 256 x 4 x 1
|
||||
nn.BatchNorm2d(256),
|
||||
nn.LeakyReLU(0.02, True),
|
||||
nn.Conv2d(256, 256, kernel_size=(3,1), stride=(1,1), padding=(1,0), bias=True), # 256 x 4 x 1
|
||||
nn.BatchNorm2d(256),
|
||||
nn.LeakyReLU(0.02, True),
|
||||
nn.Conv2d(256, 256, kernel_size=(3,1), stride=(2,1), padding=(1,0), bias=True), # 256 x 2 x 1
|
||||
nn.BatchNorm2d(256),
|
||||
nn.LeakyReLU(0.02, True),
|
||||
nn.Conv2d(256, 256, kernel_size=(3,1), stride=(2,1), padding=(1,0), bias=True), # 256 x 1 x 1
|
||||
nn.BatchNorm2d(256),
|
||||
nn.LeakyReLU(0.02, True),
|
||||
|
||||
)
|
||||
|
||||
# # lstm
|
||||
# self.LSTM = nn.LSTM(
|
||||
# input_size = self.dim_hidden,
|
||||
# hidden_size = self.dim_hidden,
|
||||
# num_layers= nLSTM,
|
||||
# dropout = 0,
|
||||
# bidirectional=False,
|
||||
# batch_first = True
|
||||
# )
|
||||
|
||||
# output
|
||||
self.decoder = nn.Sequential(
|
||||
nn.Linear(in_features=self.dim_hidden, out_features=4*self.dim_hidden),
|
||||
nn.LayerNorm(4*self.dim_hidden),
|
||||
nn.LeakyReLU(0.2),
|
||||
nn.Dropout(0.1),
|
||||
|
||||
nn.Linear(in_features=4*self.dim_hidden, out_features=self.dim_hidden),
|
||||
nn.LayerNorm(self.dim_hidden),
|
||||
nn.LeakyReLU(0.2),
|
||||
nn.Dropout(0.1),
|
||||
|
||||
nn.Linear(in_features=self.dim_hidden, out_features=self.dim_motion),
|
||||
nn.Tanh()
|
||||
)
|
||||
|
||||
def forward(self, x):
|
||||
""" forward function
|
||||
Args:
|
||||
x: torch.Tensor, [nbatch x seqlen x nwind x dim_condit]
|
||||
return:
|
||||
pred: torch.Tensor, [nbatch x seqlen x dim_motion]
|
||||
"""
|
||||
|
||||
(nbatch, nseqlen, nwind, nfeat) = x.shape # (B, nseq, 16, 29)
|
||||
debug(self.opt, f"[forward] input x shape = {x.shape}", verbose=False)
|
||||
|
||||
# preprocessing data
|
||||
x = x.reshape(nbatch * nseqlen, 1, nwind, nfeat) # (B * nseq, 1, 16, 29)
|
||||
x = torch.transpose(x, 1, 3) # (B * nseq, 29, 16, 1)
|
||||
debug(self.opt, f"[forward] transpose x shape = {x.shape}", verbose=False)
|
||||
|
||||
|
||||
feat = self.encoder(x) # (B * nseq, 256, 1, 1)
|
||||
debug(self.opt, f"[forward] encoder shape = {feat.shape}", verbose=False)
|
||||
|
||||
feat = feat.reshape(nbatch * nseqlen, -1) # (B * nseq, 256)
|
||||
debug(self.opt, f"[forward] view shape = {feat.shape}", verbose=False)
|
||||
|
||||
# feat, _ = self.LSTM(feat) # [nbatch x nseqlen x dim_hidden]
|
||||
# debug(self.opt, f"[forward] lstm shape = {feat.shape}", verbose=False)
|
||||
|
||||
pred = self.decoder(feat) # (B * nseq, dim_motion)
|
||||
debug(self.opt, f"[forward] decoder shape = {pred.shape}", verbose=False)
|
||||
|
||||
pred = pred.reshape(nbatch, nseqlen, -1) # (B, nseq, dim_motion)
|
||||
debug(self.opt, f"[forward] reshape shape = {pred.shape}", verbose=False)
|
||||
|
||||
|
||||
return pred
|
||||
|
||||
|
||||
@@ -0,0 +1,121 @@
|
||||
import torch
|
||||
import torch.nn as nn
|
||||
from common.debug import debug
|
||||
|
||||
class Audio2MotionConvLSTM(nn.Module):
|
||||
|
||||
def __init__(self, opt):
|
||||
super(Audio2MotionConvLSTM, self).__init__()
|
||||
|
||||
self.opt = opt
|
||||
self.dim_motion = opt.MODEL.dim_motion # 53
|
||||
self.dim_speech = opt.MODEL.dim_speech # 29
|
||||
self.dim_hidden = opt.MODEL.dim_hidden # 256
|
||||
|
||||
# encoder
|
||||
self.encoder = nn.Sequential( # (nbatch, nchannel=29, H=16, W=1)
|
||||
# block 1
|
||||
nn.Conv2d(self.dim_speech, 32, kernel_size=(3,1), stride=(1,1), padding=(1,0), bias=True), # 32 x 16 x 1
|
||||
nn.BatchNorm2d(32),
|
||||
nn.LeakyReLU(0.02, True),
|
||||
nn.Conv2d(32, 32, kernel_size=(3,1), stride=(1,1), padding=(1,0), bias=True), # 32 x 16 x 1
|
||||
nn.BatchNorm2d(32),
|
||||
nn.LeakyReLU(0.02, True),
|
||||
nn.Conv2d(32, 32, kernel_size=(3,1), stride=(1,1), padding=(1,0), bias=True), # 32 x 16 x 1
|
||||
nn.BatchNorm2d(32),
|
||||
nn.LeakyReLU(0.02, True),
|
||||
|
||||
# block 2
|
||||
nn.Conv2d(32, 128, kernel_size=(3,1), stride=(2,1), padding=(1,0), bias=True), # 128 x 8 x 1
|
||||
nn.BatchNorm2d(128),
|
||||
nn.LeakyReLU(0.02, True),
|
||||
nn.Conv2d(128, 128, kernel_size=(3,1), stride=(1,1), padding=(1,0), bias=True), # 128 x 8 x 1
|
||||
nn.BatchNorm2d(128),
|
||||
nn.LeakyReLU(0.02, True),
|
||||
nn.Conv2d(128, 128, kernel_size=(3,1), stride=(1,1), padding=(1,0), bias=True), # 128 x 8 x 1
|
||||
nn.BatchNorm2d(128),
|
||||
nn.LeakyReLU(0.02, True),
|
||||
nn.Conv2d(128, 128, kernel_size=(3,1), stride=(1,1), padding=(1,0), bias=True), # 128 x 8 x 1
|
||||
nn.BatchNorm2d(128),
|
||||
nn.LeakyReLU(0.02, True),
|
||||
|
||||
|
||||
# block 3
|
||||
nn.Conv2d(128, 256, kernel_size=(3,1), stride=(2,1), padding=(1,0), bias=True), # 256 x 4 x 1
|
||||
nn.BatchNorm2d(256),
|
||||
nn.LeakyReLU(0.02, True),
|
||||
nn.Conv2d(256, 256, kernel_size=(3,1), stride=(1,1), padding=(1,0), bias=True), # 256 x 4 x 1
|
||||
nn.BatchNorm2d(256),
|
||||
nn.LeakyReLU(0.02, True),
|
||||
nn.Conv2d(256, 256, kernel_size=(3,1), stride=(2,1), padding=(1,0), bias=True), # 256 x 2 x 1
|
||||
nn.BatchNorm2d(256),
|
||||
nn.LeakyReLU(0.02, True),
|
||||
nn.Conv2d(256, 256, kernel_size=(3,1), stride=(2,1), padding=(1,0), bias=True), # 256 x 1 x 1
|
||||
nn.BatchNorm2d(256),
|
||||
nn.LeakyReLU(0.02, True),
|
||||
|
||||
)
|
||||
|
||||
# # lstm
|
||||
self.LSTM = nn.LSTM(
|
||||
input_size = self.dim_hidden,
|
||||
hidden_size = self.dim_hidden,
|
||||
num_layers= 2,
|
||||
dropout = 0,
|
||||
bidirectional=False,
|
||||
batch_first = True
|
||||
)
|
||||
|
||||
# output
|
||||
self.decoder = nn.Sequential(
|
||||
nn.Linear(in_features=self.dim_hidden, out_features=4*self.dim_hidden),
|
||||
nn.LayerNorm(4*self.dim_hidden),
|
||||
nn.LeakyReLU(0.2),
|
||||
nn.Dropout(0.1),
|
||||
|
||||
nn.Linear(in_features=4*self.dim_hidden, out_features=self.dim_hidden),
|
||||
nn.LayerNorm(self.dim_hidden),
|
||||
nn.LeakyReLU(0.2),
|
||||
# nn.Dropout(0.1),
|
||||
|
||||
nn.Linear(in_features=self.dim_hidden, out_features=self.dim_motion),
|
||||
nn.Tanh()
|
||||
)
|
||||
|
||||
|
||||
def forward(self, x):
|
||||
""" forward function
|
||||
Args:
|
||||
x: torch.Tensor, [nbatch x seqlen x nwind x dim_condit]
|
||||
return:
|
||||
pred: torch.Tensor, [nbatch x seqlen x dim_motion]
|
||||
"""
|
||||
|
||||
(nbatch, nseqlen, nwind, nfeat) = x.shape # (B, nseq, 16, 29)
|
||||
debug(self.opt, f"[forward] input x shape = {x.shape}", verbose=False)
|
||||
|
||||
# preprocessing data
|
||||
x = x.reshape(nbatch * nseqlen, 1, nwind, nfeat) # (B * nseq, 1, 16, 29)
|
||||
x = torch.transpose(x, 1, 3) # (B * nseq, 29, 16, 1)
|
||||
debug(self.opt, f"[forward] transpose x shape = {x.shape}", verbose=False)
|
||||
|
||||
|
||||
feat = self.encoder(x) # (B * nseq, 256, 1, 1)
|
||||
debug(self.opt, f"[forward] encoder shape = {feat.shape}", verbose=False)
|
||||
|
||||
feat = feat.reshape(nbatch, nseqlen, -1) # (B, nseq, 256)
|
||||
debug(self.opt, f"[forward] view shape = {feat.shape}", verbose=False)
|
||||
|
||||
|
||||
feat, _ = self.LSTM(feat) # (B, nseq, 256)
|
||||
debug(self.opt, f"[forward] lstm shape = {feat.shape}", verbose=False)
|
||||
|
||||
pred = self.decoder(feat) # (B, nseq, dim_motion)
|
||||
debug(self.opt, f"[forward] decoder shape = {pred.shape}", verbose=False)
|
||||
|
||||
# pred = pred.reshape(nbatch, nseqlen, -1) # (B, nseq, dim_motion)
|
||||
# debug(self.opt, f"[forward] reshape shape = {pred.shape}", verbose=False)
|
||||
|
||||
return pred
|
||||
|
||||
|
||||
@@ -0,0 +1,90 @@
|
||||
import torch
|
||||
import torch.nn as nn
|
||||
from common.debug import debug
|
||||
|
||||
class Audio2MotionNoLSTM(nn.Module):
|
||||
|
||||
def __init__(self, opt):
|
||||
super(Audio2MotionNoLSTM, self).__init__()
|
||||
|
||||
self.opt = opt
|
||||
nseqR = opt.MODEL.n_lookprevs # 3
|
||||
nseqL = opt.MODEL.n_lookahead # 1
|
||||
nLSTM = opt.MODEL.n_layer_lstm # 3
|
||||
|
||||
self.dim_motion = opt.MODEL.dim_motion # 53
|
||||
self.dim_speech = opt.MODEL.dim_speech # 27
|
||||
self.dim_hidden = opt.MODEL.dim_hidden # 256
|
||||
self.dim_condit = self.dim_speech * (nseqR + 1 + nseqL) # 27 * (3 + 1 + 3) = 1382
|
||||
|
||||
print(f"dim_condit={self.dim_condit}")
|
||||
|
||||
# encoder
|
||||
self.encoder = nn.Sequential( # nbatch x nseqlen x 27
|
||||
nn.Linear(in_features=self.dim_condit, out_features=self.dim_hidden),
|
||||
nn.LayerNorm(self.dim_hidden),
|
||||
nn.LeakyReLU(0.2),
|
||||
# nn.Dropout(0.3),
|
||||
|
||||
nn.Linear(in_features=self.dim_hidden, out_features=1024),
|
||||
nn.LayerNorm(1024),
|
||||
nn.LeakyReLU(0.2),
|
||||
nn.Dropout(0.1),
|
||||
|
||||
nn.Linear(in_features=1024, out_features=self.dim_hidden),
|
||||
nn.LayerNorm(self.dim_hidden),
|
||||
nn.LeakyReLU(0.2),
|
||||
# nn.Dropout(0.1),
|
||||
)
|
||||
|
||||
# # lstm
|
||||
# self.LSTM = nn.LSTM(
|
||||
# input_size = self.dim_hidden,
|
||||
# hidden_size = self.dim_hidden,
|
||||
# num_layers= nLSTM,
|
||||
# dropout = 0,
|
||||
# bidirectional=False,
|
||||
# batch_first = True
|
||||
# )
|
||||
|
||||
# output
|
||||
self.decoder = nn.Sequential(
|
||||
nn.Linear(in_features=self.dim_hidden, out_features=1024),
|
||||
nn.LayerNorm(1024),
|
||||
nn.LeakyReLU(0.2),
|
||||
nn.Dropout(0.1),
|
||||
|
||||
nn.Linear(in_features=1024, out_features=1024),
|
||||
nn.LayerNorm(1024),
|
||||
nn.LeakyReLU(0.2),
|
||||
nn.Dropout(0.1),
|
||||
|
||||
nn.Linear(in_features=1024, out_features=self.dim_motion),
|
||||
nn.Tanh()
|
||||
)
|
||||
|
||||
def forward(self, x):
|
||||
""" forward function
|
||||
Args:
|
||||
x: torch.Tensor, [nbatch x seqlen x dim_condit]
|
||||
target: torch.Tensor, [nbatch x seqlen x dim_motion]
|
||||
return:
|
||||
pred: torch.Tensor, [nbatch x seqlen x dim_motion]
|
||||
"""
|
||||
|
||||
debug(self.opt, f"[forward] input x shape = {x.shape}", verbose=False)
|
||||
|
||||
feat = self.encoder(x) # [nbatch x nseqlen x dim_hidden]
|
||||
debug(self.opt, f"[forward] encoder shape = {feat.shape}", verbose=False)
|
||||
|
||||
|
||||
# feat, _ = self.LSTM(feat) # [nbatch x nseqlen x dim_hidden]
|
||||
# debug(self.opt, f"[forward] lstm shape = {feat.shape}", verbose=False)
|
||||
|
||||
|
||||
pred = self.decoder(feat) # [nbatch x nseqlen x dim_motion]
|
||||
debug(self.opt, f"[forward] decoder shape = {pred.shape}", verbose=False)
|
||||
|
||||
return pred
|
||||
|
||||
|
||||
@@ -0,0 +1,74 @@
|
||||
import torch
|
||||
import torch.nn as nn
|
||||
from common.debug import debug
|
||||
|
||||
class Audio2MotionVOCA(nn.Module):
|
||||
|
||||
def __init__(self, opt):
|
||||
super(Audio2MotionVOCA, self).__init__()
|
||||
|
||||
self.opt = opt
|
||||
self.dim_motion = opt.MODEL.dim_motion # 53
|
||||
self.dim_speech = opt.MODEL.dim_speech # 29
|
||||
self.dim_hidden = opt.MODEL.dim_hidden # 256
|
||||
|
||||
# encoder
|
||||
self.encoder = nn.Sequential( # (nbatch, nchannel=29, H=16, W=1)
|
||||
nn.BatchNorm2d(self.dim_speech),
|
||||
# block 1
|
||||
nn.Conv2d(self.dim_speech, 32, kernel_size=(3,1), stride=(2,1), padding=(1,0), bias=True), # 32 x 8 x 1
|
||||
nn.LeakyReLU(0.02, True),
|
||||
|
||||
nn.Conv2d(32, 32, kernel_size=(3,1), stride=(2,1), padding=(1,0), bias=True), # 32 x 4 x 1
|
||||
nn.LeakyReLU(0.02, True),
|
||||
|
||||
nn.Conv2d(32, 64, kernel_size=(3,1), stride=(2,1), padding=(1,0), bias=True), # 64 x 2 x 1
|
||||
nn.LeakyReLU(0.02, True),
|
||||
|
||||
nn.Conv2d(64, 64, kernel_size=(3,1), stride=(2,1), padding=(1,0), bias=True), # 64 x 1 x 1
|
||||
nn.LeakyReLU(0.02, True),
|
||||
|
||||
nn.Flatten(), # 64,
|
||||
|
||||
nn.Linear(in_features=64, out_features=128), # 128,
|
||||
nn.Tanh(),
|
||||
|
||||
nn.Linear(in_features=128, out_features=50) # 50,
|
||||
)
|
||||
|
||||
|
||||
# output
|
||||
self.decoder = nn.Sequential(
|
||||
nn.Linear(in_features=50, out_features=self.dim_motion),
|
||||
)
|
||||
|
||||
|
||||
def forward(self, x):
|
||||
""" forward function
|
||||
Args:
|
||||
x: torch.Tensor, [nbatch x seqlen x nwind x dim_condit]
|
||||
return:
|
||||
pred: torch.Tensor, [nbatch x seqlen x dim_motion]
|
||||
"""
|
||||
(nbatch, nseqlen, nwind, nfeat) = x.shape # (B, nseq, 16, 29)
|
||||
debug(self.opt, f"[forward] input x shape = {x.shape}", verbose=False)
|
||||
|
||||
# preprocessing data
|
||||
x = x.reshape(nbatch * nseqlen, 1, nwind, nfeat) # (B * nseq, 1, 16, 29)
|
||||
x = torch.transpose(x, 1, 3) # (B * nseq, 29, 16, 1)
|
||||
debug(self.opt, f"[forward] transpose x shape = {x.shape}", verbose=False)
|
||||
|
||||
|
||||
feat = self.encoder(x) # (B * nseq, 50)
|
||||
debug(self.opt, f"[forward] encoder shape = {feat.shape}", verbose=False)
|
||||
|
||||
|
||||
pred = self.decoder(feat) # (B * nseq, dim_motion)
|
||||
debug(self.opt, f"[forward] decoder shape = {pred.shape}", verbose=False)
|
||||
|
||||
pred = pred.reshape(nbatch, nseqlen, -1) # (B, nseq, dim_motion)
|
||||
debug(self.opt, f"[forward] reshape shape = {pred.shape}", verbose=False)
|
||||
|
||||
return pred
|
||||
|
||||
|
||||
@@ -0,0 +1,74 @@
|
||||
import torch
|
||||
import torch.nn as nn
|
||||
from common.debug import debug
|
||||
|
||||
class Audio2MotionVOCA2(nn.Module):
|
||||
|
||||
def __init__(self, opt):
|
||||
super(Audio2MotionVOCA2, self).__init__()
|
||||
|
||||
self.opt = opt
|
||||
self.dim_motion = opt.MODEL.dim_motion # 53
|
||||
self.dim_speech = opt.MODEL.dim_speech # 29
|
||||
self.dim_hidden = opt.MODEL.dim_hidden # 256
|
||||
|
||||
# encoder
|
||||
self.encoder = nn.Sequential( # (nbatch, nchannel=29, H=16, W=1)
|
||||
nn.BatchNorm2d(self.dim_speech),
|
||||
# block 1
|
||||
nn.Conv2d(self.dim_speech, 64, kernel_size=(3,1), stride=(2,1), padding=(1,0), bias=True), # 32 x 8 x 1
|
||||
nn.LeakyReLU(0.02, True),
|
||||
|
||||
nn.Conv2d(64, 128, kernel_size=(3,1), stride=(2,1), padding=(1,0), bias=True), # 32 x 4 x 1
|
||||
nn.LeakyReLU(0.02, True),
|
||||
|
||||
nn.Conv2d(128, 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=(2,1), padding=(1,0), bias=True), # 64 x 1 x 1
|
||||
nn.LeakyReLU(0.02, True),
|
||||
|
||||
nn.Flatten(), # 64,
|
||||
|
||||
nn.Linear(in_features=256, out_features=1024), # 128,
|
||||
nn.Tanh(),
|
||||
|
||||
nn.Linear(in_features=1024, out_features=128) # 50,
|
||||
)
|
||||
|
||||
|
||||
# output
|
||||
self.decoder = nn.Sequential(
|
||||
nn.Linear(in_features=128, out_features=self.dim_motion),
|
||||
)
|
||||
|
||||
|
||||
def forward(self, x):
|
||||
""" forward function
|
||||
Args:
|
||||
x: torch.Tensor, [nbatch x seqlen x nwind x dim_condit]
|
||||
return:
|
||||
pred: torch.Tensor, [nbatch x seqlen x dim_motion]
|
||||
"""
|
||||
(nbatch, nseqlen, nwind, nfeat) = x.shape # (B, nseq, 16, 29)
|
||||
debug(self.opt, f"[forward] input x shape = {x.shape}", verbose=False)
|
||||
|
||||
# preprocessing data
|
||||
x = x.reshape(nbatch * nseqlen, 1, nwind, nfeat) # (B * nseq, 1, 16, 29)
|
||||
x = torch.transpose(x, 1, 3) # (B * nseq, 29, 16, 1)
|
||||
debug(self.opt, f"[forward] transpose x shape = {x.shape}", verbose=False)
|
||||
|
||||
|
||||
feat = self.encoder(x) # (B * nseq, 50)
|
||||
debug(self.opt, f"[forward] encoder shape = {feat.shape}", verbose=False)
|
||||
|
||||
|
||||
pred = self.decoder(feat) # (B * nseq, dim_motion)
|
||||
debug(self.opt, f"[forward] decoder shape = {pred.shape}", verbose=False)
|
||||
|
||||
pred = pred.reshape(nbatch, nseqlen, -1) # (B, nseq, dim_motion)
|
||||
debug(self.opt, f"[forward] reshape shape = {pred.shape}", verbose=False)
|
||||
|
||||
return pred
|
||||
|
||||
|
||||
@@ -0,0 +1,69 @@
|
||||
import torch
|
||||
import torch.nn as nn
|
||||
from torch.optim import lr_scheduler
|
||||
|
||||
def get_optimizer(net, opt):
|
||||
|
||||
optim = None
|
||||
|
||||
if opt.TRAIN.optimizer == "Adam":
|
||||
optim = torch.optim.Adam(
|
||||
filter(lambda p: p.requires_grad, net.parameters()),
|
||||
lr=opt.TRAIN.lr,
|
||||
betas=(opt.TRAIN.beta1, opt.TRAIN.beta2), \
|
||||
weight_decay=opt.TRAIN.weight_decay)
|
||||
|
||||
elif opt.TRAIN.optimizer == "SGD":
|
||||
optim = torch.optim.SGD(
|
||||
filter(lambda p: p.requires_grad, net.parameters()),
|
||||
lr=opt.TRAIN.lr,
|
||||
momentum=opt.TRAIN.momentum,
|
||||
weight_decay=opt.TRAIN.weight_decay,
|
||||
nesterov=opt.TRAIN.nesterov)
|
||||
|
||||
else:
|
||||
raise NotImplementedError(f"opt.TRAIN.optimizer ({opt.TRAIN.optimizer}) NOT implemented!! ")
|
||||
|
||||
|
||||
return optim
|
||||
|
||||
def get_scheduler(optimizer, opt):
|
||||
"""Return a learning rate scheduler
|
||||
|
||||
Parameters:
|
||||
optimizer -- the optimizer of the network
|
||||
opt (option class) -- stores all the experiment flags; needs to be a subclass of BaseOptions.
|
||||
opt.lr_policy is the name of learning rate policy: linear | step | plateau | cosine
|
||||
|
||||
For 'linear', we keep the same learning rate for the first <opt.niter> epochs
|
||||
and linearly decay the rate to zero over the next <opt.niter_decay> epochs.
|
||||
For other schedulers (step, plateau, and cosine), we use the default PyTorch schedulers.
|
||||
See https://pytorch.org/docs/stable/optim.html for more details.
|
||||
"""
|
||||
if opt.TRAIN.lr_policy == 'linear':
|
||||
def lambda_rule(epoch):
|
||||
lr_l = 1.0 - max(0, epoch + opt.TRAIN.epoch_begin - opt.TRAIN.epoch_end) / float(opt.TRAIN.niter_decay + 1)
|
||||
return lr_l
|
||||
scheduler = lr_scheduler.LambdaLR(optimizer, lr_lambda=lambda_rule)
|
||||
|
||||
elif opt.TRAIN.lr_policy == 'step':
|
||||
scheduler = lr_scheduler.StepLR(optimizer, step_size=opt.TRAIN.lr_decay_iters, gamma=0.1)
|
||||
|
||||
elif opt.TRAIN.lr_policy == 'multistep':
|
||||
scheduler = lr_scheduler.MultiStepLR(optimizer, milestones=opt.TRAIN.lr_milestones, gamma=0.1)
|
||||
|
||||
elif opt.TRAIN.lr_policy == 'plateau':
|
||||
scheduler = lr_scheduler.ReduceLROnPlateau(optimizer,
|
||||
mode='min', # In min mode, lr will be reduced when the quantity monitored has stopped decreasing;
|
||||
factor=0.5, # new_lr = lr * factor. Default: 0.1., Factor by which the learning rate will be reduced.
|
||||
threshold=1e-4, # Threshold for measuring the new optimum
|
||||
min_lr=1e-6, # A lower bound on the learning rate
|
||||
patience=5, # Number of epochs with no improvement after which learning rate will be reduced
|
||||
)
|
||||
elif opt.TRAIN.lr_policy == 'cosine':
|
||||
scheduler = lr_scheduler.CosineAnnealingLR(optimizer, T_max=opt.TRAIN.epoch_end, eta_min=1e-6)
|
||||
else:
|
||||
return NotImplementedError('learning rate policy [%s] is not implemented', opt.TRAIN.lr_policy)
|
||||
|
||||
|
||||
return scheduler
|
||||
@@ -0,0 +1,40 @@
|
||||
'''A wrapper class for scheduled optimizer '''
|
||||
import numpy as np
|
||||
|
||||
class ScheduledOptim():
|
||||
'''A simple wrapper class for learning rate scheduling'''
|
||||
|
||||
def __init__(self, optimizer, lr_mul, d_model, n_warmup_steps):
|
||||
self._optimizer = optimizer
|
||||
self.lr_mul = lr_mul
|
||||
self.d_model = d_model
|
||||
self.n_warmup_steps = n_warmup_steps
|
||||
self.n_steps = 0
|
||||
|
||||
|
||||
def step_and_update_lr(self):
|
||||
"Step with the inner optimizer"
|
||||
self._update_learning_rate()
|
||||
self._optimizer.step()
|
||||
|
||||
|
||||
def zero_grad(self):
|
||||
"Zero out the gradients with the inner optimizer"
|
||||
self._optimizer.zero_grad()
|
||||
|
||||
|
||||
def _get_lr_scale(self):
|
||||
d_model = self.d_model
|
||||
n_steps, n_warmup_steps = self.n_steps, self.n_warmup_steps
|
||||
return (d_model ** -0.5) * min(n_steps ** (-0.5), n_steps * n_warmup_steps ** (-1.5))
|
||||
|
||||
|
||||
def _update_learning_rate(self):
|
||||
''' Learning rate scheduling per step '''
|
||||
|
||||
self.n_steps += 1
|
||||
lr = self.lr_mul * self._get_lr_scale()
|
||||
|
||||
for param_group in self._optimizer.param_groups:
|
||||
param_group['lr'] = lr
|
||||
|
||||
Reference in new issue
Block a user