add audio2mesh model support
This commit is contained in:
1 parent
5eb304186a
commit
386df9a4ab
83 files changed
+9318
-1307
No files matched your search
+23
-10
@@ -58,6 +58,7 @@ config.CUDNN.enable = True
|
||||
config.MODEL = edict()
|
||||
config.MODEL.name = "LandmarkAE"
|
||||
config.MODEL.name_netG = "MLP"
|
||||
config.MODEL.name_header = "resnet50"
|
||||
config.MODEL.dropout = 0.1
|
||||
|
||||
# load & init model
|
||||
@@ -66,11 +67,12 @@ 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.num_vertices = 0 # 5023
|
||||
|
||||
config.MODEL.n_lookprevs_motion = 0
|
||||
config.MODEL.n_lookprevs_speech = 0
|
||||
|
||||
@@ -80,11 +82,14 @@ config.MODEL.n_lookahead_speech = 0
|
||||
config.MODEL.n_layer_lstm = 0
|
||||
|
||||
|
||||
# # 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 MOGLOW
|
||||
config.MODEL.n_flowstep = 0
|
||||
config.MODEL.n_early_every = 0
|
||||
config.MODEL.n_early_size = 0
|
||||
config.MODEL.n_layer_wave = 0
|
||||
config.MODEL.kernel_size = 0
|
||||
config.MODEL.lambda_std = []
|
||||
config.MODEL.fix_dims = []
|
||||
|
||||
# # for transformer
|
||||
# config.MODEL.n_src_vocab = 0
|
||||
@@ -125,6 +130,8 @@ config.DATASET.sr = 16000
|
||||
config.DATASET.name = 'ravdess'
|
||||
config.DATASET.type = '' # "clips" | "frame" | "none"
|
||||
config.DATASET.root = "../data/"
|
||||
config.DATASET.root_raw = "/data/lsen/DATA/xxxx/processing"
|
||||
config.DATASET.path_mean_dict = "./data/xxxx_mean.npy"
|
||||
|
||||
# from dataset iteratiion
|
||||
config.DATASET.nwind_second_train = 0
|
||||
@@ -182,7 +189,7 @@ config.TRAIN.beta_stop = 1.0
|
||||
|
||||
config.TRAIN.optimizer = 'adam'
|
||||
config.TRAIN.momentum = 0.9
|
||||
config.TRAIN.weight_decay = 0.0001
|
||||
config.TRAIN.weight_decay = 0 #0.0001
|
||||
config.TRAIN.nesterov = False
|
||||
config.TRAIN.gamma1 = 0.99
|
||||
config.TRAIN.gamma2 = 0.0
|
||||
@@ -193,13 +200,19 @@ config.LOSS = edict()
|
||||
config.LOSS.names = ["all", "L1"]
|
||||
|
||||
config.LOSS.lambda_rec = 1
|
||||
config.LOSS.lambda_rec_smooth = 0
|
||||
|
||||
config.LOSS.lambda_rec_exp = 0
|
||||
config.LOSS.lambda_rec_pos = 0
|
||||
config.LOSS.lambda_rec_geo = 0
|
||||
config.LOSS.lambda_rec_syn = 0
|
||||
|
||||
config.LOSS.lambda_vol_exp = 0
|
||||
config.LOSS.lambda_vol_pos = 0
|
||||
config.LOSS.lambda_geo = 0
|
||||
config.LOSS.lambda_rec_smooth = 0
|
||||
config.LOSS.lambda_geo_smooth = 0
|
||||
config.LOSS.lambda_vol_geo = 0
|
||||
config.LOSS.lambda_vol_syn = 0
|
||||
|
||||
# for Flow
|
||||
config.LOSS.lambda_logp = 0
|
||||
config.LOSS.lambda_logdet = 0
|
||||
|
||||
|
||||
@@ -18,18 +18,23 @@ class MotionLiveDataset(Dataset):
|
||||
"""
|
||||
super(MotionLiveDataset, self).__init__()
|
||||
|
||||
|
||||
self.opt = opt
|
||||
self.phase = phase
|
||||
path_data= Path(opt.DATASET.root).joinpath(f"data_{phase}.npz")
|
||||
|
||||
# for test
|
||||
# if phase == "valid":
|
||||
# path_data= Path(opt.DATASET.root).joinpath(f"data_train.npz")
|
||||
|
||||
# if phase == "test":
|
||||
# path_data= Path(opt.DATASET.root).joinpath(f"data_train.npz")
|
||||
|
||||
print(f"\n [{self.phase}] load data ... --> {path_data}")
|
||||
# dict vid: {"data_motion", # [nframe, 53]
|
||||
# "data_speech", # [duration * sample_rate, ] raw deepseep
|
||||
# "nframe", "fps", "sr"}
|
||||
self.annodb = np.load(path_data, allow_pickle=True)['data'].item()
|
||||
|
||||
|
||||
self.num_pid = len(self.annodb)
|
||||
self.pids = list(self.annodb.keys())
|
||||
|
||||
@@ -60,9 +65,9 @@ class MotionLiveDataset(Dataset):
|
||||
|
||||
def __len__(self):
|
||||
if self.phase == "train":
|
||||
return 20000
|
||||
return 20000 #40000
|
||||
elif self.phase == "valid":
|
||||
return 1000
|
||||
return 2000 #5000
|
||||
else:
|
||||
return 100
|
||||
|
||||
@@ -77,11 +82,20 @@ class MotionLiveDataset(Dataset):
|
||||
"""
|
||||
np.random.seed(int(idx + time.time()))
|
||||
vid = self.pids[idx % self.num_pid]
|
||||
|
||||
# # filter "2021-P29"
|
||||
# while vid == "2021-P29":
|
||||
# vid = self.pids[idx % self.num_pid]
|
||||
|
||||
# random select idx
|
||||
data = self.annodb[vid]
|
||||
data_motion = data["data_motion"] # (nframes, nc_motion)
|
||||
data_speech = data["data_speech"] # (nsegemts, )
|
||||
data_motion = data["data_motion"] # (nframes, nc_motion)
|
||||
data_speech = data["data_speech"] # (nsegemts, )
|
||||
# data_shape = data["data_shape"] # (nframes, nc_shape)
|
||||
|
||||
data_motion = data["data_motion"] # (nframes, nc_motion)
|
||||
data_speech = data["data_speech"] # (nsegemts, )
|
||||
# data_shape = data["data_shape"] # (nframes, nc_shape)
|
||||
|
||||
nframe = data_motion.shape[0]
|
||||
nsegmt = data_speech.shape[0]
|
||||
@@ -94,22 +108,27 @@ class MotionLiveDataset(Dataset):
|
||||
end_segmt = beg_segmt + self.nsteps_segmt
|
||||
# print(f"nframe-{self.nsteps_frame:04d} =[{beg_frame:04d},{end_frame:04d})\t nsegmet-{self.nsteps_segmt:04d}=[{beg_segmt:04d},{end_segmt:04d}), vid={vid}")
|
||||
|
||||
|
||||
data_motion = data_motion[beg_frame:end_frame, :] # (nteps, 53)
|
||||
data_speech = data_speech[beg_segmt:end_segmt] # (nsegmt_steps, )
|
||||
# data_shape = data_shape[beg_frame:end_frame, :] # (nsteps, 100)
|
||||
|
||||
|
||||
# filter, explore doc: ./notebook/explore_pose.ipynb
|
||||
if self.opt.DATASET.filter == "savgol":
|
||||
data_motion = savgol_filter(data_motion, window_length=5, polyorder=3, axis=0, mode='nearest')
|
||||
# data_shape = savgol_filter(data_shape, window_length=5, polyorder=3, axis=0, mode='nearest')
|
||||
|
||||
|
||||
result = {
|
||||
"data": data_motion, # (nsteps_frame, dim_motion)
|
||||
"cond": data_speech, # (nsteps_frame, dim_speech)
|
||||
# "shape": data_shape,
|
||||
"vid": vid,
|
||||
"nframe": nframe,
|
||||
"frame_interval": [beg_frame, end_frame],
|
||||
# "duration_interval": [beg_frame/nframe, end_frame/nframe]
|
||||
}
|
||||
|
||||
assert data_speech.shape[0] == self.nsteps_segmt, f"data_speech shape={data_speech.shape}, vid={vid}"
|
||||
|
||||
return result
|
||||
@@ -0,0 +1,132 @@
|
||||
import numpy as np
|
||||
import torch
|
||||
import time
|
||||
from torch.utils.data import Dataset
|
||||
from pathlib import Path
|
||||
from scipy.signal import savgol_filter
|
||||
|
||||
from common.debug import debug
|
||||
|
||||
class MotionLive2Dataset(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(MotionLive2Dataset, self).__init__()
|
||||
|
||||
|
||||
self.opt = opt
|
||||
self.phase = phase
|
||||
path_data= Path(opt.DATASET.root).joinpath(f"data_{phase}.npz")
|
||||
|
||||
# for test
|
||||
# if phase == "valid":
|
||||
# path_data= Path(opt.DATASET.root).joinpath(f"data_train.npz")
|
||||
|
||||
# if phase == "test":
|
||||
# path_data= Path(opt.DATASET.root).joinpath(f"data_train.npz")
|
||||
|
||||
|
||||
print(f"\n [{self.phase}] load data ... --> {path_data}")
|
||||
# dict vid: {"data_motion", # [nframe, 53]
|
||||
# "data_speech", # [duration * sample_rate, ] raw deepseep
|
||||
# "nframe", "fps", "sr"}
|
||||
self.annodb = np.load(path_data, allow_pickle=True)['data'].item()
|
||||
self.num_pid = len(self.annodb)
|
||||
self.pids = list(self.annodb.keys())
|
||||
|
||||
self.fps = opt.DATASET.fps # 50
|
||||
self.sr = opt.DATASET.sr # 16000
|
||||
|
||||
self.nwind = eval(f"opt.DATASET.nwind_second_{phase}")
|
||||
self.nsteps_frame = self.nwind * self.fps
|
||||
self.nsteps_segmt = self.nwind * self.sr
|
||||
|
||||
print(f'''len(annodb)={len(self.annodb)}\t'''
|
||||
f'''nsteps_frame={self.nsteps_frame}\t'''
|
||||
f'''nsteps_segmt={self.nsteps_segmt} ''')
|
||||
|
||||
|
||||
# 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}")
|
||||
|
||||
# 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 __len__(self):
|
||||
if self.phase == "train":
|
||||
return 20000 #40000
|
||||
elif self.phase == "valid":
|
||||
return 2000 #5000
|
||||
else:
|
||||
return 100
|
||||
|
||||
def __getitem__(self, idx):
|
||||
"""
|
||||
Returns poses and conditioning.
|
||||
If data-dropout sould be applied, a random selection of the previous poses is masked.
|
||||
The control is not masked
|
||||
return:
|
||||
motion: (nsteps, nc_motion), current frame's pose (15 joint, xyz position)
|
||||
speech: (nsteps, nc_speech), conditional data = previous motion data + full windows contrl data
|
||||
"""
|
||||
np.random.seed(int(idx + time.time()))
|
||||
vid = self.pids[idx % self.num_pid]
|
||||
|
||||
# # filter "2021-P29"
|
||||
# while vid == "2021-P29":
|
||||
# vid = self.pids[idx % self.num_pid]
|
||||
|
||||
# random select idx
|
||||
data = self.annodb[vid]
|
||||
data_motion = data["data_motion"] # (nframes, nc_motion)
|
||||
data_speech = data["data_speech"] # (nsegemts, )
|
||||
data_shape = data["data_shape"] # (nframes, nc_shape)
|
||||
|
||||
nframe = data_motion.shape[0]
|
||||
nsegmt = data_speech.shape[0]
|
||||
|
||||
# random select beg:end frame
|
||||
beg_frame = np.random.randint(nframe - self.nsteps_frame - 10) + 5 # select from (5:-5)
|
||||
end_frame = beg_frame + self.nsteps_frame
|
||||
|
||||
beg_segmt = int((1.0 * beg_frame / nframe) * nsegmt)
|
||||
end_segmt = beg_segmt + self.nsteps_segmt
|
||||
# print(f"nframe-{self.nsteps_frame:04d} =[{beg_frame:04d},{end_frame:04d})\t nsegmet-{self.nsteps_segmt:04d}=[{beg_segmt:04d},{end_segmt:04d}), vid={vid}")
|
||||
|
||||
data_motion = data_motion[beg_frame:end_frame, :] # (nteps, 53)
|
||||
data_speech = data_speech[beg_segmt:end_segmt] # (nsegmt_steps, )
|
||||
data_shape = data_shape[beg_frame:end_frame, :] # (nsteps, 100)
|
||||
|
||||
|
||||
|
||||
# filter, explore doc: ./notebook/explore_pose.ipynb
|
||||
if self.opt.DATASET.filter == "savgol":
|
||||
data_motion = savgol_filter(data_motion, window_length=5, polyorder=3, axis=0, mode='nearest')
|
||||
data_shape = savgol_filter(data_shape, window_length=5, polyorder=3, axis=0, mode='nearest')
|
||||
|
||||
|
||||
result = {
|
||||
"data": data_motion, # (nsteps_frame, dim_motion)
|
||||
"cond": data_speech, # (nsteps_frame, dim_speech)
|
||||
"shape": data_shape,
|
||||
"vid": vid,
|
||||
"nframe": nframe,
|
||||
"frame_interval": [beg_frame, end_frame],
|
||||
# "duration_interval": [beg_frame/nframe, end_frame/nframe]
|
||||
}
|
||||
|
||||
assert data_speech.shape[0] == self.nsteps_segmt, f"data_speech shape={data_speech.shape}, vid={vid}"
|
||||
|
||||
return result
|
||||
@@ -0,0 +1,37 @@
|
||||
|
||||
flame_mouth_idx = [
|
||||
1576, 1577, 1578, 1579, 1580, 1581, 1582, 1583, 1584, 1585,
|
||||
1586, 1587, 1590, 1596, 1597, 1598, 1599, 1601, 1603, 1657,
|
||||
1658, 1662, 1663, 1667, 1668, 1669, 1670, 1671, 1672, 1673,
|
||||
1674, 1686, 1687, 1688, 1689, 1690, 1691, 1693, 1694, 1695,
|
||||
1696, 1697, 1698, 1699, 1700, 1701, 1702, 1703, 1704, 1705,
|
||||
1706, 1707, 1708, 1709, 1710, 1711, 1712, 1713, 1714, 1715,
|
||||
1716, 1717, 1718, 1719, 1720, 1721, 1722, 1723, 1724, 1725,
|
||||
1728, 1729, 1730, 1731, 1732, 1733, 1734, 1735, 1736, 1737,
|
||||
1738, 1740, 1741, 1743, 1748, 1749, 1750, 1751, 1758, 1763,
|
||||
1766, 1767, 1768, 1769, 1770, 1771, 1773, 1774, 1775, 1776,
|
||||
1777, 1778, 1781, 1782, 1787, 1788, 1789, 1791, 1792, 1793,
|
||||
1794, 1795, 1796, 1797, 1798, 1799, 1800, 1801, 1802, 1803,
|
||||
1804, 1805, 1826, 1827, 1836, 1848, 1849, 1850, 1863, 1864,
|
||||
1865, 1866, 2712, 2713, 2714, 2715, 2716, 2717, 2718, 2719,
|
||||
2720, 2721, 2722, 2723, 2726, 2727, 2729, 2732, 2733, 2734,
|
||||
2735, 2737, 2738, 2739, 2774, 2775, 2780, 2784, 2786, 2787,
|
||||
2788, 2789, 2790, 2791, 2803, 2804, 2805, 2806, 2807, 2808,
|
||||
2810, 2811, 2812, 2813, 2814, 2815, 2816, 2817, 2818, 2819,
|
||||
2820, 2821, 2822, 2823, 2824, 2825, 2826, 2827, 2828, 2829,
|
||||
2830, 2831, 2832, 2833, 2834, 2835, 2836, 2837, 2838, 2839,
|
||||
2840, 2841, 2842, 2843, 2844, 2845, 2846, 2847, 2848, 2849,
|
||||
2850, 2851, 2852, 2853, 2855, 2858, 2863, 2864, 2865, 2866,
|
||||
2869, 2871, 2873, 2874, 2875, 2876, 2877, 2878, 2879, 2880,
|
||||
2881, 2882, 2883, 2884, 2885, 2887, 2888, 2889, 2890, 2891,
|
||||
2892, 2894, 2895, 2896, 2897, 2898, 2899, 2900, 2901, 2902,
|
||||
2903, 2904, 2905, 2906, 2907, 2908, 2928, 2929, 2934, 2937,
|
||||
2938, 2939, 2946, 2947, 2948, 2949, 3174, 3429, 3430, 3431,
|
||||
3432, 3433, 3434, 3489, 3490, 3491, 3492, 3493, 3499, 3502,
|
||||
3503, 3504, 3506, 3507, 3509, 3511, 3513, 3515, 3531, 3537,
|
||||
3538, 3541, 3543, 3546, 3659, 3660, 3662, 3663, 3664, 3761,
|
||||
3762, 3769, 3771, 3772, 3790, 3791, 3792, 3793, 3794, 3795,
|
||||
3796, 3797, 3798, 3799, 3800, 3801, 3802, 3803, 3804, 3805,
|
||||
3806, 3914, 3915, 3916, 3917, 3918, 3919, 3920, 3921, 3922,
|
||||
3923, 3924, 3925, 3926, 3927, 3928
|
||||
]
|
||||
@@ -0,0 +1,442 @@
|
||||
import sys
|
||||
import numpy as np
|
||||
|
||||
import torch
|
||||
import torch.nn as nn
|
||||
import torch.nn.functional as F
|
||||
from pathlib import Path
|
||||
|
||||
from src.models.info import flame_mouth_idx
|
||||
from src.models 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 Audio2MeshModel(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)
|
||||
init_net(self.netG, init_type='kaiming', gpu_ids=opt.GPUS)
|
||||
|
||||
# init last layer
|
||||
init_exp_weight = np.load("/ssdata1/lsen/CODE/voca/training_data/init_expression_basis.npy")
|
||||
init_exp_weight = torch.from_numpy(init_exp_weight).float().to(self.device)
|
||||
init_exp_weight = init_exp_weight[:, :50]
|
||||
self.netG.module.decoder_mesh.weight.data = init_exp_weight
|
||||
print(f"init_exp_weight shape = {init_exp_weight.shape}")
|
||||
|
||||
# # print network parameters
|
||||
# for name, param in self.netG.named_parameters():
|
||||
# print(name, '\t\t', param.size())
|
||||
|
||||
# load mean lighting & shape
|
||||
self.netR, self.flame = define_netR(device=self.device)
|
||||
# self.netG.init_reconstruct_model(self.netR)
|
||||
|
||||
path_deca_mean = Path("./data/DECA_obama_mean.npy")
|
||||
self.mean_dict = np.load(path_deca_mean, allow_pickle=True).item()
|
||||
self.template_verts = self.get_template_vertices()
|
||||
debug(opt, f"template_verts shape = {self.template_verts.shape}")
|
||||
debug(opt, f"mean_dict keys = {self.mean_dict.keys()}", verbose=True)
|
||||
|
||||
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)
|
||||
|
||||
# define loss weight
|
||||
self.vertices_weight = torch.ones((1, 1, self.opt.MODEL.num_vertices, 3)).to(self.device)
|
||||
self.vertices_weight[:, :, flame_mouth_idx, :] = 10
|
||||
|
||||
|
||||
if self.opt.DATASET.speech_extractor == "wav2vec":
|
||||
from transformers import Wav2Vec2FeatureExtractor, Wav2Vec2Model
|
||||
print("load Wav2Vec2Model ...")
|
||||
MODEL_ID = "jonatasgrosman/wav2vec2-large-xlsr-53-chinese-zh-cn"
|
||||
self.processor = Wav2Vec2FeatureExtractor.from_pretrained(MODEL_ID)
|
||||
self.extractor = Wav2Vec2Model.from_pretrained(MODEL_ID).to(self.device)
|
||||
|
||||
|
||||
|
||||
|
||||
def set_input(self, batch_input):
|
||||
|
||||
# motion data
|
||||
self.data = batch_input["data"].float().to(self.device) # (B, nsteps, nc_motion)
|
||||
|
||||
self.batch_vid = batch_input['vid']
|
||||
self.batch_nframe = batch_input['nframe']
|
||||
self.batch_interv = batch_input['frame_interval']
|
||||
self.B, self.nsteps = self.data.size(0), self.data.size(1)
|
||||
|
||||
debug(self.opt, f"data = {self.data.shape}, dtype={self.data.dtype}", verbose=False)
|
||||
debug(self.opt, f"batch_vid = {self.batch_vid[:2]}", verbose=False)
|
||||
debug(self.opt, f"batch_nframe = {self.batch_nframe[:2]}", verbose=False)
|
||||
debug(self.opt, f"batch_interv len={len(self.batch_interv)} len([0])={len(self.batch_interv[0])}, \
|
||||
beg={self.batch_interv[0][:4]}, end={self.batch_interv[1][:4]}", verbose=False)
|
||||
|
||||
# speech data
|
||||
self.cond = None
|
||||
raw_speech = batch_input["cond"].numpy() # (B, nsegments)
|
||||
debug(self.opt, f"raw_speech = {raw_speech.shape}, dtype={raw_speech.dtype}", verbose=False)
|
||||
|
||||
if self.opt.DATASET.speech_extractor == "wav2vec":
|
||||
# raw_speech = raw_speech.reshape(self.B * self.nsteps, -1) # (B*nsteps, nsegments)
|
||||
# debug(self.opt, f"raw_speech = {raw_speech.shape}, dtype={raw_speech.dtype}", verbose=False)
|
||||
|
||||
# padding half frame length for bed and end
|
||||
npad = int(0.5 * self.opt.DATASET.sr * ( 1 / self.opt.DATASET.fps) + 0.5)
|
||||
raw_speech = np.pad(raw_speech, pad_width=((0,0), (npad, npad)), mode="edge")
|
||||
debug(self.opt, f"after padding raw_speech = {raw_speech.shape}, dtype={raw_speech.dtype}", verbose=False)
|
||||
|
||||
raw_speech = list(raw_speech)
|
||||
inputs = self.processor(raw_speech, sampling_rate=16000, return_tensors="pt")
|
||||
inputs = inputs.to(self.device)
|
||||
|
||||
with torch.no_grad():
|
||||
output = self.extractor(**inputs)
|
||||
self.cond = output.last_hidden_state
|
||||
# self.cond = output.extract_features
|
||||
else:
|
||||
assert 0, "opt.DATASET.speech_extractor should be 'wav2vec | deepspeech | mfcc ' "
|
||||
|
||||
# B x nsteps x nc_feat
|
||||
debug(self.opt, f"data = {self.data.shape}, dtype={self.data.dtype}, device={self.data.device}", verbose=False)
|
||||
debug(self.opt, f"cond = {self.cond.shape}, dtype={self.cond.dtype}, device={self.cond.device}", verbose=False)
|
||||
|
||||
# unfold speech data
|
||||
self.cond = self.cond.unfold(dimension=1, size=16, step=1) # (nseqs, nc_motion, 16)
|
||||
self.cond = self.cond.permute(0, 1, 3, 2) # (nseqs, 16, 53)
|
||||
|
||||
self.nseq = self.cond.size(1)
|
||||
self.data = self.data[:, 7:7+self.nseq, :]
|
||||
|
||||
debug(self.opt, f"\n a data = {self.data.shape}, dtype={self.data.dtype}, device={self.data.device}", verbose=False)
|
||||
debug(self.opt, f"a cond = {self.cond.shape}, dtype={self.cond.dtype}, device={self.cond.device}", verbose=False)
|
||||
|
||||
|
||||
def training(self, batch_input):
|
||||
self.train() # set train model
|
||||
self.set_input(batch_input)
|
||||
|
||||
# forward
|
||||
self.pred = self.netG(self.cond)
|
||||
self.pred += self.template_verts
|
||||
debug(self.opt, f"traing pred = {self.pred.shape}", verbose=False)
|
||||
|
||||
# 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)
|
||||
self.pred += self.template_verts
|
||||
|
||||
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) # B x N x dim_motion
|
||||
samples_pt += self.template_verts # B x N x 5023 x 3
|
||||
|
||||
print(f"testing pt shape = {samples_pt.shape}")
|
||||
|
||||
self.save_reconstruct(samples_pt, path_audio,
|
||||
path_save=Path(self.opt.OUTPUT_DIR),
|
||||
suffix=suffix)
|
||||
|
||||
# save result
|
||||
samples_pt = samples_pt.cpu().numpy()
|
||||
path_save_npy = Path(self.opt.OUTPUT_DIR).joinpath(f"{suffix}.npy")
|
||||
np.save(path_save_npy, samples_pt)
|
||||
print(f"save infer_result shape = {samples_pt.shape} -> {path_save_npy}")
|
||||
|
||||
|
||||
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) # B x N x 5023 x 3
|
||||
samples_pt += self.template_verts # B x N x 5023 x 3
|
||||
|
||||
samples_gt = self.get_vertices(self.data) # B x N x 5023 x 3
|
||||
# samples_gt = samples_gt.cpu().numpy() # B x N x 5023 x 3
|
||||
|
||||
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 get_template_vertices(self, mean_dict=None):
|
||||
|
||||
if mean_dict is not None:
|
||||
pass
|
||||
|
||||
else:
|
||||
batch_shape = torch.zeros(1, 100).to(self.device)
|
||||
batch_exp = torch.zeros(1, 50).to(self.device)
|
||||
batch_pos = torch.zeros(1, 6).to(self.device)
|
||||
|
||||
verts, _, _ = self.netR.get_vertices(batch_shape, batch_exp, batch_pos) # 1 x 5023 x 3
|
||||
verts = verts.unsqueeze(dim=0) # 1 x 1 x 5023 x 3
|
||||
print(f"template verts reshape = {verts.shape}")
|
||||
|
||||
return verts
|
||||
|
||||
|
||||
def get_vertices(self, batch_motion):
|
||||
"""
|
||||
batch_motion, (nbatch, seqlen, 53)
|
||||
"""
|
||||
batch_exp = batch_motion[..., :50]
|
||||
batch_pos = batch_motion[..., 50:]
|
||||
nbatch, seqlen = batch_exp.size(0), batch_exp.size(1)
|
||||
|
||||
batch_exp = batch_exp.reshape(nbatch * seqlen, -1) # nbatch * seqlen x 50
|
||||
batch_pos = batch_pos.reshape(nbatch * seqlen, -1) # nbatch * seqlen x 3
|
||||
|
||||
batch_shape= torch.zeros(nbatch * seqlen, 100).to(self.device) # nbatch * seqlen x 50
|
||||
batch_pose = torch.zeros(nbatch * seqlen, 6).to(self.device) # nbatch * seqlen x 6
|
||||
batch_pose[:, 3:6] = batch_pos
|
||||
|
||||
verts, _, _ = self.netR.get_vertices(batch_shape, batch_exp, batch_pose) # nbatch * seqlen x 5023 x 3
|
||||
verts = verts.reshape(nbatch, seqlen, -1, 3) # nbatch x seqlen x 5023 x 3
|
||||
# print(f"verts reshape = {verts.shape}")
|
||||
|
||||
return verts
|
||||
|
||||
|
||||
def eval_losses(self, batch_pdt_geo, batch_tgt):
|
||||
""" Computes the VAE loss function.
|
||||
pramas:
|
||||
batch_tgt, (nbatch, seqlen, dim_motion)
|
||||
batch_pdt_geo, (nbatch, seqlen, num_vertices, 3)
|
||||
"""
|
||||
loss = 0
|
||||
loss_dict = {}
|
||||
|
||||
# get mesh geometry
|
||||
batch_tgt_geo = self.get_vertices(batch_tgt) # B x nseq x num_vertices x 3
|
||||
|
||||
# synthesis geo rec
|
||||
loss = 0
|
||||
loss_rec_geo = self.loss_func_wing(batch_pdt_geo, batch_tgt_geo)
|
||||
loss_dict["loss_rec_geo"] = loss_rec_geo.detach()
|
||||
|
||||
loss_rec_geo2 = self.loss_func_wing(batch_pdt_geo, batch_tgt_geo, weight=self.vertices_weight)
|
||||
loss_dict["loss_rec_geo_w"] = loss_rec_geo2.detach()
|
||||
loss += loss_rec_geo2 * self.opt.LOSS.lambda_rec_geo
|
||||
|
||||
# synthesis geo volocity
|
||||
diff_pdt_geo = batch_pdt_geo[:, 1:, :] - batch_pdt_geo[:, :-1, :]
|
||||
diff_tgt_geo = batch_tgt_geo[:, 1:, :] - batch_tgt_geo[:, :-1, :]
|
||||
|
||||
loss_vol_geo = self.loss_func_wing(diff_pdt_geo, diff_tgt_geo)
|
||||
loss_dict["loss_vol_geo"] = loss_vol_geo.detach()
|
||||
|
||||
loss_vol_geo2 = self.loss_func_wing(diff_pdt_geo, diff_tgt_geo, weight=self.vertices_weight)
|
||||
loss_dict["loss_vol_geo_w"] = loss_vol_geo2.detach()
|
||||
loss += loss_vol_geo2 * self.opt.LOSS.lambda_vol_geo
|
||||
|
||||
# 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 i in range(B):
|
||||
igeo_pt = samples_pt[i, ...]
|
||||
ipath_save = path_save.joinpath(f"{suffix}_{i:02d}.mp4")
|
||||
|
||||
v_render_pt = []
|
||||
for k in range(0, N, nbatch_render):
|
||||
# split
|
||||
kgeo_pt = igeo_pt[k:k+nbatch_render, ...] # [nbatch_real x 5023 x 3]
|
||||
nbatch_real = kgeo_pt.size(0)
|
||||
|
||||
# cam
|
||||
cam = torch.tensor([5, 0, 0], device=self.device) # (1, 3)
|
||||
cam = cam.repeat(nbatch_real, 1) # (nbatch_real, 3)
|
||||
# print(f"cam shape = {cam.shape}")
|
||||
|
||||
# render
|
||||
render_pt = self.netR.render_geometry(kgeo_pt, cam, self.device) # (nbatch_real, 3, 512, 512)
|
||||
# print(f"render_pt ={render_pt.shape}, render_gt={render_gt.shape}")
|
||||
|
||||
# append each frame
|
||||
for m in range(nbatch_real):
|
||||
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, ipath_save)
|
||||
|
||||
|
||||
def save_reconstruct_with_gt(self, samples_pt, samples_gt, path_save, suffix=""):
|
||||
# samples_pt, [B x N x 5023 x 3]
|
||||
# samples_gt, [B x N x 5023 x 3]
|
||||
B, N, *_ = samples_pt.shape
|
||||
nbatch_render = 10
|
||||
|
||||
# for each batch
|
||||
for i in range(B):
|
||||
igeo_pt = samples_pt[i, ...] # [N x 5023 x 3]
|
||||
igeo_gt = samples_gt[i, ...] # [N x 5023 x 3]
|
||||
ipath_save = path_save.joinpath(f"{suffix}_{i:02d}.mp4")
|
||||
|
||||
v_render_pt = []
|
||||
v_render_gt = []
|
||||
|
||||
for k in range(0, N, nbatch_render):
|
||||
|
||||
# split
|
||||
kgeo_pt = igeo_pt[k:k+nbatch_render, ...] # [nbatch_real x 5023 x 3]
|
||||
kgeo_gt = igeo_gt[k:k+nbatch_render, ...] # [nbatch_real x 5023 x 3]
|
||||
nbatch_real = kgeo_pt.size(0)
|
||||
|
||||
# cam
|
||||
cam = torch.tensor([5, 0, 0], device=self.device) # (1, 3)
|
||||
cam = cam.repeat(nbatch_real, 1) # (nbatch_real, 3)
|
||||
# print(f"cam shape = {cam.shape}")
|
||||
|
||||
# render
|
||||
render_pt = self.netR.render_geometry(kgeo_pt, cam, self.device) # (nbatch_real, 3, 512, 512)
|
||||
render_gt = self.netR.render_geometry(kgeo_gt, cam, self.device) # (nbatch_real, 3, 512, 512)
|
||||
# print(f"render_pt ={render_pt.shape}, render_gt={render_gt.shape}")
|
||||
|
||||
# append each frame
|
||||
for m in range(nbatch_real):
|
||||
v_render_pt.append(tensor2image(render_pt[m, ...]))
|
||||
v_render_gt.append(tensor2image(render_gt[m, ...]))
|
||||
|
||||
# get audio
|
||||
jvid = self.batch_vid[i]
|
||||
jnframe = self.batch_nframe[i].numpy()
|
||||
jstart_frame = self.batch_interv[0][i].numpy()
|
||||
|
||||
jpath_audio = f"{self.opt.DATASET.root_raw}/{jvid}/audio/audio_trim.wav"
|
||||
jstart_time = (jstart_frame + 7) / self.opt.DATASET.fps # xxx.yyy min
|
||||
jend_time = (jstart_frame + 7 + self.nseq) / self.opt.DATASET.fps # xxx.yyy min
|
||||
# print(f"jvid={jvid}, jnfram={jnframe}, jstart_frame={jstart_frame}, jpath_audio={jpath_audio}")
|
||||
# print(f"jstart_time={jstart_time}, jend_time={jend_time}")
|
||||
|
||||
|
||||
# save animation
|
||||
# print(f"testing v_render_pt = {len(v_render_pt)}, gt shape = {len(v_render_gt)}")
|
||||
save_animation_with_gt2(v_render_pt, v_render_gt, ipath_save, fps=self.opt.DATASET.fps,\
|
||||
path_audio=jpath_audio, start_time=jstart_time, end_time=jend_time)
|
||||
|
||||
#########################################
|
||||
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 == "audio2mesh":
|
||||
from src.nn.audio2mesh import Audio2Mesh
|
||||
netG = Audio2Mesh(opt)
|
||||
|
||||
elif opt.MODEL.name_netG == "audio2mesh_voca":
|
||||
from src.nn.audio2mesh_voca import Audio2Mesh
|
||||
netG = Audio2Mesh(opt)
|
||||
|
||||
elif opt.MODEL.name_netG == "audio2mesh_resnet":
|
||||
from src.nn.audio2mesh_resnet import Audio2Mesh
|
||||
netG = Audio2Mesh(opt)
|
||||
|
||||
else:
|
||||
raise NameError(f"The model of opt.MODEL.name_netAE(={opt.MODEL.name_netG}) not existing!")
|
||||
|
||||
# to GPU
|
||||
netG.to(f"cuda:{opt.GPUS[0]}")
|
||||
netG = torch.nn.DataParallel(netG, opt.GPUS) # multi-GPUs
|
||||
|
||||
return netG
|
||||
|
||||
|
||||
def define_netR(device):
|
||||
# import
|
||||
|
||||
from src.nn.FLAME import FLAME
|
||||
|
||||
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)
|
||||
|
||||
# flame model
|
||||
flame = FLAME(deca_cfg.model).to(device)
|
||||
|
||||
|
||||
return netR, flame
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,346 @@
|
||||
|
||||
import sys
|
||||
import torch
|
||||
import torch.nn as nn
|
||||
import numpy as np
|
||||
from pathlib import Path
|
||||
|
||||
from src.models.base import Base
|
||||
from src.optims import get_optimizer, get_scheduler
|
||||
|
||||
from common.debug import debug
|
||||
from common.animation import save_animation_with_gt2, save_images_with_audio
|
||||
|
||||
class Audio2MeshFModel(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)
|
||||
|
||||
# init
|
||||
if self.opt.MODEL.pretrain or self.opt.TRAIN.resume:
|
||||
self.netG.module.set_actnorm_init(True)
|
||||
else:
|
||||
self.netG.module.set_actnorm_init(False)
|
||||
|
||||
|
||||
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, self.flame = 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()
|
||||
self.template_verts = self.get_template_vertices()
|
||||
self.num_vertices = self.opt.MODEL.num_vertices
|
||||
debug(opt, f"template_verts shape = {self.template_verts.shape}")
|
||||
debug(opt, f"mean_dict keys = {self.mean_dict.keys()}", verbose=True)
|
||||
|
||||
|
||||
if self.opt.DATASET.speech_extractor == "wav2vec":
|
||||
from transformers import Wav2Vec2FeatureExtractor, Wav2Vec2Model
|
||||
print("load Wav2Vec2Model ...")
|
||||
MODEL_ID = "jonatasgrosman/wav2vec2-large-xlsr-53-chinese-zh-cn"
|
||||
self.processor = Wav2Vec2FeatureExtractor.from_pretrained(MODEL_ID)
|
||||
self.extractor = Wav2Vec2Model.from_pretrained(MODEL_ID).to(self.device)
|
||||
|
||||
def set_input(self, batch_input):
|
||||
|
||||
# motion data
|
||||
self.data = batch_input['data'].float().to(self.device) # (B, nsteps, nc_motion)
|
||||
|
||||
self.batch_vid = batch_input['vid']
|
||||
self.batch_nframe = batch_input['nframe']
|
||||
self.batch_interv = batch_input['frame_interval']
|
||||
|
||||
debug(self.opt, f"data = {self.data.shape}, dtype={self.data.dtype}", verbose=False)
|
||||
debug(self.opt, f"batch_vid = {self.batch_vid[:2]}", verbose=False)
|
||||
debug(self.opt, f"batch_nframe = {self.batch_nframe[:2]}", verbose=False)
|
||||
debug(self.opt, f"batch_interv len={len(self.batch_interv)} len([0])={len(self.batch_interv[0])}, \
|
||||
beg={self.batch_interv[0][:4]}, end={self.batch_interv[1][:4]}", verbose=False)
|
||||
|
||||
# speech data
|
||||
self.cond = None
|
||||
raw_speech = batch_input["cond"].numpy() # (B, nsegments)
|
||||
debug(self.opt, f"raw_speech = {raw_speech.shape}, dtype={raw_speech.dtype}", verbose=False)
|
||||
|
||||
if self.opt.DATASET.speech_extractor == "wav2vec":
|
||||
|
||||
# padding half frame length for bed and end
|
||||
npad = int(0.5 * self.opt.DATASET.sr * ( 1 / self.opt.DATASET.fps) + 0.5)
|
||||
raw_speech = np.pad(raw_speech, pad_width=((0,0), (npad, npad)), mode="edge")
|
||||
debug(self.opt, f"after padding raw_speech = {raw_speech.shape}, dtype={raw_speech.dtype}", verbose=False)
|
||||
|
||||
raw_speech = list(raw_speech)
|
||||
inputs = self.processor(raw_speech, sampling_rate=16000, return_tensors="pt")
|
||||
inputs = inputs.to(self.device)
|
||||
|
||||
with torch.no_grad():
|
||||
output = self.extractor(**inputs)
|
||||
self.cond = output.last_hidden_state
|
||||
# self.cond = output.extract_features
|
||||
else:
|
||||
assert 0, "opt.DATASET.speech_extractor should be 'wav2vec | deepspeech | mfcc ' "
|
||||
|
||||
|
||||
# B x nsteps x nc_feat
|
||||
debug(self.opt, f"data = {self.data.shape}, dtype={self.data.dtype}, device={self.data.device}", verbose=False)
|
||||
debug(self.opt, f"cond = {self.cond.shape}, dtype={self.cond.dtype}, device={self.cond.device}", verbose=False)
|
||||
|
||||
self.cond = self.cond.permute(0, 2, 1) # (B, nc_motion, nseqs)
|
||||
self.data = self.data.permute(0, 2, 1) # (B, nc_condit, nseqs)
|
||||
self.nseq = self.cond.size(2)
|
||||
|
||||
debug(self.opt, f"\n a data = {self.data.shape}, dtype={self.data.dtype}, device={self.data.device}", verbose=False)
|
||||
debug(self.opt, f"a cond = {self.cond.shape}, dtype={self.cond.dtype}, device={self.cond.device}", verbose=False)
|
||||
|
||||
|
||||
def remove_weightnorm(self):
|
||||
def remove(conv_list):
|
||||
new_conv_list = nn.ModuleList()
|
||||
for old_conv in conv_list:
|
||||
old_conv = nn.utils.remove_weight_norm(old_conv)
|
||||
new_conv_list.append(old_conv)
|
||||
return new_conv_list
|
||||
|
||||
for model in self.netG.module.FusionNets:
|
||||
model.layer_head = nn.utils.remove_weight_norm(model.layer_head)
|
||||
model.layer_cond = nn.utils.remove_weight_norm(model.layer_cond)
|
||||
model.in_layers = remove(model.in_layers)
|
||||
model.res_skip_layers = remove(model.res_skip_layers)
|
||||
|
||||
|
||||
def training(self, batch_input):
|
||||
self.train() # set train model
|
||||
self.set_input(batch_input)
|
||||
|
||||
data_input = self.get_vertices(self.data) # nbatch x 5023*3 x nsteps
|
||||
|
||||
# forward
|
||||
z, logdet = self.netG(data_input, self.cond)
|
||||
debug(self.opt, f"[Train] netG z shape = {len(z)}, logs shape = {logdet.shape}", verbose=False)
|
||||
|
||||
# loss
|
||||
# loss, self.loss_dict = self.netG.module.eval_losses()
|
||||
loss, self.loss_dict = self.netG.module.loss_function_(z, logdet)
|
||||
debug(self.opt, f"[Train] loss shape = {loss.shape}", verbose=False)
|
||||
|
||||
# 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)
|
||||
|
||||
# step
|
||||
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():
|
||||
data_input = self.get_vertices(self.data) # nbatch x 5023*3 x nsteps
|
||||
|
||||
z, logdet = self.netG(data_input, self.cond)
|
||||
loss, self.loss_dict = self.netG.module.loss_function_(z, logdet)
|
||||
return loss
|
||||
|
||||
|
||||
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.module.inverse(self.cond) # B x 5023*3 x nsteps
|
||||
|
||||
# add template mesh
|
||||
B, N = samples_pt.size(0), samples_pt.size(2)
|
||||
samples_pt = samples_pt.permute(0, 2, 1) # B x nsteps x 5023*3
|
||||
samples_pt = samples_pt.reshape(B, N, self.num_vertices, 3) # B x nsteps x 5023 x 3
|
||||
samples_pt += self.template_verts # B x nsteps x 5023 x 3
|
||||
|
||||
#
|
||||
samples_gt = self.get_vertices(self.data) # B x 5023*3 x nsteps
|
||||
samples_gt = samples_gt.permute(0, 2, 1) # B x nsteps x 5023*3
|
||||
samples_gt = samples_gt.reshape(B, N, self.num_vertices, 3) # B x nsteps x 5023 x 3
|
||||
samples_gt += self.template_verts # B x nsteps x 5023 x 3
|
||||
|
||||
# self.data.permute(0, 2, 1).cpu().numpy() # B x nsteps 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 infer(self, batch_cond, path_audio, suffix=""):
|
||||
self.eval()
|
||||
# self.cond =
|
||||
|
||||
|
||||
def get_template_vertices(self, ):
|
||||
|
||||
batch_shape = torch.zeros(1, 100).to(self.device)
|
||||
batch_exp = torch.zeros(1, 50).to(self.device)
|
||||
batch_pos = torch.zeros(1, 6).to(self.device)
|
||||
|
||||
verts, _, _ = self.netR.get_vertices(batch_shape, batch_exp, batch_pos) # 1 x 5023 x 3
|
||||
verts = verts.unsqueeze(dim=0) # 1 x 1 x 5023 x 3
|
||||
print(f"template verts reshape = {verts.shape}")
|
||||
|
||||
return verts
|
||||
|
||||
|
||||
def get_vertices(self, batch_motion):
|
||||
"""
|
||||
batch_motion, (nbatch, nc_motion, nsteps)
|
||||
"""
|
||||
|
||||
# transpose
|
||||
batch_motion = batch_motion.permute(0, 2, 1) # nbatch x nsteps x nc_motion
|
||||
|
||||
batch_exp = batch_motion[..., :50]
|
||||
batch_pos = batch_motion[..., 50:]
|
||||
nbatch, nsteps = batch_exp.size(0), batch_exp.size(1)
|
||||
|
||||
batch_exp = batch_exp.reshape(nbatch * nsteps, -1) # nbatch * nsteps x 50
|
||||
batch_pos = batch_pos.reshape(nbatch * nsteps, -1) # nbatch * nsteps x 3
|
||||
|
||||
batch_shape= torch.zeros(nbatch * nsteps, 100).to(self.device) # nbatch * nsteps x 50
|
||||
batch_pose = torch.zeros(nbatch * nsteps, 6).to(self.device) # nbatch * nsteps x 6
|
||||
batch_pose[:, 3:6] = batch_pos
|
||||
|
||||
verts, _, _ = self.netR.get_vertices(batch_shape, batch_exp, batch_pose) # nbatch * nsteps x 5023 x 3
|
||||
verts = verts.reshape(nbatch, nsteps, -1) # nbatch x nsteps x 5023*3
|
||||
verts = verts.permute(0, 2, 1) # nbatch x 5023*3 x nsteps
|
||||
# print(f"verts reshape = {verts.shape}")
|
||||
|
||||
return verts
|
||||
|
||||
def save_reconstruct_with_gt(self, samples_pt, samples_gt, path_save, suffix=""):
|
||||
# samples_pt, [B x N x 5023 x 3]
|
||||
# samples_gt, [B x N x 5023 x 3]
|
||||
B, N, *_ = samples_pt.shape
|
||||
nbatch_render = 10
|
||||
|
||||
# for each batch
|
||||
for i in range(B):
|
||||
igeo_pt = samples_pt[i, ...] # [N x 5023 x 3]
|
||||
igeo_gt = samples_gt[i, ...] # [N x 5023 x 3]
|
||||
ipath_save = path_save.joinpath(f"{suffix}_{i:02d}.mp4")
|
||||
|
||||
v_render_pt = []
|
||||
v_render_gt = []
|
||||
|
||||
for k in range(0, N, nbatch_render):
|
||||
|
||||
# split
|
||||
kgeo_pt = igeo_pt[k:k+nbatch_render, ...] # [nbatch_real x 5023 x 3]
|
||||
kgeo_gt = igeo_gt[k:k+nbatch_render, ...] # [nbatch_real x 5023 x 3]
|
||||
nbatch_real = kgeo_pt.size(0)
|
||||
|
||||
# cam
|
||||
cam = torch.tensor([5, 0, 0], device=self.device) # (1, 3)
|
||||
cam = cam.repeat(nbatch_real, 1) # (nbatch_real, 3)
|
||||
# print(f"cam shape = {cam.shape}")
|
||||
|
||||
# render
|
||||
render_pt = self.netR.render_geometry(kgeo_pt, cam, self.device) # (nbatch_real, 3, 512, 512)
|
||||
render_gt = self.netR.render_geometry(kgeo_gt, cam, self.device) # (nbatch_real, 3, 512, 512)
|
||||
# print(f"render_pt ={render_pt.shape}, render_gt={render_gt.shape}")
|
||||
|
||||
# append each frame
|
||||
for m in range(nbatch_real):
|
||||
v_render_pt.append(tensor2image(render_pt[m, ...]))
|
||||
v_render_gt.append(tensor2image(render_gt[m, ...]))
|
||||
|
||||
# get audio
|
||||
jvid = self.batch_vid[i]
|
||||
jnframe = self.batch_nframe[i].numpy()
|
||||
jstart_frame = self.batch_interv[0][i].numpy()
|
||||
|
||||
jpath_audio = f"{self.opt.DATASET.root_raw}/{jvid}/audio/audio_trim.wav"
|
||||
jstart_time = jstart_frame / self.opt.DATASET.fps # xxx.yyy min
|
||||
jend_time = (jstart_frame + self.nseq) / self.opt.DATASET.fps # xxx.yyy min
|
||||
# print(f"jvid={jvid}, jnfram={jnframe}, jstart_frame={jstart_frame}, jpath_audio={jpath_audio}")
|
||||
# print(f"jstart_time={jstart_time}, jend_time={jend_time}")
|
||||
|
||||
# save animation
|
||||
# print(f"testing v_render_pt = {len(v_render_pt)}, gt shape = {len(v_render_gt)}")
|
||||
save_animation_with_gt2(v_render_pt, v_render_gt, ipath_save, fps=self.opt.DATASET.fps,\
|
||||
path_audio=jpath_audio, start_time=jstart_time, end_time=jend_time)
|
||||
|
||||
#########################################
|
||||
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 == "MotionWaveFlow":
|
||||
from src.nn.MotionWaveFlow import MotionWaveFlow
|
||||
netG = MotionWaveFlow(opt)
|
||||
|
||||
else:
|
||||
raise NameError(f"The model of opt.MODEL.name_netG(={opt.MODEL.name_netG}) not existing!")
|
||||
|
||||
# to GPU
|
||||
netG.to(f"cuda:{opt.GPUS[0]}")
|
||||
netG = torch.nn.DataParallel(netG, opt.GPUS) # multi-GPUs
|
||||
|
||||
|
||||
return netG
|
||||
|
||||
|
||||
def define_netR(device):
|
||||
# import
|
||||
|
||||
from src.nn.FLAME import FLAME
|
||||
|
||||
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)
|
||||
|
||||
# flame model
|
||||
flame = FLAME(deca_cfg.model).to(device)
|
||||
|
||||
|
||||
return netR, flame
|
||||
@@ -0,0 +1,472 @@
|
||||
import sys
|
||||
import numpy as np
|
||||
|
||||
import torch
|
||||
import torch.nn as nn
|
||||
import torch.nn.functional as F
|
||||
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 Audio2MeshModel(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, self.flame = 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())
|
||||
|
||||
if self.opt.DATASET.speech_extractor == "wav2vec":
|
||||
from transformers import Wav2Vec2FeatureExtractor, Wav2Vec2Model
|
||||
print("load Wav2Vec2Model ...")
|
||||
MODEL_ID = "jonatasgrosman/wav2vec2-large-xlsr-53-chinese-zh-cn"
|
||||
self.processor = Wav2Vec2FeatureExtractor.from_pretrained(MODEL_ID)
|
||||
self.extractor = Wav2Vec2Model.from_pretrained(MODEL_ID).to(self.device)
|
||||
|
||||
|
||||
|
||||
def set_input(self, batch_input):
|
||||
|
||||
# motion data
|
||||
self.data = batch_input["data"].float().to(self.device) # (B, nsteps, nc_motion)
|
||||
|
||||
self.batch_vid = batch_input['vid']
|
||||
self.batch_nframe = batch_input['nframe']
|
||||
self.batch_interv = batch_input['frame_interval']
|
||||
|
||||
debug(self.opt, f"data = {self.data.shape}, dtype={self.data.dtype}", verbose=False)
|
||||
debug(self.opt, f"batch_vid = {self.batch_vid[:2]}", verbose=False)
|
||||
debug(self.opt, f"batch_nframe = {self.batch_nframe[:2]}", verbose=False)
|
||||
debug(self.opt, f"batch_interv len={len(self.batch_interv)} len([0])={len(self.batch_interv[0])}, \
|
||||
beg={self.batch_interv[0][:4]}, end={self.batch_interv[1][:4]}", verbose=False)
|
||||
|
||||
self.B, self.nsteps = self.data.size(0), self.data.size(1)
|
||||
|
||||
# speech data
|
||||
raw_speech = batch_input["cond"].numpy() # (B, nsegments)
|
||||
debug(self.opt, f"raw_speech = {raw_speech.shape}, dtype={raw_speech.dtype}", verbose=False)
|
||||
|
||||
if self.opt.DATASET.speech_extractor == "wav2vec":
|
||||
# raw_speech = raw_speech.reshape(self.B * self.nsteps, -1) # (B*nsteps, nsegments)
|
||||
# debug(self.opt, f"raw_speech = {raw_speech.shape}, dtype={raw_speech.dtype}", verbose=False)
|
||||
|
||||
# padding half frame length for bed and end
|
||||
npad = int(0.5 * self.opt.DATASET.sr * ( 1 / self.opt.DATASET.fps) + 0.5)
|
||||
raw_speech = np.pad(raw_speech, pad_width=((0,0), (npad, npad)), mode="edge")
|
||||
debug(self.opt, f"after padding raw_speech = {raw_speech.shape}, dtype={raw_speech.dtype}", verbose=False)
|
||||
|
||||
raw_speech = list(raw_speech)
|
||||
inputs = self.processor(raw_speech, sampling_rate=16000, return_tensors="pt")
|
||||
inputs = inputs.to(self.device)
|
||||
|
||||
with torch.no_grad():
|
||||
output = self.extractor(**inputs)
|
||||
self.cond = output.last_hidden_state
|
||||
# self.cond = output.extract_features
|
||||
|
||||
# B x nsteps x nc_feat
|
||||
debug(self.opt, f"data = {self.data.shape}, dtype={self.data.dtype}, device={self.data.device}", verbose=False)
|
||||
debug(self.opt, f"cond = {self.cond.shape}, dtype={self.cond.dtype}, device={self.cond.device}", verbose=False)
|
||||
|
||||
# unfold
|
||||
# self.data = self.data.unfold(dimension=1, size=16, step=1) # (B, nseqs, nc_motion, 16)
|
||||
# self.data = self.data.permute(0, 1, 3, 2) # (B, nseqs, 16, 53)
|
||||
|
||||
self.cond = self.cond.unfold(dimension=1, size=16, step=1) # (nseqs, nc_motion, 16)
|
||||
self.cond = self.cond.permute(0, 1, 3, 2) # (nseqs, 16, 53)
|
||||
|
||||
self.nseq = self.cond.size(1)
|
||||
self.data = self.data[:, 7:7+self.nseq, :]
|
||||
|
||||
debug(self.opt, f"\n a data = {self.data.shape}, dtype={self.data.dtype}, device={self.data.device}", verbose=False)
|
||||
debug(self.opt, f"a cond = {self.cond.shape}, dtype={self.cond.dtype}, device={self.cond.device}", verbose=False)
|
||||
|
||||
def training(self, batch_input):
|
||||
self.train() # set train model
|
||||
self.set_input(batch_input)
|
||||
|
||||
# forward
|
||||
self.pred_coef, self.pred_vert = self.netG(self.cond)
|
||||
|
||||
# loss
|
||||
loss, self.loss_dict = self.eval_losses(self.pred_coef, self.pred_vert, 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_coef = self.netG(self.cond)
|
||||
loss, self.loss_dict = self.eval_losses(self.pred_coef, 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 get_vertices(self, batch_exp, batch_pos):
|
||||
"""
|
||||
batch_exp, (nbatch, seqlen, 50)
|
||||
batch_pos, (nbatch, seqlen, 3)
|
||||
"""
|
||||
nbatch, seqlen = batch_exp.size(0), batch_exp.size(1)
|
||||
batch_exp = batch_exp.reshape(nbatch * seqlen, -1) # nbatch * seqlen x 50
|
||||
batch_pos = batch_pos.reshape(nbatch * seqlen, -1) # nbatch * seqlen x 3
|
||||
|
||||
batch_shape = np.repeat([self.mean_dict["shape"]], nbatch * seqlen, axis=0) # (nbatch * seqlen, 100)
|
||||
batch_shape= torch.from_numpy(batch_shape).to(self.device)
|
||||
|
||||
batch_pose = np.repeat([self.mean_dict["pose"]], nbatch * seqlen, axis=0) # (nbatch * seqlen, 6)
|
||||
batch_pose = torch.from_numpy(batch_pose).to(self.device)
|
||||
batch_pose[:, 3:6] = batch_pos
|
||||
|
||||
|
||||
verts, _, _ = self.netR.get_vertices(batch_shape, batch_exp, batch_pose) # nbatch * seqlen x 5023 x 3
|
||||
verts = verts.reshape(nbatch, seqlen, -1, 3) # nbatch x seqlen x 5023 x 3
|
||||
# print(f"verts reshape = {verts.shape}")
|
||||
|
||||
return verts
|
||||
|
||||
def eval_losses(self, batch_pdt_coef, batch_pdt_geo, batch_tgt):
|
||||
""" Computes the VAE loss function.
|
||||
pramas:
|
||||
batch_tgt, (nbatch, seqlen, dim_motion)
|
||||
batch_pdt_coef, (nbatch, seqlen, dim_motion)
|
||||
batch_pdt_geo, (nbatch, seqlen, num_vertices, 3)
|
||||
"""
|
||||
loss = 0
|
||||
loss_dict = {}
|
||||
|
||||
batch_pdt_exp = batch_pdt_coef[..., :50]
|
||||
batch_pdt_pos = batch_pdt_coef[..., 50:]
|
||||
|
||||
batch_tgt_exp = batch_tgt[..., :50]
|
||||
batch_tgt_pos = batch_tgt[..., 50:]
|
||||
|
||||
|
||||
# get mesh geometry
|
||||
batch_syn_geo = self.get_vertices(batch_pdt_exp, batch_pdt_pos) # B x nseq x num_vertices x 3
|
||||
batch_tgt_geo = self.get_vertices(batch_tgt_exp, batch_tgt_pos) # B x nseq x num_vertices x 3
|
||||
|
||||
|
||||
# rec loss
|
||||
loss = 0
|
||||
loss_rec_exp = self.loss_func_wing(batch_pdt_exp, batch_tgt_exp) / 50
|
||||
loss_dict["loss_rec_exp"] = loss_rec_exp.detach()
|
||||
|
||||
loss_rec_pos = self.loss_func_wing(batch_pdt_pos, batch_tgt_pos) / 3
|
||||
loss_dict["loss_rec_pos"] = loss_rec_pos.detach()
|
||||
|
||||
loss += loss_rec_exp * self.opt.LOSS.lambda_rec_exp
|
||||
loss += loss_rec_pos * self.opt.LOSS.lambda_rec_pos
|
||||
|
||||
|
||||
# rec smooth
|
||||
diff_pdt_exp = batch_pdt_exp[:, 1:, :] - batch_pdt_exp[:, :-1, :]
|
||||
diff_tgt_exp = batch_tgt_exp[:, 1:, :] - batch_tgt_exp[:, :-1, :]
|
||||
loss_vol_exp = self.loss_func_wing(diff_pdt_exp, diff_tgt_exp) / 50
|
||||
loss_dict["loss_vol_exp"] = loss_vol_exp.detach()
|
||||
|
||||
diff_pdt_pos = batch_pdt_pos[:, 1:, :] - batch_pdt_pos[:, :-1, :]
|
||||
diff_tgt_pos = batch_tgt_pos[:, 1:, :] - batch_tgt_pos[:, :-1, :]
|
||||
loss_vol_pos = self.loss_func_wing(diff_pdt_pos, diff_tgt_pos) / 3
|
||||
loss_dict["loss_vol_pos"] = loss_vol_pos.detach()
|
||||
|
||||
loss += loss_vol_exp * self.opt.LOSS.lambda_vol_exp
|
||||
loss += loss_vol_pos * self.opt.LOSS.lambda_vol_pos
|
||||
|
||||
# synthesis geo rec
|
||||
loss_rec_geo = self.loss_func_wing(batch_syn_geo, batch_tgt_geo)
|
||||
loss_dict["loss_rec_syn"] = loss_rec_geo.detach()
|
||||
loss += loss_rec_geo * self.opt.LOSS.lambda_rec_syn
|
||||
|
||||
|
||||
# synthesis geo volocity
|
||||
diff_syn_geo = batch_syn_geo[:, 1:, :] - batch_syn_geo[:, :-1, :]
|
||||
diff_tgt_geo = batch_tgt_geo[:, 1:, :] - batch_tgt_geo[:, :-1, :]
|
||||
loss_vol_geo = self.loss_func_wing(diff_syn_geo, diff_tgt_geo)
|
||||
loss_dict["loss_vol_syn"] = loss_vol_geo.detach()
|
||||
loss += loss_vol_geo * self.opt.LOSS.lambda_vol_syn
|
||||
|
||||
# synthesis geo rec
|
||||
loss_rec_geo = self.loss_func_wing(batch_pdt_geo, batch_tgt_geo)
|
||||
loss_dict["loss_rec_geo"] = loss_rec_geo.detach()
|
||||
loss += loss_rec_geo * self.opt.LOSS.lambda_rec_geo
|
||||
|
||||
# synthesis geo volocity
|
||||
diff_pdt_geo = batch_pdt_geo[:, 1:, :] - batch_pdt_geo[:, :-1, :]
|
||||
diff_tgt_geo = batch_tgt_geo[:, 1:, :] - batch_tgt_geo[:, :-1, :]
|
||||
loss_vol_geo = self.loss_func_wing(diff_pdt_geo, diff_tgt_geo)
|
||||
loss_dict["loss_vol_geo"] = loss_vol_geo.detach()
|
||||
loss += loss_vol_geo * self.opt.LOSS.lambda_vol_geo
|
||||
|
||||
# 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, ...]))
|
||||
|
||||
# get audio
|
||||
jvid = self.batch_vid[j]
|
||||
jnframe = self.batch_nframe[j].numpy()
|
||||
jstart_frame = self.batch_interv[0][j].numpy()
|
||||
|
||||
jpath_audio = f"/yrfs/lsen/DATA/LuoXData/processing2/{jvid}/audio/audio_trim.wav"
|
||||
jstart_time = (jstart_frame + 7) / self.opt.DATASET.fps # xxx.yyy min
|
||||
jend_time = (jstart_frame + 7 + self.nseq) / self.opt.DATASET.fps # xxx.yyy min
|
||||
|
||||
|
||||
|
||||
print(f"jvid={jvid}, jnfram={jnframe}, jstart_frame={jstart_frame}, jpath_audio={jpath_audio}")
|
||||
print(f"jstart_time={jstart_time}, jend_time={jend_time}")
|
||||
|
||||
|
||||
# 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, fps=self.opt.DATASET.fps,\
|
||||
path_audio=jpath_audio, start_time=jstart_time, end_time=jend_time)
|
||||
|
||||
|
||||
#########################################
|
||||
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_voca4":
|
||||
from src.nn.audio2motion_voca4 import Audio2MotionVOCA
|
||||
netG = Audio2MotionVOCA(opt)
|
||||
|
||||
elif opt.MODEL.name_netG == "audio2motion_voca":
|
||||
from src.nn.audio2motion_voca import Audio2MotionVOCA
|
||||
netG = Audio2MotionVOCA(opt)
|
||||
|
||||
elif opt.MODEL.name_netG == "audio2motion_voca3":
|
||||
from src.nn.audio2motion_voca3 import Audio2MotionVOCA3
|
||||
netG = Audio2MotionVOCA3(opt)
|
||||
|
||||
elif opt.MODEL.name_netG == "audio2motion_voca33":
|
||||
from src.nn.audio2motion_voca33 import Audio2MotionVOCA
|
||||
netG = Audio2MotionVOCA(opt)
|
||||
|
||||
elif opt.MODEL.name_netG == "audio2motion":
|
||||
from src.nn.audio2motion import Audio2Motion
|
||||
netG = Audio2Motion(opt)
|
||||
|
||||
elif opt.MODEL.name_netG == "audio2motion2":
|
||||
from src.nn.audio2motion2 import Audio2Motion2
|
||||
netG = Audio2Motion2(opt)
|
||||
else:
|
||||
raise NameError(f"The model of opt.MODEL.name_netAE(={opt.MODEL.name_netG}) not existing!")
|
||||
|
||||
|
||||
return netG
|
||||
|
||||
|
||||
def define_netR(device):
|
||||
# import
|
||||
|
||||
from src.nn.FLAME import FLAME
|
||||
|
||||
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)
|
||||
|
||||
# flame model
|
||||
flame = FLAME(deca_cfg.model).to(device)
|
||||
|
||||
|
||||
return netR, flame
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,448 @@
|
||||
import sys
|
||||
import numpy as np
|
||||
|
||||
import torch
|
||||
import torch.nn as nn
|
||||
import torch.nn.functional as F
|
||||
from pathlib import Path
|
||||
|
||||
from src.models.info import flame_mouth_idx
|
||||
from src.models 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 Audio2MeshSpecificModel(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)
|
||||
init_net(self.netG, init_type='kaiming', gpu_ids=opt.GPUS)
|
||||
|
||||
# init last layer
|
||||
init_exp_weight = np.load("/ssdata1/lsen/CODE/voca/training_data/init_expression_basis.npy")
|
||||
init_exp_weight = torch.from_numpy(init_exp_weight).float().to(self.device)
|
||||
init_exp_weight = init_exp_weight[:, :50]
|
||||
self.netG.module.decoder_mesh.weight.data = init_exp_weight
|
||||
print(f"init_exp_weight shape = {init_exp_weight.shape}")
|
||||
|
||||
# # print network parameters
|
||||
# for name, param in self.netG.named_parameters():
|
||||
# print(name, '\t\t', param.size())
|
||||
|
||||
# load mean lighting & shape
|
||||
self.netR, self.flame = define_netR(device=self.device)
|
||||
# self.netG.init_reconstruct_model(self.netR)
|
||||
|
||||
# path_deca_mean = Path("./data/DECA_obama_mean.npy")
|
||||
path_deca_mean = self.opt.DATASET.path_mean_dict
|
||||
self.mean_dict = np.load(path_deca_mean, allow_pickle=True).item()
|
||||
print(f"mean_dict keys = {self.mean_dict.keys()}")
|
||||
|
||||
self.template_verts = self.get_template_vertices(self.mean_dict)
|
||||
debug(opt, f"template_verts shape = {self.template_verts.shape}")
|
||||
debug(opt, f"mean_dict keys = {self.mean_dict.keys()}", verbose=True)
|
||||
|
||||
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)
|
||||
|
||||
# define loss weight
|
||||
self.vertices_weight = torch.ones((1, 1, self.opt.MODEL.num_vertices, 3)).to(self.device)
|
||||
self.vertices_weight[:, :, flame_mouth_idx, :] = 50 # 10
|
||||
|
||||
|
||||
if self.opt.DATASET.speech_extractor == "wav2vec":
|
||||
from transformers import Wav2Vec2FeatureExtractor, Wav2Vec2Model
|
||||
print("load Wav2Vec2Model ...")
|
||||
MODEL_ID = "jonatasgrosman/wav2vec2-large-xlsr-53-chinese-zh-cn"
|
||||
self.processor = Wav2Vec2FeatureExtractor.from_pretrained(MODEL_ID)
|
||||
self.extractor = Wav2Vec2Model.from_pretrained(MODEL_ID).to(self.device)
|
||||
|
||||
|
||||
def set_input(self, batch_input):
|
||||
|
||||
# motion data
|
||||
self.data = batch_input["data"].float().to(self.device) # (B, nsteps, nc_motion)
|
||||
self.batch_shape = batch_input["shape"].float().to(self.device) # (B, nsteps, nc_shape)
|
||||
|
||||
self.batch_vid = batch_input['vid']
|
||||
self.batch_nframe = batch_input['nframe']
|
||||
self.batch_interv = batch_input['frame_interval']
|
||||
self.B, self.nsteps = self.data.size(0), self.data.size(1)
|
||||
|
||||
debug(self.opt, f"data = {self.data.shape}, dtype={self.data.dtype}", verbose=False)
|
||||
debug(self.opt, f"batch_vid = {self.batch_vid[:2]}", verbose=False)
|
||||
debug(self.opt, f"batch_nframe = {self.batch_nframe[:2]}", verbose=False)
|
||||
debug(self.opt, f"batch_interv len={len(self.batch_interv)} len([0])={len(self.batch_interv[0])}, \
|
||||
beg={self.batch_interv[0][:4]}, end={self.batch_interv[1][:4]}", verbose=False)
|
||||
|
||||
# speech data
|
||||
self.cond = None
|
||||
raw_speech = batch_input["cond"].numpy() # (B, nsegments)
|
||||
debug(self.opt, f"raw_speech = {raw_speech.shape}, dtype={raw_speech.dtype}", verbose=False)
|
||||
|
||||
if self.opt.DATASET.speech_extractor == "wav2vec":
|
||||
# raw_speech = raw_speech.reshape(self.B * self.nsteps, -1) # (B*nsteps, nsegments)
|
||||
# debug(self.opt, f"raw_speech = {raw_speech.shape}, dtype={raw_speech.dtype}", verbose=False)
|
||||
|
||||
# padding half frame length for bed and end
|
||||
npad = int(0.5 * self.opt.DATASET.sr * ( 1 / self.opt.DATASET.fps) + 0.5)
|
||||
raw_speech = np.pad(raw_speech, pad_width=((0,0), (npad, npad)), mode="edge")
|
||||
debug(self.opt, f"after padding raw_speech = {raw_speech.shape}, dtype={raw_speech.dtype}", verbose=False)
|
||||
|
||||
raw_speech = list(raw_speech)
|
||||
inputs = self.processor(raw_speech, sampling_rate=16000, return_tensors="pt")
|
||||
inputs = inputs.to(self.device)
|
||||
|
||||
with torch.no_grad():
|
||||
output = self.extractor(**inputs)
|
||||
self.cond = output.last_hidden_state
|
||||
# self.cond = output.extract_features
|
||||
else:
|
||||
assert 0, "opt.DATASET.speech_extractor should be 'wav2vec | deepspeech | mfcc ' "
|
||||
|
||||
# B x nsteps x nc_feat
|
||||
debug(self.opt, f"data = {self.data.shape}, dtype={self.data.dtype}, device={self.data.device}", verbose=False)
|
||||
debug(self.opt, f"cond = {self.cond.shape}, dtype={self.cond.dtype}, device={self.cond.device}", verbose=False)
|
||||
|
||||
# unfold speech data
|
||||
self.cond = self.cond.unfold(dimension=1, size=16, step=1) # (nseqs, nc_motion, 16)
|
||||
self.cond = self.cond.permute(0, 1, 3, 2) # (nseqs, 16, 53)
|
||||
|
||||
self.nseq = self.cond.size(1)
|
||||
self.data = self.data[:, 7:7+self.nseq, :]
|
||||
self.batch_shape = self.batch_shape[:, 7:7+self.nseq, :] # (B, nsteps, nc_shape)
|
||||
|
||||
debug(self.opt, f"\n a data = {self.data.shape}, dtype={self.data.dtype}, device={self.data.device}", verbose=False)
|
||||
debug(self.opt, f"a cond = {self.cond.shape}, dtype={self.cond.dtype}, device={self.cond.device}", verbose=False)
|
||||
|
||||
|
||||
def training(self, batch_input):
|
||||
self.train() # set train model
|
||||
self.set_input(batch_input)
|
||||
|
||||
# forward
|
||||
self.pred = self.netG(self.cond)
|
||||
self.pred += self.template_verts
|
||||
debug(self.opt, f"traing pred = {self.pred.shape}", verbose=False)
|
||||
|
||||
# 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)
|
||||
self.pred += self.template_verts
|
||||
|
||||
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) # B x N x dim_motion
|
||||
samples_pt += self.template_verts # B x N x 5023 x 3
|
||||
|
||||
print(f"testing pt shape = {samples_pt.shape}")
|
||||
|
||||
self.save_reconstruct(samples_pt, path_audio,
|
||||
path_save=Path(self.opt.OUTPUT_DIR),
|
||||
suffix=suffix)
|
||||
|
||||
# save result
|
||||
samples_pt = samples_pt.cpu().numpy()
|
||||
path_save_npy = Path(self.opt.OUTPUT_DIR).joinpath(f"{suffix}.npy")
|
||||
np.save(path_save_npy, samples_pt)
|
||||
print(f"save infer_result shape = {samples_pt.shape} -> {path_save_npy}")
|
||||
|
||||
|
||||
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) # B x N x 5023 x 3
|
||||
samples_pt += self.template_verts # B x N x 5023 x 3
|
||||
|
||||
samples_gt = self.get_vertices(self.data, self.batch_shape) # B x N x 5023 x 3
|
||||
# samples_gt = samples_gt.cpu().numpy() # B x N x 5023 x 3
|
||||
|
||||
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 get_template_vertices(self, mean_dict=None):
|
||||
|
||||
batch_exp = torch.zeros(1, 50).to(self.device)
|
||||
batch_pos = torch.zeros(1, 6).to(self.device)
|
||||
|
||||
if mean_dict is not None:
|
||||
batch_shape = self.mean_dict["shape"].reshape(1, 100)
|
||||
batch_shape = torch.from_numpy(batch_shape).float().to(self.device)
|
||||
else:
|
||||
batch_shape = torch.zeros(1, 100).to(self.device)
|
||||
|
||||
|
||||
verts, _, _ = self.netR.get_vertices(batch_shape, batch_exp, batch_pos) # 1 x 5023 x 3
|
||||
verts = verts.unsqueeze(dim=0) # 1 x 1 x 5023 x 3
|
||||
print(f"template verts reshape = {verts.shape}")
|
||||
|
||||
return verts
|
||||
|
||||
|
||||
def get_vertices(self, batch_motion, batch_shape):
|
||||
"""
|
||||
batch_motion, (nbatch, seqlen, 53)
|
||||
batch_shape, (nbatch, seqlen, 100)
|
||||
"""
|
||||
batch_exp = batch_motion[..., :50]
|
||||
batch_pos = batch_motion[..., 50:]
|
||||
nbatch, seqlen = batch_exp.size(0), batch_exp.size(1)
|
||||
|
||||
batch_exp = batch_exp.reshape(nbatch * seqlen, 50) # nbatch * seqlen x 50
|
||||
batch_pos = batch_pos.reshape(nbatch * seqlen, 3) # nbatch * seqlen x 3
|
||||
batch_idn = batch_shape.reshape(nbatch * seqlen, 100) # nbatch * seqlen x 100
|
||||
|
||||
# pose
|
||||
batch_pose = torch.zeros(nbatch * seqlen, 6).to(self.device) # nbatch * seqlen x 6
|
||||
batch_pose[:, 3:6] = batch_pos
|
||||
|
||||
verts, _, _ = self.netR.get_vertices(batch_idn, batch_exp, batch_pose) # nbatch * seqlen x 5023 x 3
|
||||
verts = verts.reshape(nbatch, seqlen, -1, 3) # nbatch x seqlen x 5023 x 3
|
||||
# print(f"verts reshape = {verts.shape}")
|
||||
|
||||
return verts
|
||||
|
||||
|
||||
def eval_losses(self, batch_pdt_geo, batch_tgt):
|
||||
""" Computes the VAE loss function.
|
||||
pramas:
|
||||
batch_tgt, (nbatch, seqlen, dim_motion)
|
||||
batch_pdt_geo, (nbatch, seqlen, num_vertices, 3)
|
||||
"""
|
||||
loss = 0
|
||||
loss_dict = {}
|
||||
|
||||
# get mesh geometry
|
||||
batch_tgt_geo = self.get_vertices(batch_tgt, self.batch_shape) # B x nseq x num_vertices x 3
|
||||
|
||||
# synthesis geo rec
|
||||
loss = 0
|
||||
loss_rec_geo = self.loss_func_wing(batch_pdt_geo, batch_tgt_geo)
|
||||
loss_dict["loss_rec_geo"] = loss_rec_geo.detach()
|
||||
|
||||
loss_rec_geo2 = self.loss_func_wing(batch_pdt_geo, batch_tgt_geo, weight=self.vertices_weight)
|
||||
loss_dict["loss_rec_geo_w"] = loss_rec_geo2.detach()
|
||||
loss += loss_rec_geo2 * self.opt.LOSS.lambda_rec_geo
|
||||
|
||||
# synthesis geo volocity
|
||||
diff_pdt_geo = batch_pdt_geo[:, 1:, :] - batch_pdt_geo[:, :-1, :]
|
||||
diff_tgt_geo = batch_tgt_geo[:, 1:, :] - batch_tgt_geo[:, :-1, :]
|
||||
|
||||
loss_vol_geo = self.loss_func_wing(diff_pdt_geo, diff_tgt_geo)
|
||||
loss_dict["loss_vol_geo"] = loss_vol_geo.detach()
|
||||
|
||||
loss_vol_geo2 = self.loss_func_wing(diff_pdt_geo, diff_tgt_geo, weight=self.vertices_weight)
|
||||
loss_dict["loss_vol_geo_w"] = loss_vol_geo2.detach()
|
||||
loss += loss_vol_geo2 * self.opt.LOSS.lambda_vol_geo
|
||||
|
||||
# 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 i in range(B):
|
||||
igeo_pt = samples_pt[i, ...]
|
||||
ipath_save = path_save.joinpath(f"{suffix}_{i:02d}.mp4")
|
||||
|
||||
v_render_pt = []
|
||||
for k in range(0, N, nbatch_render):
|
||||
# split
|
||||
kgeo_pt = igeo_pt[k:k+nbatch_render, ...] # [nbatch_real x 5023 x 3]
|
||||
nbatch_real = kgeo_pt.size(0)
|
||||
|
||||
# cam
|
||||
cam = torch.tensor([5, 0, 0], device=self.device) # (1, 3)
|
||||
cam = cam.repeat(nbatch_real, 1) # (nbatch_real, 3)
|
||||
# print(f"cam shape = {cam.shape}")
|
||||
|
||||
# render
|
||||
render_pt = self.netR.render_geometry(kgeo_pt, cam, self.device) # (nbatch_real, 3, 512, 512)
|
||||
# print(f"render_pt ={render_pt.shape}, render_gt={render_gt.shape}")
|
||||
|
||||
# append each frame
|
||||
for m in range(nbatch_real):
|
||||
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, ipath_save)
|
||||
|
||||
|
||||
def save_reconstruct_with_gt(self, samples_pt, samples_gt, path_save, suffix=""):
|
||||
# samples_pt, [B x N x 5023 x 3]
|
||||
# samples_gt, [B x N x 5023 x 3]
|
||||
B, N, *_ = samples_pt.shape
|
||||
nbatch_render = 10
|
||||
|
||||
# for each batch
|
||||
for i in range(B):
|
||||
igeo_pt = samples_pt[i, ...] # [N x 5023 x 3]
|
||||
igeo_gt = samples_gt[i, ...] # [N x 5023 x 3]
|
||||
ipath_save = path_save.joinpath(f"{suffix}_{i:02d}.mp4")
|
||||
|
||||
v_render_pt = []
|
||||
v_render_gt = []
|
||||
|
||||
for k in range(0, N, nbatch_render):
|
||||
|
||||
# split
|
||||
kgeo_pt = igeo_pt[k:k+nbatch_render, ...] # [nbatch_real x 5023 x 3]
|
||||
kgeo_gt = igeo_gt[k:k+nbatch_render, ...] # [nbatch_real x 5023 x 3]
|
||||
nbatch_real = kgeo_pt.size(0)
|
||||
|
||||
# cam
|
||||
cam = torch.tensor([5, 0, 0], device=self.device) # (1, 3)
|
||||
cam = cam.repeat(nbatch_real, 1) # (nbatch_real, 3)
|
||||
# print(f"cam shape = {cam.shape}")
|
||||
|
||||
# render
|
||||
render_pt = self.netR.render_geometry(kgeo_pt, cam, self.device) # (nbatch_real, 3, 512, 512)
|
||||
render_gt = self.netR.render_geometry(kgeo_gt, cam, self.device) # (nbatch_real, 3, 512, 512)
|
||||
# print(f"render_pt ={render_pt.shape}, render_gt={render_gt.shape}")
|
||||
|
||||
# append each frame
|
||||
for m in range(nbatch_real):
|
||||
v_render_pt.append(tensor2image(render_pt[m, ...]))
|
||||
v_render_gt.append(tensor2image(render_gt[m, ...]))
|
||||
|
||||
# get audio
|
||||
jvid = self.batch_vid[i]
|
||||
jnframe = self.batch_nframe[i].numpy()
|
||||
jstart_frame = self.batch_interv[0][i].numpy()
|
||||
|
||||
jpath_audio = f"{self.opt.DATASET.root_raw}/{jvid}/audio/audio_trim.wav"
|
||||
jstart_time = (jstart_frame + 7) / self.opt.DATASET.fps # xxx.yyy min
|
||||
jend_time = (jstart_frame + 7 + self.nseq) / self.opt.DATASET.fps # xxx.yyy min
|
||||
# print(f"jvid={jvid}, jnfram={jnframe}, jstart_frame={jstart_frame}, jpath_audio={jpath_audio}")
|
||||
# print(f"jstart_time={jstart_time}, jend_time={jend_time}")
|
||||
|
||||
|
||||
# save animation
|
||||
# print(f"testing v_render_pt = {len(v_render_pt)}, gt shape = {len(v_render_gt)}")
|
||||
save_animation_with_gt2(v_render_pt, v_render_gt, ipath_save, fps=self.opt.DATASET.fps,\
|
||||
path_audio=jpath_audio, start_time=jstart_time, end_time=jend_time)
|
||||
|
||||
#########################################
|
||||
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 == "audio2mesh":
|
||||
from src.nn.audio2mesh import Audio2Mesh
|
||||
netG = Audio2Mesh(opt)
|
||||
|
||||
elif opt.MODEL.name_netG == "audio2mesh_voca":
|
||||
from src.nn.audio2mesh_voca import Audio2Mesh
|
||||
netG = Audio2Mesh(opt)
|
||||
|
||||
elif opt.MODEL.name_netG == "audio2mesh_resnet":
|
||||
from src.nn.audio2mesh_resnet import Audio2Mesh
|
||||
netG = Audio2Mesh(opt)
|
||||
|
||||
else:
|
||||
raise NameError(f"The model of opt.MODEL.name_netAE(={opt.MODEL.name_netG}) not existing!")
|
||||
|
||||
# to GPU
|
||||
netG.to(f"cuda:{opt.GPUS[0]}")
|
||||
netG = torch.nn.DataParallel(netG, opt.GPUS) # multi-GPUs
|
||||
|
||||
return netG
|
||||
|
||||
|
||||
def define_netR(device):
|
||||
# import
|
||||
|
||||
from src.nn.FLAME import FLAME
|
||||
|
||||
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)
|
||||
|
||||
# flame model
|
||||
flame = FLAME(deca_cfg.model).to(device)
|
||||
|
||||
|
||||
return netR, flame
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,334 @@
|
||||
|
||||
import sys
|
||||
import torch
|
||||
import torch.nn as nn
|
||||
import numpy as np
|
||||
from pathlib import Path
|
||||
|
||||
from src.models.base import Base
|
||||
from src.optims import get_optimizer, get_scheduler
|
||||
|
||||
from common.debug import debug
|
||||
from common.animation import save_animation_with_gt2
|
||||
|
||||
class Audio2MotionFModel(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)
|
||||
|
||||
# init
|
||||
if self.opt.MODEL.pretrain or self.opt.TRAIN.resume:
|
||||
self.netG.module.set_actnorm_init(True)
|
||||
else:
|
||||
self.netG.module.set_actnorm_init(False)
|
||||
|
||||
|
||||
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, self.flame = 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())
|
||||
|
||||
|
||||
if self.opt.DATASET.speech_extractor == "wav2vec":
|
||||
from transformers import Wav2Vec2FeatureExtractor, Wav2Vec2Model
|
||||
print("load Wav2Vec2Model ...")
|
||||
MODEL_ID = "jonatasgrosman/wav2vec2-large-xlsr-53-chinese-zh-cn"
|
||||
self.processor = Wav2Vec2FeatureExtractor.from_pretrained(MODEL_ID)
|
||||
self.extractor = Wav2Vec2Model.from_pretrained(MODEL_ID).to(self.device)
|
||||
|
||||
def set_input(self, batch_input):
|
||||
|
||||
# motion data
|
||||
self.data = batch_input['data'].float().to(self.device) # (B, nsteps, nc_motion)
|
||||
self.batch_vid = batch_input['vid']
|
||||
self.batch_nframe = batch_input['nframe']
|
||||
self.batch_interv = batch_input['frame_interval']
|
||||
|
||||
debug(self.opt, f"data = {self.data.shape}, dtype={self.data.dtype}", verbose=False)
|
||||
debug(self.opt, f"batch_vid = {self.batch_vid[:2]}", verbose=False)
|
||||
debug(self.opt, f"batch_nframe = {self.batch_nframe[:2]}", verbose=False)
|
||||
debug(self.opt, f"batch_interv len={len(self.batch_interv)} len([0])={len(self.batch_interv[0])}, \
|
||||
beg={self.batch_interv[0][:4]}, end={self.batch_interv[1][:4]}", verbose=False)
|
||||
|
||||
# speech data
|
||||
self.cond = None
|
||||
raw_speech = batch_input["cond"].numpy() # (B, nsegments)
|
||||
|
||||
if self.opt.DATASET.speech_extractor == "wav2vec":
|
||||
|
||||
# padding half frame length for bed and end
|
||||
npad = int(0.5 * self.opt.DATASET.sr * ( 1 / self.opt.DATASET.fps) + 0.5)
|
||||
raw_speech = np.pad(raw_speech, pad_width=((0,0), (npad, npad)), mode="edge")
|
||||
debug(self.opt, f"after padding raw_speech = {raw_speech.shape}, dtype={raw_speech.dtype}", verbose=False)
|
||||
|
||||
raw_speech = list(raw_speech)
|
||||
inputs = self.processor(raw_speech, sampling_rate=16000, return_tensors="pt")
|
||||
inputs = inputs.to(self.device)
|
||||
|
||||
with torch.no_grad():
|
||||
output = self.extractor(**inputs)
|
||||
self.cond = output.last_hidden_state
|
||||
# self.cond = output.extract_features
|
||||
else:
|
||||
assert 0, "opt.DATASET.speech_extractor should be 'wav2vec | deepspeech | mfcc ' "
|
||||
|
||||
|
||||
# B x nsteps x nc_feat
|
||||
debug(self.opt, f"data = {self.data.shape}, dtype={self.data.dtype}, device={self.data.device}", verbose=False)
|
||||
debug(self.opt, f"cond = {self.cond.shape}, dtype={self.cond.dtype}, device={self.cond.device}", verbose=False)
|
||||
|
||||
self.cond = self.cond.permute(0, 2, 1) # (B, nc_motion, nseqs)
|
||||
self.data = self.data.permute(0, 2, 1) # (B, nc_condit, nseqs)
|
||||
self.nseq = self.cond.size(2)
|
||||
debug(self.opt, f"permute data = {self.data.shape}, dtype={self.data.dtype}, device={self.data.device}", verbose=False)
|
||||
debug(self.opt, f"permute cond = {self.cond.shape}, dtype={self.cond.dtype}, device={self.cond.device}", verbose=False)
|
||||
|
||||
def remove_weightnorm(self):
|
||||
def remove(conv_list):
|
||||
new_conv_list = nn.ModuleList()
|
||||
for old_conv in conv_list:
|
||||
old_conv = nn.utils.remove_weight_norm(old_conv)
|
||||
new_conv_list.append(old_conv)
|
||||
return new_conv_list
|
||||
|
||||
for model in self.netG.module.FusionNets:
|
||||
model.layer_head = nn.utils.remove_weight_norm(model.layer_head)
|
||||
model.layer_cond = nn.utils.remove_weight_norm(model.layer_cond)
|
||||
model.in_layers = remove(model.in_layers)
|
||||
model.res_skip_layers = remove(model.res_skip_layers)
|
||||
|
||||
|
||||
def training(self, batch_input):
|
||||
self.train() # set train model
|
||||
self.set_input(batch_input)
|
||||
|
||||
# forward
|
||||
z, logdet = self.netG(self.data, self.cond)
|
||||
debug(self.opt, f"[Train] netG z shape = {len(z)}, logs shape = {logdet.shape}", verbose=False)
|
||||
|
||||
# loss
|
||||
# loss, self.loss_dict = self.netG.module.eval_losses()
|
||||
loss, self.loss_dict = self.netG.module.loss_function_(z, logdet)
|
||||
debug(self.opt, f"[Train] loss shape = {loss.shape}", verbose=False)
|
||||
|
||||
# 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)
|
||||
|
||||
# step
|
||||
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():
|
||||
z, logdet = self.netG(self.data, self.cond)
|
||||
loss, self.loss_dict = self.netG.module.loss_function_(z, logdet)
|
||||
return loss
|
||||
|
||||
|
||||
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.module.inverse(self.cond) # B x dim_motion x nsteps
|
||||
|
||||
samples_pt = samples_pt.permute(0, 2, 1).cpu().numpy() # B x nsteps x dim_motion
|
||||
samples_gt = self.data.permute(0, 2, 1).cpu().numpy() # B x nsteps 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 infer(self, batch_cond, path_audio, suffix=""):
|
||||
self.eval()
|
||||
# self.cond =
|
||||
|
||||
def get_vertices(self, batch_exp, batch_pos):
|
||||
"""
|
||||
batch_exp, (nbatch, seqlen, 50)
|
||||
batch_pos, (nbatch, seqlen, 3)
|
||||
"""
|
||||
nbatch, seqlen = batch_exp.size(0), batch_exp.size(1)
|
||||
batch_exp = batch_exp.reshape(nbatch * seqlen, -1) # nbatch * seqlen x 50
|
||||
batch_pos = batch_pos.reshape(nbatch * seqlen, -1) # nbatch * seqlen x 3
|
||||
|
||||
batch_shape = np.repeat([self.mean_dict["shape"]], nbatch * seqlen, axis=0) # (nbatch * seqlen, 100)
|
||||
batch_shape= torch.from_numpy(batch_shape).to(self.device)
|
||||
|
||||
batch_pose = np.repeat([self.mean_dict["pose"]], nbatch * seqlen, axis=0) # (nbatch * seqlen, 6)
|
||||
batch_pose = torch.from_numpy(batch_pose).to(self.device)
|
||||
batch_pose[:, 3:6] = batch_pos
|
||||
|
||||
|
||||
verts, _, _ = self.netR.get_vertices(batch_shape, batch_exp, batch_pose) # nbatch * seqlen x 5023 x 3
|
||||
verts = verts.reshape(nbatch, seqlen, -1, 3) # nbatch x seqlen x 5023 x 3
|
||||
# print(f"verts reshape = {verts.shape}")
|
||||
|
||||
return verts
|
||||
|
||||
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, ...]))
|
||||
|
||||
# get audio
|
||||
jvid = self.batch_vid[j]
|
||||
jnframe = self.batch_nframe[j].numpy()
|
||||
jstart_frame = self.batch_interv[0][j].numpy()
|
||||
|
||||
|
||||
jpath_audio = f"{self.opt.DATASET.root_raw}/{jvid}/audio/audio_trim.wav"
|
||||
# jpath_audio = f"/yrfs/lsen/DATA/LuoXData/processing2/{jvid}/audio/audio_trim.wav"
|
||||
jstart_time = (jstart_frame) / self.opt.DATASET.fps # xxx.yyy min
|
||||
jend_time = (jstart_frame + self.nseq) / self.opt.DATASET.fps # xxx.yyy min
|
||||
|
||||
|
||||
print(f"jvid={jvid}, jnfram={jnframe}, jstart_frame={jstart_frame}, jpath_audio={jpath_audio}")
|
||||
print(f"jstart_time={jstart_time}, jend_time={jend_time}")
|
||||
|
||||
|
||||
# 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, fps=self.opt.DATASET.fps,\
|
||||
path_audio=jpath_audio, start_time=jstart_time, end_time=jend_time)
|
||||
|
||||
|
||||
|
||||
#########################################
|
||||
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 == "MotionWaveFlow":
|
||||
from src.nn.MotionWaveFlow import MotionWaveFlow
|
||||
netG = MotionWaveFlow(opt)
|
||||
|
||||
elif opt.MODEL.name_netG == "MotionWaveFlow2":
|
||||
from src.nn.MotionWaveFlow2 import MotionWaveFlow
|
||||
netG = MotionWaveFlow(opt)
|
||||
|
||||
else:
|
||||
raise NameError(f"The model of opt.MODEL.name_netG(={opt.MODEL.name_netG}) not existing!")
|
||||
|
||||
# to GPU
|
||||
netG.to(f"cuda:{opt.GPUS[0]}")
|
||||
netG = torch.nn.DataParallel(netG, opt.GPUS) # multi-GPUs
|
||||
|
||||
|
||||
return netG
|
||||
|
||||
|
||||
def define_netR(device):
|
||||
# import
|
||||
|
||||
from src.nn.FLAME import FLAME
|
||||
|
||||
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)
|
||||
|
||||
# flame model
|
||||
flame = FLAME(deca_cfg.model).to(device)
|
||||
|
||||
|
||||
return netR, flame
|
||||
@@ -0,0 +1,354 @@
|
||||
|
||||
import sys
|
||||
import torch
|
||||
import torch.nn as nn
|
||||
import numpy as np
|
||||
from pathlib import Path
|
||||
|
||||
from src.models.base import Base
|
||||
from src.optims import get_optimizer, get_scheduler
|
||||
|
||||
from common.debug import debug
|
||||
from common.animation import save_animation_with_gt2
|
||||
|
||||
class Audio2MotionFWModel(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)
|
||||
|
||||
# init
|
||||
if self.opt.MODEL.pretrain or self.opt.TRAIN.resume:
|
||||
self.netG.module.set_actnorm_init(True)
|
||||
else:
|
||||
self.netG.module.set_actnorm_init(False)
|
||||
|
||||
|
||||
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, self.flame = 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())
|
||||
|
||||
|
||||
if self.opt.DATASET.speech_extractor == "wav2vec":
|
||||
from transformers import Wav2Vec2FeatureExtractor, Wav2Vec2Model
|
||||
print("load Wav2Vec2Model ...")
|
||||
MODEL_ID = "jonatasgrosman/wav2vec2-large-xlsr-53-chinese-zh-cn"
|
||||
self.processor = Wav2Vec2FeatureExtractor.from_pretrained(MODEL_ID)
|
||||
self.extractor = Wav2Vec2Model.from_pretrained(MODEL_ID).to(self.device)
|
||||
|
||||
def set_input(self, batch_input):
|
||||
|
||||
# motion data
|
||||
self.data = batch_input['data'].float().to(self.device) # (B, nsteps, nc_motion)
|
||||
self.batch_vid = batch_input['vid']
|
||||
self.batch_nframe = batch_input['nframe']
|
||||
self.batch_interv = batch_input['frame_interval']
|
||||
|
||||
debug(self.opt, f"data = {self.data.shape}, dtype={self.data.dtype}", verbose=False)
|
||||
debug(self.opt, f"batch_vid = {self.batch_vid[:2]}", verbose=False)
|
||||
debug(self.opt, f"batch_nframe = {self.batch_nframe[:2]}", verbose=False)
|
||||
debug(self.opt, f"batch_interv len={len(self.batch_interv)} len([0])={len(self.batch_interv[0])}, \
|
||||
beg={self.batch_interv[0][:4]}, end={self.batch_interv[1][:4]}", verbose=False)
|
||||
|
||||
# speech data
|
||||
self.cond = None
|
||||
raw_speech = batch_input["cond"].numpy() # (B, nsegments)
|
||||
|
||||
if self.opt.DATASET.speech_extractor == "wav2vec":
|
||||
|
||||
# padding half frame length for bed and end
|
||||
npad = int(0.5 * self.opt.DATASET.sr * ( 1 / self.opt.DATASET.fps) + 0.5)
|
||||
raw_speech = np.pad(raw_speech, pad_width=((0,0), (npad, npad)), mode="edge")
|
||||
debug(self.opt, f"after padding raw_speech = {raw_speech.shape}, dtype={raw_speech.dtype}", verbose=False)
|
||||
|
||||
raw_speech = list(raw_speech)
|
||||
inputs = self.processor(raw_speech, sampling_rate=16000, return_tensors="pt")
|
||||
inputs = inputs.to(self.device)
|
||||
|
||||
with torch.no_grad():
|
||||
output = self.extractor(**inputs)
|
||||
self.cond = output.last_hidden_state
|
||||
# self.cond = output.extract_features
|
||||
else:
|
||||
assert 0, "opt.DATASET.speech_extractor should be 'wav2vec | deepspeech | mfcc ' "
|
||||
|
||||
|
||||
# B x nsteps x nc_feat
|
||||
debug(self.opt, f"data = {self.data.shape}, dtype={self.data.dtype}, device={self.data.device}", verbose=False)
|
||||
debug(self.opt, f"cond = {self.cond.shape}, dtype={self.cond.dtype}, device={self.cond.device}", verbose=False)
|
||||
|
||||
# unfold
|
||||
self.cond = self.cond.unfold(dimension=1, size=16, step=1) # (B, nsteps2, nc_motion, 16)
|
||||
self.cond = self.cond.permute(0, 1, 3, 2) # (B, nsteps2, 16, nc_motion)
|
||||
|
||||
|
||||
# self.cond = self.cond.permute(0, 2, 1) # (B, nc_motion, nsteps)
|
||||
|
||||
self.nseq = self.cond.size(1) # nsteps2
|
||||
self.data = self.data.permute(0, 2, 1) # (B, nc_condit, nsteps)
|
||||
self.data = self.data[:, :, 7:7+self.nseq] # (B, nc_condit, nsteps2)
|
||||
|
||||
debug(self.opt, f"permute data = {self.data.shape}, dtype={self.data.dtype}, device={self.data.device}", verbose=False)
|
||||
debug(self.opt, f"permute cond = {self.cond.shape}, dtype={self.cond.dtype}, device={self.cond.device}", verbose=False)
|
||||
|
||||
def remove_weightnorm(self):
|
||||
def remove(conv_list):
|
||||
new_conv_list = nn.ModuleList()
|
||||
for old_conv in conv_list:
|
||||
old_conv = nn.utils.remove_weight_norm(old_conv)
|
||||
new_conv_list.append(old_conv)
|
||||
return new_conv_list
|
||||
|
||||
for model in self.netG.module.FusionNets:
|
||||
model.layer_head = nn.utils.remove_weight_norm(model.layer_head)
|
||||
model.layer_cond = nn.utils.remove_weight_norm(model.layer_cond)
|
||||
model.in_layers = remove(model.in_layers)
|
||||
model.res_skip_layers = remove(model.res_skip_layers)
|
||||
|
||||
|
||||
def training(self, batch_input):
|
||||
self.train() # set train model
|
||||
self.set_input(batch_input)
|
||||
|
||||
# forward
|
||||
z, logdet = self.netG(self.data, self.cond)
|
||||
debug(self.opt, f"[Train] netG z shape = {len(z)}, logs shape = {logdet.shape}", verbose=False)
|
||||
|
||||
# loss
|
||||
# loss, self.loss_dict = self.netG.module.eval_losses()
|
||||
loss, self.loss_dict = self.netG.module.loss_function_(z, logdet)
|
||||
debug(self.opt, f"[Train] loss shape = {loss.shape}", verbose=False)
|
||||
|
||||
# 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)
|
||||
|
||||
# step
|
||||
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():
|
||||
z, logdet = self.netG(self.data, self.cond)
|
||||
loss, self.loss_dict = self.netG.module.loss_function_(z, logdet)
|
||||
return loss
|
||||
|
||||
|
||||
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.module.inverse(self.cond) # B x dim_motion x nsteps
|
||||
|
||||
samples_pt = samples_pt.permute(0, 2, 1).cpu().numpy() # B x nsteps x dim_motion
|
||||
samples_gt = self.data.permute(0, 2, 1).cpu().numpy() # B x nsteps 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 infer(self, batch_cond, path_audio, suffix=""):
|
||||
self.eval()
|
||||
# self.cond =
|
||||
|
||||
def get_vertices(self, batch_exp, batch_pos):
|
||||
"""
|
||||
batch_exp, (nbatch, seqlen, 50)
|
||||
batch_pos, (nbatch, seqlen, 3)
|
||||
"""
|
||||
nbatch, seqlen = batch_exp.size(0), batch_exp.size(1)
|
||||
batch_exp = batch_exp.reshape(nbatch * seqlen, -1) # nbatch * seqlen x 50
|
||||
batch_pos = batch_pos.reshape(nbatch * seqlen, -1) # nbatch * seqlen x 3
|
||||
|
||||
batch_shape = np.repeat([self.mean_dict["shape"]], nbatch * seqlen, axis=0) # (nbatch * seqlen, 100)
|
||||
batch_shape= torch.from_numpy(batch_shape).to(self.device)
|
||||
|
||||
batch_pose = np.repeat([self.mean_dict["pose"]], nbatch * seqlen, axis=0) # (nbatch * seqlen, 6)
|
||||
batch_pose = torch.from_numpy(batch_pose).to(self.device)
|
||||
batch_pose[:, 3:6] = batch_pos
|
||||
|
||||
|
||||
verts, _, _ = self.netR.get_vertices(batch_shape, batch_exp, batch_pose) # nbatch * seqlen x 5023 x 3
|
||||
verts = verts.reshape(nbatch, seqlen, -1, 3) # nbatch x seqlen x 5023 x 3
|
||||
# print(f"verts reshape = {verts.shape}")
|
||||
|
||||
return verts
|
||||
|
||||
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, ...]))
|
||||
|
||||
# get audio
|
||||
jvid = self.batch_vid[j]
|
||||
jnframe = self.batch_nframe[j].numpy()
|
||||
jstart_frame = self.batch_interv[0][j].numpy() + 7
|
||||
|
||||
|
||||
jpath_audio = f"{self.opt.DATASET.root_raw}/{jvid}/audio/audio_trim.wav"
|
||||
# jpath_audio = f"/yrfs/lsen/DATA/LuoXData/processing2/{jvid}/audio/audio_trim.wav"
|
||||
jstart_time = (jstart_frame ) / self.opt.DATASET.fps # xxx.yyy min
|
||||
jend_time = (jstart_frame + self.nseq) / self.opt.DATASET.fps # xxx.yyy min
|
||||
|
||||
|
||||
print(f"jvid={jvid}, jnfram={jnframe}, jstart_frame={jstart_frame}, jpath_audio={jpath_audio}")
|
||||
print(f"jstart_time={jstart_time}, jend_time={jend_time}")
|
||||
|
||||
|
||||
# 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, fps=self.opt.DATASET.fps,\
|
||||
path_audio=jpath_audio, start_time=jstart_time, end_time=jend_time)
|
||||
|
||||
|
||||
|
||||
#########################################
|
||||
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 == "MotionWaveFlow":
|
||||
from src.nn.MotionWaveFlow import MotionWaveFlow
|
||||
netG = MotionWaveFlow(opt)
|
||||
|
||||
elif opt.MODEL.name_netG == "MotionWaveFlow2":
|
||||
from src.nn.MotionWaveFlow2 import MotionWaveFlow
|
||||
netG = MotionWaveFlow(opt)
|
||||
|
||||
elif opt.MODEL.name_netG == "MotionWaveFlow22":
|
||||
from src.nn.MotionWaveFlow22 import MotionWaveFlow
|
||||
netG = MotionWaveFlow(opt)
|
||||
|
||||
elif opt.MODEL.name_netG == "MotionWaveFlow3":
|
||||
from src.nn.MotionWaveFlow3 import MotionWaveFlow
|
||||
netG = MotionWaveFlow(opt)
|
||||
|
||||
elif opt.MODEL.name_netG == "MotionWaveFlow4":
|
||||
from src.nn.MotionWaveFlow4 import MotionWaveFlow
|
||||
netG = MotionWaveFlow(opt)
|
||||
|
||||
else:
|
||||
raise NameError(f"The model of opt.MODEL.name_netG(={opt.MODEL.name_netG}) not existing!")
|
||||
|
||||
# to GPU
|
||||
netG.to(f"cuda:{opt.GPUS[0]}")
|
||||
netG = torch.nn.DataParallel(netG, opt.GPUS) # multi-GPUs
|
||||
|
||||
|
||||
return netG
|
||||
|
||||
|
||||
def define_netR(device):
|
||||
# import
|
||||
|
||||
from src.nn.FLAME import FLAME
|
||||
|
||||
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)
|
||||
|
||||
# flame model
|
||||
flame = FLAME(deca_cfg.model).to(device)
|
||||
|
||||
|
||||
return netR, flame
|
||||
@@ -331,7 +331,9 @@ class Audio2motionLive2Model(Base):
|
||||
jnframe = self.batch_nframe[j].numpy()
|
||||
jstart_frame = self.batch_interv[0][j].numpy()
|
||||
|
||||
jpath_audio = f"/yrfs/lsen/DATA/LuoXData/processing2/{jvid}/audio/audio_trim.wav"
|
||||
|
||||
jpath_audio = f"{self.opt.DATASET.root_raw}/{jvid}/audio/audio_trim.wav"
|
||||
# jpath_audio = f"/yrfs/lsen/DATA/LuoXData/processing2/{jvid}/audio/audio_trim.wav"
|
||||
jstart_time = (jstart_frame + 7) / self.opt.DATASET.fps # xxx.yyy min
|
||||
jend_time = (jstart_frame + 7 + self.nseq) / self.opt.DATASET.fps # xxx.yyy min
|
||||
|
||||
@@ -367,9 +369,9 @@ def define_netG(opt):
|
||||
from src.nn.audio2motion_voca import Audio2MotionVOCA
|
||||
netG = Audio2MotionVOCA(opt)
|
||||
|
||||
elif opt.MODEL.name_netG == "audio2motion_voca3":
|
||||
from src.nn.audio2motion_voca3 import Audio2MotionVOCA3
|
||||
netG = Audio2MotionVOCA3(opt)
|
||||
elif opt.MODEL.name_netG == "audio2motion_voca34":
|
||||
from src.nn.audio2motion_voca34 import Audio2MotionVOCA
|
||||
netG = Audio2MotionVOCA(opt)
|
||||
|
||||
elif opt.MODEL.name_netG == "audio2motion_voca33":
|
||||
from src.nn.audio2motion_voca33 import Audio2MotionVOCA
|
||||
|
||||
@@ -0,0 +1,464 @@
|
||||
import sys
|
||||
import numpy as np
|
||||
|
||||
import torch
|
||||
import torch.nn as nn
|
||||
import torch.nn.functional as F
|
||||
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 Audio2motionLive3Model(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, self.flame = 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())
|
||||
|
||||
if self.opt.DATASET.speech_extractor == "wav2vec":
|
||||
from transformers import Wav2Vec2FeatureExtractor, Wav2Vec2Model
|
||||
print("load Wav2Vec2Model ...")
|
||||
MODEL_ID = "jonatasgrosman/wav2vec2-large-xlsr-53-chinese-zh-cn"
|
||||
self.processor = Wav2Vec2FeatureExtractor.from_pretrained(MODEL_ID)
|
||||
self.extractor = Wav2Vec2Model.from_pretrained(MODEL_ID).to(self.device)
|
||||
|
||||
|
||||
|
||||
def set_input(self, batch_input):
|
||||
|
||||
# motion data
|
||||
self.data = batch_input["data"].float().to(self.device) # (B, nsteps, nc_motion)
|
||||
|
||||
self.batch_vid = batch_input['vid']
|
||||
self.batch_nframe = batch_input['nframe']
|
||||
self.batch_interv = batch_input['frame_interval']
|
||||
|
||||
debug(self.opt, f"data = {self.data.shape}, dtype={self.data.dtype}", verbose=False)
|
||||
debug(self.opt, f"batch_vid = {self.batch_vid[:2]}", verbose=False)
|
||||
debug(self.opt, f"batch_nframe = {self.batch_nframe[:2]}", verbose=False)
|
||||
debug(self.opt, f"batch_interv len={len(self.batch_interv)} len([0])={len(self.batch_interv[0])}, \
|
||||
beg={self.batch_interv[0][:4]}, end={self.batch_interv[1][:4]}", verbose=False)
|
||||
|
||||
self.B, self.nsteps = self.data.size(0), self.data.size(1)
|
||||
|
||||
# speech data
|
||||
raw_speech = batch_input["cond"].numpy() # (B, nsegments)
|
||||
debug(self.opt, f"raw_speech = {raw_speech.shape}, dtype={raw_speech.dtype}", verbose=False)
|
||||
|
||||
if self.opt.DATASET.speech_extractor == "wav2vec":
|
||||
# raw_speech = raw_speech.reshape(self.B * self.nsteps, -1) # (B*nsteps, nsegments)
|
||||
# debug(self.opt, f"raw_speech = {raw_speech.shape}, dtype={raw_speech.dtype}", verbose=False)
|
||||
|
||||
# padding half frame length for bed and end
|
||||
npad = int(0.5 * self.opt.DATASET.sr * ( 1 / self.opt.DATASET.fps) + 0.5)
|
||||
raw_speech = np.pad(raw_speech, pad_width=((0,0), (npad, npad)), mode="edge")
|
||||
debug(self.opt, f"after padding raw_speech = {raw_speech.shape}, dtype={raw_speech.dtype}", verbose=False)
|
||||
|
||||
raw_speech = list(raw_speech)
|
||||
inputs = self.processor(raw_speech, sampling_rate=16000, return_tensors="pt")
|
||||
inputs = inputs.to(self.device)
|
||||
|
||||
with torch.no_grad():
|
||||
output = self.extractor(**inputs)
|
||||
self.cond = output.last_hidden_state
|
||||
# self.cond = output.extract_features
|
||||
|
||||
# B x nsteps x nc_feat
|
||||
debug(self.opt, f"data = {self.data.shape}, dtype={self.data.dtype}, device={self.data.device}", verbose=False)
|
||||
debug(self.opt, f"cond = {self.cond.shape}, dtype={self.cond.dtype}, device={self.cond.device}", verbose=False)
|
||||
|
||||
# unfold
|
||||
# self.data = self.data.unfold(dimension=1, size=16, step=1) # (B, nseqs, nc_motion, 16)
|
||||
# self.data = self.data.permute(0, 1, 3, 2) # (B, nseqs, 16, 53)
|
||||
|
||||
self.cond = self.cond.unfold(dimension=1, size=16, step=1) # (nseqs, nc_motion, 16)
|
||||
self.cond = self.cond.permute(0, 1, 3, 2) # (nseqs, 16, 53)
|
||||
|
||||
self.nseq = self.cond.size(1)
|
||||
self.data = self.data[:, 7:7+self.nseq, :]
|
||||
|
||||
debug(self.opt, f"\n a data = {self.data.shape}, dtype={self.data.dtype}, device={self.data.device}", verbose=False)
|
||||
debug(self.opt, f"a cond = {self.cond.shape}, dtype={self.cond.dtype}, device={self.cond.device}", 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)
|
||||
|
||||
# save result
|
||||
path_save_npy = Path(self.opt.OUTPUT_DIR).joinpath(f"{suffix}.npy")
|
||||
np.save(path_save_npy, samples_pt)
|
||||
print(f"save infer_result shape = {samples_pt.shape} -> {path_save_npy}")
|
||||
|
||||
|
||||
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 get_vertices(self, batch_exp, batch_pos):
|
||||
"""
|
||||
batch_exp, (nbatch, seqlen, 50)
|
||||
batch_pos, (nbatch, seqlen, 3)
|
||||
"""
|
||||
nbatch, seqlen = batch_exp.size(0), batch_exp.size(1)
|
||||
batch_exp = batch_exp.reshape(nbatch * seqlen, -1) # nbatch * seqlen x 50
|
||||
batch_pos = batch_pos.reshape(nbatch * seqlen, -1) # nbatch * seqlen x 3
|
||||
|
||||
batch_shape = np.repeat([self.mean_dict["shape"]], nbatch * seqlen, axis=0) # (nbatch * seqlen, 100)
|
||||
batch_shape= torch.from_numpy(batch_shape).to(self.device)
|
||||
|
||||
batch_pose = np.repeat([self.mean_dict["pose"]], nbatch * seqlen, axis=0) # (nbatch * seqlen, 6)
|
||||
batch_pose = torch.from_numpy(batch_pose).to(self.device)
|
||||
batch_pose[:, 3:6] = batch_pos
|
||||
|
||||
|
||||
verts, _, _ = self.netR.get_vertices(batch_shape, batch_exp, batch_pose) # nbatch * seqlen x 5023 x 3
|
||||
verts = verts.reshape(nbatch, seqlen, -1, 3) # nbatch x seqlen x 5023 x 3
|
||||
# print(f"verts reshape = {verts.shape}")
|
||||
|
||||
return verts
|
||||
|
||||
|
||||
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 = {}
|
||||
|
||||
batch_pdt_exp = batch_pdt[..., :50]
|
||||
batch_pdt_pos = batch_pdt[..., 50:]
|
||||
|
||||
batch_tgt_exp = batch_tgt[..., :50]
|
||||
batch_tgt_pos = batch_tgt[..., 50:]
|
||||
|
||||
# get reconstruction
|
||||
batch_pdt_geo = self.get_vertices(batch_pdt_exp, batch_pdt_pos) # B x nseq x num_vertices x 3
|
||||
batch_tgt_geo = self.get_vertices(batch_tgt_exp, batch_tgt_pos) # B x nseq x num_vertices x 3
|
||||
|
||||
# rec loss
|
||||
loss = 0
|
||||
loss_rec_exp = self.loss_func_wing(batch_pdt_exp, batch_tgt_exp) / 50
|
||||
loss_dict["loss_rec_exp"] = loss_rec_exp.detach()
|
||||
|
||||
loss_rec_pos = self.loss_func_wing(batch_pdt_pos, batch_tgt_pos) / 3
|
||||
loss_dict["loss_rec_pos"] = loss_rec_pos.detach()
|
||||
|
||||
loss += loss_rec_exp * self.opt.LOSS.lambda_rec_exp
|
||||
loss += loss_rec_pos * self.opt.LOSS.lambda_rec_pos
|
||||
|
||||
# rec smooth
|
||||
diff_pdt_exp = batch_pdt_exp[:, 1:, :] - batch_pdt_exp[:, :-1, :]
|
||||
diff_tgt_exp = batch_tgt_exp[:, 1:, :] - batch_tgt_exp[:, :-1, :]
|
||||
loss_vol_exp = self.loss_func_wing(diff_pdt_exp, diff_tgt_exp) / 50
|
||||
loss_dict["loss_vol_exp"] = loss_vol_exp.detach()
|
||||
|
||||
diff_pdt_pos = batch_pdt_pos[:, 1:, :] - batch_pdt_pos[:, :-1, :]
|
||||
diff_tgt_pos = batch_tgt_pos[:, 1:, :] - batch_tgt_pos[:, :-1, :]
|
||||
loss_vol_pos = self.loss_func_wing(diff_pdt_pos, diff_tgt_pos) / 3
|
||||
loss_dict["loss_vol_pos"] = loss_vol_pos.detach()
|
||||
|
||||
loss += loss_vol_exp * self.opt.LOSS.lambda_vol_exp
|
||||
loss += loss_vol_pos * self.opt.LOSS.lambda_vol_pos
|
||||
|
||||
# geo rec
|
||||
loss_rec_geo = self.loss_func_wing(batch_pdt_geo, batch_tgt_geo)
|
||||
loss_dict["loss_rec_geo"] = loss_rec_geo.detach()
|
||||
loss += loss_rec_geo * self.opt.LOSS.lambda_rec_geo
|
||||
|
||||
|
||||
# geo volocity
|
||||
diff_pdt_geo = batch_pdt_geo[:, 1:, :] - batch_pdt_geo[:, :-1, :]
|
||||
diff_tgt_geo = batch_tgt_geo[:, 1:, :] - batch_tgt_geo[:, :-1, :]
|
||||
loss_vol_geo = self.loss_func_wing(diff_pdt_geo, diff_tgt_geo)
|
||||
loss_dict["loss_vol_geo"] = loss_vol_geo.detach()
|
||||
loss += loss_vol_geo * self.opt.LOSS.lambda_vol_geo
|
||||
|
||||
|
||||
# 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, ...]))
|
||||
|
||||
# get audio
|
||||
jvid = self.batch_vid[j]
|
||||
jnframe = self.batch_nframe[j].numpy()
|
||||
jstart_frame = self.batch_interv[0][j].numpy() + 7
|
||||
|
||||
|
||||
jpath_audio = f"{self.opt.DATASET.root_raw}/{jvid}/audio/audio_trim.wav"
|
||||
# jpath_audio = f"/yrfs/lsen/DATA/LuoXData/processing2/{jvid}/audio/audio_trim.wav"
|
||||
jstart_time = (jstart_frame) / self.opt.DATASET.fps # xxx.yyy min
|
||||
jend_time = (jstart_frame + self.nseq) / self.opt.DATASET.fps # xxx.yyy min
|
||||
|
||||
|
||||
|
||||
print(f"jvid={jvid}, jnfram={jnframe}, jstart_frame={jstart_frame}, jpath_audio={jpath_audio}")
|
||||
print(f"jstart_time={jstart_time}, jend_time={jend_time}")
|
||||
|
||||
|
||||
# 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, fps=self.opt.DATASET.fps,\
|
||||
path_audio=jpath_audio, start_time=jstart_time, end_time=jend_time)
|
||||
|
||||
|
||||
#########################################
|
||||
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_voca4":
|
||||
from src.nn.audio2motion_voca4 import Audio2MotionVOCA
|
||||
netG = Audio2MotionVOCA(opt)
|
||||
|
||||
elif opt.MODEL.name_netG == "audio2motion_voca":
|
||||
from src.nn.audio2motion_voca import Audio2MotionVOCA
|
||||
netG = Audio2MotionVOCA(opt)
|
||||
|
||||
elif opt.MODEL.name_netG == "audio2motion_voca34":
|
||||
from src.nn.audio2motion_voca34 import Audio2MotionVOCA
|
||||
netG = Audio2MotionVOCA(opt)
|
||||
|
||||
elif opt.MODEL.name_netG == "audio2motion_voca33":
|
||||
from src.nn.audio2motion_voca33 import Audio2MotionVOCA
|
||||
netG = Audio2MotionVOCA(opt)
|
||||
|
||||
elif opt.MODEL.name_netG == "audio2motion":
|
||||
from src.nn.audio2motion import Audio2Motion
|
||||
netG = Audio2Motion(opt)
|
||||
|
||||
elif opt.MODEL.name_netG == "audio2motion2":
|
||||
from src.nn.audio2motion2 import Audio2Motion2
|
||||
netG = Audio2Motion2(opt)
|
||||
else:
|
||||
raise NameError(f"The model of opt.MODEL.name_netAE(={opt.MODEL.name_netG}) not existing!")
|
||||
|
||||
|
||||
return netG
|
||||
|
||||
|
||||
def define_netR(device):
|
||||
# import
|
||||
|
||||
from src.nn.FLAME import FLAME
|
||||
|
||||
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)
|
||||
|
||||
# flame model
|
||||
flame = FLAME(deca_cfg.model).to(device)
|
||||
|
||||
|
||||
return netR, flame
|
||||
|
||||
|
||||
|
||||
+266
@@ -0,0 +1,266 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
#
|
||||
# Max-Planck-Gesellschaft zur Förderung der Wissenschaften e.V. (MPG) is
|
||||
# holder of all proprietary rights on this computer program.
|
||||
# Using this computer program means that you agree to the terms
|
||||
# in the LICENSE file included with this software distribution.
|
||||
# Any use not explicitly granted by the LICENSE is prohibited.
|
||||
#
|
||||
# Copyright©2019 Max-Planck-Gesellschaft zur Förderung
|
||||
# der Wissenschaften e.V. (MPG). acting on behalf of its Max Planck Institute
|
||||
# for Intelligent Systems. All rights reserved.
|
||||
#
|
||||
# For comments or questions, please email us at deca@tue.mpg.de
|
||||
# For commercial licensing contact, please contact ps-license@tuebingen.mpg.de
|
||||
|
||||
import torch
|
||||
import torch.nn as nn
|
||||
import numpy as np
|
||||
import pickle
|
||||
import torch.nn.functional as F
|
||||
|
||||
from .lbs import lbs, batch_rodrigues, vertices2landmarks, rot_mat_to_euler
|
||||
|
||||
def to_tensor(array, dtype=torch.float32):
|
||||
if 'torch.tensor' not in str(type(array)):
|
||||
return torch.tensor(array, dtype=dtype)
|
||||
def to_np(array, dtype=np.float32):
|
||||
if 'scipy.sparse' in str(type(array)):
|
||||
array = array.todense()
|
||||
return np.array(array, dtype=dtype)
|
||||
|
||||
class Struct(object):
|
||||
def __init__(self, **kwargs):
|
||||
for key, val in kwargs.items():
|
||||
setattr(self, key, val)
|
||||
|
||||
class FLAME(nn.Module):
|
||||
"""
|
||||
borrowed from https://github.com/soubhiksanyal/FLAME_PyTorch/blob/master/FLAME.py
|
||||
Given flame parameters this class generates a differentiable FLAME function
|
||||
which outputs the a mesh and 2D/3D facial landmarks
|
||||
"""
|
||||
def __init__(self, config):
|
||||
super(FLAME, self).__init__()
|
||||
print("creating the FLAME Decoder")
|
||||
with open(config.flame_model_path, 'rb') as f:
|
||||
ss = pickle.load(f, encoding='latin1')
|
||||
flame_model = Struct(**ss)
|
||||
|
||||
self.dtype = torch.float32
|
||||
self.register_buffer('faces_tensor', to_tensor(to_np(flame_model.f, dtype=np.int64), dtype=torch.long))
|
||||
# The vertices of the template model
|
||||
self.register_buffer('v_template', to_tensor(to_np(flame_model.v_template), dtype=self.dtype))
|
||||
# The shape components and expression
|
||||
shapedirs = to_tensor(to_np(flame_model.shapedirs), dtype=self.dtype)
|
||||
shapedirs = torch.cat([shapedirs[:,:,:config.n_shape], shapedirs[:,:,300:300+config.n_exp]], 2)
|
||||
self.register_buffer('shapedirs', shapedirs)
|
||||
# The pose components
|
||||
num_pose_basis = flame_model.posedirs.shape[-1]
|
||||
posedirs = np.reshape(flame_model.posedirs, [-1, num_pose_basis]).T
|
||||
self.register_buffer('posedirs', to_tensor(to_np(posedirs), dtype=self.dtype))
|
||||
#
|
||||
self.register_buffer('J_regressor', to_tensor(to_np(flame_model.J_regressor), dtype=self.dtype))
|
||||
parents = to_tensor(to_np(flame_model.kintree_table[0])).long(); parents[0] = -1
|
||||
self.register_buffer('parents', parents)
|
||||
self.register_buffer('lbs_weights', to_tensor(to_np(flame_model.weights), dtype=self.dtype))
|
||||
|
||||
# Fixing Eyeball and neck rotation
|
||||
default_eyball_pose = torch.zeros([1, 6], dtype=self.dtype, requires_grad=False)
|
||||
self.register_parameter('eye_pose', nn.Parameter(default_eyball_pose,
|
||||
requires_grad=False))
|
||||
default_neck_pose = torch.zeros([1, 3], dtype=self.dtype, requires_grad=False)
|
||||
self.register_parameter('neck_pose', nn.Parameter(default_neck_pose,
|
||||
requires_grad=False))
|
||||
|
||||
# Static and Dynamic Landmark embeddings for FLAME
|
||||
lmk_embeddings = np.load(config.flame_lmk_embedding_path, allow_pickle=True, encoding='latin1')
|
||||
lmk_embeddings = lmk_embeddings[()]
|
||||
self.register_buffer('lmk_faces_idx', torch.from_numpy(lmk_embeddings['static_lmk_faces_idx']).long())
|
||||
self.register_buffer('lmk_bary_coords', torch.from_numpy(lmk_embeddings['static_lmk_bary_coords']).to(self.dtype))
|
||||
self.register_buffer('dynamic_lmk_faces_idx', lmk_embeddings['dynamic_lmk_faces_idx'].long())
|
||||
self.register_buffer('dynamic_lmk_bary_coords', lmk_embeddings['dynamic_lmk_bary_coords'].to(self.dtype))
|
||||
self.register_buffer('full_lmk_faces_idx', torch.from_numpy(lmk_embeddings['full_lmk_faces_idx']).long())
|
||||
self.register_buffer('full_lmk_bary_coords', torch.from_numpy(lmk_embeddings['full_lmk_bary_coords']).to(self.dtype))
|
||||
|
||||
neck_kin_chain = []; NECK_IDX=1
|
||||
curr_idx = torch.tensor(NECK_IDX, dtype=torch.long)
|
||||
while curr_idx != -1:
|
||||
neck_kin_chain.append(curr_idx)
|
||||
curr_idx = self.parents[curr_idx]
|
||||
self.register_buffer('neck_kin_chain', torch.stack(neck_kin_chain))
|
||||
|
||||
def _find_dynamic_lmk_idx_and_bcoords(self, pose, dynamic_lmk_faces_idx,
|
||||
dynamic_lmk_b_coords,
|
||||
neck_kin_chain, dtype=torch.float32):
|
||||
"""
|
||||
Selects the face contour depending on the reletive position of the head
|
||||
Input:
|
||||
vertices: N X num_of_vertices X 3
|
||||
pose: N X full pose
|
||||
dynamic_lmk_faces_idx: The list of contour face indexes
|
||||
dynamic_lmk_b_coords: The list of contour barycentric weights
|
||||
neck_kin_chain: The tree to consider for the relative rotation
|
||||
dtype: Data type
|
||||
return:
|
||||
The contour face indexes and the corresponding barycentric weights
|
||||
"""
|
||||
|
||||
batch_size = pose.shape[0]
|
||||
|
||||
aa_pose = torch.index_select(pose.view(batch_size, -1, 3), 1,
|
||||
neck_kin_chain)
|
||||
rot_mats = batch_rodrigues(
|
||||
aa_pose.view(-1, 3), dtype=dtype).view(batch_size, -1, 3, 3)
|
||||
|
||||
rel_rot_mat = torch.eye(3, device=pose.device,
|
||||
dtype=dtype).unsqueeze_(dim=0).expand(batch_size, -1, -1)
|
||||
for idx in range(len(neck_kin_chain)):
|
||||
rel_rot_mat = torch.bmm(rot_mats[:, idx], rel_rot_mat)
|
||||
|
||||
y_rot_angle = torch.round(
|
||||
torch.clamp(rot_mat_to_euler(rel_rot_mat) * 180.0 / np.pi,
|
||||
max=39)).to(dtype=torch.long)
|
||||
|
||||
neg_mask = y_rot_angle.lt(0).to(dtype=torch.long)
|
||||
mask = y_rot_angle.lt(-39).to(dtype=torch.long)
|
||||
neg_vals = mask * 78 + (1 - mask) * (39 - y_rot_angle)
|
||||
y_rot_angle = (neg_mask * neg_vals +
|
||||
(1 - neg_mask) * y_rot_angle)
|
||||
|
||||
dyn_lmk_faces_idx = torch.index_select(dynamic_lmk_faces_idx,
|
||||
0, y_rot_angle)
|
||||
dyn_lmk_b_coords = torch.index_select(dynamic_lmk_b_coords,
|
||||
0, y_rot_angle)
|
||||
return dyn_lmk_faces_idx, dyn_lmk_b_coords
|
||||
|
||||
def _vertices2landmarks(self, vertices, faces, lmk_faces_idx, lmk_bary_coords):
|
||||
"""
|
||||
Calculates landmarks by barycentric interpolation
|
||||
Input:
|
||||
vertices: torch.tensor NxVx3, dtype = torch.float32
|
||||
The tensor of input vertices
|
||||
faces: torch.tensor (N*F)x3, dtype = torch.long
|
||||
The faces of the mesh
|
||||
lmk_faces_idx: torch.tensor N X L, dtype = torch.long
|
||||
The tensor with the indices of the faces used to calculate the
|
||||
landmarks.
|
||||
lmk_bary_coords: torch.tensor N X L X 3, dtype = torch.float32
|
||||
The tensor of barycentric coordinates that are used to interpolate
|
||||
the landmarks
|
||||
|
||||
Returns:
|
||||
landmarks: torch.tensor NxLx3, dtype = torch.float32
|
||||
The coordinates of the landmarks for each mesh in the batch
|
||||
"""
|
||||
# Extract the indices of the vertices for each face
|
||||
# NxLx3
|
||||
batch_size, num_verts = vertices.shape[:dd2]
|
||||
lmk_faces = torch.index_select(faces, 0, lmk_faces_idx.view(-1)).view(
|
||||
1, -1, 3).view(batch_size, lmk_faces_idx.shape[1], -1)
|
||||
|
||||
lmk_faces += torch.arange(batch_size, dtype=torch.long).view(-1, 1, 1).to(
|
||||
device=vertices.device) * num_verts
|
||||
|
||||
lmk_vertices = vertices.view(-1, 3)[lmk_faces]
|
||||
landmarks = torch.einsum('blfi,blf->bli', [lmk_vertices, lmk_bary_coords])
|
||||
return landmarks
|
||||
|
||||
def seletec_3d68(self, vertices):
|
||||
landmarks3d = vertices2landmarks(vertices, self.faces_tensor,
|
||||
self.full_lmk_faces_idx.repeat(vertices.shape[0], 1),
|
||||
self.full_lmk_bary_coords.repeat(vertices.shape[0], 1, 1))
|
||||
return landmarks3d
|
||||
|
||||
def forward(self, shape_params=None, expression_params=None, pose_params=None, eye_pose_params=None):
|
||||
"""
|
||||
Input:
|
||||
shape_params: N X number of shape parameters
|
||||
expression_params: N X number of expression parameters
|
||||
pose_params: N X number of pose parameters (6)
|
||||
return:d
|
||||
vertices: N X V X 3
|
||||
landmarks: N X number of landmarks X 3
|
||||
"""
|
||||
batch_size = shape_params.shape[0]
|
||||
if eye_pose_params is None:
|
||||
eye_pose_params = self.eye_pose.expand(batch_size, -1)
|
||||
betas = torch.cat([shape_params, expression_params], dim=1)
|
||||
full_pose = torch.cat([pose_params[:, :3],
|
||||
self.neck_pose.expand(batch_size, -1),
|
||||
pose_params[:, 3:],
|
||||
eye_pose_params], dim=1)
|
||||
template_vertices = self.v_template.unsqueeze(0).expand(batch_size, -1, -1)
|
||||
|
||||
vertices, _ = lbs(betas, full_pose, template_vertices,
|
||||
self.shapedirs, self.posedirs,
|
||||
self.J_regressor, self.parents,
|
||||
self.lbs_weights, dtype=self.dtype)
|
||||
|
||||
lmk_faces_idx = self.lmk_faces_idx.unsqueeze(dim=0).expand(batch_size, -1)
|
||||
lmk_bary_coords = self.lmk_bary_coords.unsqueeze(dim=0).expand(batch_size, -1, -1)
|
||||
|
||||
dyn_lmk_faces_idx, dyn_lmk_bary_coords = self._find_dynamic_lmk_idx_and_bcoords(
|
||||
full_pose, self.dynamic_lmk_faces_idx,
|
||||
self.dynamic_lmk_bary_coords,
|
||||
self.neck_kin_chain, dtype=self.dtype)
|
||||
lmk_faces_idx = torch.cat([dyn_lmk_faces_idx, lmk_faces_idx], 1)
|
||||
lmk_bary_coords = torch.cat([dyn_lmk_bary_coords, lmk_bary_coords], 1)
|
||||
|
||||
landmarks2d = vertices2landmarks(vertices, self.faces_tensor,
|
||||
lmk_faces_idx,
|
||||
lmk_bary_coords)
|
||||
bz = vertices.shape[0]
|
||||
landmarks3d = vertices2landmarks(vertices, self.faces_tensor,
|
||||
self.full_lmk_faces_idx.repeat(bz, 1),
|
||||
self.full_lmk_bary_coords.repeat(bz, 1, 1))
|
||||
|
||||
return vertices, landmarks2d, landmarks3d
|
||||
|
||||
class FLAMETex(nn.Module):
|
||||
"""
|
||||
FLAME texture:
|
||||
https://github.com/TimoBolkart/TF_FLAME/blob/ade0ab152300ec5f0e8555d6765411555c5ed43d/sample_texture.py#L64
|
||||
FLAME texture converted from BFM:
|
||||
https://github.com/TimoBolkart/BFM_to_FLAME
|
||||
"""
|
||||
def __init__(self, config):
|
||||
super(FLAMETex, self).__init__()
|
||||
if config.tex_type == 'BFM':
|
||||
mu_key = 'MU'
|
||||
pc_key = 'PC'
|
||||
n_pc = 199
|
||||
tex_path = config.tex_path
|
||||
tex_space = np.load(tex_path)
|
||||
texture_mean = tex_space[mu_key].reshape(1, -1)
|
||||
texture_basis = tex_space[pc_key].reshape(-1, n_pc)
|
||||
|
||||
elif config.tex_type == 'FLAME':
|
||||
mu_key = 'mean'
|
||||
pc_key = 'tex_dir'
|
||||
n_pc = 200
|
||||
tex_path = config.flame_tex_path
|
||||
tex_space = np.load(tex_path)
|
||||
texture_mean = tex_space[mu_key].reshape(1, -1)/255.
|
||||
texture_basis = tex_space[pc_key].reshape(-1, n_pc)/255.
|
||||
else:
|
||||
print('texture type ', config.tex_type, 'not exist!')
|
||||
raise NotImplementedError
|
||||
|
||||
n_tex = config.n_tex
|
||||
num_components = texture_basis.shape[1]
|
||||
texture_mean = torch.from_numpy(texture_mean).float()[None,...]
|
||||
texture_basis = torch.from_numpy(texture_basis[:,:n_tex]).float()[None,...]
|
||||
self.register_buffer('texture_mean', texture_mean)
|
||||
self.register_buffer('texture_basis', texture_basis)
|
||||
|
||||
def forward(self, texcode):
|
||||
'''
|
||||
texcode: [batchsize, n_tex]
|
||||
texture: [bz, 3, 256, 256], range: 0-1
|
||||
'''
|
||||
texture = self.texture_mean + (self.texture_basis*texcode[:,None,:]).sum(-1)
|
||||
texture = texture.reshape(texcode.shape[0], 512, 512, 3).permute(0,3,1,2)
|
||||
texture = F.interpolate(texture, [256, 256])
|
||||
texture = texture[:,[2,1,0], :,:]
|
||||
return texture
|
||||
@@ -0,0 +1,304 @@
|
||||
import torch
|
||||
import torch.nn as nn
|
||||
import torch.nn.functional as F
|
||||
import numpy as np
|
||||
|
||||
from common.debug import debug
|
||||
from src.nn.layers import ActNorm1d, Invertible1x1Conv1d as Invertible1x1Conv
|
||||
|
||||
# @torch.jit.script
|
||||
def fused_add_tanh_sigmoid_multiply(input_a, input_b, n_channels):
|
||||
n_channels_int = n_channels[0]
|
||||
in_act = input_a + input_b
|
||||
t_act = torch.tanh(in_act[:, :n_channels_int, :])
|
||||
s_act = torch.sigmoid(in_act[:, n_channels_int:, :])
|
||||
acts = t_act * s_act
|
||||
return acts
|
||||
|
||||
|
||||
class MotionWaveFlow(nn.Module):
|
||||
|
||||
def __init__(self, opt):
|
||||
super(MotionWaveFlow, self).__init__()
|
||||
|
||||
self.opt = opt
|
||||
self.nc_motion = opt.MODEL.dim_motion # 5023
|
||||
self.nc_condit = opt.MODEL.dim_speech # 1024
|
||||
|
||||
self.n_flows = opt.MODEL.n_flowstep # 12
|
||||
self.n_early_every = opt.MODEL.n_early_every # 4 --> 3
|
||||
|
||||
self.fix_dims = np.array(opt.MODEL.fix_dims)
|
||||
self.lambda_std = np.array(opt.MODEL.lambda_std) # [1, 0.75, 0.5, 0.25]
|
||||
self.lambda_std = torch.from_numpy(self.lambda_std).float().cuda(opt.GPUS[0])
|
||||
|
||||
self.Conv1x1Invs = nn.ModuleList()
|
||||
self.FusionNets = nn.ModuleList()
|
||||
self.Actnorms = nn.ModuleList()
|
||||
nc_motion_rest = self.nc_motion # 8 --> 136
|
||||
|
||||
for k in range(self.n_flows):
|
||||
if k % self.n_early_every == 0 and k > 0: # k = 3, 6, 9
|
||||
nc_motion_rest = nc_motion_rest - nc_motion_rest // 2 # = 84, 42, 21
|
||||
|
||||
self.Actnorms.append(ActNorm1d(num_channels=nc_motion_rest))
|
||||
self.Conv1x1Invs.append(Invertible1x1Conv(nc_motion_rest))
|
||||
self.FusionNets.append(FusionNet(self.opt, nc_motion=nc_motion_rest - nc_motion_rest//2,
|
||||
nc_condit=self.nc_condit,
|
||||
nc_output=2*(nc_motion_rest//2)))
|
||||
|
||||
debug(self.opt, f"[Model] k={k} nc_motion_rest={nc_motion_rest}")
|
||||
|
||||
self.nc_motion_rest = nc_motion_rest # Useful during inference, 72 / 8
|
||||
|
||||
|
||||
def set_actnorm_init(self, inited=True):
|
||||
for name, m in self.named_modules():
|
||||
if (m.__class__.__name__.find("ActNorm") >= 0):
|
||||
m.inited = inited
|
||||
debug(self.opt, f"[Model] set module {m.__class__.__name__} inited = {inited}")
|
||||
|
||||
|
||||
def forward(self, x, c):
|
||||
"""For training, x --> z
|
||||
x shape = (B, nc_motion, nsteps),
|
||||
c shape = (B, nc_condit, nsteps),
|
||||
return:
|
||||
z shape = (B, dim_motin, nsteps)
|
||||
"""
|
||||
|
||||
debug(self.opt, f"\n[Forward] start x shape={x.shape}, c={c.shape}", verbose=False)
|
||||
|
||||
predt_z = []
|
||||
logdet = torch.zeros(c.size(0), dtype=c.dtype, device=c.device)
|
||||
|
||||
for k in range(self.n_flows):
|
||||
|
||||
x, logdet = self.Actnorms[k](x, logdet)
|
||||
debug(self.opt, f"[Forward] k={k}, actnorm x shape = {x.shape} logdet={logdet.shape}", verbose=False)
|
||||
|
||||
x, logdet = self.Conv1x1Invs[k](x, logdet)
|
||||
debug(self.opt, f"[Forward] k={k}, Conv1x1Invs x={x.shape}, logdet={logdet.shape}")
|
||||
|
||||
# coupling layers
|
||||
nc_motion_half = x.size(1) - x.size(1) // 2
|
||||
x1, x2 = x[:, :nc_motion_half, :], x[:, nc_motion_half:, :]
|
||||
debug(self.opt, f"[Forward] k={k}, coupling split x1={x1.shape}, x2={x2.shape}")
|
||||
|
||||
feat = self.FusionNets[k](x1, c) # (B, nc_motion_half, dim_output)
|
||||
shift, scale = feat[:, 0::2, :], feat[:, 1::2, :]
|
||||
scale = torch.sigmoid(scale + 2.) + 1e-6 # to make scale > 1, so that log(s) > 0
|
||||
x2 = (x2 + shift) * scale
|
||||
logdet = torch.sum(torch.log(scale), dim=[1, 2]) + logdet
|
||||
|
||||
# multi-scale split
|
||||
if k % self.n_early_every == (self.n_early_every -1) and k > 0 and k < self.n_flows -1:
|
||||
predt_z.append(x2)
|
||||
x = x1
|
||||
debug(self.opt, f"[Forward] k={k}, coupling muli-scale x={x.shape}, x2={x2.shape}, logdet={logdet.shape}", verbose=False)
|
||||
else:
|
||||
x = torch.cat([x1, x2], dim=1)
|
||||
debug(self.opt, f"[Forward] k={k}, coupling concat x={x.shape}, logdet={logdet.shape}", verbose=False)
|
||||
|
||||
|
||||
# append the last x
|
||||
predt_z.append(x)
|
||||
predt_z = list(reversed(predt_z))
|
||||
# predt_z = torch.cat(predt_z, dim=1)
|
||||
|
||||
# [Model] k=0 nc_motion_rest=15069
|
||||
# [Model] k=1 nc_motion_rest=15069
|
||||
# [Model] k=2 nc_motion_rest=15069
|
||||
# [Model] k=3 nc_motion_rest=7535
|
||||
# [Model] k=4 nc_motion_rest=7535
|
||||
# [Model] k=5 nc_motion_rest=7535
|
||||
# [Model] k=6 nc_motion_rest=3768
|
||||
# [Model] k=7 nc_motion_rest=3768
|
||||
# [Model] k=8 nc_motion_rest=3768
|
||||
# [Model] k=9 nc_motion_rest=1884
|
||||
# [Model] k=10 nc_motion_rest=1884
|
||||
# [Model] k=11 nc_motion_rest=1884
|
||||
|
||||
return predt_z, logdet
|
||||
|
||||
def inverse(self, c):
|
||||
"""For inference, z --> x
|
||||
c shape = (B, nc_condit, nsteps_c)
|
||||
return:
|
||||
x shape = (B, nc_motion, nsteps_x)
|
||||
"""
|
||||
|
||||
B, nsteps = c.size(0), c.size(2)
|
||||
|
||||
# add z
|
||||
mu = torch.zeros(B, self.nc_motion_rest, nsteps, device=c.device)
|
||||
std = torch.ones(B, self.nc_motion_rest, nsteps, device=c.device) * self.lambda_std[0]
|
||||
x = torch.normal(mean=mu, std=std)
|
||||
# x = torch.zeros(B, self.nc_motion_rest, nsteps, device=c.device).normal_() # (B, 40, 60)
|
||||
|
||||
logdet = torch.zeros(c.size(0), dtype=c.dtype, device=c.device)
|
||||
debug(self.opt, f"[Inverse] c={c.shape}, x={x.shape}, feac_c={c.shape}")
|
||||
|
||||
istd = 1
|
||||
for k in reversed(range(self.n_flows)):
|
||||
# coupling layer
|
||||
nc_motion_half = x.size(1) - x.size(1) // 2
|
||||
x1, x2 = x[:, :nc_motion_half, :], x[:, nc_motion_half:, :]
|
||||
debug(self.opt, f"[Inverse] k={k}, x1={x1.shape}, x2={x2.shape}", verbose=False)
|
||||
|
||||
feat = self.FusionNets[k](x1, c) # (B, 1, dim_output)
|
||||
shift, scale = feat[:, 0::2, :], feat[:, 1::2, :]
|
||||
scale = torch.sigmoid(scale + 2.) + 1e-6 # to make scale > 1, so that log(s) > 0
|
||||
debug(self.opt, f"[Inverse] k={k}, coupling feat shape={feat.shape}, shift={shift.shape}, scale={scale.shape}", verbose=False)
|
||||
|
||||
x2 = x2 / scale - shift
|
||||
x = torch.cat([x1, x2], dim=1)
|
||||
logdet = - torch.sum(torch.log(scale), dim=[1,2]) + logdet
|
||||
debug(self.opt, f"[Inverse] k={k}, coupling concat x={x.shape}, logdet={logdet.shape}", verbose=False)
|
||||
|
||||
# 1 x 1 conv inv
|
||||
x, logdet = self.Conv1x1Invs[k].inverse(x, logdet)
|
||||
debug(self.opt, f"[Inverse] k={k}, Conv1x1Invs x={x.shape}")
|
||||
|
||||
# actnorm
|
||||
x, logdet = self.Actnorms[k].inverse(x, logdet)
|
||||
debug(self.opt, f"[Inverse] k={k}, actnorm x shape = {x.shape}", verbose=False)
|
||||
|
||||
# add noise
|
||||
if k % self.n_early_every == 0 and k > 0:
|
||||
# z = torch.zeros(B, x.size(1), nsteps, device=c.device).normal_() # (B, 40, 60)
|
||||
num_dims = x.size(1) + self.fix_dims[istd]
|
||||
|
||||
mu = torch.zeros(B, num_dims, nsteps, device=c.device)
|
||||
std = torch.ones(B, num_dims, nsteps, device=c.device) * self.lambda_std[istd]
|
||||
z = torch.normal(mean=mu, std=std)
|
||||
istd += 1
|
||||
|
||||
x = torch.cat((x, z), dim=1) # (B, 8/40/72/104/136, 25)
|
||||
debug(self.opt, f"[Inverse] k={k}, ADD noise + {x.size(1)} channel, x shape = {x.shape}", verbose=False)
|
||||
|
||||
return x.detach(), logdet # (B, nc_motion, nsteps)
|
||||
|
||||
|
||||
def loss_function_(self, z, logdet, sigma=1.0):
|
||||
"""z = list (B, nc_motion, N)
|
||||
logdet = list (B, )
|
||||
"""
|
||||
|
||||
loss = 0
|
||||
loss_dict = {}
|
||||
nsteps = z[0].size(2)
|
||||
debug(self.opt, f"[Loss] z shape={z[0].shape}, logdet={logdet.shape}")
|
||||
assert len(z) == len(self.lambda_std)
|
||||
|
||||
logp = 0
|
||||
for std, zn in zip(self.lambda_std, z):
|
||||
ilogp = -torch.log(std) - 0.5*zn*zn / (std * std) - 0.5 * torch.log(2 * torch.tensor(np.pi)) # B x nc x nsteps
|
||||
logp += torch.sum(ilogp, dim=[1,2]) / (2*sigma * sigma) # (B, )
|
||||
|
||||
# logp = - 0.5*z*z - 0.5 * torch.log(2 * torch.tensor(np.pi)) # (B, N, nc_motion)
|
||||
# logp = torch.sum(logp, dim=[1,2]) / (2*sigma * sigma) # (B, )
|
||||
|
||||
loss_logp = - torch.mean(logp) / (np.log(2.0) * nsteps * len(z))
|
||||
loss_logdet = - torch.mean(logdet) / (np.log(2.0) * nsteps)
|
||||
loss = loss_logp * self.opt.LOSS.lambda_logp + loss_logdet * self.opt.LOSS.lambda_logdet
|
||||
|
||||
loss_dict["loss_logp"] = loss_logp.detach()
|
||||
loss_dict["loss_logdet"] = loss_logdet.detach()
|
||||
loss_dict["loss_all"] = loss.detach()
|
||||
|
||||
return loss, loss_dict
|
||||
|
||||
|
||||
class FusionNet(nn.Module):
|
||||
"""
|
||||
This is the WaveNet like layer for the affine coupling. The primary difference
|
||||
from WaveNet is the convolutions need not be causal. There is also no dilation
|
||||
size reset. The dilation only doubles on each layer
|
||||
"""
|
||||
|
||||
def __init__(self, opt, nc_motion, nc_condit, nc_output):
|
||||
super(FusionNet, self).__init__()
|
||||
|
||||
self.opt = opt
|
||||
|
||||
self.n_layers = opt.MODEL.n_layer_wave # 4
|
||||
self.nc_hidden = opt.MODEL.dim_hidden # 256
|
||||
|
||||
kernel_size = opt.MODEL.kernel_size # 3
|
||||
assert(kernel_size % 2 == 1)
|
||||
assert(self.nc_hidden % 2 == 0)
|
||||
|
||||
|
||||
layer_head = nn.Conv1d(nc_motion, self.nc_hidden, kernel_size=1)
|
||||
layer_head = nn.utils.weight_norm(layer_head, name='weight')
|
||||
self.layer_head = layer_head
|
||||
|
||||
# Initializing last layer to 0 makes the affine coupling layers
|
||||
# do nothing at first. This helps with training stability
|
||||
layer_tail = nn.Conv1d(self.nc_hidden, nc_output, kernel_size=1)
|
||||
layer_tail.weight.data.zero_()
|
||||
layer_tail.bias.data.zero_()
|
||||
self.layer_tail = layer_tail
|
||||
|
||||
# for
|
||||
layer_cond = nn.Conv1d(nc_condit, 2*self.nc_hidden*self.n_layers, 1)
|
||||
self.layer_cond = nn.utils.weight_norm(layer_cond, name='weight')
|
||||
self.layer_cond = layer_cond
|
||||
|
||||
self.in_layers = nn.ModuleList()
|
||||
self.res_skip_layers = nn.ModuleList()
|
||||
|
||||
for i in range(self.n_layers):
|
||||
dilation = 2 ** i # 1, 2, 4, 8
|
||||
padding = (kernel_size * dilation - dilation) // 2 # 1, 2, 4, 8
|
||||
in_layer = nn.Conv1d(self.nc_hidden, 2*self.nc_hidden, kernel_size, dilation=dilation, padding=padding)
|
||||
in_layer = nn.utils.weight_norm(in_layer, name='weight')
|
||||
self.in_layers.append(in_layer)
|
||||
|
||||
# last one is not necessary
|
||||
nc_skip = 2 * self.nc_hidden if (i < self.n_layers - 1) else self.nc_hidden
|
||||
layer_skip = nn.Conv1d(self.nc_hidden, nc_skip, kernel_size=1)
|
||||
layer_skip = nn.utils.weight_norm(layer_skip, name='weight')
|
||||
self.res_skip_layers.append(layer_skip)
|
||||
|
||||
|
||||
def forward(self, x, c):
|
||||
""" forward function
|
||||
x shape = (B x nfeat1 x nsteps1) B x nc_motion_half x nstep
|
||||
c shape = (B x nfeat2 x nsteps2) B x nc_condit*nc_motion x nstep
|
||||
"""
|
||||
|
||||
feat_x = self.layer_head(x) # B x nc_hidden x nstep
|
||||
feat_c = self.layer_cond(c) # B x 4*nc_hidden x nstep
|
||||
feat_o = torch.zeros_like(feat_x) # B x nc_hidden x nstep
|
||||
debug(self.opt, f"\t[FusionNet] feat_x={feat_x.shape}, feat_c={feat_c.shape}, feat_o={feat_o.shape}")
|
||||
|
||||
nc_hidden_tensor = torch.IntTensor([self.nc_hidden])
|
||||
|
||||
for i in range(self.n_layers):
|
||||
c_offset = i * 2 * self.nc_hidden
|
||||
debug(self.opt, f"\t[FusionNet] layers={i} c_offset={c_offset}")
|
||||
|
||||
|
||||
ifeat_x = self.in_layers[i](feat_x) # B x 2*nc_hidden x nstep
|
||||
ifeat_c = feat_c[:, c_offset:c_offset+2*self.nc_hidden, :] # B x 2*nc_hidden x nstep
|
||||
debug(self.opt, f"\t[FusionNet] \tifeat_x={ifeat_x.shape} ifeat_c={ifeat_c.shape}")
|
||||
|
||||
ifeat_m = fused_add_tanh_sigmoid_multiply(ifeat_x, ifeat_c, nc_hidden_tensor) # B x nc_hidden x nstep
|
||||
debug(self.opt, f"\t[FusionNet] \tifeat_m={ifeat_m.shape}")
|
||||
|
||||
ifeat_m = self.res_skip_layers[i](ifeat_m) # B x 2*nc_hidden x nstep if not last layer else B x nc_hidden x 25
|
||||
debug(self.opt, f"\t[FusionNet] \t res skip ifeat_m={ifeat_m.shape}")
|
||||
|
||||
if i < self.n_layers - 1:
|
||||
feat_x = feat_x + ifeat_m[:, :self.nc_hidden, :] # B x nc_hidden x nstep
|
||||
feat_o = feat_o + ifeat_m[:, self.nc_hidden:, :] # B x nc_hidden x nstep
|
||||
else:
|
||||
feat_o = feat_o + ifeat_m # B x nc_hidden x nstep
|
||||
|
||||
feat_o = self.layer_tail(feat_o) # B x nc_motion_half x nstep
|
||||
debug(self.opt, f"\t[FusionNet] tail feat_o={feat_o.shape}")
|
||||
|
||||
return feat_o
|
||||
|
||||
@@ -0,0 +1,371 @@
|
||||
import torch
|
||||
import torch.nn as nn
|
||||
import torch.nn.functional as F
|
||||
import numpy as np
|
||||
|
||||
from common.debug import debug
|
||||
from src.nn.layers import ActNorm1d, Invertible1x1Conv1d as Invertible1x1Conv
|
||||
|
||||
# @torch.jit.script
|
||||
def fused_add_tanh_sigmoid_multiply(input_a, input_b, n_channels):
|
||||
n_channels_int = n_channels[0]
|
||||
in_act = input_a + input_b
|
||||
t_act = torch.tanh(in_act[:, :n_channels_int, :])
|
||||
s_act = torch.sigmoid(in_act[:, n_channels_int:, :])
|
||||
acts = t_act * s_act
|
||||
return acts
|
||||
|
||||
|
||||
class MotionWaveFlow(nn.Module):
|
||||
|
||||
def __init__(self, opt):
|
||||
super(MotionWaveFlow, self).__init__()
|
||||
|
||||
self.opt = opt
|
||||
self.nc_motion = opt.MODEL.dim_motion # 5023
|
||||
self.nc_condit = opt.MODEL.dim_speech # 1024
|
||||
self.nc_hidden = opt.MODEL.dim_hidden # 256
|
||||
|
||||
|
||||
self.n_flows = opt.MODEL.n_flowstep # 12
|
||||
self.n_early_every = opt.MODEL.n_early_every # 4 --> 3
|
||||
|
||||
self.fix_dims = np.array(opt.MODEL.fix_dims)
|
||||
self.lambda_std = np.array(opt.MODEL.lambda_std) # [1, 0.75, 0.5, 0.25]
|
||||
self.lambda_std = torch.from_numpy(self.lambda_std).float().cuda(opt.GPUS[0])
|
||||
|
||||
self.speechEncoder = SpeechEncoderNet(opt, self.nc_condit, self.nc_hidden)
|
||||
self.Conv1x1Invs = nn.ModuleList()
|
||||
self.FusionNets = nn.ModuleList()
|
||||
self.Actnorms = nn.ModuleList()
|
||||
nc_motion_rest = self.nc_motion # 8 --> 136
|
||||
|
||||
for k in range(self.n_flows):
|
||||
if k % self.n_early_every == 0 and k > 0: # k = 3, 6, 9
|
||||
nc_motion_rest = nc_motion_rest - nc_motion_rest // 2 # = 84, 42, 21
|
||||
|
||||
self.Actnorms.append(ActNorm1d(num_channels=nc_motion_rest))
|
||||
self.Conv1x1Invs.append(Invertible1x1Conv(nc_motion_rest))
|
||||
self.FusionNets.append(FusionNet(self.opt, nc_motion=nc_motion_rest - nc_motion_rest//2,
|
||||
nc_condit=self.nc_hidden,
|
||||
nc_output=2*(nc_motion_rest//2)))
|
||||
|
||||
debug(self.opt, f"[Model] k={k} nc_motion_rest={nc_motion_rest}")
|
||||
|
||||
self.nc_motion_rest = nc_motion_rest # Useful during inference, 72 / 8
|
||||
|
||||
|
||||
def set_actnorm_init(self, inited=True):
|
||||
for name, m in self.named_modules():
|
||||
if (m.__class__.__name__.find("ActNorm") >= 0):
|
||||
m.inited = inited
|
||||
debug(self.opt, f"[Model] set module {m.__class__.__name__} inited = {inited}")
|
||||
|
||||
|
||||
def forward(self, x, c):
|
||||
"""For training, x --> z
|
||||
x shape = (B, nc_motion, nsteps),
|
||||
c shape = (B, nsteps, nwind, nc_speech),
|
||||
return:
|
||||
z shape = (B, dim_motin, nsteps)
|
||||
"""
|
||||
|
||||
debug(self.opt, f"\n[Forward] start x shape={x.shape}, c={c.shape}", verbose=False)
|
||||
|
||||
predt_z = []
|
||||
feat_c = self.speechEncoder(c) # (B, nc_hidden, nsteps)
|
||||
logdet = torch.zeros(c.size(0), dtype=c.dtype, device=c.device)
|
||||
debug(self.opt, f"\n[Forward] feat_c shape={feat_c.shape}, logdet={logdet.shape}", verbose=False)
|
||||
|
||||
for k in range(self.n_flows):
|
||||
|
||||
x, logdet = self.Actnorms[k](x, logdet)
|
||||
debug(self.opt, f"[Forward] k={k}, actnorm x shape = {x.shape} logdet={logdet.shape}", verbose=False)
|
||||
|
||||
x, logdet = self.Conv1x1Invs[k](x, logdet)
|
||||
debug(self.opt, f"[Forward] k={k}, Conv1x1Invs x={x.shape}, logdet={logdet.shape}")
|
||||
|
||||
# coupling layers
|
||||
nc_motion_half = x.size(1) - x.size(1) // 2
|
||||
x1, x2 = x[:, :nc_motion_half, :], x[:, nc_motion_half:, :]
|
||||
debug(self.opt, f"[Forward] k={k}, coupling split x1={x1.shape}, x2={x2.shape}")
|
||||
|
||||
feat = self.FusionNets[k](x1, feat_c) # (B, nc_motion_half, nc_output)
|
||||
shift, scale = feat[:, 0::2, :], feat[:, 1::2, :]
|
||||
scale = torch.sigmoid(scale + 2.) + 1e-6 # to make scale > 1, so that log(s) > 0
|
||||
x2 = (x2 + shift) * scale
|
||||
logdet = torch.sum(torch.log(scale), dim=[1, 2]) + logdet
|
||||
|
||||
# multi-scale split
|
||||
if k % self.n_early_every == (self.n_early_every -1) and k > 0 and k < self.n_flows -1:
|
||||
predt_z.append(x2)
|
||||
x = x1
|
||||
debug(self.opt, f"[Forward] k={k}, coupling muli-scale x={x.shape}, x2={x2.shape}, logdet={logdet.shape}", verbose=False)
|
||||
else:
|
||||
x = torch.cat([x1, x2], dim=1)
|
||||
debug(self.opt, f"[Forward] k={k}, coupling concat x={x.shape}, logdet={logdet.shape}", verbose=False)
|
||||
|
||||
|
||||
# append the last x
|
||||
predt_z.append(x)
|
||||
predt_z = list(reversed(predt_z))
|
||||
# predt_z = torch.cat(predt_z, dim=1)
|
||||
|
||||
return predt_z, logdet
|
||||
|
||||
def inverse(self, c):
|
||||
"""For inference, z --> x
|
||||
# c shape = (B, nc_condit, nsteps_c)
|
||||
c shape = (B, nsteps, nwind, nc_speech),
|
||||
return:
|
||||
x shape = (B, nc_motion, nsteps_x)
|
||||
"""
|
||||
|
||||
B, nsteps = c.size(0), c.size(1)
|
||||
|
||||
# add z
|
||||
mu = torch.zeros(B, self.nc_motion_rest, nsteps, device=c.device)
|
||||
std = torch.ones(B, self.nc_motion_rest, nsteps, device=c.device) * self.lambda_std[0]
|
||||
x = torch.normal(mean=mu, std=std)
|
||||
# x = torch.zeros(B, self.nc_motion_rest, nsteps, device=c.device).normal_() # (B, 40, 60)
|
||||
|
||||
feat_c = self.speechEncoder(c) # (B, nc_hidden, nsteps)
|
||||
logdet = torch.zeros(B, dtype=c.dtype, device=c.device)
|
||||
debug(self.opt, f"\n[Inverse] feat_c shape={feat_c.shape}, logdet={logdet.shape}", verbose=False)
|
||||
|
||||
istd = 1
|
||||
for k in reversed(range(self.n_flows)):
|
||||
# coupling layer
|
||||
nc_motion_half = x.size(1) - x.size(1) // 2
|
||||
x1, x2 = x[:, :nc_motion_half, :], x[:, nc_motion_half:, :]
|
||||
debug(self.opt, f"[Inverse] k={k}, x1={x1.shape}, x2={x2.shape}", verbose=False)
|
||||
|
||||
feat = self.FusionNets[k](x1, feat_c) # (B, 1, nc_output)
|
||||
shift, scale = feat[:, 0::2, :], feat[:, 1::2, :]
|
||||
scale = torch.sigmoid(scale + 2.) + 1e-6 # to make scale > 1, so that log(s) > 0
|
||||
debug(self.opt, f"[Inverse] k={k}, coupling feat shape={feat.shape}, shift={shift.shape}, scale={scale.shape}", verbose=False)
|
||||
|
||||
x2 = x2 / scale - shift
|
||||
x = torch.cat([x1, x2], dim=1)
|
||||
logdet = - torch.sum(torch.log(scale), dim=[1,2]) + logdet
|
||||
debug(self.opt, f"[Inverse] k={k}, coupling concat x={x.shape}, logdet={logdet.shape}", verbose=False)
|
||||
|
||||
# 1 x 1 conv inv
|
||||
x, logdet = self.Conv1x1Invs[k].inverse(x, logdet)
|
||||
debug(self.opt, f"[Inverse] k={k}, Conv1x1Invs x={x.shape}")
|
||||
|
||||
# actnorm
|
||||
x, logdet = self.Actnorms[k].inverse(x, logdet)
|
||||
debug(self.opt, f"[Inverse] k={k}, actnorm x shape = {x.shape}", verbose=False)
|
||||
|
||||
# add noise
|
||||
if k % self.n_early_every == 0 and k > 0:
|
||||
# z = torch.zeros(B, x.size(1), nsteps, device=c.device).normal_() # (B, 40, 60)
|
||||
num_dims = x.size(1) + self.fix_dims[istd]
|
||||
|
||||
mu = torch.zeros(B, num_dims, nsteps, device=c.device)
|
||||
std = torch.ones(B, num_dims, nsteps, device=c.device) * self.lambda_std[istd]
|
||||
z = torch.normal(mean=mu, std=std)
|
||||
istd += 1
|
||||
|
||||
x = torch.cat((x, z), dim=1) # (B, 8/40/72/104/136, 25)
|
||||
debug(self.opt, f"[Inverse] k={k}, ADD noise + {x.size(1)} channel, x shape = {x.shape}", verbose=False)
|
||||
|
||||
return x.detach(), logdet # (B, nc_motion, nsteps)
|
||||
|
||||
|
||||
def loss_function_(self, z, logdet, sigma=1.0):
|
||||
"""z = list (B, nc_motion, N)
|
||||
logdet = list (B, )
|
||||
"""
|
||||
|
||||
loss = 0
|
||||
loss_dict = {}
|
||||
nsteps = z[0].size(2)
|
||||
debug(self.opt, f"[Loss] z shape={z[0].shape}, logdet={logdet.shape}")
|
||||
assert len(z) == len(self.lambda_std)
|
||||
|
||||
logp = 0
|
||||
for std, zn in zip(self.lambda_std, z):
|
||||
ilogp = -torch.log(std) - 0.5*zn*zn / (std * std) - 0.5 * torch.log(2 * torch.tensor(np.pi)) # B x nc x nsteps
|
||||
logp += torch.sum(ilogp, dim=[1,2]) / (2*sigma * sigma) # (B, )
|
||||
|
||||
# logp = - 0.5*z*z - 0.5 * torch.log(2 * torch.tensor(np.pi)) # (B, N, nc_motion)
|
||||
# logp = torch.sum(logp, dim=[1,2]) / (2*sigma * sigma) # (B, )
|
||||
|
||||
loss_logp = - torch.mean(logp) / (np.log(2.0) * nsteps * len(z))
|
||||
loss_logdet = - torch.mean(logdet) / (np.log(2.0) * nsteps)
|
||||
loss = loss_logp * self.opt.LOSS.lambda_logp + loss_logdet * self.opt.LOSS.lambda_logdet
|
||||
|
||||
loss_dict["loss_logp"] = loss_logp.detach()
|
||||
loss_dict["loss_logdet"] = loss_logdet.detach()
|
||||
loss_dict["loss_all"] = loss.detach()
|
||||
|
||||
return loss, loss_dict
|
||||
|
||||
|
||||
class SpeechEncoderNet(nn.Module):
|
||||
"""
|
||||
This is a 2D Conv encoder network for speech data with windows
|
||||
"""
|
||||
def __init__(self, opt, nc_speech, nc_output):
|
||||
super(SpeechEncoderNet, self).__init__()
|
||||
|
||||
self.opt = opt
|
||||
# encoder
|
||||
self.encoder = nn.Sequential( # (nbatch, nchannel=1024, H=16, W=1)
|
||||
nn.BatchNorm2d(nc_speech),
|
||||
|
||||
# block 1
|
||||
nn.Conv2d(nc_speech, 512, kernel_size=(3,1), stride=(2,1), padding=(1,0), bias=True), # 32 x 8 x 1
|
||||
nn.LeakyReLU(0.02, True),
|
||||
nn.Conv2d(512, 512, kernel_size=(3,1), stride=(1,1), padding=(1,0), bias=True), # 32 x 8 x 1
|
||||
nn.LeakyReLU(0.02, True),
|
||||
|
||||
nn.Conv2d(512, 512, kernel_size=(3,1), stride=(2,1), padding=(1,0), bias=True), # 32 x 4 x 1
|
||||
nn.LeakyReLU(0.02, True),
|
||||
nn.Conv2d(512, 512, kernel_size=(3,1), stride=(1,1), padding=(1,0), bias=True), # 32 x 8 x 1
|
||||
nn.LeakyReLU(0.02, True),
|
||||
|
||||
|
||||
nn.Conv2d(512, 256, kernel_size=(3,1), stride=(2,1), padding=(1,0), bias=True), # 64 x 2 x 1
|
||||
nn.LeakyReLU(0.02, True),
|
||||
nn.Conv2d(256, 256, kernel_size=(3,1), stride=(1,1), padding=(1,0), bias=True), # 32 x 8 x 1
|
||||
nn.LeakyReLU(0.02, True),
|
||||
|
||||
|
||||
nn.Conv2d(256, 256, kernel_size=(3,1), stride=(2,1), padding=(1,0), bias=True), # 64 x 1 x 1
|
||||
nn.LeakyReLU(0.02, True),
|
||||
nn.Conv2d(256, 256, kernel_size=(3,1), stride=(1,1), padding=(1,0), bias=True), # 32 x 8 x 1
|
||||
nn.LeakyReLU(0.02, True),
|
||||
|
||||
nn.Conv2d(256, 128, kernel_size=(3,1), stride=(2,1), padding=(1,0), bias=True), # 64 x 1 x 1
|
||||
nn.LeakyReLU(0.02, True),
|
||||
|
||||
nn.Flatten(), # 64,
|
||||
|
||||
nn.Linear(in_features=128, out_features=2048), # 128,
|
||||
nn.Tanh(),
|
||||
|
||||
nn.Linear(in_features=2048, out_features=nc_output) # 50,
|
||||
)
|
||||
|
||||
def forward(self, x):
|
||||
""" forward function
|
||||
Args:
|
||||
x: [nbatch x nsteps x nwind x dim_condit]
|
||||
return:
|
||||
pred: [nbatch x nc_output x nsteps]
|
||||
"""
|
||||
|
||||
(nbatch, nsteps, nwind, nfeat) = x.shape # (B, nsetps, 16, nc_speech)
|
||||
debug(self.opt, f"[SpeechEncoderNet] input x shape = {x.shape}", verbose=False)
|
||||
|
||||
# preprocessing data
|
||||
x = x.reshape(nbatch * nsteps, 1, nwind, nfeat) # (B * nsteps, 1, 16, nc_speech)
|
||||
x = torch.transpose(x, 1, 3) # (B * nsteps, nc_speech, 16, 1)
|
||||
debug(self.opt, f"[SpeechEncoderNet] transpose x shape = {x.shape}", verbose=False)
|
||||
|
||||
|
||||
feat = self.encoder(x) # (B * nsteps, nc_output)
|
||||
debug(self.opt, f"[SpeechEncoderNet] encoder shape = {feat.shape}", verbose=False)
|
||||
|
||||
feat = feat.reshape(nbatch, nsteps, -1) # (B, nsteps, nc_output)
|
||||
feat = torch.transpose(feat, 1, 2) # (B, nc_output, nsteps)
|
||||
debug(self.opt, f"[SpeechEncoderNet] reshape shape = {feat.shape}", verbose=False)
|
||||
|
||||
return feat
|
||||
|
||||
|
||||
class FusionNet(nn.Module):
|
||||
"""
|
||||
This is the WaveNet like layer for the affine coupling. The primary difference
|
||||
from WaveNet is the convolutions need not be causal. There is also no dilation
|
||||
size reset. The dilation only doubles on each layer
|
||||
"""
|
||||
|
||||
def __init__(self, opt, nc_motion, nc_condit, nc_output):
|
||||
super(FusionNet, self).__init__()
|
||||
|
||||
self.opt = opt
|
||||
|
||||
self.n_layers = opt.MODEL.n_layer_wave # 4
|
||||
self.nc_hidden = opt.MODEL.dim_hidden # 256
|
||||
|
||||
kernel_size = opt.MODEL.kernel_size # 3
|
||||
assert(kernel_size % 2 == 1)
|
||||
assert(self.nc_hidden % 2 == 0)
|
||||
|
||||
|
||||
layer_head = nn.Conv1d(nc_motion, self.nc_hidden, kernel_size=1)
|
||||
layer_head = nn.utils.weight_norm(layer_head, name='weight')
|
||||
self.layer_head = layer_head
|
||||
|
||||
# Initializing last layer to 0 makes the affine coupling layers
|
||||
# do nothing at first. This helps with training stability
|
||||
layer_tail = nn.Conv1d(self.nc_hidden, nc_output, kernel_size=1)
|
||||
layer_tail.weight.data.zero_()
|
||||
layer_tail.bias.data.zero_()
|
||||
self.layer_tail = layer_tail
|
||||
|
||||
# for
|
||||
layer_cond = nn.Conv1d(nc_condit, 2*self.nc_hidden*self.n_layers, 1)
|
||||
self.layer_cond = nn.utils.weight_norm(layer_cond, name='weight')
|
||||
self.layer_cond = layer_cond
|
||||
|
||||
self.in_layers = nn.ModuleList()
|
||||
self.res_skip_layers = nn.ModuleList()
|
||||
|
||||
for i in range(self.n_layers):
|
||||
dilation = 2 ** i # 1, 2, 4, 8
|
||||
padding = (kernel_size * dilation - dilation) // 2 # 1, 2, 4, 8
|
||||
in_layer = nn.Conv1d(self.nc_hidden, 2*self.nc_hidden, kernel_size, dilation=dilation, padding=padding)
|
||||
in_layer = nn.utils.weight_norm(in_layer, name='weight')
|
||||
self.in_layers.append(in_layer)
|
||||
|
||||
# last one is not necessary
|
||||
nc_skip = 2 * self.nc_hidden if (i < self.n_layers - 1) else self.nc_hidden
|
||||
layer_skip = nn.Conv1d(self.nc_hidden, nc_skip, kernel_size=1)
|
||||
layer_skip = nn.utils.weight_norm(layer_skip, name='weight')
|
||||
self.res_skip_layers.append(layer_skip)
|
||||
|
||||
|
||||
def forward(self, x, c):
|
||||
""" forward function
|
||||
x shape = (B x nfeat1 x nsteps1) B x nc_motion_half x nstep
|
||||
c shape = (B x nfeat2 x nsteps2) B x nc_condit*nc_motion x nstep
|
||||
"""
|
||||
|
||||
feat_x = self.layer_head(x) # B x nc_hidden x nstep
|
||||
feat_c = self.layer_cond(c) # B x 4*nc_hidden x nstep
|
||||
feat_o = torch.zeros_like(feat_x) # B x nc_hidden x nstep
|
||||
debug(self.opt, f"\t[FusionNet] feat_x={feat_x.shape}, feat_c={feat_c.shape}, feat_o={feat_o.shape}")
|
||||
|
||||
nc_hidden_tensor = torch.IntTensor([self.nc_hidden])
|
||||
|
||||
for i in range(self.n_layers):
|
||||
c_offset = i * 2 * self.nc_hidden
|
||||
debug(self.opt, f"\t[FusionNet] layers={i} c_offset={c_offset}")
|
||||
|
||||
|
||||
ifeat_x = self.in_layers[i](feat_x) # B x 2*nc_hidden x nstep
|
||||
ifeat_c = feat_c[:, c_offset:c_offset+2*self.nc_hidden, :] # B x 2*nc_hidden x nstep
|
||||
debug(self.opt, f"\t[FusionNet] \tifeat_x={ifeat_x.shape} ifeat_c={ifeat_c.shape}")
|
||||
|
||||
ifeat_m = fused_add_tanh_sigmoid_multiply(ifeat_x, ifeat_c, nc_hidden_tensor) # B x nc_hidden x nstep
|
||||
debug(self.opt, f"\t[FusionNet] \tifeat_m={ifeat_m.shape}")
|
||||
|
||||
ifeat_m = self.res_skip_layers[i](ifeat_m) # B x 2*nc_hidden x nstep if not last layer else B x nc_hidden x 25
|
||||
debug(self.opt, f"\t[FusionNet] \t res skip ifeat_m={ifeat_m.shape}")
|
||||
|
||||
if i < self.n_layers - 1:
|
||||
feat_x = feat_x + ifeat_m[:, :self.nc_hidden, :] # B x nc_hidden x nstep
|
||||
feat_o = feat_o + ifeat_m[:, self.nc_hidden:, :] # B x nc_hidden x nstep
|
||||
else:
|
||||
feat_o = feat_o + ifeat_m # B x nc_hidden x nstep
|
||||
|
||||
feat_o = self.layer_tail(feat_o) # B x nc_motion_half x nstep
|
||||
debug(self.opt, f"\t[FusionNet] tail feat_o={feat_o.shape}")
|
||||
|
||||
return feat_o
|
||||
|
||||
@@ -0,0 +1,375 @@
|
||||
import torch
|
||||
import torch.nn as nn
|
||||
import torch.nn.functional as F
|
||||
import numpy as np
|
||||
|
||||
from common.debug import debug
|
||||
from src.nn.layers import ActNorm1d, Invertible1x1Conv1d as Invertible1x1Conv
|
||||
|
||||
# @torch.jit.script
|
||||
def fused_add_tanh_sigmoid_multiply(input_a, input_b, n_channels):
|
||||
n_channels_int = n_channels[0]
|
||||
in_act = input_a + input_b
|
||||
t_act = torch.tanh(in_act[:, :n_channels_int, :])
|
||||
s_act = torch.sigmoid(in_act[:, n_channels_int:, :])
|
||||
acts = t_act * s_act
|
||||
return acts
|
||||
|
||||
|
||||
class MotionWaveFlow(nn.Module):
|
||||
|
||||
def __init__(self, opt):
|
||||
super(MotionWaveFlow, self).__init__()
|
||||
|
||||
self.opt = opt
|
||||
self.nc_motion = opt.MODEL.dim_motion # 5023
|
||||
self.nc_condit = opt.MODEL.dim_speech # 1024
|
||||
self.nc_hidden = opt.MODEL.dim_hidden # 256
|
||||
|
||||
|
||||
self.n_flows = opt.MODEL.n_flowstep # 12
|
||||
self.n_early_every = opt.MODEL.n_early_every # 4 --> 3
|
||||
|
||||
self.fix_dims = np.array(opt.MODEL.fix_dims)
|
||||
self.lambda_std = np.array(opt.MODEL.lambda_std) # [1, 0.75, 0.5, 0.25]
|
||||
self.lambda_std = torch.from_numpy(self.lambda_std).float().cuda(opt.GPUS[0])
|
||||
|
||||
self.Conv1x1Invs = nn.ModuleList()
|
||||
self.FusionNets = nn.ModuleList()
|
||||
self.Actnorms = nn.ModuleList()
|
||||
nc_motion_rest = self.nc_motion # 8 --> 136
|
||||
|
||||
for k in range(self.n_flows):
|
||||
if k % self.n_early_every == 0 and k > 0: # k = 3, 6, 9
|
||||
nc_motion_rest = nc_motion_rest - nc_motion_rest // 2 # = 84, 42, 21
|
||||
|
||||
self.Actnorms.append(ActNorm1d(num_channels=nc_motion_rest))
|
||||
self.Conv1x1Invs.append(Invertible1x1Conv(nc_motion_rest))
|
||||
self.FusionNets.append(FusionNet(self.opt, nc_motion=nc_motion_rest - nc_motion_rest//2,
|
||||
nc_condit=self.nc_condit,
|
||||
nc_output=2*(nc_motion_rest//2)))
|
||||
|
||||
debug(self.opt, f"[Model] k={k} nc_motion_rest={nc_motion_rest}")
|
||||
|
||||
self.nc_motion_rest = nc_motion_rest # Useful during inference, 72 / 8
|
||||
|
||||
|
||||
def set_actnorm_init(self, inited=True):
|
||||
for name, m in self.named_modules():
|
||||
if (m.__class__.__name__.find("ActNorm") >= 0):
|
||||
m.inited = inited
|
||||
debug(self.opt, f"[Model] set module {m.__class__.__name__} inited = {inited}")
|
||||
|
||||
|
||||
def forward(self, x, c):
|
||||
"""For training, x --> z
|
||||
x shape = (B, nc_motion, nsteps),
|
||||
c shape = (B, nsteps, nwind, nc_speech),
|
||||
return:
|
||||
z shape = (B, dim_motin, nsteps)
|
||||
"""
|
||||
|
||||
debug(self.opt, f"\n[Forward] start x shape={x.shape}, c={c.shape}", verbose=False)
|
||||
|
||||
predt_z = []
|
||||
# feat_c = self.speechEncoder(c) # (B, nc_hidden, nsteps)
|
||||
logdet = torch.zeros(c.size(0), dtype=c.dtype, device=c.device)
|
||||
debug(self.opt, f"\n[Forward] c shape={c.shape}, logdet={logdet.shape}", verbose=False)
|
||||
|
||||
for k in range(self.n_flows):
|
||||
|
||||
x, logdet = self.Actnorms[k](x, logdet)
|
||||
debug(self.opt, f"[Forward] k={k}, actnorm x shape = {x.shape} logdet={logdet.shape}", verbose=False)
|
||||
|
||||
x, logdet = self.Conv1x1Invs[k](x, logdet)
|
||||
debug(self.opt, f"[Forward] k={k}, Conv1x1Invs x={x.shape}, logdet={logdet.shape}")
|
||||
|
||||
# coupling layers
|
||||
nc_motion_half = x.size(1) - x.size(1) // 2
|
||||
x1, x2 = x[:, :nc_motion_half, :], x[:, nc_motion_half:, :]
|
||||
debug(self.opt, f"[Forward] k={k}, coupling split x1={x1.shape}, x2={x2.shape}")
|
||||
|
||||
feat = self.FusionNets[k](x1, c) # (B, nc_motion_half, nc_output)
|
||||
shift, scale = feat[:, 0::2, :], feat[:, 1::2, :]
|
||||
scale = torch.sigmoid(scale + 2.) + 1e-6 # to make scale > 1, so that log(s) > 0
|
||||
x2 = (x2 + shift) * scale
|
||||
logdet = torch.sum(torch.log(scale), dim=[1, 2]) + logdet
|
||||
|
||||
# multi-scale split
|
||||
if k % self.n_early_every == (self.n_early_every -1) and k > 0 and k < self.n_flows -1:
|
||||
predt_z.append(x2)
|
||||
x = x1
|
||||
debug(self.opt, f"[Forward] k={k}, coupling muli-scale x={x.shape}, x2={x2.shape}, logdet={logdet.shape}", verbose=False)
|
||||
else:
|
||||
x = torch.cat([x1, x2], dim=1)
|
||||
debug(self.opt, f"[Forward] k={k}, coupling concat x={x.shape}, logdet={logdet.shape}", verbose=False)
|
||||
|
||||
|
||||
# append the last x
|
||||
predt_z.append(x)
|
||||
predt_z = list(reversed(predt_z))
|
||||
# predt_z = torch.cat(predt_z, dim=1)
|
||||
|
||||
return predt_z, logdet
|
||||
|
||||
def inverse(self, c):
|
||||
"""For inference, z --> x
|
||||
# c shape = (B, nc_condit, nsteps_c)
|
||||
c shape = (B, nsteps, nwind, nc_speech),
|
||||
return:
|
||||
x shape = (B, nc_motion, nsteps_x)
|
||||
"""
|
||||
|
||||
B, nsteps = c.size(0), c.size(1)
|
||||
|
||||
# add z
|
||||
mu = torch.zeros(B, self.nc_motion_rest, nsteps, device=c.device)
|
||||
std = torch.ones(B, self.nc_motion_rest, nsteps, device=c.device) * self.lambda_std[0]
|
||||
x = torch.normal(mean=mu, std=std)
|
||||
# x = torch.zeros(B, self.nc_motion_rest, nsteps, device=c.device).normal_() # (B, 40, 60)
|
||||
|
||||
# feat_c = self.speechEncoder(c) # (B, nc_hidden, nsteps)
|
||||
logdet = torch.zeros(B, dtype=c.dtype, device=c.device)
|
||||
debug(self.opt, f"\n[Inverse] c shape={c.shape}, logdet={logdet.shape}", verbose=False)
|
||||
|
||||
istd = 1
|
||||
for k in reversed(range(self.n_flows)):
|
||||
# coupling layer
|
||||
nc_motion_half = x.size(1) - x.size(1) // 2
|
||||
x1, x2 = x[:, :nc_motion_half, :], x[:, nc_motion_half:, :]
|
||||
debug(self.opt, f"[Inverse] k={k}, x1={x1.shape}, x2={x2.shape}", verbose=False)
|
||||
|
||||
feat = self.FusionNets[k](x1, c) # (B, 1, nc_output)
|
||||
shift, scale = feat[:, 0::2, :], feat[:, 1::2, :]
|
||||
scale = torch.sigmoid(scale + 2.) + 1e-6 # to make scale > 1, so that log(s) > 0
|
||||
debug(self.opt, f"[Inverse] k={k}, coupling feat shape={feat.shape}, shift={shift.shape}, scale={scale.shape}", verbose=False)
|
||||
|
||||
x2 = x2 / scale - shift
|
||||
x = torch.cat([x1, x2], dim=1)
|
||||
logdet = - torch.sum(torch.log(scale), dim=[1,2]) + logdet
|
||||
debug(self.opt, f"[Inverse] k={k}, coupling concat x={x.shape}, logdet={logdet.shape}", verbose=False)
|
||||
|
||||
# 1 x 1 conv inv
|
||||
x, logdet = self.Conv1x1Invs[k].inverse(x, logdet)
|
||||
debug(self.opt, f"[Inverse] k={k}, Conv1x1Invs x={x.shape}")
|
||||
|
||||
# actnorm
|
||||
x, logdet = self.Actnorms[k].inverse(x, logdet)
|
||||
debug(self.opt, f"[Inverse] k={k}, actnorm x shape = {x.shape}", verbose=False)
|
||||
|
||||
# add noise
|
||||
if k % self.n_early_every == 0 and k > 0:
|
||||
# z = torch.zeros(B, x.size(1), nsteps, device=c.device).normal_() # (B, 40, 60)
|
||||
num_dims = x.size(1) + self.fix_dims[istd]
|
||||
|
||||
mu = torch.zeros(B, num_dims, nsteps, device=c.device)
|
||||
std = torch.ones(B, num_dims, nsteps, device=c.device) * self.lambda_std[istd]
|
||||
z = torch.normal(mean=mu, std=std)
|
||||
istd += 1
|
||||
|
||||
x = torch.cat((x, z), dim=1) # (B, 8/40/72/104/136, 25)
|
||||
debug(self.opt, f"[Inverse] k={k}, ADD noise + {x.size(1)} channel, x shape = {x.shape}", verbose=False)
|
||||
|
||||
return x.detach(), logdet # (B, nc_motion, nsteps)
|
||||
|
||||
|
||||
def loss_function_(self, z, logdet, sigma=1.0):
|
||||
"""z = list (B, nc_motion, N)
|
||||
logdet = list (B, )
|
||||
"""
|
||||
|
||||
loss = 0
|
||||
loss_dict = {}
|
||||
nsteps = z[0].size(2)
|
||||
debug(self.opt, f"[Loss] z shape={z[0].shape}, logdet={logdet.shape}")
|
||||
assert len(z) == len(self.lambda_std)
|
||||
|
||||
logp = 0
|
||||
for std, zn in zip(self.lambda_std, z):
|
||||
ilogp = -torch.log(std) - 0.5*zn*zn / (std * std) - 0.5 * torch.log(2 * torch.tensor(np.pi)) # B x nc x nsteps
|
||||
logp += torch.sum(ilogp, dim=[1,2]) / (2*sigma * sigma) # (B, )
|
||||
|
||||
# logp = - 0.5*z*z - 0.5 * torch.log(2 * torch.tensor(np.pi)) # (B, N, nc_motion)
|
||||
# logp = torch.sum(logp, dim=[1,2]) / (2*sigma * sigma) # (B, )
|
||||
|
||||
loss_logp = - torch.mean(logp) / (np.log(2.0) * nsteps * len(z))
|
||||
loss_logdet = - torch.mean(logdet) / (np.log(2.0) * nsteps)
|
||||
loss = loss_logp * self.opt.LOSS.lambda_logp + loss_logdet * self.opt.LOSS.lambda_logdet
|
||||
|
||||
loss_dict["loss_logp"] = loss_logp.detach()
|
||||
loss_dict["loss_logdet"] = loss_logdet.detach()
|
||||
loss_dict["loss_all"] = loss.detach()
|
||||
|
||||
return loss, loss_dict
|
||||
|
||||
|
||||
class SpeechEncoderNet(nn.Module):
|
||||
"""
|
||||
This is a 2D Conv encoder network for speech data with windows
|
||||
"""
|
||||
def __init__(self, opt, nc_speech, nc_output):
|
||||
super(SpeechEncoderNet, self).__init__()
|
||||
|
||||
self.opt = opt
|
||||
# encoder
|
||||
self.encoder = nn.Sequential( # (nbatch, nchannel=1024, H=16, W=1)
|
||||
nn.BatchNorm2d(nc_speech),
|
||||
|
||||
# block 1
|
||||
nn.Conv2d(nc_speech, 512, kernel_size=(3,1), stride=(2,1), padding=(1,0), bias=True), # 32 x 8 x 1
|
||||
nn.LeakyReLU(0.02, True),
|
||||
nn.Conv2d(512, 512, kernel_size=(3,1), stride=(1,1), padding=(1,0), bias=True), # 32 x 8 x 1
|
||||
nn.LeakyReLU(0.02, True),
|
||||
|
||||
nn.Conv2d(512, 512, kernel_size=(3,1), stride=(2,1), padding=(1,0), bias=True), # 32 x 4 x 1
|
||||
nn.LeakyReLU(0.02, True),
|
||||
nn.Conv2d(512, 512, kernel_size=(3,1), stride=(1,1), padding=(1,0), bias=True), # 32 x 8 x 1
|
||||
nn.LeakyReLU(0.02, True),
|
||||
|
||||
|
||||
nn.Conv2d(512, 256, kernel_size=(3,1), stride=(2,1), padding=(1,0), bias=True), # 64 x 2 x 1
|
||||
nn.LeakyReLU(0.02, True),
|
||||
nn.Conv2d(256, 256, kernel_size=(3,1), stride=(1,1), padding=(1,0), bias=True), # 32 x 8 x 1
|
||||
nn.LeakyReLU(0.02, True),
|
||||
|
||||
|
||||
nn.Conv2d(256, 256, kernel_size=(3,1), stride=(2,1), padding=(1,0), bias=True), # 64 x 1 x 1
|
||||
nn.LeakyReLU(0.02, True),
|
||||
nn.Conv2d(256, 256, kernel_size=(3,1), stride=(1,1), padding=(1,0), bias=True), # 32 x 8 x 1
|
||||
nn.LeakyReLU(0.02, True),
|
||||
|
||||
nn.Conv2d(256, 128, kernel_size=(3,1), stride=(2,1), padding=(1,0), bias=True), # 64 x 1 x 1
|
||||
nn.LeakyReLU(0.02, True),
|
||||
|
||||
nn.Flatten(), # 64,
|
||||
|
||||
nn.Linear(in_features=128, out_features=50), # 128,
|
||||
nn.Tanh(),
|
||||
|
||||
nn.Linear(in_features=50, out_features=nc_output) # 50,
|
||||
)
|
||||
|
||||
def forward(self, x):
|
||||
""" forward function
|
||||
Args:
|
||||
x: [nbatch x nsteps x nwind x dim_condit]
|
||||
return:
|
||||
pred: [nbatch x nc_output x nsteps]
|
||||
"""
|
||||
|
||||
(nbatch, nsteps, nwind, nfeat) = x.shape # (B, nsetps, 16, nc_speech)
|
||||
debug(self.opt, f"[SpeechEncoderNet] input x shape = {x.shape}", verbose=False)
|
||||
|
||||
# preprocessing data
|
||||
x = x.reshape(nbatch * nsteps, 1, nwind, nfeat) # (B * nsteps, 1, 16, nc_speech)
|
||||
x = torch.transpose(x, 1, 3) # (B * nsteps, nc_speech, 16, 1)
|
||||
debug(self.opt, f"[SpeechEncoderNet] transpose x shape = {x.shape}", verbose=False)
|
||||
|
||||
|
||||
feat = self.encoder(x) # (B * nsteps, nc_output)
|
||||
debug(self.opt, f"[SpeechEncoderNet] encoder shape = {feat.shape}", verbose=False)
|
||||
|
||||
feat = feat.reshape(nbatch, nsteps, -1) # (B, nsteps, nc_output)
|
||||
feat = torch.transpose(feat, 1, 2) # (B, nc_output, nsteps)
|
||||
debug(self.opt, f"[SpeechEncoderNet] reshape shape = {feat.shape}", verbose=False)
|
||||
|
||||
return feat
|
||||
|
||||
|
||||
class FusionNet(nn.Module):
|
||||
"""
|
||||
This is the WaveNet like layer for the affine coupling. The primary difference
|
||||
from WaveNet is the convolutions need not be causal. There is also no dilation
|
||||
size reset. The dilation only doubles on each layer
|
||||
"""
|
||||
|
||||
def __init__(self, opt, nc_motion, nc_condit, nc_output):
|
||||
super(FusionNet, self).__init__()
|
||||
|
||||
self.opt = opt
|
||||
|
||||
self.n_layers = opt.MODEL.n_layer_wave # 4
|
||||
self.nc_hidden = opt.MODEL.dim_hidden # 256
|
||||
|
||||
kernel_size = opt.MODEL.kernel_size # 3
|
||||
assert(kernel_size % 2 == 1)
|
||||
assert(self.nc_hidden % 2 == 0)
|
||||
|
||||
|
||||
# audio encoder
|
||||
self.layer_cond = SpeechEncoderNet(opt, nc_condit, 2* self.nc_hidden * self.n_layers)
|
||||
|
||||
# # for
|
||||
# layer_cond = nn.Conv1d(self.nc_hidden, 2*self.nc_hidden*self.n_layers, 1)
|
||||
# self.layer_cond = nn.utils.weight_norm(layer_cond, name='weight')
|
||||
# self.layer_cond = layer_cond
|
||||
|
||||
|
||||
layer_head = nn.Conv1d(nc_motion, self.nc_hidden, kernel_size=1)
|
||||
layer_head = nn.utils.weight_norm(layer_head, name='weight')
|
||||
self.layer_head = layer_head
|
||||
|
||||
# Initializing last layer to 0 makes the affine coupling layers
|
||||
# do nothing at first. This helps with training stability
|
||||
layer_tail = nn.Conv1d(self.nc_hidden, nc_output, kernel_size=1)
|
||||
layer_tail.weight.data.zero_()
|
||||
layer_tail.bias.data.zero_()
|
||||
self.layer_tail = layer_tail
|
||||
|
||||
|
||||
self.in_layers = nn.ModuleList()
|
||||
self.res_skip_layers = nn.ModuleList()
|
||||
|
||||
for i in range(self.n_layers):
|
||||
dilation = 2 ** i # 1, 2, 4, 8
|
||||
padding = (kernel_size * dilation - dilation) // 2 # 1, 2, 4, 8
|
||||
in_layer = nn.Conv1d(self.nc_hidden, 2*self.nc_hidden, kernel_size, dilation=dilation, padding=padding)
|
||||
in_layer = nn.utils.weight_norm(in_layer, name='weight')
|
||||
self.in_layers.append(in_layer)
|
||||
|
||||
# last one is not necessary
|
||||
nc_skip = 2 * self.nc_hidden if (i < self.n_layers - 1) else self.nc_hidden
|
||||
layer_skip = nn.Conv1d(self.nc_hidden, nc_skip, kernel_size=1)
|
||||
layer_skip = nn.utils.weight_norm(layer_skip, name='weight')
|
||||
self.res_skip_layers.append(layer_skip)
|
||||
|
||||
|
||||
def forward(self, x, c):
|
||||
""" forward function
|
||||
x shape = (B x nfeat1 x nsteps1) B x nc_motion_half x nstep
|
||||
c shape = (B x nfeat2 x nsteps2) B x nc_condit*nc_motion x nstep
|
||||
"""
|
||||
|
||||
feat_x = self.layer_head(x) # B x nc_hidden x nstep
|
||||
feat_c = self.layer_cond(c) # B x 4*nc_hidden x nstep
|
||||
feat_o = torch.zeros_like(feat_x) # B x nc_hidden x nstep
|
||||
debug(self.opt, f"\t[FusionNet] feat_x={feat_x.shape}, feat_c={feat_c.shape}, feat_o={feat_o.shape}")
|
||||
|
||||
nc_hidden_tensor = torch.IntTensor([self.nc_hidden])
|
||||
|
||||
for i in range(self.n_layers):
|
||||
c_offset = i * 2 * self.nc_hidden
|
||||
debug(self.opt, f"\t[FusionNet] layers={i} c_offset={c_offset}")
|
||||
|
||||
|
||||
ifeat_x = self.in_layers[i](feat_x) # B x 2*nc_hidden x nstep
|
||||
ifeat_c = feat_c[:, c_offset:c_offset+2*self.nc_hidden, :] # B x 2*nc_hidden x nstep
|
||||
debug(self.opt, f"\t[FusionNet] \tifeat_x={ifeat_x.shape} ifeat_c={ifeat_c.shape}")
|
||||
|
||||
ifeat_m = fused_add_tanh_sigmoid_multiply(ifeat_x, ifeat_c, nc_hidden_tensor) # B x nc_hidden x nstep
|
||||
debug(self.opt, f"\t[FusionNet] \tifeat_m={ifeat_m.shape}")
|
||||
|
||||
ifeat_m = self.res_skip_layers[i](ifeat_m) # B x 2*nc_hidden x nstep if not last layer else B x nc_hidden x 25
|
||||
debug(self.opt, f"\t[FusionNet] \t res skip ifeat_m={ifeat_m.shape}")
|
||||
|
||||
if i < self.n_layers - 1:
|
||||
feat_x = feat_x + ifeat_m[:, :self.nc_hidden, :] # B x nc_hidden x nstep
|
||||
feat_o = feat_o + ifeat_m[:, self.nc_hidden:, :] # B x nc_hidden x nstep
|
||||
else:
|
||||
feat_o = feat_o + ifeat_m # B x nc_hidden x nstep
|
||||
|
||||
feat_o = self.layer_tail(feat_o) # B x nc_motion_half x nstep
|
||||
debug(self.opt, f"\t[FusionNet] tail feat_o={feat_o.shape}")
|
||||
|
||||
return feat_o
|
||||
|
||||
@@ -0,0 +1,339 @@
|
||||
import torch
|
||||
import torch.nn as nn
|
||||
import torch.nn.functional as F
|
||||
import numpy as np
|
||||
|
||||
from common.debug import debug
|
||||
from src.nn.layers import ActNorm1d, Invertible1x1Conv1d as Invertible1x1Conv
|
||||
|
||||
# @torch.jit.script
|
||||
def fused_add_tanh_sigmoid_multiply(input_a, input_b, n_channels):
|
||||
n_channels_int = n_channels[0]
|
||||
in_act = input_a + input_b
|
||||
t_act = torch.tanh(in_act[:, :n_channels_int, :])
|
||||
s_act = torch.sigmoid(in_act[:, n_channels_int:, :])
|
||||
acts = t_act * s_act
|
||||
return acts
|
||||
|
||||
|
||||
class MotionWaveFlow(nn.Module):
|
||||
|
||||
def __init__(self, opt):
|
||||
super(MotionWaveFlow, self).__init__()
|
||||
|
||||
self.opt = opt
|
||||
self.nc_motion = opt.MODEL.dim_motion # 5023
|
||||
self.nc_condit = opt.MODEL.dim_speech # 1024
|
||||
self.nc_hidden = opt.MODEL.dim_hidden # 256
|
||||
|
||||
|
||||
self.n_flows = opt.MODEL.n_flowstep # 12
|
||||
self.n_early_every = opt.MODEL.n_early_every # 4 --> 3
|
||||
|
||||
self.fix_dims = np.array(opt.MODEL.fix_dims)
|
||||
self.lambda_std = np.array(opt.MODEL.lambda_std) # [1, 0.75, 0.5, 0.25]
|
||||
self.lambda_std = torch.from_numpy(self.lambda_std).float().cuda(opt.GPUS[0])
|
||||
|
||||
self.Conv1x1Invs = nn.ModuleList()
|
||||
self.FusionNets = nn.ModuleList()
|
||||
self.Actnorms = nn.ModuleList()
|
||||
nc_motion_rest = self.nc_motion # 8 --> 136
|
||||
|
||||
for k in range(self.n_flows):
|
||||
if k % self.n_early_every == 0 and k > 0: # k = 3, 6, 9
|
||||
nc_motion_rest = nc_motion_rest - nc_motion_rest // 2 # = 84, 42, 21
|
||||
|
||||
self.Actnorms.append(ActNorm1d(num_channels=nc_motion_rest))
|
||||
self.Conv1x1Invs.append(Invertible1x1Conv(nc_motion_rest))
|
||||
self.FusionNets.append(FusionNet(self.opt, nc_motion=nc_motion_rest - nc_motion_rest//2,
|
||||
nc_condit=self.nc_condit,
|
||||
nc_output=2*(nc_motion_rest//2)))
|
||||
|
||||
debug(self.opt, f"[Model] k={k} nc_motion_rest={nc_motion_rest}")
|
||||
|
||||
self.nc_motion_rest = nc_motion_rest # Useful during inference, 72 / 8
|
||||
|
||||
|
||||
def set_actnorm_init(self, inited=True):
|
||||
for name, m in self.named_modules():
|
||||
if (m.__class__.__name__.find("ActNorm") >= 0):
|
||||
m.inited = inited
|
||||
debug(self.opt, f"[Model] set module {m.__class__.__name__} inited = {inited}")
|
||||
|
||||
|
||||
def forward(self, x, c):
|
||||
"""For training, x --> z
|
||||
x shape = (B, nc_motion, nsteps),
|
||||
c shape = (B, nsteps, nwind, nc_speech),
|
||||
return:
|
||||
z shape = (B, dim_motin, nsteps)
|
||||
"""
|
||||
|
||||
debug(self.opt, f"\n[Forward] start x shape={x.shape}, c={c.shape}", verbose=False)
|
||||
|
||||
predt_z = []
|
||||
# feat_c = self.speechEncoder(c) # (B, nc_hidden, nsteps)
|
||||
logdet = torch.zeros(c.size(0), dtype=c.dtype, device=c.device)
|
||||
debug(self.opt, f"\n[Forward] c shape={c.shape}, logdet={logdet.shape}", verbose=False)
|
||||
|
||||
for k in range(self.n_flows):
|
||||
|
||||
x, logdet = self.Actnorms[k](x, logdet)
|
||||
debug(self.opt, f"[Forward] k={k}, actnorm x shape = {x.shape} logdet={logdet.shape}", verbose=False)
|
||||
|
||||
x, logdet = self.Conv1x1Invs[k](x, logdet)
|
||||
debug(self.opt, f"[Forward] k={k}, Conv1x1Invs x={x.shape}, logdet={logdet.shape}")
|
||||
|
||||
# coupling layers
|
||||
nc_motion_half = x.size(1) - x.size(1) // 2
|
||||
x1, x2 = x[:, :nc_motion_half, :], x[:, nc_motion_half:, :]
|
||||
debug(self.opt, f"[Forward] k={k}, coupling split x1={x1.shape}, x2={x2.shape}")
|
||||
|
||||
feat = self.FusionNets[k](x1, c) # (B, nc_motion_half, nc_output)
|
||||
shift, scale = feat[:, 0::2, :], feat[:, 1::2, :]
|
||||
scale = torch.sigmoid(scale + 2.) + 1e-6 # to make scale > 1, so that log(s) > 0
|
||||
x2 = (x2 + shift) * scale
|
||||
logdet = torch.sum(torch.log(scale), dim=[1, 2]) + logdet
|
||||
|
||||
# multi-scale split
|
||||
if k % self.n_early_every == (self.n_early_every -1) and k > 0 and k < self.n_flows -1:
|
||||
predt_z.append(x2)
|
||||
x = x1
|
||||
debug(self.opt, f"[Forward] k={k}, coupling muli-scale x={x.shape}, x2={x2.shape}, logdet={logdet.shape}", verbose=False)
|
||||
else:
|
||||
x = torch.cat([x1, x2], dim=1)
|
||||
debug(self.opt, f"[Forward] k={k}, coupling concat x={x.shape}, logdet={logdet.shape}", verbose=False)
|
||||
|
||||
|
||||
# append the last x
|
||||
predt_z.append(x)
|
||||
predt_z = list(reversed(predt_z))
|
||||
# predt_z = torch.cat(predt_z, dim=1)
|
||||
|
||||
return predt_z, logdet
|
||||
|
||||
def inverse(self, c):
|
||||
"""For inference, z --> x
|
||||
# c shape = (B, nc_condit, nsteps_c)
|
||||
c shape = (B, nsteps, nwind, nc_speech),
|
||||
return:
|
||||
x shape = (B, nc_motion, nsteps_x)
|
||||
"""
|
||||
|
||||
B, nsteps = c.size(0), c.size(1)
|
||||
|
||||
# add z
|
||||
mu = torch.zeros(B, self.nc_motion_rest, nsteps, device=c.device)
|
||||
std = torch.ones(B, self.nc_motion_rest, nsteps, device=c.device) * self.lambda_std[0]
|
||||
x = torch.normal(mean=mu, std=std)
|
||||
# x = torch.zeros(B, self.nc_motion_rest, nsteps, device=c.device).normal_() # (B, 40, 60)
|
||||
|
||||
# feat_c = self.speechEncoder(c) # (B, nc_hidden, nsteps)
|
||||
logdet = torch.zeros(B, dtype=c.dtype, device=c.device)
|
||||
debug(self.opt, f"\n[Inverse] c shape={c.shape}, logdet={logdet.shape}", verbose=False)
|
||||
|
||||
istd = 1
|
||||
for k in reversed(range(self.n_flows)):
|
||||
# coupling layer
|
||||
nc_motion_half = x.size(1) - x.size(1) // 2
|
||||
x1, x2 = x[:, :nc_motion_half, :], x[:, nc_motion_half:, :]
|
||||
debug(self.opt, f"[Inverse] k={k}, x1={x1.shape}, x2={x2.shape}", verbose=False)
|
||||
|
||||
feat = self.FusionNets[k](x1, c) # (B, 1, nc_output)
|
||||
shift, scale = feat[:, 0::2, :], feat[:, 1::2, :]
|
||||
scale = torch.sigmoid(scale + 2.) + 1e-6 # to make scale > 1, so that log(s) > 0
|
||||
debug(self.opt, f"[Inverse] k={k}, coupling feat shape={feat.shape}, shift={shift.shape}, scale={scale.shape}", verbose=False)
|
||||
|
||||
x2 = x2 / scale - shift
|
||||
x = torch.cat([x1, x2], dim=1)
|
||||
logdet = - torch.sum(torch.log(scale), dim=[1,2]) + logdet
|
||||
debug(self.opt, f"[Inverse] k={k}, coupling concat x={x.shape}, logdet={logdet.shape}", verbose=False)
|
||||
|
||||
# 1 x 1 conv inv
|
||||
x, logdet = self.Conv1x1Invs[k].inverse(x, logdet)
|
||||
debug(self.opt, f"[Inverse] k={k}, Conv1x1Invs x={x.shape}")
|
||||
|
||||
# actnorm
|
||||
x, logdet = self.Actnorms[k].inverse(x, logdet)
|
||||
debug(self.opt, f"[Inverse] k={k}, actnorm x shape = {x.shape}", verbose=False)
|
||||
|
||||
# add noise
|
||||
if k % self.n_early_every == 0 and k > 0:
|
||||
# z = torch.zeros(B, x.size(1), nsteps, device=c.device).normal_() # (B, 40, 60)
|
||||
num_dims = x.size(1) + self.fix_dims[istd]
|
||||
|
||||
mu = torch.zeros(B, num_dims, nsteps, device=c.device)
|
||||
std = torch.ones(B, num_dims, nsteps, device=c.device) * self.lambda_std[istd]
|
||||
z = torch.normal(mean=mu, std=std)
|
||||
istd += 1
|
||||
|
||||
x = torch.cat((x, z), dim=1) # (B, 8/40/72/104/136, 25)
|
||||
debug(self.opt, f"[Inverse] k={k}, ADD noise + {x.size(1)} channel, x shape = {x.shape}", verbose=False)
|
||||
|
||||
return x.detach(), logdet # (B, nc_motion, nsteps)
|
||||
|
||||
|
||||
def loss_function_(self, z, logdet, sigma=1.0):
|
||||
"""z = list (B, nc_motion, N)
|
||||
logdet = list (B, )
|
||||
"""
|
||||
|
||||
loss = 0
|
||||
loss_dict = {}
|
||||
nsteps = z[0].size(2)
|
||||
debug(self.opt, f"[Loss] z shape={z[0].shape}, logdet={logdet.shape}")
|
||||
assert len(z) == len(self.lambda_std)
|
||||
|
||||
logp = 0
|
||||
for std, zn in zip(self.lambda_std, z):
|
||||
ilogp = -torch.log(std) - 0.5*zn*zn / (std * std) - 0.5 * torch.log(2 * torch.tensor(np.pi)) # B x nc x nsteps
|
||||
logp += torch.sum(ilogp, dim=[1,2]) / (2*sigma * sigma) # (B, )
|
||||
|
||||
# logp = - 0.5*z*z - 0.5 * torch.log(2 * torch.tensor(np.pi)) # (B, N, nc_motion)
|
||||
# logp = torch.sum(logp, dim=[1,2]) / (2*sigma * sigma) # (B, )
|
||||
|
||||
loss_logp = - torch.mean(logp) / (np.log(2.0) * nsteps * len(z))
|
||||
loss_logdet = - torch.mean(logdet) / (np.log(2.0) * nsteps)
|
||||
loss = loss_logp * self.opt.LOSS.lambda_logp + loss_logdet * self.opt.LOSS.lambda_logdet
|
||||
|
||||
loss_dict["loss_logp"] = loss_logp.detach()
|
||||
loss_dict["loss_logdet"] = loss_logdet.detach()
|
||||
loss_dict["loss_all"] = loss.detach()
|
||||
|
||||
return loss, loss_dict
|
||||
|
||||
|
||||
class SpeechEncoderNet(nn.Module):
|
||||
"""
|
||||
This is a 2D Conv encoder network for speech data with windows
|
||||
"""
|
||||
def __init__(self, opt, nc_speech, nc_output):
|
||||
super(SpeechEncoderNet, self).__init__()
|
||||
|
||||
self.opt = opt
|
||||
# encoder
|
||||
self.encoder = nn.Sequential( # (nbatch, nchannel=1024, H=16, W=1)
|
||||
nn.BatchNorm2d(nc_speech),
|
||||
|
||||
# block 1
|
||||
nn.Conv2d(nc_speech, 512, kernel_size=(3,1), stride=(2,1), padding=(1,0), bias=True), # 32 x 8 x 1
|
||||
nn.LeakyReLU(0.02, True),
|
||||
nn.Conv2d(512, 512, kernel_size=(3,1), stride=(1,1), padding=(1,0), bias=True), # 32 x 8 x 1
|
||||
nn.LeakyReLU(0.02, True),
|
||||
|
||||
nn.Conv2d(512, 512, kernel_size=(3,1), stride=(2,1), padding=(1,0), bias=True), # 32 x 4 x 1
|
||||
nn.LeakyReLU(0.02, True),
|
||||
nn.Conv2d(512, 512, kernel_size=(3,1), stride=(1,1), padding=(1,0), bias=True), # 32 x 8 x 1
|
||||
nn.LeakyReLU(0.02, True),
|
||||
|
||||
|
||||
nn.Conv2d(512, 256, kernel_size=(3,1), stride=(2,1), padding=(1,0), bias=True), # 64 x 2 x 1
|
||||
nn.LeakyReLU(0.02, True),
|
||||
nn.Conv2d(256, 256, kernel_size=(3,1), stride=(1,1), padding=(1,0), bias=True), # 32 x 8 x 1
|
||||
nn.LeakyReLU(0.02, True),
|
||||
|
||||
|
||||
nn.Conv2d(256, 256, kernel_size=(3,1), stride=(2,1), padding=(1,0), bias=True), # 64 x 1 x 1
|
||||
nn.LeakyReLU(0.02, True),
|
||||
nn.Conv2d(256, 256, kernel_size=(3,1), stride=(1,1), padding=(1,0), bias=True), # 32 x 8 x 1
|
||||
nn.LeakyReLU(0.02, True),
|
||||
|
||||
nn.Conv2d(256, 128, kernel_size=(3,1), stride=(2,1), padding=(1,0), bias=True), # 64 x 1 x 1
|
||||
nn.LeakyReLU(0.02, True),
|
||||
|
||||
nn.Flatten(), # 64,
|
||||
|
||||
nn.Linear(in_features=128, out_features=50), # 128,
|
||||
nn.Tanh(),
|
||||
|
||||
nn.Linear(in_features=50, out_features=nc_output) # 50,
|
||||
)
|
||||
|
||||
def forward(self, x):
|
||||
""" forward function
|
||||
Args:
|
||||
x: [nbatch x nsteps x nwind x dim_condit]
|
||||
return:
|
||||
pred: [nbatch x nc_output x nsteps]
|
||||
"""
|
||||
|
||||
(nbatch, nsteps, nwind, nfeat) = x.shape # (B, nsetps, 16, nc_speech)
|
||||
debug(self.opt, f"[SpeechEncoderNet] input x shape = {x.shape}", verbose=False)
|
||||
|
||||
# preprocessing data
|
||||
x = x.reshape(nbatch * nsteps, 1, nwind, nfeat) # (B * nsteps, 1, 16, nc_speech)
|
||||
x = torch.transpose(x, 1, 3) # (B * nsteps, nc_speech, 16, 1)
|
||||
debug(self.opt, f"[SpeechEncoderNet] transpose x shape = {x.shape}", verbose=False)
|
||||
|
||||
|
||||
feat = self.encoder(x) # (B * nsteps, nc_output)
|
||||
debug(self.opt, f"[SpeechEncoderNet] encoder shape = {feat.shape}", verbose=False)
|
||||
|
||||
feat = feat.reshape(nbatch, nsteps, -1) # (B, nsteps, nc_output)
|
||||
feat = torch.transpose(feat, 1, 2) # (B, nc_output, nsteps)
|
||||
debug(self.opt, f"[SpeechEncoderNet] reshape shape = {feat.shape}", verbose=False)
|
||||
|
||||
return feat
|
||||
|
||||
|
||||
class FusionNet(nn.Module):
|
||||
"""
|
||||
This is the WaveNet like layer for the affine coupling. The primary difference
|
||||
from WaveNet is the convolutions need not be causal. There is also no dilation
|
||||
size reset. The dilation only doubles on each layer
|
||||
"""
|
||||
|
||||
def __init__(self, opt, nc_motion, nc_condit, nc_output):
|
||||
super(FusionNet, self).__init__()
|
||||
|
||||
self.opt = opt
|
||||
|
||||
self.n_layers = opt.MODEL.n_layer_wave # 4
|
||||
self.nc_hidden = opt.MODEL.dim_hidden # 256
|
||||
|
||||
kernel_size = opt.MODEL.kernel_size # 3
|
||||
assert(kernel_size % 2 == 1)
|
||||
assert(self.nc_hidden % 2 == 0)
|
||||
|
||||
# audio encoder
|
||||
self.layer_cond = SpeechEncoderNet(opt, nc_condit, 2 * self.nc_hidden)
|
||||
|
||||
# # for
|
||||
# layer_cond = nn.Conv1d(self.nc_hidden, 2*self.nc_hidden*self.n_layers, 1)
|
||||
# self.layer_cond = nn.utils.weight_norm(layer_cond, name='weight')
|
||||
# self.layer_cond = layer_cond
|
||||
|
||||
|
||||
layer_head = nn.Conv1d(nc_motion, 2 * self.nc_hidden, kernel_size=1)
|
||||
layer_head = nn.utils.weight_norm(layer_head, name='weight')
|
||||
self.layer_head = layer_head
|
||||
|
||||
# Initializing last layer to 0 makes the affine coupling layers
|
||||
# do nothing at first. This helps with training stability
|
||||
layer_tail = nn.Conv1d(self.nc_hidden, nc_output, kernel_size=1)
|
||||
layer_tail.weight.data.zero_()
|
||||
layer_tail.bias.data.zero_()
|
||||
self.layer_tail = layer_tail
|
||||
|
||||
|
||||
def forward(self, x, c):
|
||||
""" forward function
|
||||
x shape = (B x nfeat1 x nsteps1) B x nc_motion_half x nstep
|
||||
c shape = (B x nfeat2 x nsteps2) B x nc_condit*nc_motion x nstep
|
||||
"""
|
||||
|
||||
feat_x = self.layer_head(x) # B x 2*nc_hidden x nstep
|
||||
feat_c = self.layer_cond(c) # B x 2*nc_hidden x nstep
|
||||
debug(self.opt, f"\t[FusionNet] feat_x={feat_x.shape}, feat_c={feat_c.shape}")
|
||||
|
||||
nc_hidden_tensor = torch.IntTensor([self.nc_hidden])
|
||||
feat_m = fused_add_tanh_sigmoid_multiply(feat_x, feat_c, nc_hidden_tensor) # B x nc_hidden x nstep
|
||||
debug(self.opt, f"\t[FusionNet] \tfeat_m={feat_m.shape}")
|
||||
|
||||
|
||||
feat_o = self.layer_tail(feat_m) # B x nc_motion_half x nstep
|
||||
debug(self.opt, f"\t[FusionNet] tail feat_o={feat_o.shape}")
|
||||
|
||||
|
||||
return feat_o
|
||||
|
||||
@@ -0,0 +1,351 @@
|
||||
import torch
|
||||
import torch.nn as nn
|
||||
import torch.nn.functional as F
|
||||
import numpy as np
|
||||
|
||||
from common.debug import debug
|
||||
from src.nn.layers import ActNorm1d, Invertible1x1Conv1d as Invertible1x1Conv
|
||||
|
||||
# @torch.jit.script
|
||||
def fused_add_tanh_sigmoid_multiply(input_a, input_b, n_channels):
|
||||
n_channels_int = n_channels[0]
|
||||
in_act = input_a + input_b
|
||||
t_act = torch.tanh(in_act[:, :n_channels_int, :])
|
||||
s_act = torch.sigmoid(in_act[:, n_channels_int:, :])
|
||||
acts = t_act * s_act
|
||||
return acts
|
||||
|
||||
|
||||
class MotionWaveFlow(nn.Module):
|
||||
|
||||
def __init__(self, opt):
|
||||
super(MotionWaveFlow, self).__init__()
|
||||
|
||||
self.opt = opt
|
||||
self.nc_motion = opt.MODEL.dim_motion # 5023
|
||||
self.nc_condit = opt.MODEL.dim_speech # 1024
|
||||
self.nc_hidden = opt.MODEL.dim_hidden # 256
|
||||
|
||||
|
||||
self.n_flows = opt.MODEL.n_flowstep # 12
|
||||
self.n_early_every = opt.MODEL.n_early_every # 4 --> 3
|
||||
|
||||
self.fix_dims = np.array(opt.MODEL.fix_dims)
|
||||
self.lambda_std = np.array(opt.MODEL.lambda_std) # [1, 0.75, 0.5, 0.25]
|
||||
self.lambda_std = torch.from_numpy(self.lambda_std).float().cuda(opt.GPUS[0])
|
||||
|
||||
self.Conv1x1Invs = nn.ModuleList()
|
||||
self.FusionNets = nn.ModuleList()
|
||||
self.Actnorms = nn.ModuleList()
|
||||
nc_motion_rest = self.nc_motion # 8 --> 136
|
||||
|
||||
for k in range(self.n_flows):
|
||||
if k % self.n_early_every == 0 and k > 0: # k = 3, 6, 9
|
||||
nc_motion_rest = nc_motion_rest - nc_motion_rest // 2 # = 84, 42, 21
|
||||
|
||||
self.Actnorms.append(ActNorm1d(num_channels=nc_motion_rest))
|
||||
self.Conv1x1Invs.append(Invertible1x1Conv(nc_motion_rest))
|
||||
self.FusionNets.append(FusionNet(self.opt, nc_motion=nc_motion_rest - nc_motion_rest//2,
|
||||
nc_condit=self.nc_condit,
|
||||
nc_output=2*(nc_motion_rest//2)))
|
||||
|
||||
debug(self.opt, f"[Model] k={k} nc_motion_rest={nc_motion_rest}")
|
||||
|
||||
self.nc_motion_rest = nc_motion_rest # Useful during inference, 72 / 8
|
||||
|
||||
|
||||
def set_actnorm_init(self, inited=True):
|
||||
for name, m in self.named_modules():
|
||||
if (m.__class__.__name__.find("ActNorm") >= 0):
|
||||
m.inited = inited
|
||||
debug(self.opt, f"[Model] set module {m.__class__.__name__} inited = {inited}")
|
||||
|
||||
|
||||
def forward(self, x, c):
|
||||
"""For training, x --> z
|
||||
x shape = (B, nc_motion, nsteps),
|
||||
c shape = (B, nsteps, nwind, nc_speech),
|
||||
return:
|
||||
z shape = (B, dim_motin, nsteps)
|
||||
"""
|
||||
|
||||
debug(self.opt, f"\n[Forward] start x shape={x.shape}, c={c.shape}", verbose=False)
|
||||
|
||||
predt_z = []
|
||||
# feat_c = self.speechEncoder(c) # (B, nc_hidden, nsteps)
|
||||
logdet = torch.zeros(c.size(0), dtype=c.dtype, device=c.device)
|
||||
debug(self.opt, f"\n[Forward] c shape={c.shape}, logdet={logdet.shape}", verbose=False)
|
||||
|
||||
for k in range(self.n_flows):
|
||||
|
||||
x, logdet = self.Actnorms[k](x, logdet)
|
||||
debug(self.opt, f"[Forward] k={k}, actnorm x shape = {x.shape} logdet={logdet.shape}", verbose=False)
|
||||
|
||||
x, logdet = self.Conv1x1Invs[k](x, logdet)
|
||||
debug(self.opt, f"[Forward] k={k}, Conv1x1Invs x={x.shape}, logdet={logdet.shape}")
|
||||
|
||||
# coupling layers
|
||||
nc_motion_half = x.size(1) - x.size(1) // 2
|
||||
x1, x2 = x[:, :nc_motion_half, :], x[:, nc_motion_half:, :]
|
||||
debug(self.opt, f"[Forward] k={k}, coupling split x1={x1.shape}, x2={x2.shape}")
|
||||
|
||||
feat = self.FusionNets[k](x1, c) # (B, nc_motion_half, nc_output)
|
||||
shift, scale = feat[:, 0::2, :], feat[:, 1::2, :]
|
||||
scale = torch.sigmoid(scale + 2.) + 1e-6 # to make scale > 1, so that log(s) > 0
|
||||
x2 = (x2 + shift) * scale
|
||||
logdet = torch.sum(torch.log(scale), dim=[1, 2]) + logdet
|
||||
|
||||
# multi-scale split
|
||||
if k % self.n_early_every == (self.n_early_every -1) and k > 0 and k < self.n_flows -1:
|
||||
predt_z.append(x2)
|
||||
x = x1
|
||||
debug(self.opt, f"[Forward] k={k}, coupling muli-scale x={x.shape}, x2={x2.shape}, logdet={logdet.shape}", verbose=False)
|
||||
else:
|
||||
x = torch.cat([x1, x2], dim=1)
|
||||
debug(self.opt, f"[Forward] k={k}, coupling concat x={x.shape}, logdet={logdet.shape}", verbose=False)
|
||||
|
||||
|
||||
# append the last x
|
||||
predt_z.append(x)
|
||||
predt_z = list(reversed(predt_z))
|
||||
# predt_z = torch.cat(predt_z, dim=1)
|
||||
|
||||
return predt_z, logdet
|
||||
|
||||
def inverse(self, c):
|
||||
"""For inference, z --> x
|
||||
# c shape = (B, nc_condit, nsteps_c)
|
||||
c shape = (B, nsteps, nwind, nc_speech),
|
||||
return:
|
||||
x shape = (B, nc_motion, nsteps_x)
|
||||
"""
|
||||
|
||||
B, nsteps = c.size(0), c.size(1)
|
||||
|
||||
# add z
|
||||
mu = torch.zeros(B, self.nc_motion_rest, nsteps, device=c.device)
|
||||
std = torch.ones(B, self.nc_motion_rest, nsteps, device=c.device) * self.lambda_std[0]
|
||||
x = torch.normal(mean=mu, std=std)
|
||||
# x = torch.zeros(B, self.nc_motion_rest, nsteps, device=c.device).normal_() # (B, 40, 60)
|
||||
|
||||
# feat_c = self.speechEncoder(c) # (B, nc_hidden, nsteps)
|
||||
logdet = torch.zeros(B, dtype=c.dtype, device=c.device)
|
||||
debug(self.opt, f"\n[Inverse] c shape={c.shape}, logdet={logdet.shape}", verbose=False)
|
||||
|
||||
istd = 1
|
||||
for k in reversed(range(self.n_flows)):
|
||||
# coupling layer
|
||||
nc_motion_half = x.size(1) - x.size(1) // 2
|
||||
x1, x2 = x[:, :nc_motion_half, :], x[:, nc_motion_half:, :]
|
||||
debug(self.opt, f"[Inverse] k={k}, x1={x1.shape}, x2={x2.shape}", verbose=False)
|
||||
|
||||
feat = self.FusionNets[k](x1, c) # (B, 1, nc_output)
|
||||
shift, scale = feat[:, 0::2, :], feat[:, 1::2, :]
|
||||
scale = torch.sigmoid(scale + 2.) + 1e-6 # to make scale > 1, so that log(s) > 0
|
||||
debug(self.opt, f"[Inverse] k={k}, coupling feat shape={feat.shape}, shift={shift.shape}, scale={scale.shape}", verbose=False)
|
||||
|
||||
x2 = x2 / scale - shift
|
||||
x = torch.cat([x1, x2], dim=1)
|
||||
logdet = - torch.sum(torch.log(scale), dim=[1,2]) + logdet
|
||||
debug(self.opt, f"[Inverse] k={k}, coupling concat x={x.shape}, logdet={logdet.shape}", verbose=False)
|
||||
|
||||
# 1 x 1 conv inv
|
||||
x, logdet = self.Conv1x1Invs[k].inverse(x, logdet)
|
||||
debug(self.opt, f"[Inverse] k={k}, Conv1x1Invs x={x.shape}")
|
||||
|
||||
# actnorm
|
||||
x, logdet = self.Actnorms[k].inverse(x, logdet)
|
||||
debug(self.opt, f"[Inverse] k={k}, actnorm x shape = {x.shape}", verbose=False)
|
||||
|
||||
# add noise
|
||||
if k % self.n_early_every == 0 and k > 0:
|
||||
# z = torch.zeros(B, x.size(1), nsteps, device=c.device).normal_() # (B, 40, 60)
|
||||
num_dims = x.size(1) + self.fix_dims[istd]
|
||||
|
||||
mu = torch.zeros(B, num_dims, nsteps, device=c.device)
|
||||
std = torch.ones(B, num_dims, nsteps, device=c.device) * self.lambda_std[istd]
|
||||
z = torch.normal(mean=mu, std=std)
|
||||
istd += 1
|
||||
|
||||
x = torch.cat((x, z), dim=1) # (B, 8/40/72/104/136, 25)
|
||||
debug(self.opt, f"[Inverse] k={k}, ADD noise + {x.size(1)} channel, x shape = {x.shape}", verbose=False)
|
||||
|
||||
return x.detach(), logdet # (B, nc_motion, nsteps)
|
||||
|
||||
|
||||
def loss_function_(self, z, logdet, sigma=1.0):
|
||||
"""z = list (B, nc_motion, N)
|
||||
logdet = list (B, )
|
||||
"""
|
||||
|
||||
loss = 0
|
||||
loss_dict = {}
|
||||
nsteps = z[0].size(2)
|
||||
debug(self.opt, f"[Loss] z shape={z[0].shape}, logdet={logdet.shape}")
|
||||
assert len(z) == len(self.lambda_std)
|
||||
|
||||
logp = 0
|
||||
for std, zn in zip(self.lambda_std, z):
|
||||
ilogp = -torch.log(std) - 0.5*zn*zn / (std * std) - 0.5 * torch.log(2 * torch.tensor(np.pi)) # B x nc x nsteps
|
||||
logp += torch.sum(ilogp, dim=[1,2]) / (2*sigma * sigma) # (B, )
|
||||
|
||||
# logp = - 0.5*z*z - 0.5 * torch.log(2 * torch.tensor(np.pi)) # (B, N, nc_motion)
|
||||
# logp = torch.sum(logp, dim=[1,2]) / (2*sigma * sigma) # (B, )
|
||||
|
||||
loss_logp = - torch.mean(logp) / (np.log(2.0) * nsteps * len(z))
|
||||
loss_logdet = - torch.mean(logdet) / (np.log(2.0) * nsteps)
|
||||
loss = loss_logp * self.opt.LOSS.lambda_logp + loss_logdet * self.opt.LOSS.lambda_logdet
|
||||
|
||||
loss_dict["loss_logp"] = loss_logp.detach()
|
||||
loss_dict["loss_logdet"] = loss_logdet.detach()
|
||||
loss_dict["loss_all"] = loss.detach()
|
||||
|
||||
return loss, loss_dict
|
||||
|
||||
|
||||
class SpeechEncoderNet(nn.Module):
|
||||
"""
|
||||
This is a 2D Conv encoder network for speech data with windows
|
||||
"""
|
||||
def __init__(self, opt, nc_speech, nc_output):
|
||||
super(SpeechEncoderNet, self).__init__()
|
||||
|
||||
self.opt = opt
|
||||
# encoder
|
||||
self.encoder = nn.Sequential( # (nbatch, nchannel=1024, H=16, W=1)
|
||||
nn.BatchNorm2d(nc_speech),
|
||||
|
||||
# block 1
|
||||
nn.Conv2d(nc_speech, 512, kernel_size=(3,1), stride=(2,1), padding=(1,0), bias=True), # 32 x 8 x 1
|
||||
nn.LeakyReLU(0.02, True),
|
||||
nn.Conv2d(512, 512, kernel_size=(3,1), stride=(1,1), padding=(1,0), bias=True), # 32 x 8 x 1
|
||||
nn.LeakyReLU(0.02, True),
|
||||
|
||||
nn.Conv2d(512, 512, kernel_size=(3,1), stride=(2,1), padding=(1,0), bias=True), # 32 x 4 x 1
|
||||
nn.LeakyReLU(0.02, True),
|
||||
nn.Conv2d(512, 512, kernel_size=(3,1), stride=(1,1), padding=(1,0), bias=True), # 32 x 8 x 1
|
||||
nn.LeakyReLU(0.02, True),
|
||||
|
||||
|
||||
nn.Conv2d(512, 256, kernel_size=(3,1), stride=(2,1), padding=(1,0), bias=True), # 64 x 2 x 1
|
||||
nn.LeakyReLU(0.02, True),
|
||||
nn.Conv2d(256, 256, kernel_size=(3,1), stride=(1,1), padding=(1,0), bias=True), # 32 x 8 x 1
|
||||
nn.LeakyReLU(0.02, True),
|
||||
|
||||
|
||||
nn.Conv2d(256, 256, kernel_size=(3,1), stride=(2,1), padding=(1,0), bias=True), # 64 x 1 x 1
|
||||
nn.LeakyReLU(0.02, True),
|
||||
nn.Conv2d(256, 256, kernel_size=(3,1), stride=(1,1), padding=(1,0), bias=True), # 32 x 8 x 1
|
||||
nn.LeakyReLU(0.02, True),
|
||||
|
||||
nn.Conv2d(256, 128, kernel_size=(3,1), stride=(2,1), padding=(1,0), bias=True), # 64 x 1 x 1
|
||||
nn.LeakyReLU(0.02, True),
|
||||
|
||||
nn.Flatten(), # 64,
|
||||
|
||||
nn.Linear(in_features=128, out_features=50), # 128,
|
||||
nn.Tanh(),
|
||||
|
||||
nn.Linear(in_features=50, out_features=nc_output) # 50,
|
||||
)
|
||||
|
||||
def forward(self, x):
|
||||
""" forward function
|
||||
Args:
|
||||
x: [nbatch x nsteps x nwind x dim_condit]
|
||||
return:
|
||||
pred: [nbatch x nc_output x nsteps]
|
||||
"""
|
||||
|
||||
(nbatch, nsteps, nwind, nfeat) = x.shape # (B, nsetps, 16, nc_speech)
|
||||
debug(self.opt, f"[SpeechEncoderNet] input x shape = {x.shape}", verbose=False)
|
||||
|
||||
# preprocessing data
|
||||
x = x.reshape(nbatch * nsteps, 1, nwind, nfeat) # (B * nsteps, 1, 16, nc_speech)
|
||||
x = torch.transpose(x, 1, 3) # (B * nsteps, nc_speech, 16, 1)
|
||||
debug(self.opt, f"[SpeechEncoderNet] transpose x shape = {x.shape}", verbose=False)
|
||||
|
||||
|
||||
feat = self.encoder(x) # (B * nsteps, nc_output)
|
||||
debug(self.opt, f"[SpeechEncoderNet] encoder shape = {feat.shape}", verbose=False)
|
||||
|
||||
feat = feat.reshape(nbatch, nsteps, -1) # (B, nsteps, nc_output)
|
||||
feat = torch.transpose(feat, 1, 2) # (B, nc_output, nsteps)
|
||||
debug(self.opt, f"[SpeechEncoderNet] reshape shape = {feat.shape}", verbose=False)
|
||||
|
||||
return feat
|
||||
|
||||
|
||||
class FusionNet(nn.Module):
|
||||
"""
|
||||
This is the WaveNet like layer for the affine coupling. The primary difference
|
||||
from WaveNet is the convolutions need not be causal. There is also no dilation
|
||||
size reset. The dilation only doubles on each layer
|
||||
"""
|
||||
|
||||
def __init__(self, opt, nc_motion, nc_condit, nc_output):
|
||||
super(FusionNet, self).__init__()
|
||||
|
||||
self.opt = opt
|
||||
|
||||
self.n_layers = opt.MODEL.n_layer_wave # 4
|
||||
self.nc_hidden = opt.MODEL.dim_hidden # 256
|
||||
|
||||
kernel_size = opt.MODEL.kernel_size # 3
|
||||
assert(kernel_size % 2 == 1)
|
||||
assert(self.nc_hidden % 2 == 0)
|
||||
|
||||
# audio encoder
|
||||
self.layer_cond = SpeechEncoderNet(opt, nc_condit, 2 * self.nc_hidden)
|
||||
|
||||
# # for
|
||||
# layer_cond = nn.Conv1d(self.nc_hidden, 2*self.nc_hidden*self.n_layers, 1)
|
||||
# self.layer_cond = nn.utils.weight_norm(layer_cond, name='weight')
|
||||
# self.layer_cond = layer_cond
|
||||
|
||||
|
||||
layer_head = nn.Conv1d(nc_motion, 2 * self.nc_hidden, kernel_size=1)
|
||||
layer_head = nn.utils.weight_norm(layer_head, name='weight')
|
||||
self.layer_head = layer_head
|
||||
|
||||
# Initializing last layer to 0 makes the affine coupling layers
|
||||
# do nothing at first. This helps with training stability
|
||||
layer_tail = nn.Conv1d(self.nc_hidden, nc_output, kernel_size=1)
|
||||
layer_tail.weight.data.zero_()
|
||||
layer_tail.bias.data.zero_()
|
||||
self.layer_tail = layer_tail
|
||||
|
||||
|
||||
self.RNN = nn.LSTM(input_size = self.nc_hidden,
|
||||
hidden_size = self.nc_hidden,
|
||||
num_layers = 2,
|
||||
batch_first=True)
|
||||
|
||||
|
||||
def forward(self, x, c):
|
||||
""" forward function
|
||||
x shape = (B x nfeat1 x nsteps1) B x nc_motion_half x nstep
|
||||
c shape = (B x nfeat2 x nsteps2) B x nc_condit*nc_motion x nstep
|
||||
"""
|
||||
|
||||
feat_x = self.layer_head(x) # B x 2*nc_hidden x nstep
|
||||
feat_c = self.layer_cond(c) # B x 2*nc_hidden x nstep
|
||||
debug(self.opt, f"\t[FusionNet] feat_x={feat_x.shape}, feat_c={feat_c.shape}")
|
||||
|
||||
nc_hidden_tensor = torch.IntTensor([self.nc_hidden])
|
||||
feat_m = fused_add_tanh_sigmoid_multiply(feat_x, feat_c, nc_hidden_tensor) # B x nc_hidden x nstep
|
||||
debug(self.opt, f"\t[FusionNet] \tfeat_m={feat_m.shape}")
|
||||
|
||||
|
||||
# RNN
|
||||
feat_m = torch.transpose(feat_m, 1, 2)
|
||||
feat_m, _ = self.RNN(feat_m) # B x nc_hidden x nstep
|
||||
feat_m = torch.transpose(feat_m, 1, 2)
|
||||
|
||||
# output
|
||||
feat_o = self.layer_tail(feat_m) # B x nc_motion_half x nstep
|
||||
debug(self.opt, f"\t[FusionNet] tail feat_o={feat_o.shape}")
|
||||
|
||||
|
||||
return feat_o
|
||||
|
||||
@@ -0,0 +1,94 @@
|
||||
import torch
|
||||
import torch.nn as nn
|
||||
from common.debug import debug
|
||||
|
||||
class Audio2Mesh(nn.Module):
|
||||
|
||||
def __init__(self, opt):
|
||||
super(Audio2Mesh, self).__init__()
|
||||
|
||||
self.opt = opt
|
||||
self.num_vertices = opt.MODEL.num_vertices
|
||||
|
||||
self.dim_coef = opt.MODEL.dim_motion # 53
|
||||
self.dim_mesh = 3 * self.num_vertices # 3 * 5023
|
||||
self.dim_cond = opt.MODEL.dim_speech # 1024
|
||||
|
||||
# encoder
|
||||
self.encoder = nn.Sequential( # (nbatch, nchannel=1024, H=16, W=1)
|
||||
nn.BatchNorm2d(self.dim_cond),
|
||||
|
||||
# block 1
|
||||
nn.Conv2d(self.dim_cond, 512, kernel_size=(3,1), stride=(2,1), padding=(1,0), bias=True), # 32 x 8 x 1
|
||||
nn.LeakyReLU(0.02, True),
|
||||
nn.Conv2d(512, 512, kernel_size=(3,1), stride=(1,1), padding=(1,0), bias=True), # 32 x 8 x 1
|
||||
nn.LeakyReLU(0.02, True),
|
||||
|
||||
nn.Conv2d(512, 512, kernel_size=(3,1), stride=(2,1), padding=(1,0), bias=True), # 32 x 4 x 1
|
||||
nn.LeakyReLU(0.02, True),
|
||||
nn.Conv2d(512, 512, kernel_size=(3,1), stride=(1,1), padding=(1,0), bias=True), # 32 x 8 x 1
|
||||
nn.LeakyReLU(0.02, True),
|
||||
|
||||
|
||||
nn.Conv2d(512, 256, kernel_size=(3,1), stride=(2,1), padding=(1,0), bias=True), # 64 x 2 x 1
|
||||
nn.LeakyReLU(0.02, True),
|
||||
nn.Conv2d(256, 256, kernel_size=(3,1), stride=(1,1), padding=(1,0), bias=True), # 32 x 8 x 1
|
||||
nn.LeakyReLU(0.02, True),
|
||||
|
||||
|
||||
nn.Conv2d(256, 256, kernel_size=(3,1), stride=(2,1), padding=(1,0), bias=True), # 64 x 1 x 1
|
||||
nn.LeakyReLU(0.02, True),
|
||||
nn.Conv2d(256, 256, kernel_size=(3,1), stride=(1,1), padding=(1,0), bias=True), # 32 x 8 x 1
|
||||
nn.LeakyReLU(0.02, True),
|
||||
|
||||
nn.Conv2d(256, 128, kernel_size=(3,1), stride=(2,1), padding=(1,0), bias=True), # 64 x 1 x 1
|
||||
nn.LeakyReLU(0.02, True),
|
||||
|
||||
nn.Flatten(), # 64,
|
||||
|
||||
nn.Linear(in_features=128, out_features=2048), # 128,
|
||||
nn.Tanh(),
|
||||
|
||||
nn.Linear(in_features=2048, out_features=50) # 50,
|
||||
)
|
||||
|
||||
# output FLAME mesh
|
||||
self.decoder_mesh = nn.Linear(in_features=50, out_features=self.dim_mesh)
|
||||
|
||||
|
||||
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_coef]
|
||||
"""
|
||||
(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)
|
||||
|
||||
|
||||
# # predict FLAME coeff
|
||||
# pred_coef = self.decoder_coef(feat) # (B * nseq, dim_coef)
|
||||
# debug(self.opt, f"[forward] decoder coeff shape = {pred_coef.shape}", verbose=False)
|
||||
|
||||
# pred_coef = pred_coef.reshape(nbatch, nseqlen, -1) # (B, nseq, dim_coef)
|
||||
# debug(self.opt, f"[forward] reshape shape = {pred_coef.shape}", verbose=False)
|
||||
|
||||
# predict FLAME mesh
|
||||
pred_vert = self.decoder_mesh(feat) # (B * nseq, dim_mesh)
|
||||
debug(self.opt, f"[forward] decoder mesh shape = {pred_vert.shape}", verbose=False)
|
||||
|
||||
pred_vert = pred_vert.reshape(nbatch, nseqlen, self.num_vertices, 3) # (B, nseq, num_vertices, 3)
|
||||
debug(self.opt, f"[forward] reshape shape = {pred_vert.shape}", verbose=False)
|
||||
|
||||
return pred_vert
|
||||
|
||||
|
||||
@@ -0,0 +1,93 @@
|
||||
from termios import NCCS
|
||||
import torch
|
||||
import torch.nn as nn
|
||||
from common.debug import debug
|
||||
|
||||
|
||||
class Audio2Mesh(nn.Module):
|
||||
|
||||
def __init__(self, opt):
|
||||
super(Audio2Mesh, self).__init__()
|
||||
|
||||
self.opt = opt
|
||||
self.num_vertices = opt.MODEL.num_vertices
|
||||
|
||||
self.dim_coef = opt.MODEL.dim_motion # 53
|
||||
self.dim_mesh = 3 * self.num_vertices # 3 * 5023
|
||||
self.dim_cond = opt.MODEL.dim_speech # 1024
|
||||
|
||||
self.layer_bn = nn.BatchNorm2d(self.dim_cond)
|
||||
|
||||
# resnet header
|
||||
self.header = self.get_resnet(nc=self.dim_cond)
|
||||
|
||||
# encoder
|
||||
self.encoder = nn.Sequential(
|
||||
nn.Linear(in_features=2048, out_features=256), # 128,
|
||||
nn.Tanh(),
|
||||
|
||||
nn.Linear(in_features=256, out_features=50)
|
||||
)
|
||||
|
||||
# output FLAME mesh
|
||||
self.decoder_mesh = nn.Linear(in_features=50, out_features=self.dim_mesh)
|
||||
|
||||
|
||||
def get_resnet(self, nc=3):
|
||||
if self.opt.MODEL.name_header == "resnet34":
|
||||
from src.nn.resnet import ResNet34
|
||||
return ResNet34(num_input=nc)
|
||||
|
||||
elif self.opt.MODEL.name_header == "resnet50":
|
||||
from src.nn.resnet import ResNet50
|
||||
return ResNet50(num_input=nc)
|
||||
|
||||
elif self.opt.MODEL.name_header == "resnet101":
|
||||
from src.nn.resnet import ResNet101
|
||||
return ResNet101(num_input=nc)
|
||||
|
||||
else:
|
||||
raise("opt.MODEL.name_header should be 'resnet34 | resnet50 | resnet101' ")
|
||||
|
||||
|
||||
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_coef]
|
||||
"""
|
||||
(nbatch, nseqlen, nwind, nfeat) = x.shape # (B, nseq, 16, nfeat)
|
||||
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, nfeat)
|
||||
x = torch.transpose(x, 1, 3) # (B * nseq, nfeat, 16, 1)
|
||||
debug(self.opt, f"[forward] transpose x shape = {x.shape}", verbose=False)
|
||||
|
||||
x = self.layer_bn(x) # (B * nseq, nfeat, 16, 1)
|
||||
debug(self.opt, f"[forward] bn layer x shape = {x.shape}", verbose=False)
|
||||
|
||||
feat = self.header.get_features(x) # (B * nseq, 2048)
|
||||
debug(self.opt, f"[forward] header shape = {feat.shape}", verbose=False)
|
||||
|
||||
feat = self.encoder(feat) # (B * nseq, 50)
|
||||
debug(self.opt, f"[forward] encoder shape = {feat.shape}", verbose=False)
|
||||
|
||||
# # predict FLAME coeff
|
||||
# pred_coef = self.decoder_coef(feat) # (B * nseq, dim_coef)
|
||||
# debug(self.opt, f"[forward] decoder coeff shape = {pred_coef.shape}", verbose=False)
|
||||
|
||||
# pred_coef = pred_coef.reshape(nbatch, nseqlen, -1) # (B, nseq, dim_coef)
|
||||
# debug(self.opt, f"[forward] reshape shape = {pred_coef.shape}", verbose=False)
|
||||
|
||||
# predict FLAME mesh
|
||||
pred_vert = self.decoder_mesh(feat) # (B * nseq, dim_mesh)
|
||||
debug(self.opt, f"[forward] decoder mesh shape = {pred_vert.shape}", verbose=False)
|
||||
|
||||
pred_vert = pred_vert.reshape(nbatch, nseqlen, self.num_vertices, 3) # (B, nseq, num_vertices, 3)
|
||||
debug(self.opt, f"[forward] reshape shape = {pred_vert.shape}", verbose=False)
|
||||
|
||||
return pred_vert
|
||||
|
||||
|
||||
@@ -0,0 +1,74 @@
|
||||
import torch
|
||||
import torch.nn as nn
|
||||
from common.debug import debug
|
||||
|
||||
class Audio2Mesh(nn.Module):
|
||||
|
||||
def __init__(self, opt):
|
||||
super(Audio2Mesh, self).__init__()
|
||||
|
||||
self.opt = opt
|
||||
self.num_vertices = opt.MODEL.num_vertices
|
||||
|
||||
self.dim_coef = opt.MODEL.dim_motion # 53
|
||||
self.dim_mesh = 3 * self.num_vertices # 3 * 5023
|
||||
self.dim_cond = opt.MODEL.dim_speech # 1024
|
||||
|
||||
# encoder
|
||||
self.encoder = nn.Sequential( # (nbatch, nchannel=1024, H=16, W=1)
|
||||
nn.BatchNorm2d(self.dim_cond),
|
||||
|
||||
# block 1
|
||||
nn.Conv2d(self.dim_cond, 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 FLAME mesh
|
||||
self.decoder_mesh = nn.Linear(in_features=50, out_features=self.dim_mesh)
|
||||
|
||||
|
||||
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_coef]
|
||||
"""
|
||||
(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)
|
||||
|
||||
# predict FLAME mesh
|
||||
pred_vert = self.decoder_mesh(feat) # (B * nseq, dim_mesh)
|
||||
debug(self.opt, f"[forward] decoder mesh shape = {pred_vert.shape}", verbose=False)
|
||||
|
||||
pred_vert = pred_vert.reshape(nbatch, nseqlen, self.num_vertices, 3) # (B, nseq, num_vertices, 3)
|
||||
debug(self.opt, f"[forward] reshape shape = {pred_vert.shape}", verbose=False)
|
||||
|
||||
return pred_vert
|
||||
|
||||
|
||||
@@ -57,16 +57,14 @@ class Audio2MotionVOCA3(nn.Module):
|
||||
(nbatch, nseqlen, nwind, nfeat) = x.shape # (B, nseq, 16, 29)
|
||||
debug(self.opt, f"[forward] input x shape = {x.shape}", verbose=False)
|
||||
|
||||
# preprocessing data
|
||||
# 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)
|
||||
|
||||
|
||||
@@ -0,0 +1,116 @@
|
||||
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, 512, kernel_size=(3,1), stride=(2,1), padding=(1,0), bias=True), # 32 x 8 x 1
|
||||
nn.LeakyReLU(0.02, True),
|
||||
nn.Conv2d(512, 512, kernel_size=(3,1), stride=(1,1), padding=(1,0), bias=True), # 32 x 8 x 1
|
||||
nn.LeakyReLU(0.02, True),
|
||||
|
||||
|
||||
nn.Conv2d(512, 512, kernel_size=(3,1), stride=(2,1), padding=(1,0), bias=True), # 32 x 4 x 1
|
||||
nn.LeakyReLU(0.02, True),
|
||||
nn.Conv2d(512, 512, kernel_size=(3,1), stride=(1,1), padding=(1,0), bias=True), # 32 x 8 x 1
|
||||
nn.LeakyReLU(0.02, True),
|
||||
|
||||
|
||||
nn.Conv2d(512, 256, kernel_size=(3,1), stride=(2,1), padding=(1,0), bias=True), # 64 x 2 x 1
|
||||
nn.LeakyReLU(0.02, True),
|
||||
nn.Conv2d(256, 256, kernel_size=(3,1), stride=(1,1), padding=(1,0), bias=True), # 32 x 8 x 1
|
||||
nn.LeakyReLU(0.02, True),
|
||||
|
||||
|
||||
nn.Conv2d(256, 256, kernel_size=(3,1), stride=(2,1), padding=(1,0), bias=True), # 64 x 1 x 1
|
||||
nn.LeakyReLU(0.02, True),
|
||||
nn.Conv2d(256, 256, kernel_size=(3,1), stride=(1,1), padding=(1,0), bias=True), # 32 x 8 x 1
|
||||
nn.LeakyReLU(0.02, True),
|
||||
|
||||
nn.Conv2d(256, 128, kernel_size=(3,1), stride=(2,1), padding=(1,0), bias=True), # 64 x 1 x 1
|
||||
nn.LeakyReLU(0.02, True),
|
||||
|
||||
nn.Flatten(), # 64,
|
||||
|
||||
nn.Linear(in_features=128, out_features=512), # 128,
|
||||
nn.LeakyReLU(0.02, True),
|
||||
|
||||
nn.Linear(in_features=512, out_features=512), # 128,
|
||||
nn.LeakyReLU(0.02, True),
|
||||
|
||||
nn.Linear(in_features=512, out_features=512), # 128,
|
||||
nn.LeakyReLU(0.02, True),
|
||||
|
||||
nn.Linear(in_features=512, out_features=512), # 128,
|
||||
nn.LeakyReLU(0.02, True),
|
||||
|
||||
nn.Linear(in_features=512, out_features=1024), # 128,
|
||||
nn.LeakyReLU(0.02, True),
|
||||
|
||||
nn.Linear(in_features=1024, out_features=1024), # 128,
|
||||
nn.LeakyReLU(0.02, True),
|
||||
|
||||
nn.Linear(in_features=1024, out_features=1024), # 128,
|
||||
nn.LeakyReLU(0.02, True),
|
||||
|
||||
nn.Linear(in_features=1024, out_features=1024), # 128,
|
||||
nn.LeakyReLU(0.02, True),
|
||||
|
||||
nn.Linear(in_features=1024, out_features=2048), # 128,
|
||||
nn.LeakyReLU(0.02, True),
|
||||
|
||||
nn.Linear(in_features=2048, out_features=256), # 128,
|
||||
nn.Tanh(),
|
||||
|
||||
nn.Linear(in_features=256, 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
|
||||
|
||||
|
||||
@@ -16,57 +16,49 @@ class Audio2MotionVOCA(nn.Module):
|
||||
self.encoder = nn.Sequential( # (nbatch, nchannel=29, H=16, W=1)
|
||||
nn.BatchNorm2d(self.dim_speech),
|
||||
|
||||
|
||||
# block 1
|
||||
nn.Conv2d(self.dim_speech, 128, kernel_size=(3,1), stride=(1,1), padding=(1,0), bias=True), # 128 x 16 x 1
|
||||
nn.BatchNorm2d(128),
|
||||
nn.Conv2d(self.dim_speech, 512, kernel_size=(3,1), stride=(2,1), padding=(1,0), bias=True), # 32 x 8 x 1
|
||||
nn.LeakyReLU(0.02, True),
|
||||
nn.Conv2d(128, 128, kernel_size=(3,1), stride=(1,1), padding=(1,0), bias=True), # 128 x 16 x 1
|
||||
nn.BatchNorm2d(128),
|
||||
nn.Conv2d(512, 512, kernel_size=(3,1), stride=(1,1), padding=(1,0), bias=True), # 32 x 8 x 1
|
||||
nn.LeakyReLU(0.02, True),
|
||||
nn.Conv2d(128, 128, kernel_size=(3,1), stride=(1,1), padding=(1,0), bias=True), # 128 x 16 x 1
|
||||
nn.BatchNorm2d(128),
|
||||
nn.LeakyReLU(0.02, True),
|
||||
|
||||
# block 2
|
||||
nn.Conv2d(128, 256, kernel_size=(3,1), stride=(2,1), padding=(1,0), bias=True), # 256 x 8 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 8 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 8 x 1
|
||||
nn.BatchNorm2d(256),
|
||||
nn.LeakyReLU(0.02, True),
|
||||
nn.Conv2d(256, 512, kernel_size=(3,1), stride=(1,1), padding=(1,0), bias=True), # 512 x 8 x 1
|
||||
nn.BatchNorm2d(512),
|
||||
nn.LeakyReLU(0.02, True),
|
||||
|
||||
|
||||
# block 3
|
||||
nn.Conv2d(512, 512, kernel_size=(3,1), stride=(2,1), padding=(1,0), bias=True), # 512 x 4 x 1
|
||||
nn.BatchNorm2d(512),
|
||||
nn.LeakyReLU(0.02, True),
|
||||
nn.Conv2d(512, 512, kernel_size=(3,1), stride=(1,1), padding=(1,0), bias=True), # 512 x 4 x 1
|
||||
nn.BatchNorm2d(512),
|
||||
nn.LeakyReLU(0.02, True),
|
||||
nn.Conv2d(512, 512, kernel_size=(3,1), stride=(2,1), padding=(1,0), bias=True), # 512 x 2 x 1
|
||||
nn.BatchNorm2d(512),
|
||||
nn.LeakyReLU(0.02, True),
|
||||
nn.Conv2d(512, 512, kernel_size=(3,1), stride=(2,1), padding=(1,0), bias=True), # 512 x 1 x 1
|
||||
nn.BatchNorm2d(512),
|
||||
nn.Conv2d(512, 512, kernel_size=(3,1), stride=(1,1), padding=(1,0), bias=True), # 32 x 8 x 1
|
||||
nn.LeakyReLU(0.02, True),
|
||||
|
||||
|
||||
nn.Flatten(), # 256,
|
||||
nn.Conv2d(512, 512, kernel_size=(3,1), stride=(2,1), padding=(1,0), bias=True), # 32 x 4 x 1
|
||||
nn.LeakyReLU(0.02, True),
|
||||
nn.Conv2d(512, 512, kernel_size=(3,1), stride=(1,1), padding=(1,0), bias=True), # 32 x 8 x 1
|
||||
nn.LeakyReLU(0.02, True),
|
||||
nn.Conv2d(512, 512, kernel_size=(3,1), stride=(1,1), padding=(1,0), bias=True), # 32 x 8 x 1
|
||||
nn.LeakyReLU(0.02, True),
|
||||
|
||||
nn.Linear(in_features=512, out_features=128), # 2014,
|
||||
nn.Conv2d(512, 256, kernel_size=(3,1), stride=(2,1), padding=(1,0), bias=True), # 64 x 2 x 1
|
||||
nn.LeakyReLU(0.02, True),
|
||||
nn.Conv2d(256, 256, kernel_size=(3,1), stride=(1,1), padding=(1,0), bias=True), # 32 x 8 x 1
|
||||
nn.LeakyReLU(0.02, True),
|
||||
nn.Conv2d(256, 256, kernel_size=(3,1), stride=(1,1), padding=(1,0), bias=True), # 32 x 8 x 1
|
||||
nn.LeakyReLU(0.02, True),
|
||||
|
||||
|
||||
nn.Conv2d(256, 256, kernel_size=(3,1), stride=(2,1), padding=(1,0), bias=True), # 64 x 1 x 1
|
||||
nn.LeakyReLU(0.02, True),
|
||||
nn.Conv2d(256, 256, kernel_size=(3,1), stride=(1,1), padding=(1,0), bias=True), # 32 x 8 x 1
|
||||
nn.LeakyReLU(0.02, True),
|
||||
nn.Conv2d(256, 256, kernel_size=(3,1), stride=(1,1), padding=(1,0), bias=True), # 32 x 8 x 1
|
||||
nn.LeakyReLU(0.02, True),
|
||||
|
||||
nn.Conv2d(256, 128, kernel_size=(3,1), stride=(2,1), padding=(1,0), bias=True), # 64 x 1 x 1
|
||||
nn.LeakyReLU(0.02, True),
|
||||
|
||||
nn.Flatten(), # 64,
|
||||
|
||||
nn.Linear(in_features=128, out_features=256), # 128,
|
||||
nn.LeakyReLU(0.02, True),
|
||||
|
||||
nn.Linear(in_features=256, out_features=2048), # 128,
|
||||
nn.Tanh(),
|
||||
|
||||
nn.Linear(in_features=128, out_features=2048), # 2014,
|
||||
nn.Tanh(),
|
||||
|
||||
nn.Linear(in_features=2048, out_features=128) # 128,
|
||||
nn.Linear(in_features=2048, out_features=128) # 50,
|
||||
)
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,190 @@
|
||||
import torch
|
||||
import torch.nn as nn
|
||||
import torch.nn.functional as F
|
||||
"""
|
||||
Follow:
|
||||
https://github.com/PolinaKirichenko/flows_ood/blob/master/flow_ssl/glow/glow_utils.py
|
||||
https://github.com/tatsy/normalizing-flows-pytorch/blob/master/flows/modules.py
|
||||
"""
|
||||
|
||||
class Invertible1x1Conv1d(nn.Module):
|
||||
"""
|
||||
The layer outputs both the convolution, and the log determinant
|
||||
of its weight matrix. If reverse=True it does convolution with
|
||||
inverse
|
||||
"""
|
||||
|
||||
def __init__(self, num_channels):
|
||||
super(Invertible1x1Conv1d, self).__init__()
|
||||
|
||||
self.num_channels = num_channels
|
||||
weight = torch.qr(torch.randn((num_channels, num_channels)))[0]
|
||||
self.weight = nn.Parameter(weight) # (num_channels, num_channels)
|
||||
|
||||
def forward(self, input, logdet=None):
|
||||
"""
|
||||
log-det = log|abs(|W|)| * nseq
|
||||
"""
|
||||
|
||||
nbatch, nchannels, nseq = input.size() # (B,C,N)
|
||||
slogdet = (torch.slogdet(self.weight)[1] * nseq).expand(nbatch) # w * h * log |det w|
|
||||
|
||||
weight = self.weight.view(self.num_channels, self.num_channels, 1)
|
||||
z = F.conv1d(input, weight)
|
||||
|
||||
logdet = logdet + slogdet if (logdet is not None) else slogdet
|
||||
|
||||
return z, logdet
|
||||
|
||||
def inverse(self, input, logdet=None):
|
||||
"""
|
||||
log-det = log|det(W^-1)| * nseq = - log|det(W)| * nseq
|
||||
"""
|
||||
nbatch, nchannels, nseq = input.size() # (B,C,N)
|
||||
slogdet = - (torch.slogdet(self.weight)[1] * nseq).expand(nbatch) # w * h * log |det w|
|
||||
|
||||
weight = torch.inverse(self.weight)
|
||||
weight = weight.view(self.num_channels, self.num_channels, 1)
|
||||
z = F.conv1d(input, weight)
|
||||
|
||||
logdet = logdet + slogdet if (logdet is not None) else slogdet
|
||||
|
||||
return z, logdet
|
||||
|
||||
|
||||
class Invertible1x1Conv2d(nn.Module):
|
||||
"""
|
||||
The layer outputs both the convolution, and the log determinant
|
||||
of its weight matrix. If reverse=True it does convolution with
|
||||
inverse
|
||||
"""
|
||||
|
||||
def __init__(self, num_channels):
|
||||
super(Invertible1x1Conv2d).__init__()
|
||||
|
||||
self.num_channels = num_channels
|
||||
weight = torch.qr(torch.randn((num_channels, num_channels)))[0]
|
||||
self.weight = nn.Parameter(weight) # (num_channels, num_channels)
|
||||
|
||||
def forward(self, input, logdet=None):
|
||||
"""
|
||||
log-det = log|abs(|W|)| * h * w
|
||||
"""
|
||||
nbatch, nchannels, h, w = input.size() # (B, C, H, W)
|
||||
slogdet = (torch.slogdet(self.weight)[1] * h * w).expand(nbatch) # w * h * log |det w|
|
||||
|
||||
weight = self.weight.view(self.num_channels, self.num_channels, 1, 1)
|
||||
z = F.conv2d(input, weight)
|
||||
logdet = logdet + slogdet if (logdet is not None) else None
|
||||
|
||||
return z, logdet
|
||||
|
||||
def inverse(self, input, logdet=None):
|
||||
"""
|
||||
log-det = log|det(W^-1)| * h * w = - log|det(W)| * h * w
|
||||
"""
|
||||
nbatch, nchannels, h, w = input.size() # (B,C,N)
|
||||
slogdet = - (torch.slogdet(self.weight)[1] * h * w).expand(nbatch) # w * h * log |det w|
|
||||
|
||||
weight = torch.inverse(self.weight)
|
||||
weight = weight.view(self.num_channels, self.num_channels, 1, 1)
|
||||
z = F.conv2d(input, weight)
|
||||
logdet = logdet + slogdet if (logdet is not None) else None
|
||||
|
||||
return z, logdet
|
||||
|
||||
|
||||
class ActNorm1d(nn.Module):
|
||||
""" Initializ at the first minibatch with zero mean and unit variance,
|
||||
After initialization, the bias and logs are treated as a regular trainable parameters that are dependent of data.
|
||||
"""
|
||||
def __init__(self, num_channels, eps=1e-6):
|
||||
super(ActNorm1d, self).__init__()
|
||||
|
||||
self.inited = False
|
||||
self.eps = eps
|
||||
self.num_channels = num_channels
|
||||
|
||||
# register bias and scale
|
||||
self.bias = nn.Parameter(torch.zeros((1, num_channels, 1)))
|
||||
self.logs = nn.Parameter(torch.zeros((1, num_channels, 1))) # log scale, which easy for det(log|s|)
|
||||
|
||||
def init_parameters(self, input):
|
||||
if not self.training:
|
||||
raise ValueError("In Eval mode, but ActNorm not inited")
|
||||
|
||||
with torch.no_grad():
|
||||
bias = torch.mean(input, dim=[0,2], keepdim=True) # (1, C, 1)
|
||||
logs = torch.log(torch.std(input, dim=[0,2], keepdim=True) + self.eps) # (1, C, 1)
|
||||
self.bias.data.copy_(bias.data)
|
||||
self.logs.data.copy_(logs.data)
|
||||
self.inited = True
|
||||
|
||||
|
||||
def forward(self, input, logdet=None):
|
||||
B,C,N = input.size()
|
||||
|
||||
if not self.inited:
|
||||
self.init_parameters(input)
|
||||
|
||||
z = (input - self.bias) / torch.exp(self.logs) # Normalize by element-wise
|
||||
dlogdet = - torch.sum(self.logs) * N
|
||||
logdet = logdet + dlogdet if (logdet is not None) else None
|
||||
|
||||
return z, logdet
|
||||
|
||||
def inverse(self, input, logdet=None):
|
||||
B,C,N = input.size()
|
||||
|
||||
z = input * torch.exp(self.logs) + self.bias
|
||||
dlogdet = torch.sum(self.logs) * N
|
||||
logdet = logdet + dlogdet if (logdet is not None) else None
|
||||
return z, logdet
|
||||
|
||||
|
||||
class ActNorm2d(nn.Module):
|
||||
""" Initializ at the first minibatch with zero mean and unit variance,
|
||||
After initialization, the bias and logs are treated as a regular trainable parameters that are dependent of data.
|
||||
"""
|
||||
def __init__(self, num_channels, eps=1e-6):
|
||||
super(ActNorm2d, self).__init__()
|
||||
|
||||
self.inited = False
|
||||
self.eps = eps
|
||||
self.num_channels = num_channels
|
||||
|
||||
# register bias and scale
|
||||
self.bias = nn.Parameter(torch.zeros((1, num_channels, 1, 1)))
|
||||
self.logs = nn.Parameter(torch.zeros((1, num_channels, 1, 1))) # log scale, which easy for det(log|s|)
|
||||
|
||||
def init_parameters(self, input):
|
||||
if not self.training:
|
||||
raise ValueError("In Eval mode, but ActNorm not inited")
|
||||
|
||||
with torch.no_grad():
|
||||
bias = torch.mean(input, dim=[0,2,3], keepdim=True) # (1, C, 1, 1)
|
||||
logs = torch.log(torch.std(input, dim=[0,2,3], keepdim=True) + self.eps) # (1, C, 1, 1)
|
||||
self.bias.data.copy_(bias.data)
|
||||
self.logs.data.copy_(logs.data)
|
||||
self.inited = True
|
||||
|
||||
def forward(self, input, logdet=None):
|
||||
B,C,H,W = input.size()
|
||||
|
||||
if not self.inited:
|
||||
self.init_parameters(input)
|
||||
|
||||
z = (input - self.bias) / torch.exp(self.logs)
|
||||
dlogdet = - torch.sum(self.logs) * H * W
|
||||
logdet = logdet + dlogdet if (logdet is not None) else None
|
||||
|
||||
return z, logdet
|
||||
|
||||
def inverse(self, input, logdet=None):
|
||||
B,C,H,W = input.size()
|
||||
|
||||
z = input * torch.exp(self.logs) + self.bias
|
||||
dlogdet = torch.sum(self.logs) * H * W
|
||||
logdet = logdet + dlogdet if (logdet is not None) else None
|
||||
|
||||
return z, logdet
|
||||
+378
@@ -0,0 +1,378 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
|
||||
# Max-Planck-Gesellschaft zur Förderung der Wissenschaften e.V. (MPG) is
|
||||
# holder of all proprietary rights on this computer program.
|
||||
# You can only use this computer program if you have closed
|
||||
# a license agreement with MPG or you get the right to use the computer
|
||||
# program from someone who is authorized to grant you that right.
|
||||
# Any use of the computer program without a valid license is prohibited and
|
||||
# liable to prosecution.
|
||||
#
|
||||
# Copyright©2019 Max-Planck-Gesellschaft zur Förderung
|
||||
# der Wissenschaften e.V. (MPG). acting on behalf of its Max Planck Institute
|
||||
# for Intelligent Systems. All rights reserved.
|
||||
#
|
||||
# Contact: ps-license@tuebingen.mpg.de
|
||||
|
||||
from __future__ import absolute_import
|
||||
from __future__ import print_function
|
||||
from __future__ import division
|
||||
|
||||
import numpy as np
|
||||
|
||||
import torch
|
||||
import torch.nn.functional as F
|
||||
|
||||
def rot_mat_to_euler(rot_mats):
|
||||
# Calculates rotation matrix to euler angles
|
||||
# Careful for extreme cases of eular angles like [0.0, pi, 0.0]
|
||||
|
||||
sy = torch.sqrt(rot_mats[:, 0, 0] * rot_mats[:, 0, 0] +
|
||||
rot_mats[:, 1, 0] * rot_mats[:, 1, 0])
|
||||
return torch.atan2(-rot_mats[:, 2, 0], sy)
|
||||
|
||||
def find_dynamic_lmk_idx_and_bcoords(vertices, pose, dynamic_lmk_faces_idx,
|
||||
dynamic_lmk_b_coords,
|
||||
neck_kin_chain, dtype=torch.float32):
|
||||
''' Compute the faces, barycentric coordinates for the dynamic landmarks
|
||||
|
||||
|
||||
To do so, we first compute the rotation of the neck around the y-axis
|
||||
and then use a pre-computed look-up table to find the faces and the
|
||||
barycentric coordinates that will be used.
|
||||
|
||||
Special thanks to Soubhik Sanyal (soubhik.sanyal@tuebingen.mpg.de)
|
||||
for providing the original TensorFlow implementation and for the LUT.
|
||||
|
||||
Parameters
|
||||
----------
|
||||
vertices: torch.tensor BxVx3, dtype = torch.float32
|
||||
The tensor of input vertices
|
||||
pose: torch.tensor Bx(Jx3), dtype = torch.float32
|
||||
The current pose of the body model
|
||||
dynamic_lmk_faces_idx: torch.tensor L, dtype = torch.long
|
||||
The look-up table from neck rotation to faces
|
||||
dynamic_lmk_b_coords: torch.tensor Lx3, dtype = torch.float32
|
||||
The look-up table from neck rotation to barycentric coordinates
|
||||
neck_kin_chain: list
|
||||
A python list that contains the indices of the joints that form the
|
||||
kinematic chain of the neck.
|
||||
dtype: torch.dtype, optional
|
||||
|
||||
Returns
|
||||
-------
|
||||
dyn_lmk_faces_idx: torch.tensor, dtype = torch.long
|
||||
A tensor of size BxL that contains the indices of the faces that
|
||||
will be used to compute the current dynamic landmarks.
|
||||
dyn_lmk_b_coords: torch.tensor, dtype = torch.float32
|
||||
A tensor of size BxL that contains the indices of the faces that
|
||||
will be used to compute the current dynamic landmarks.
|
||||
'''
|
||||
|
||||
batch_size = vertices.shape[0]
|
||||
|
||||
aa_pose = torch.index_select(pose.view(batch_size, -1, 3), 1,
|
||||
neck_kin_chain)
|
||||
rot_mats = batch_rodrigues(
|
||||
aa_pose.view(-1, 3), dtype=dtype).view(batch_size, -1, 3, 3)
|
||||
|
||||
rel_rot_mat = torch.eye(3, device=vertices.device,
|
||||
dtype=dtype).unsqueeze_(dim=0)
|
||||
for idx in range(len(neck_kin_chain)):
|
||||
rel_rot_mat = torch.bmm(rot_mats[:, idx], rel_rot_mat)
|
||||
|
||||
y_rot_angle = torch.round(
|
||||
torch.clamp(-rot_mat_to_euler(rel_rot_mat) * 180.0 / np.pi,
|
||||
max=39)).to(dtype=torch.long)
|
||||
neg_mask = y_rot_angle.lt(0).to(dtype=torch.long)
|
||||
mask = y_rot_angle.lt(-39).to(dtype=torch.long)
|
||||
neg_vals = mask * 78 + (1 - mask) * (39 - y_rot_angle)
|
||||
y_rot_angle = (neg_mask * neg_vals +
|
||||
(1 - neg_mask) * y_rot_angle)
|
||||
|
||||
dyn_lmk_faces_idx = torch.index_select(dynamic_lmk_faces_idx,
|
||||
0, y_rot_angle)
|
||||
dyn_lmk_b_coords = torch.index_select(dynamic_lmk_b_coords,
|
||||
0, y_rot_angle)
|
||||
|
||||
return dyn_lmk_faces_idx, dyn_lmk_b_coords
|
||||
|
||||
|
||||
def vertices2landmarks(vertices, faces, lmk_faces_idx, lmk_bary_coords):
|
||||
''' Calculates landmarks by barycentric interpolation
|
||||
|
||||
Parameters
|
||||
----------
|
||||
vertices: torch.tensor BxVx3, dtype = torch.float32
|
||||
The tensor of input vertices
|
||||
faces: torch.tensor Fx3, dtype = torch.long
|
||||
The faces of the mesh
|
||||
lmk_faces_idx: torch.tensor L, dtype = torch.long
|
||||
The tensor with the indices of the faces used to calculate the
|
||||
landmarks.
|
||||
lmk_bary_coords: torch.tensor Lx3, dtype = torch.float32
|
||||
The tensor of barycentric coordinates that are used to interpolate
|
||||
the landmarks
|
||||
|
||||
Returns
|
||||
-------
|
||||
landmarks: torch.tensor BxLx3, dtype = torch.float32
|
||||
The coordinates of the landmarks for each mesh in the batch
|
||||
'''
|
||||
# Extract the indices of the vertices for each face
|
||||
# BxLx3
|
||||
batch_size, num_verts = vertices.shape[:2]
|
||||
device = vertices.device
|
||||
|
||||
lmk_faces = torch.index_select(faces, 0, lmk_faces_idx.view(-1)).view(
|
||||
batch_size, -1, 3)
|
||||
|
||||
lmk_faces += torch.arange(
|
||||
batch_size, dtype=torch.long, device=device).view(-1, 1, 1) * num_verts
|
||||
|
||||
lmk_vertices = vertices.view(-1, 3)[lmk_faces].view(
|
||||
batch_size, -1, 3, 3)
|
||||
|
||||
landmarks = torch.einsum('blfi,blf->bli', [lmk_vertices, lmk_bary_coords])
|
||||
return landmarks
|
||||
|
||||
|
||||
def lbs(betas, pose, v_template, shapedirs, posedirs, J_regressor, parents,
|
||||
lbs_weights, pose2rot=True, dtype=torch.float32):
|
||||
''' Performs Linear Blend Skinning with the given shape and pose parameters
|
||||
|
||||
Parameters
|
||||
----------
|
||||
betas : torch.tensor BxNB
|
||||
The tensor of shape parameters
|
||||
pose : torch.tensor Bx(J + 1) * 3
|
||||
The pose parameters in axis-angle format
|
||||
v_template torch.tensor BxVx3
|
||||
The template mesh that will be deformed
|
||||
shapedirs : torch.tensor 1xNB
|
||||
The tensor of PCA shape displacements
|
||||
posedirs : torch.tensor Px(V * 3)
|
||||
The pose PCA coefficients
|
||||
J_regressor : torch.tensor JxV
|
||||
The regressor array that is used to calculate the joints from
|
||||
the position of the vertices
|
||||
parents: torch.tensor J
|
||||
The array that describes the kinematic tree for the model
|
||||
lbs_weights: torch.tensor N x V x (J + 1)
|
||||
The linear blend skinning weights that represent how much the
|
||||
rotation matrix of each part affects each vertex
|
||||
pose2rot: bool, optional
|
||||
Flag on whether to convert the input pose tensor to rotation
|
||||
matrices. The default value is True. If False, then the pose tensor
|
||||
should already contain rotation matrices and have a size of
|
||||
Bx(J + 1)x9
|
||||
dtype: torch.dtype, optional
|
||||
|
||||
Returns
|
||||
-------
|
||||
verts: torch.tensor BxVx3
|
||||
The vertices of the mesh after applying the shape and pose
|
||||
displacements.
|
||||
joints: torch.tensor BxJx3
|
||||
The joints of the model
|
||||
'''
|
||||
|
||||
batch_size = max(betas.shape[0], pose.shape[0])
|
||||
device = betas.device
|
||||
|
||||
# Add shape contribution
|
||||
v_shaped = v_template + blend_shapes(betas, shapedirs)
|
||||
|
||||
# Get the joints
|
||||
# NxJx3 array
|
||||
J = vertices2joints(J_regressor, v_shaped)
|
||||
|
||||
# 3. Add pose blend shapes
|
||||
# N x J x 3 x 3
|
||||
ident = torch.eye(3, dtype=dtype, device=device)
|
||||
if pose2rot:
|
||||
rot_mats = batch_rodrigues(
|
||||
pose.view(-1, 3), dtype=dtype).view([batch_size, -1, 3, 3])
|
||||
|
||||
pose_feature = (rot_mats[:, 1:, :, :] - ident).view([batch_size, -1])
|
||||
# (N x P) x (P, V * 3) -> N x V x 3
|
||||
pose_offsets = torch.matmul(pose_feature, posedirs) \
|
||||
.view(batch_size, -1, 3)
|
||||
else:
|
||||
pose_feature = pose[:, 1:].view(batch_size, -1, 3, 3) - ident
|
||||
rot_mats = pose.view(batch_size, -1, 3, 3)
|
||||
|
||||
pose_offsets = torch.matmul(pose_feature.view(batch_size, -1),
|
||||
posedirs).view(batch_size, -1, 3)
|
||||
|
||||
v_posed = pose_offsets + v_shaped
|
||||
# 4. Get the global joint location
|
||||
J_transformed, A = batch_rigid_transform(rot_mats, J, parents, dtype=dtype)
|
||||
|
||||
# 5. Do skinning:
|
||||
# W is N x V x (J + 1)
|
||||
W = lbs_weights.unsqueeze(dim=0).expand([batch_size, -1, -1])
|
||||
# (N x V x (J + 1)) x (N x (J + 1) x 16)
|
||||
num_joints = J_regressor.shape[0]
|
||||
T = torch.matmul(W, A.view(batch_size, num_joints, 16)) \
|
||||
.view(batch_size, -1, 4, 4)
|
||||
|
||||
homogen_coord = torch.ones([batch_size, v_posed.shape[1], 1],
|
||||
dtype=dtype, device=device)
|
||||
v_posed_homo = torch.cat([v_posed, homogen_coord], dim=2)
|
||||
v_homo = torch.matmul(T, torch.unsqueeze(v_posed_homo, dim=-1))
|
||||
|
||||
verts = v_homo[:, :, :3, 0]
|
||||
|
||||
return verts, J_transformed
|
||||
|
||||
|
||||
def vertices2joints(J_regressor, vertices):
|
||||
''' Calculates the 3D joint locations from the vertices
|
||||
|
||||
Parameters
|
||||
----------
|
||||
J_regressor : torch.tensor JxV
|
||||
The regressor array that is used to calculate the joints from the
|
||||
position of the vertices
|
||||
vertices : torch.tensor BxVx3
|
||||
The tensor of mesh vertices
|
||||
|
||||
Returns
|
||||
-------
|
||||
torch.tensor BxJx3
|
||||
The location of the joints
|
||||
'''
|
||||
|
||||
return torch.einsum('bik,ji->bjk', [vertices, J_regressor])
|
||||
|
||||
|
||||
def blend_shapes(betas, shape_disps):
|
||||
''' Calculates the per vertex displacement due to the blend shapes
|
||||
|
||||
|
||||
Parameters
|
||||
----------
|
||||
betas : torch.tensor Bx(num_betas)
|
||||
Blend shape coefficients
|
||||
shape_disps: torch.tensor Vx3x(num_betas)
|
||||
Blend shapes
|
||||
|
||||
Returns
|
||||
-------
|
||||
torch.tensor BxVx3
|
||||
The per-vertex displacement due to shape deformation
|
||||
'''
|
||||
|
||||
# Displacement[b, m, k] = sum_{l} betas[b, l] * shape_disps[m, k, l]
|
||||
# i.e. Multiply each shape displacement by its corresponding beta and
|
||||
# then sum them.
|
||||
blend_shape = torch.einsum('bl,mkl->bmk', [betas, shape_disps])
|
||||
return blend_shape
|
||||
|
||||
|
||||
def batch_rodrigues(rot_vecs, epsilon=1e-8, dtype=torch.float32):
|
||||
''' Calculates the rotation matrices for a batch of rotation vectors
|
||||
Parameters
|
||||
----------
|
||||
rot_vecs: torch.tensor Nx3
|
||||
array of N axis-angle vectors
|
||||
Returns
|
||||
-------
|
||||
R: torch.tensor Nx3x3
|
||||
The rotation matrices for the given axis-angle parameters
|
||||
'''
|
||||
|
||||
batch_size = rot_vecs.shape[0]
|
||||
device = rot_vecs.device
|
||||
|
||||
angle = torch.norm(rot_vecs + 1e-8, dim=1, keepdim=True)
|
||||
rot_dir = rot_vecs / angle
|
||||
|
||||
cos = torch.unsqueeze(torch.cos(angle), dim=1)
|
||||
sin = torch.unsqueeze(torch.sin(angle), dim=1)
|
||||
|
||||
# Bx1 arrays
|
||||
rx, ry, rz = torch.split(rot_dir, 1, dim=1)
|
||||
K = torch.zeros((batch_size, 3, 3), dtype=dtype, device=device)
|
||||
|
||||
zeros = torch.zeros((batch_size, 1), dtype=dtype, device=device)
|
||||
K = torch.cat([zeros, -rz, ry, rz, zeros, -rx, -ry, rx, zeros], dim=1) \
|
||||
.view((batch_size, 3, 3))
|
||||
|
||||
ident = torch.eye(3, dtype=dtype, device=device).unsqueeze(dim=0)
|
||||
rot_mat = ident + sin * K + (1 - cos) * torch.bmm(K, K)
|
||||
return rot_mat
|
||||
|
||||
|
||||
def transform_mat(R, t):
|
||||
''' Creates a batch of transformation matrices
|
||||
Args:
|
||||
- R: Bx3x3 array of a batch of rotation matrices
|
||||
- t: Bx3x1 array of a batch of translation vectors
|
||||
Returns:
|
||||
- T: Bx4x4 Transformation matrix
|
||||
'''
|
||||
# No padding left or right, only add an extra row
|
||||
return torch.cat([F.pad(R, [0, 0, 0, 1]),
|
||||
F.pad(t, [0, 0, 0, 1], value=1)], dim=2)
|
||||
|
||||
|
||||
def batch_rigid_transform(rot_mats, joints, parents, dtype=torch.float32):
|
||||
"""
|
||||
Applies a batch of rigid transformations to the joints
|
||||
|
||||
Parameters
|
||||
----------
|
||||
rot_mats : torch.tensor BxNx3x3
|
||||
Tensor of rotation matrices
|
||||
joints : torch.tensor BxNx3
|
||||
Locations of joints
|
||||
parents : torch.tensor BxN
|
||||
The kinematic tree of each object
|
||||
dtype : torch.dtype, optional:
|
||||
The data type of the created tensors, the default is torch.float32
|
||||
|
||||
Returns
|
||||
-------
|
||||
posed_joints : torch.tensor BxNx3
|
||||
The locations of the joints after applying the pose rotations
|
||||
rel_transforms : torch.tensor BxNx4x4
|
||||
The relative (with respect to the root joint) rigid transformations
|
||||
for all the joints
|
||||
"""
|
||||
|
||||
joints = torch.unsqueeze(joints, dim=-1)
|
||||
|
||||
rel_joints = joints.clone()
|
||||
rel_joints[:, 1:] -= joints[:, parents[1:]]
|
||||
|
||||
# transforms_mat = transform_mat(
|
||||
# rot_mats.view(-1, 3, 3),
|
||||
# rel_joints.view(-1, 3, 1)).view(-1, joints.shape[1], 4, 4)
|
||||
transforms_mat = transform_mat(
|
||||
rot_mats.view(-1, 3, 3),
|
||||
rel_joints.reshape(-1, 3, 1)).reshape(-1, joints.shape[1], 4, 4)
|
||||
|
||||
transform_chain = [transforms_mat[:, 0]]
|
||||
for i in range(1, parents.shape[0]):
|
||||
# Subtract the joint location at the rest pose
|
||||
# No need for rotation, since it's identity when at rest
|
||||
curr_res = torch.matmul(transform_chain[parents[i]],
|
||||
transforms_mat[:, i])
|
||||
transform_chain.append(curr_res)
|
||||
|
||||
transforms = torch.stack(transform_chain, dim=1)
|
||||
|
||||
# The last column of the transformations contains the posed joints
|
||||
posed_joints = transforms[:, :, :3, 3]
|
||||
|
||||
# The last column of the transformations contains the posed joints
|
||||
posed_joints = transforms[:, :, :3, 3]
|
||||
|
||||
joints_homogen = F.pad(joints, [0, 0, 0, 1])
|
||||
|
||||
rel_transforms = transforms - F.pad(
|
||||
torch.matmul(transforms, joints_homogen), [3, 0, 0, 0, 0, 0, 0, 0])
|
||||
|
||||
return posed_joints, rel_transforms
|
||||
@@ -0,0 +1,187 @@
|
||||
'''ResNet in PyTorch.
|
||||
For Pre-activation ResNet, see 'preact_resnet.py'.
|
||||
Reference:
|
||||
[1] Kaiming He, Xiangyu Zhang, Shaoqing Ren, Jian Sun
|
||||
Deep Residual Learning for Image Recognition. arXiv:1512.03385
|
||||
'''
|
||||
|
||||
import torch
|
||||
import torch.nn as nn
|
||||
import torch.nn.functional as F
|
||||
|
||||
def debug(opt=None, msg="", verbose=False):
|
||||
if opt is None:
|
||||
if verbose: print(msg)
|
||||
|
||||
elif opt.DEBUG or verbose:
|
||||
print(msg)
|
||||
|
||||
|
||||
|
||||
class BasicBlock(nn.Module):
|
||||
expansion = 1
|
||||
def __init__(self, in_planes, planes, stride=1):
|
||||
super(BasicBlock, self).__init__()
|
||||
self.conv1 = nn.Conv2d(in_planes, planes, kernel_size=(3,1), stride=(stride,1), padding=(1,0), bias=False)
|
||||
self.bn1 = nn.BatchNorm2d(planes)
|
||||
|
||||
self.conv2 = nn.Conv2d(planes, planes, kernel_size=(3,1), stride=(1,1), padding=(1,0), bias=False)
|
||||
self.bn2 = nn.BatchNorm2d(planes)
|
||||
|
||||
self.shortcut = nn.Sequential()
|
||||
if stride != 1 or in_planes != self.expansion*planes:
|
||||
self.shortcut = nn.Sequential(
|
||||
nn.Conv2d(in_planes, self.expansion*planes, kernel_size=(1,1), stride=(stride,1), bias=False),
|
||||
nn.BatchNorm2d(self.expansion*planes)
|
||||
)
|
||||
|
||||
def forward(self, x):
|
||||
out = F.relu(self.bn1(self.conv1(x)))
|
||||
out = self.bn2(self.conv2(out))
|
||||
out += self.shortcut(x)
|
||||
out = F.relu(out)
|
||||
return out
|
||||
|
||||
class Bottleneck(nn.Module):
|
||||
expansion = 4
|
||||
|
||||
def __init__(self, in_planes, planes, stride=1):
|
||||
super(Bottleneck, self).__init__()
|
||||
self.conv1 = nn.Conv2d(in_planes, planes, kernel_size=(1,1), bias=False)
|
||||
self.bn1 = nn.BatchNorm2d(planes)
|
||||
|
||||
self.conv2 = nn.Conv2d(planes, planes, kernel_size=(3,1), stride=(stride,1), padding=(1,0), bias=False)
|
||||
self.bn2 = nn.BatchNorm2d(planes)
|
||||
|
||||
self.conv3 = nn.Conv2d(planes, self.expansion * planes, kernel_size=(1,1), bias=False)
|
||||
self.bn3 = nn.BatchNorm2d(self.expansion*planes)
|
||||
|
||||
self.shortcut = nn.Sequential()
|
||||
if stride != 1 or in_planes != self.expansion*planes:
|
||||
self.shortcut = nn.Sequential(
|
||||
nn.Conv2d(in_planes, self.expansion*planes, kernel_size=(1,1), stride=(stride,1), bias=False),
|
||||
nn.BatchNorm2d(self.expansion*planes)
|
||||
)
|
||||
|
||||
def forward(self, x):
|
||||
out = F.relu(self.bn1(self.conv1(x)))
|
||||
out = F.relu(self.bn2(self.conv2(out)))
|
||||
out = self.bn3(self.conv3(out))
|
||||
out += self.shortcut(x)
|
||||
out = F.relu(out)
|
||||
return out
|
||||
|
||||
|
||||
class ResNet(nn.Module):
|
||||
def __init__(self, block, num_blocks, num_input=3, num_classes=10):
|
||||
super(ResNet, self).__init__()
|
||||
self.in_planes = 64
|
||||
|
||||
self.conv1 = nn.Conv2d(num_input, 64, kernel_size=(3,1), stride=(1,1), padding=(1,0), bias=False)
|
||||
self.bn1 = nn.BatchNorm2d(64)
|
||||
self.avgpool = nn.AvgPool2d(kernel_size=(2,1))
|
||||
|
||||
self.layer1 = self._make_layer(block, 64, num_blocks[0], stride=1)
|
||||
self.layer2 = self._make_layer(block, 128, num_blocks[1], stride=2)
|
||||
self.layer3 = self._make_layer(block, 256, num_blocks[2], stride=2)
|
||||
self.layer4 = self._make_layer(block, 512, num_blocks[3], stride=2)
|
||||
self.linear = nn.Linear(512*block.expansion, num_classes)
|
||||
|
||||
def _make_layer(self, block, planes, num_blocks, stride):
|
||||
strides = [stride] + [1]*(num_blocks-1)
|
||||
layers = []
|
||||
for stride in strides:
|
||||
layers.append(block(self.in_planes, planes, stride))
|
||||
self.in_planes = planes * block.expansion
|
||||
return nn.Sequential(*layers)
|
||||
|
||||
def get_features(self, x):
|
||||
out = F.relu(self.bn1(self.conv1(x)))
|
||||
# debug(msg=f"[forward] conv1 shape = {out.shape}", verbose=True)
|
||||
|
||||
out = self.layer1(out)
|
||||
# debug(msg=f"[forward] layer1 shape = {out.shape}", verbose=True)
|
||||
|
||||
out = self.layer2(out)
|
||||
# debug(msg=f"[forward] layer2 shape = {out.shape}", verbose=True)
|
||||
|
||||
out = self.layer3(out)
|
||||
# debug(msg=f"[forward] layer3 shape = {out.shape}", verbose=True)
|
||||
|
||||
out = self.layer4(out)
|
||||
# debug(msg=f"[forward] layer4 shape = {out.shape}", verbose=True)
|
||||
|
||||
# out = F.avg_pool2d(out, 2)
|
||||
out = self.avgpool(out)
|
||||
# debug(msg=f"[forward] avg shape = {out.shape}", verbose=True)
|
||||
|
||||
out = out.view(out.size(0), -1)
|
||||
# debug(msg=f"[forward] view shape = {out.shape}", verbose=True)
|
||||
|
||||
return out
|
||||
|
||||
|
||||
def forward(self, x):
|
||||
# debug(msg=f"[forward] input x shape = {x.shape}", verbose=True)
|
||||
|
||||
out = F.relu(self.bn1(self.conv1(x)))
|
||||
# debug(msg=f"[forward] conv1 shape = {out.shape}", verbose=True)
|
||||
|
||||
out = self.layer1(out)
|
||||
# debug(msg=f"[forward] layer1 shape = {out.shape}", verbose=True)
|
||||
|
||||
out = self.layer2(out)
|
||||
# debug(msg=f"[forward] layer2 shape = {out.shape}", verbose=True)
|
||||
|
||||
out = self.layer3(out)
|
||||
# debug(msg=f"[forward] layer3 shape = {out.shape}", verbose=True)
|
||||
|
||||
out = self.layer4(out)
|
||||
# debug(msg=f"[forward] layer4 shape = {out.shape}", verbose=True)
|
||||
|
||||
# out = F.avg_pool2d(out, 2)
|
||||
out = self.avgpool(out)
|
||||
# debug(msg=f"[forward] avg shape = {out.shape}", verbose=True)
|
||||
|
||||
out = out.view(out.size(0), -1)
|
||||
# debug(msg=f"[forward] view shape = {out.shape}", verbose=True)
|
||||
|
||||
out = self.linear(out)
|
||||
# debug(msg=f"[forward] output shape = {out.shape}", verbose=True)
|
||||
|
||||
return out
|
||||
|
||||
|
||||
def ResNet18(num_input=3, num_classes=10):
|
||||
return ResNet(BasicBlock, [2, 2, 2, 2], num_input=num_input, num_classes=num_classes)
|
||||
|
||||
|
||||
def ResNet34(num_input=3, num_classes=10):
|
||||
return ResNet(BasicBlock, [3, 4, 6, 3], num_input=num_input, num_classes=num_classes)
|
||||
|
||||
|
||||
def ResNet50(num_input=3, num_classes=10):
|
||||
return ResNet(Bottleneck, [3, 4, 6, 3], num_input=num_input, num_classes=num_classes)
|
||||
|
||||
|
||||
def ResNet101(num_input=3, num_classes=10):
|
||||
return ResNet(Bottleneck, [3, 4, 23, 3], num_input=num_input, num_classes=num_classes)
|
||||
|
||||
|
||||
# def ResNet101():
|
||||
# return ResNet(Bottleneck, [3, 4, 23, 3])
|
||||
|
||||
def ResNet152():
|
||||
return ResNet(Bottleneck, [3, 8, 36, 3])
|
||||
|
||||
|
||||
def test():
|
||||
net = ResNet50(num_input=1024, num_classes=256)
|
||||
# y = net(torch.randn(1, 3, 32, 32))
|
||||
|
||||
# y = net(torch.randn(1, 1024, 16, 1))
|
||||
y = net.get_features(torch.randn(1, 1024, 16, 1))
|
||||
|
||||
print(y.size())
|
||||
|
||||
# test()
|
||||
Reference in new issue
Block a user