beta add render
This commit is contained in:
1 parent
83f99d9ec5
commit
b4c197a8ac
30 files changed
+3210
-235
No files matched your search
@@ -1,5 +1,4 @@
|
||||
import torch
|
||||
import torch.nn as nn
|
||||
import logging
|
||||
|
||||
def init_weights(net, init_type='normal', init_gain=0.02):
|
||||
@@ -18,22 +17,22 @@ def init_weights(net, init_type='normal', init_gain=0.02):
|
||||
#print(classname, hasattr(m, 'weight'),)
|
||||
if hasattr(m, 'weight') and (classname.find('Conv') != -1 or classname.find('Linear') != -1):
|
||||
if init_type == 'normal':
|
||||
nn.init.normal_(m.weight.data, 0.0, init_gain)
|
||||
torch.nn.init.normal_(m.weight.data, 0.0, init_gain)
|
||||
elif init_type == 'xavier':
|
||||
nn.init.xavier_normal_(m.weight.data, gain=init_gain)
|
||||
torch.nn.init.xavier_normal_(m.weight.data, gain=init_gain)
|
||||
elif init_type == 'kaiming':
|
||||
nn.init.kaiming_normal_(m.weight.data, a=0, mode='fan_in')
|
||||
torch.nn.init.kaiming_normal_(m.weight.data, a=0, mode='fan_in')
|
||||
elif init_type == 'orthogonal':
|
||||
nn.init.orthogonal_(m.weight.data, gain=init_gain)
|
||||
torch.nn.init.orthogonal_(m.weight.data, gain=init_gain)
|
||||
else:
|
||||
raise NotImplementedError('initialization method [%s] is not implemented' % init_type)
|
||||
|
||||
if hasattr(m, 'bias') and m.bias is not None:
|
||||
nn.init.constant_(m.bias.data, 0.0)
|
||||
torch.nn.init.constant_(m.bias.data, 0.0)
|
||||
|
||||
elif classname.find('BatchNorm2d') != -1: # BatchNorm Layer's weight is not a matrix; only normal distribution applies.
|
||||
nn.init.normal_(m.weight.data, 1.0, init_gain)
|
||||
nn.init.constant_(m.bias.data, 0.0)
|
||||
torch.nn.init.normal_(m.weight.data, 1.0, init_gain)
|
||||
torch.nn.init.constant_(m.bias.data, 0.0)
|
||||
|
||||
logging.info('initialize network with %s' % init_type)
|
||||
net.apply(init_func) # apply the initialization function <init_func>
|
||||
|
||||
@@ -1,72 +0,0 @@
|
||||
import torch
|
||||
import torch.nn as nn
|
||||
import logging
|
||||
|
||||
from .encoders import ResnetEncoder, VOCAEncoder
|
||||
from ..mesh.FLAME import FLAME, FLAMETex
|
||||
|
||||
|
||||
class Audio2Coeff(nn.Module):
|
||||
|
||||
def __init__(self, opt, opt_FLAME):
|
||||
super(Audio2Coeff, self).__init__()
|
||||
|
||||
self.opt = opt
|
||||
self.dim_motion = opt.dim_motion # 53
|
||||
self.dim_speech = opt.dim_speech # 29
|
||||
self.dim_hidden = opt.dim_hidden # 256
|
||||
|
||||
# creat model
|
||||
self.driven = VOCAEncoder(outsize=self.dim_motion)
|
||||
self.flame = FLAME(opt_FLAME)
|
||||
|
||||
# setup render
|
||||
|
||||
def _setup_renderer(self, model_cfg):
|
||||
set_rasterizer(self.cfg.rasterizer_type)
|
||||
self.render = SRenderY(self.image_size, obj_filename=model_cfg.topology_path, uv_size=model_cfg.uv_size, rasterizer_type=self.cfg.rasterizer_type).to(self.device)
|
||||
|
||||
# face mask for rendering details
|
||||
mask = imread(model_cfg.face_eye_mask_path).astype(np.float32)/255.; mask = torch.from_numpy(mask[:,:,0])[None,None,:,:].contiguous()
|
||||
self.uv_face_eye_mask = F.interpolate(mask, [model_cfg.uv_size, model_cfg.uv_size]).to(self.device)
|
||||
mask = imread(model_cfg.face_mask_path).astype(np.float32)/255.; mask = torch.from_numpy(mask[:,:,0])[None,None,:,:].contiguous()
|
||||
self.uv_face_mask = F.interpolate(mask, [model_cfg.uv_size, model_cfg.uv_size]).to(self.device)
|
||||
# displacement correction
|
||||
fixed_dis = np.load(model_cfg.fixed_displacement_path)
|
||||
self.fixed_uv_dis = torch.tensor(fixed_dis).float().to(self.device)
|
||||
# mean texture
|
||||
mean_texture = imread(model_cfg.mean_tex_path).astype(np.float32)/255.; mean_texture = torch.from_numpy(mean_texture.transpose(2,0,1))[None,:,:,:].contiguous()
|
||||
self.mean_texture = F.interpolate(mean_texture, [model_cfg.uv_size, model_cfg.uv_size]).to(self.device)
|
||||
# dense mesh template, for save detail mesh
|
||||
self.dense_template = np.load(model_cfg.dense_template_path, allow_pickle=True, encoding='latin1').item()
|
||||
|
||||
|
||||
|
||||
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)
|
||||
logging.debug(f"[forward] input x shape = {x.shape}")
|
||||
|
||||
# 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)
|
||||
logging.debug(f"[forward] transpose x shape = {x.shape}")
|
||||
|
||||
feat = self.encoder(x) # (B * nseq, 50)
|
||||
logging.debug(f"[forward] encoder shape = {feat.shape}")
|
||||
|
||||
pred = self.decoder(feat) # (B * nseq, dim_motion)
|
||||
logging.debug(f"[forward] decoder shape = {pred.shape}")
|
||||
|
||||
pred = pred.reshape(nbatch, nseqlen, -1) # (B, nseq, dim_motion)
|
||||
logging.debug(f"[forward] reshape shape = {pred.shape}")
|
||||
|
||||
|
||||
return pred
|
||||
|
||||
|
||||
@@ -0,0 +1,89 @@
|
||||
import torch
|
||||
import torch.nn as nn
|
||||
import logging
|
||||
|
||||
class Audio2Motion(nn.Module):
|
||||
|
||||
def __init__(self, nc_motion, nc_condit):
|
||||
super(Audio2Motion, self).__init__()
|
||||
|
||||
self.nc_motion = nc_motion # 53
|
||||
self.nc_condit = nc_condit # 29
|
||||
|
||||
# creat model
|
||||
self.encoder = nn.Sequential( # (nbatch, nchannel=29, H=16, W=1)
|
||||
nn.BatchNorm2d(self.nc_condit),
|
||||
|
||||
# block 1
|
||||
nn.Conv2d(self.nc_condit, 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=128) # 50,
|
||||
)
|
||||
|
||||
# output
|
||||
self.decoder = nn.Sequential(
|
||||
nn.Linear(in_features=128, out_features=self.nc_motion),
|
||||
)
|
||||
|
||||
|
||||
def forward(self, x):
|
||||
""" forward function
|
||||
Args:
|
||||
x: torch.Tensor, [B x nwind x dim_condit]
|
||||
return:
|
||||
pred: torch.Tensor, [B x nc_motion]
|
||||
"""
|
||||
logging.debug(f"[forward] input x shape = {x.shape}")
|
||||
|
||||
# remember high dimenstion
|
||||
shape_dims = x.shape
|
||||
if len(shape_dims) > 3:
|
||||
x = x.reshape(-1, x.shape[-2], x.shape[-1])
|
||||
|
||||
# preprocessing data
|
||||
x = x.unsqueeze(dim=1).transpose(1,3) # (B, 1, W, nc_motion) --> (B, nc_motion, W, 1)
|
||||
logging.debug(f"[forward] transpose x shape = {x.shape}")
|
||||
|
||||
feat = self.encoder(x) # (B, 50)
|
||||
logging.debug(f"[forward] encoder shape = {feat.shape}")
|
||||
|
||||
pred = self.decoder(feat) # (B, nc_motion)
|
||||
logging.debug(f"[forward] decoder shape = {pred.shape}")
|
||||
|
||||
# recover high dimension
|
||||
if len(shape_dims) > 3:
|
||||
pred = pred.reshape(list(shape_dims[:-2]) + list(pred.shape[1:]))
|
||||
|
||||
logging.debug(f"[forward] reshape shape = {pred.shape}")
|
||||
return pred
|
||||
|
||||
|
||||
@@ -24,7 +24,7 @@ from src.mesh import util
|
||||
from src.utils.animation import write_video, write_video_with_gt
|
||||
|
||||
|
||||
class Audio2CoeffModel(LightningModule):
|
||||
class Audio2RenderModel(LightningModule):
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
@@ -61,23 +61,26 @@ class Audio2CoeffModel(LightningModule):
|
||||
# init netG
|
||||
init_weights(self.netG, init_type='kaiming')
|
||||
|
||||
# init last layer
|
||||
init_exp_weight = np.load(opt.path_init_expression_basis)
|
||||
init_exp_weight = torch.from_numpy(init_exp_weight).float() #.to(self.device)
|
||||
init_exp_weight = init_exp_weight[:, :50]
|
||||
self.netG.decoder_mesh.weight.data = init_exp_weight
|
||||
logging.info(f"init_exp_weight shape = {init_exp_weight.shape}")
|
||||
# # init last layer
|
||||
# init_exp_weight = np.load(opt.path_init_expression_basis)
|
||||
# init_exp_weight = torch.from_numpy(init_exp_weight).float() #.to(self.device)
|
||||
# init_exp_weight = init_exp_weight[:, :50]
|
||||
# self.netG.decoder_mesh.weight.data = init_exp_weight
|
||||
# logging.info(f"init_exp_weight shape = {init_exp_weight.shape}")
|
||||
|
||||
|
||||
# load mean
|
||||
path_deca_mean = self.opt.path_mean_dict
|
||||
self.mean_dict = np.load(path_deca_mean, allow_pickle=True).item()
|
||||
|
||||
# save mean shape
|
||||
self.register_buffer("mean_shape", torch.from_numpy(self.mean_dict["shape"].reshape(1, 1, 100))) # (1,1,100)
|
||||
|
||||
|
||||
# get template (with specific avator)
|
||||
temp_verts, temp_ldmk2d, temp_ldmk3d = self.get_template_vertices() # verts: (1 x 1 x 5023 x 3), ldmk: (1 x 1 x 68 x 3)
|
||||
temp_verts, temp_ldmk2d, temp_ldmk3d = self.get_template_vertices() # verts: (1 x 1 x 5023 x 3), ldmk: (1 x 1 x 68 x 3)
|
||||
temp_verts_specific, temp_ldmk2d_specific, temp_ldmk3d_specific \
|
||||
= self.get_template_vertices(self.mean_dict) # verts: (1 x 1 x 5023 x 3), ldmk: (1 x 1 x 68 x 3)
|
||||
|
||||
self.register_buffer("temp_verts", temp_verts)
|
||||
self.register_buffer("temp_verts_specific", temp_verts_specific)
|
||||
|
||||
@@ -86,8 +89,8 @@ class Audio2CoeffModel(LightningModule):
|
||||
vertices_weight[:, :, flame_mouth_idx, :] = 10
|
||||
self.register_buffer("vertices_weight", vertices_weight)
|
||||
|
||||
landmarks_weight = self._set_landmark68_weight()
|
||||
self.register_buffer("landmarks_weight", landmarks_weight)
|
||||
landmark_weight = self._set_landmark68_weight()
|
||||
self.register_buffer("landmark_weight", landmark_weight)
|
||||
|
||||
# loss function
|
||||
self.loss_func_wing = WingLoss(reduction="none") # return (B, )
|
||||
@@ -166,14 +169,18 @@ class Audio2CoeffModel(LightningModule):
|
||||
param.requires_grad = False
|
||||
|
||||
# face mask for rendering details
|
||||
mask = imread(opt_netR.face_eye_mask_path).astype(np.float32)/255.
|
||||
mask = torch.from_numpy(mask[:,:,0])[None,None,:,:].contiguous()
|
||||
uv_face_eye_mask = F.interpolate(mask, [opt_netR.uv_size, opt_netR.uv_size])
|
||||
mask = imread(opt_netR.face_eye_mask_path).astype(np.float32)/255.
|
||||
mask = torch.from_numpy(mask[:,:,0])[None,None,:,:].contiguous() # (1, 1, 256, 256)
|
||||
uv_face_eye_mask = F.interpolate(mask, [opt_netR.uv_size, opt_netR.uv_size]) # (1, 1, 512, 512)
|
||||
# mask = torch.from_numpy(mask[:,:,0])[None, None,None,:,:].contiguous() # (1, 1, 1, 256, 256)
|
||||
# uv_face_eye_mask = F.interpolate(mask, [1, opt_netR.uv_size, opt_netR.uv_size]) # (1, 1, 1, 512, 512)
|
||||
self.register_buffer("uv_face_eye_mask", uv_face_eye_mask)
|
||||
|
||||
mask = imread(opt_netR.face_mask_path).astype(np.float32)/255.
|
||||
mask = torch.from_numpy(mask[:,:,0])[None,None,:,:].contiguous()
|
||||
uv_face_mask = F.interpolate(mask, [opt_netR.uv_size, opt_netR.uv_size])
|
||||
# mask = torch.from_numpy(mask[:,:,0])[None,None,:,:].contiguous() # (1, 1, 256, 256)
|
||||
# uv_face_mask = F.interpolate(mask, [opt_netR.uv_size, opt_netR.uv_size]) # (1, 1, 512, 512)
|
||||
mask = torch.from_numpy(mask[:,:,0])[None, None,None,:,:].contiguous() # (1, 1, 1, 256, 256)
|
||||
uv_face_mask = F.interpolate(mask, [1, opt_netR.uv_size, opt_netR.uv_size]) # (1, 1, 1, 512, 512)
|
||||
self.register_buffer("uv_face_mask", uv_face_mask)
|
||||
|
||||
# # displacement correction
|
||||
@@ -183,10 +190,14 @@ class Audio2CoeffModel(LightningModule):
|
||||
|
||||
# mean texture
|
||||
mean_texture = imread(opt_netR.mean_tex_path).astype(np.float32)/255.
|
||||
mean_texture = torch.from_numpy(mean_texture.transpose(2,0,1))[None,:,:,:].contiguous()
|
||||
mean_texture = F.interpolate(mean_texture, [opt_netR.uv_size, opt_netR.uv_size])
|
||||
mean_texture = torch.from_numpy(mean_texture.transpose(2,0,1))[None,None, :,:,:].contiguous() # (1, 1, 1, 256, 256)
|
||||
mean_texture = F.interpolate(mean_texture, [1, opt_netR.uv_size, opt_netR.uv_size]) # (1, 1, 1, 512, 512)
|
||||
self.register_buffer("mean_texture", mean_texture)
|
||||
|
||||
|
||||
debug(f"uv_face_eye_mask = {uv_face_eye_mask.shape}, uv_face_mask={uv_face_mask.shape},mean_texture={mean_texture.shape}")
|
||||
|
||||
|
||||
# # dense mesh template, for save detail mesh
|
||||
# self.dense_template = np.load(opt_netR.dense_template_path, allow_pickle=True, encoding='latin1').item()
|
||||
|
||||
@@ -233,34 +244,9 @@ class Audio2CoeffModel(LightningModule):
|
||||
|
||||
@torch.no_grad()
|
||||
def set_input(self, batch:Any):
|
||||
|
||||
# logging.info(f"\n[set_input] self.device = {self.device}")
|
||||
|
||||
# motion data
|
||||
data = batch["data"].float() # (B, nsteps, nc_motion)
|
||||
debug(f"data = {data.shape}, dtype={data.dtype}", verbose=False)
|
||||
|
||||
|
||||
images = batch['image'] # [B, nsteps, 3, size, size] ==> [BxK, 3, size, size]
|
||||
images = images.view(-1, images.shape[-3], images.shape[-2], images.shape[-1])
|
||||
lmk = batch['landmark'] # [B, nsteps, 3, size, size] ==> [BxK, 3, size, size]
|
||||
lmk = lmk.view(-1, lmk.shape[-2], lmk.shape[-1])
|
||||
masks = batch['mask'] # [B, nsteps, 3, size, size] ==> [BxK, 3, size, size]
|
||||
masks = masks.view(-1, images.shape[-2], images.shape[-1])
|
||||
|
||||
# batch information
|
||||
batch_info = {
|
||||
"vid": batch['vid'],
|
||||
"nframe": batch['nframe'],
|
||||
"interv": batch['frame_interval'],
|
||||
"images": images,
|
||||
"lmk": lmk,
|
||||
"masks": masks
|
||||
}
|
||||
|
||||
# speech data
|
||||
cond = None
|
||||
raw_speech = batch["cond"].cpu().numpy() # (B, nsegments)
|
||||
# processing speech feature
|
||||
raw_speech = batch["data_audio"].cpu().numpy() # (B, nsegments)
|
||||
debug(f"raw_speech = {raw_speech.shape}, dtype={raw_speech.dtype}", verbose=False)
|
||||
|
||||
# padding half frame length for bed and end
|
||||
@@ -269,103 +255,122 @@ class Audio2CoeffModel(LightningModule):
|
||||
debug(f"after padding raw_speech = {raw_speech.shape}, dtype={raw_speech.dtype}", verbose=False)
|
||||
|
||||
inputs = self.processor(list(raw_speech), sampling_rate=16000, return_tensors="pt")
|
||||
cond = self.netW(**inputs.to(self.device)).last_hidden_state # B x nsteps x nc_feat
|
||||
debug(f"cond = {cond.shape}, dtype={cond.dtype}, device={cond.device}", verbose=False)
|
||||
audio_feat = self.netW(**inputs.to(self.device)).last_hidden_state # B x nsteps x nc_feat
|
||||
debug(f"audio_feat = {audio_feat.shape}, dtype={audio_feat.dtype}, device={audio_feat.device}", verbose=False)
|
||||
|
||||
# unfold speech data
|
||||
cond = cond.unfold(dimension=1, size=16, step=1) # (B, nseqs, nc_codit, 16)
|
||||
cond = cond.permute(0, 1, 3, 2) # (B, nseqs, 16, nc_condit)
|
||||
audio_feat = audio_feat.unfold(dimension=1, size=16, step=1) # (B, N, nc_codit, 16)
|
||||
audio_feat = audio_feat.permute(0, 1, 3, 2) # (B, N, 16, nc_condit)
|
||||
B, N, W, nc_condit = audio_feat.size()
|
||||
|
||||
# setup
|
||||
self.cond = cond
|
||||
self.B, self.nsteps, self.nwind, self.dim_speech = cond.size()
|
||||
data = data[:, 7:7+self.nsteps, :]
|
||||
self.vert, self.ldmk2d, self.ldmk3d = self.get_vertices(data)
|
||||
# setup raw-speech
|
||||
idx_segmt_beg = int(7 * self.opt.sr / self.opt.fps + 0.5)
|
||||
idx_segmt_end = int((7 + N) * self.opt.sr / self.opt.fps + 0.5)
|
||||
raw_speech = raw_speech[:, idx_segmt_beg: idx_segmt_end] # (B, nsteps * sr / fps)
|
||||
|
||||
# cut audio clips
|
||||
idx_beg = int(7 * self.opt.sr / self.opt.fps + 0.5)
|
||||
idx_end = int((7 + self.nsteps) * self.opt.sr / self.opt.fps + 0.5)
|
||||
self.raw_speech = raw_speech[:, idx_beg: idx_end] # (B, nsteps * sr / fps)
|
||||
# setup others data
|
||||
data_coeff = batch["data_coeff"][:, 7:7+N] # (B, N, nc_coeff)
|
||||
data_frame = batch['data_frame'][:, 7:7+N] # [B, N, 3, 512, 512]
|
||||
data_mask = batch['data_mask'][:, 7:7+N] # [B, N, 512, 512]
|
||||
data_ldmk = batch['data_ldmk'][:, 7:7+N] # [B, N, 68, 2]
|
||||
|
||||
debug(f"[set_input] vert = {self.vert.shape}, dtype={self.vert.dtype}, device={self.vert.device}", verbose=False)
|
||||
debug(f"[set_input] cond = {self.cond.shape}, dtype={self.cond.dtype}, device={self.cond.device}", verbose=False)
|
||||
debug(f"[set_input] ldmk2d = {self.ldmk2d.shape}, dtype={self.ldmk2d.dtype}, device={self.ldmk2d.device}", verbose=False)
|
||||
debug(f"[set_input] ldmk3d = {self.ldmk3d.shape}, dtype={self.ldmk3d.dtype}, device={self.ldmk3d.device}", verbose=False)
|
||||
# update batch information
|
||||
batch["data_audio"] = audio_feat # (B, N, 16, nc_condit)
|
||||
batch["data_frame"] = data_frame # [B, N, 3, 512, 512]
|
||||
batch["data_mask"] = data_mask # [B, N, 512, 512]
|
||||
batch["data_ldmk"] = data_ldmk # [B, N, 68, 2]
|
||||
batch["data_coeff"] = data_coeff # (B, N, 236)
|
||||
batch["raw_speech"] = raw_speech # (B, N * sr / fps)
|
||||
|
||||
return self.cond, self.vert, batch_info
|
||||
debug(f"[set_input] audio_feat = {audio_feat.shape}, dtype={audio_feat.dtype}, device={audio_feat.device}", verbose=False)
|
||||
debug(f"[set_input] data_frame = {data_frame.shape}, dtype={data_frame.dtype}, device={data_frame.device}", verbose=False)
|
||||
debug(f"[set_input] data_mask = {data_mask.shape}, dtype={data_mask.dtype}, device={data_mask.device}", verbose=False)
|
||||
debug(f"[set_input] data_ldmk = {data_ldmk.shape}, dtype={data_ldmk.dtype}, device={data_ldmk.device}", verbose=False)
|
||||
debug(f"[set_input] data_coeff = {data_coeff.shape}, dtype={data_coeff.dtype}, device={data_coeff.device}", verbose=False)
|
||||
debug(f"[set_input] raw_speech = {raw_speech.shape}, dtype={raw_speech.dtype}", verbose=False)
|
||||
|
||||
return B, N, batch
|
||||
|
||||
|
||||
def forward(self, x:torch.Tensor):
|
||||
return self.netG(x)
|
||||
pass
|
||||
|
||||
|
||||
def step(self, batch:Any, return_vis:bool=False):
|
||||
def step(self, batch:Any):
|
||||
|
||||
batch_x, batch_tgt, batch_info = self.set_input(batch)
|
||||
B, N = batch_x.size(0), batch_x.size(1) # get batch_size
|
||||
B, N, batch_set = self.set_input(batch)
|
||||
|
||||
batch_x = batch_set["data_audio"] # (B, N, 16, nc_condit)
|
||||
batch_pdt = self.netG(batch_x) # (B, N, nc_motion=53)
|
||||
debug(f"batch_pdt = {batch_pdt.shape}")
|
||||
|
||||
# get exp + pos
|
||||
batch_pdt = self.netG(batch_x) # B*N x dim_motion
|
||||
|
||||
# prepare codedict for render
|
||||
codedict = {}
|
||||
codedict["exp"] = batch_pdt['exp'] # from predict
|
||||
codedict["pos"] = batch_pdt['pos'] # from predict
|
||||
codedict["exp"] = batch_pdt[:, :, :50] # (B, N, 50), from predict
|
||||
codedict["shape"] = self.mean_shape.expand(B, N, -1) # (B, N, 100), use mean shape, NOT GT
|
||||
codedict["tex"] = batch_set['data_coeff'][:, :, 100:150] # (B, N, 50), from GT
|
||||
codedict["cam"] = batch_set['data_coeff'][:, :, 206:209] # (B, N, 3), from GT
|
||||
codedict["light"] = batch_set['data_coeff'][:, :, 209:236].reshape(B, N, 9, 3) # (B, N, 9, 3), from GT
|
||||
codedict["pose"]= torch.cat([ # (B, N, 6), from GT & predict
|
||||
batch_set['data_coeff'][:, :, 150:153], # head pose, from GT
|
||||
batch_pdt[:, :, 50:53], # mouth pose, from predict result
|
||||
], dim=2)
|
||||
|
||||
codedict["shape"] = batch_info['shape'] # from ** mean ** shape
|
||||
codedict["tex"] = batch_info['tex'] # from predict
|
||||
codedict["cam"] = batch_info['cam'] # from predict
|
||||
codedict["pose"] = batch_info['pose'] # from predict
|
||||
codedict["light"] = batch_info['light'] # from predict
|
||||
|
||||
#
|
||||
# get geometry vertice
|
||||
verts, landmarks2d, landmarks3d = self.netF(
|
||||
verts, landmarks2d, landmarks3d = self.netF( # (B, N, 5023, 3), (B,N,68,3), (B,N,68,3)
|
||||
shape_params=codedict['shape'], expression_params=codedict['exp'], pose_params=codedict['pose'])
|
||||
debug(f"verts = {verts.shape},landmarks2d={landmarks2d.shape}, landmarks3d = {landmarks3d.shape}")
|
||||
|
||||
# get albedo texture
|
||||
albedo = self.netT(codedict['tex'])
|
||||
albedo = self.netT(codedict['tex']) # (B, N, 3, 512, 512)
|
||||
debug(f"albedo = {albedo.shape}")
|
||||
|
||||
## projection with camera (2D landmarks, 3D landmarks, verts)
|
||||
landmarks3d_world = landmarks3d.clone()
|
||||
landmarks2d = util.batch_orth_proj(landmarks2d, codedict['cam'])[:,:,:2]
|
||||
landmarks2d[:,:,1:] = -landmarks2d[:,:,1:]
|
||||
landmarks2d = util.batch_orth_proj(landmarks2d, codedict['cam'])[..., :2]
|
||||
landmarks2d[..., 1:] = -landmarks2d[..., 1:]
|
||||
|
||||
landmarks3d = util.batch_orth_proj(landmarks3d, codedict['cam'])
|
||||
landmarks3d[:,:,1:] = -landmarks3d[:,:,1:]
|
||||
landmarks3d[..., 1:] = -landmarks3d[..., 1:]
|
||||
|
||||
trans_verts = util.batch_orth_proj(verts, codedict['cam'])
|
||||
trans_verts[:,:,1:] = -trans_verts[:,:,1:]
|
||||
trans_verts[..., 1:] = -trans_verts[..., 1:]
|
||||
|
||||
# render to image
|
||||
ops = self.netR(verts, trans_verts, albedo, codedict['light'])
|
||||
|
||||
|
||||
## output
|
||||
opdict = {
|
||||
'images': batch_info['images'],
|
||||
'lmk': batch_info['lmk'],
|
||||
'albedo': albedo,
|
||||
'verts': verts,
|
||||
'trans_verts': trans_verts,
|
||||
'landmarks2d': landmarks2d,
|
||||
'landmarks3d': landmarks3d,
|
||||
'landmarks3d_world': landmarks3d_world,
|
||||
'grid': ops['grid'],
|
||||
'rendered_images': ops['images'],
|
||||
'alpha_images': ops['alpha_images'],
|
||||
'normal_images': ops['normal_images']
|
||||
'albedo': albedo, # (B, N, 3, 512, 512)
|
||||
'verts': verts, # (B, N, 5023, 3)
|
||||
'trans_verts': trans_verts, # (B, N, 5023, 3)
|
||||
'landmarks2d': landmarks2d, # (B, N, 68, 2)
|
||||
'landmarks3d': landmarks3d, # (B, N, 68, 3)
|
||||
'landmarks3d_world': landmarks3d_world, # (B, N, 68, 3)
|
||||
'grid': ops['grid'], # (B, N, 512, 512, 2)
|
||||
'rendered_images': ops['images'], # (B, N, 3, 512, 512)
|
||||
'alpha_images': ops['alpha_images'], # (B, N, 1, 512, 512)
|
||||
'normal_images': ops['normal_images'] # (B, N, 3, 512, 512)
|
||||
}
|
||||
|
||||
# get mask predicted_images
|
||||
mask_face_eye = F.grid_sample(self.uv_face_eye_mask.expand(B,-1,-1,-1), opdict['grid'].detach(), align_corners=False)
|
||||
debug(f"grid = {ops['grid'].shape},rendered_images={ops['images'].shape}, alpha_images={ops['alpha_images'].shape}, normal_images={ops['normal_images'].shape}")
|
||||
|
||||
# get mask predicted_images # uv_face_eye_mask > (1, 1, 1, 512, 512)
|
||||
opdict['grid'] = opdict['grid'].reshape(B*N, 512, 512, 2)
|
||||
mask_face_eye = F.grid_sample(self.uv_face_eye_mask.expand(B*N, -1,-1,-1), opdict['grid'].detach(), align_corners=False)
|
||||
mask_face_eye = mask_face_eye.reshape(B, N, mask_face_eye.shape[-3], mask_face_eye.shape[-2], mask_face_eye.shape[-1])
|
||||
|
||||
predicted_images = opdict['rendered_images'] * mask_face_eye * opdict['alpha_images']
|
||||
opdict['predicted_images'] = predicted_images
|
||||
debug(f"mask_face_eye = {mask_face_eye.shape}, predicted_images={predicted_images.shape}")
|
||||
|
||||
|
||||
|
||||
# eval loss
|
||||
loss, loss_dict = self.eval_losses(batch_pdt, batch_tgt)
|
||||
|
||||
|
||||
return loss, loss_dict, batch_pdt, batch_tgt, batch_info
|
||||
loss, loss_dict = self.eval_losses(batch_set, opdict, mask_face_eye, batch_pdt)
|
||||
|
||||
return loss, loss_dict
|
||||
|
||||
|
||||
def training_step(self, batch, batch_idx):
|
||||
@@ -439,45 +444,54 @@ class Audio2CoeffModel(LightningModule):
|
||||
self.test_rec.reset(), self.test_vel.reset()
|
||||
|
||||
|
||||
def eval_loss(self, lmk, mask_face_eye, images, predicted_images, opdict, codedict):
|
||||
def eval_losses(self, batch_set, opdict, mask_face_eye, batch_pdt):
|
||||
|
||||
loss = 0
|
||||
loss_dict = {}
|
||||
|
||||
## base shape
|
||||
predicted_landmarks = opdict['landmarks2d']
|
||||
tgt_ldmk = batch_set["data_ldmk"] # [B, N, 68, 2], GT 2D landmarks
|
||||
pdt_ldmk = opdict['landmarks2d'] # [B, N, 68, 2], PT 2D lanmdarks
|
||||
|
||||
# landmarks loss
|
||||
loss_lmk = lossfunc.landmark_loss(predicted_landmarks, lmk, self.landmak_weight)
|
||||
loss_lmk = lossfunc.landmark_loss(pdt_ldmk, tgt_ldmk, self.landmark_weight)
|
||||
loss_dict['landmark'] = loss_lmk.detach()
|
||||
if self.opt_loss.lmk > 0.0:
|
||||
loss += loss_lmk * self.opt_loss.lmk
|
||||
if self.opt_loss.lambda_lmk > 0.0:
|
||||
loss += loss_lmk * self.opt_loss.lambda_lmk
|
||||
|
||||
# eye closure loss
|
||||
loss_eye = lossfunc.eyed_loss(predicted_landmarks, lmk)
|
||||
loss_eye = lossfunc.eyed_loss(pdt_ldmk, tgt_ldmk)
|
||||
loss_dict['eye_distance'] = loss_eye.detach()
|
||||
if self.opt_loss.eyed > 0.0:
|
||||
loss += loss_eye * self.opt_loss.eyed
|
||||
if self.opt_loss.lambda_eyed > 0.0:
|
||||
loss += loss_eye * self.opt_loss.lambda_eyed
|
||||
|
||||
# lip closure loss
|
||||
loss_lip = lossfunc.lipd_loss(predicted_landmarks, lmk)
|
||||
loss_lip = lossfunc.lipd_loss(pdt_ldmk, tgt_ldmk)
|
||||
loss_dict['lip_distance'] = loss_lip.detach()
|
||||
if self.opt_loss.lipd > 0.0:
|
||||
loss += loss_lip * self.opt_loss.lipd
|
||||
if self.opt_loss.lambda_lipd > 0.0:
|
||||
loss += loss_lip * self.opt_loss.lambda_lipd
|
||||
|
||||
# photometric loss
|
||||
masks = masks[:,None,:,:] if self.opt_loss.useSeg else (mask_face_eye * opdict['alpha_images'])
|
||||
loss_pho = masks * (predicted_images - images).abs().mean()
|
||||
tgt_image = batch_set["data_frame"] # [B, N, 3, 512, 512]
|
||||
pdt_image = opdict['predicted_images'] # [B, N, 3, 512, 512]
|
||||
tgt_mask = batch_set["data_mask"] # [B, N, 512, 512]
|
||||
|
||||
if self.opt_loss.useSeg:
|
||||
tgt_mask = tgt_mask[:,:,None,:,:] # [B, N, 1, 512, 512]
|
||||
else:
|
||||
tgt_mask = (mask_face_eye * opdict['alpha_images'])
|
||||
|
||||
loss_pho = tgt_mask * (pdt_image - tgt_image).abs().mean()
|
||||
loss_dict['photometric_texture'] = loss_pho.detach()
|
||||
if self.opt_loss.photo > 0.0:
|
||||
loss += loss_pho * self.opt_loss.photo
|
||||
if self.opt_loss.lambda_photo > 0.0:
|
||||
loss += loss_pho * self.opt_loss.lambda_photo
|
||||
|
||||
# expression regularization
|
||||
loss_reg = torch.sum(codedict['exp']**2)/2
|
||||
loss_reg = torch.sum(batch_pdt**2)/2
|
||||
loss_dict['expression_reg'] = loss_reg.detach()
|
||||
if self.opt_loss.reg > 0.0 :
|
||||
if self.opt_loss.lambda_reg > 0.0 :
|
||||
# import ipdb; ipdb.set_trace()
|
||||
loss += loss_reg * self.opt_loss.reg
|
||||
loss += loss_reg * self.opt_loss.lambda_reg
|
||||
|
||||
|
||||
#########################################################
|
||||
@@ -486,8 +500,7 @@ class Audio2CoeffModel(LightningModule):
|
||||
return loss, loss_dict
|
||||
|
||||
|
||||
|
||||
def eval_losses(self, batch_pdt_geo, batch_tgt_geo):
|
||||
def eval_losses2(self, batch_pdt_geo, batch_tgt_geo):
|
||||
""" Computes the loss function.
|
||||
pramas:
|
||||
batch_tgt_geo, (nbatch, seqlen, num_vertices, 3)
|
||||
@@ -633,7 +646,7 @@ class Audio2CoeffModel(LightningModule):
|
||||
|
||||
@torch.no_grad()
|
||||
def save_reconstruct(self, batch_pdt_geo, batch_speech, path_save, suffix="", vis_landmarks=False):
|
||||
# batch_pdt_pos, [B x N x dim_motion]
|
||||
# batch_pdt_pos, [B x N x nc_motion]
|
||||
# batch_speech, [B x N*sr/fps ]
|
||||
|
||||
B, N, *_ = batch_pdt_geo.shape
|
||||
Reference in new issue
Block a user