large refactor
This commit is contained in:
+93
-66
@@ -21,24 +21,22 @@ import random
|
||||
import numpy as np
|
||||
import scipy as sp
|
||||
from custom_utils.custom_utils import UV2Mesh, maskFacesBatch, _maskFaces
|
||||
from tensorboardX import SummaryWriter
|
||||
import plotly.graph_objects as go
|
||||
import plotly.express as ex
|
||||
from PIL import Image
|
||||
|
||||
from utils import str_to_bool
|
||||
from tf_utils import check_tf_version, allow_memory_growth, split_gpu_for_testing
|
||||
from load_models import load_generator, load_discriminator
|
||||
from losses import d_logistic, d_logistic_r1_reg, g_logistic_non_saturating, g_logistic_ns_pathreg, edge_loss, uv_mask_loss, bend_loss
|
||||
# from losses import collision_penalty as collision_penalty
|
||||
from losses import collision_loss as collision_penalty
|
||||
from custom_utils.custom_utils import batch_to_dict, load_model
|
||||
from dataset import DatasetFactory, StaticDataset
|
||||
from custom_utils.smpl import SMPL
|
||||
from models.cvae_model import CVAE, CVAE128, CVAE32
|
||||
from models.cvae_model import CVAE#, CVAE128, CVAE32
|
||||
from models.upscaler import UpscalerBasic as Upscaler
|
||||
|
||||
|
||||
name='cvae_low_1_d128'
|
||||
name='cvae_low_4_2_d32'
|
||||
def init_wandb():
|
||||
run = wandb.init(project='vae', name=name,
|
||||
notes='learn offsets. smaller flattened latent vectors. with 25-85k pretraining. smaller batchsize. fixed balancing of reconst and kl loss for baseline. \
|
||||
@@ -49,7 +47,8 @@ use mean l2 loss. small batch. l2 * 1000, balancing to 1 from 0.01\
|
||||
fixed gender issue and retrained body encoder\
|
||||
remove shape from unposed garment\
|
||||
training on 100 garments , absolute, not offsets\
|
||||
using filled versions')
|
||||
using custom enhancer for upscaling, using not filled versions\
|
||||
calculating loss at full res')
|
||||
artifact = wandb.Artifact('code', type='code')
|
||||
artifact.add_file('cvae.py')
|
||||
artifact.add_file('models/cvae_model.py')
|
||||
@@ -130,62 +129,57 @@ def train_step(batch):
|
||||
with tf.GradientTape() as tape:
|
||||
uv_curvature = tf.one_hot(batch['uv_curvature'], 7)
|
||||
uv_curvature_low = tf.one_hot(batch['uv_curvature' + res_modifier], 7)
|
||||
pred, mean, logvar, z = model([batch['uv_unposed' + res_modifier], batch['uv_static' + res_modifier], batch['uv_body_posed' + res_modifier], uv_curvature_low, batch['uv_static'], batch['uv_body_posed'], uv_curvature])
|
||||
pred, mean, logvar, z = model([batch['uv_unposed' + res_modifier], batch['uv_static' + res_modifier], batch['uv_body_posed' + res_modifier], uv_curvature_low,
|
||||
batch['uv_mask' + res_modifier], batch['uv_static'], batch['uv_body_posed'], uv_curvature, batch['uv_mask']], use_mask=True)
|
||||
# pred = pred * batch['uv_mask' + res_modifier][:,:,:,tf.newaxis]
|
||||
|
||||
mesh_pred = uv2mesh(tf.transpose(pred, [0,3,1,2]))
|
||||
mesh_pred_posed = smpl.run_garment(batch['pose_shape'][:, :72], batch['pose_shape'][:, 72:], mesh_pred)
|
||||
|
||||
pred_enhanced = enhance(upscale_enhancer, pred, batch['uv_mask' + res_modifier], training=False)
|
||||
pred_full_res = tf.image.resize(pred_enhanced, size=(512, 256), method=tf.image.ResizeMethod.LANCZOS5)
|
||||
mesh_pred = uv2mesh(pred_enhanced)
|
||||
mesh_orig = batch['mesh_unposed']
|
||||
|
||||
shape = batch['pose_shape'][:, 72:]
|
||||
gender = tf.cast(tf.greater_equal(shape[:, 10] , 0.5), tf.int32)
|
||||
shape_offsets = tf.stack([tf.gather(tf.tensordot(shape[i,:10][tf.newaxis, :], smpl.shapedirs[gender[i]], axes=[[1], [2]])[0,:,:], smpl.to_keep, axis=0) for i in range(shape.shape[0])])
|
||||
mesh_pred_posed = mesh_pred_posed + shape_offsets * batch['mesh_mask'][:,:,tf.newaxis]
|
||||
mesh_pred_shaped = mesh_pred + shape_offsets * batch['mesh_mask'][:,:,tf.newaxis]
|
||||
mesh_pred_posed = smpl.run_garment(batch['pose_shape'][:, :72], batch['pose_shape'][:, 72:], mesh_pred_shaped)
|
||||
|
||||
e_loss = tf.reduce_mean(edge_loss(mesh_pred, mesh_orig, batch['mesh_mask']))
|
||||
c_loss = tf.reduce_mean(collision_penalty(mesh_pred_posed, batch['mesh_body_posed'], batch['mesh_mask']))
|
||||
# l1_loss = tf.reduce_sum(tf.reduce_sum((tf.math.abs(tf.transpose(batch['uv_unposed' + res_modifier], [0,2,3,1]) - pred)), axis=-1) * batch['uv_mask' + res_modifier], axis=[1, 2])
|
||||
l1_loss = tf.reduce_sum(tf.reduce_sum((tf.math.abs(tf.transpose(batch['uv_unposed' + res_modifier], [0,2,3,1]) - pred)), axis=-1), axis=[1, 2])
|
||||
# l2_loss = 1e3 * tf.reduce_mean(tf.reduce_sum(((tf.transpose(batch['uv_unposed' + res_modifier], [0,2,3,1]) - pred) ** 2), axis=-1) * batch['uv_mask' + res_modifier], axis=[1, 2])
|
||||
l2_loss = 1e3 * tf.reduce_mean(tf.reduce_sum(((tf.transpose(batch['uv_unposed' + res_modifier], [0,2,3,1]) - pred) ** 2), axis=-1), axis=[1, 2])
|
||||
# ms_ssim = tf.image.ssim_multiscale(tf.transpose(pred, [0,2,3,1]) + 1, tf.transpose(batch['uv_unposed'], [0,2,3,1]) + 1, max_val=2)
|
||||
# ms_ssim = tf.image.ssim_multiscale(pred + 1, tf.transpose(batch['uv_unposed' + res_modifier], [0,2,3,1]) + 1, max_val=3, power_factors=(0.6, 0.4)) #(0.0448, 0.2856, 0.3001, 0.2363, 0.1333)
|
||||
ms_ssim = tf.image.ssim(pred + 1, tf.transpose(batch['uv_unposed' + res_modifier], [0,2,3,1]) + 1, max_val=3) #(0.0448, 0.2856, 0.3001, 0.2363, 0.1333)
|
||||
# ms_ssim = tf.reduce_mean(tf.image.ssim_multiscale((tf.transpose(pred, [0,2,3,1]) + 1) * batch['uv_mask'][:,:,:,tf.newaxis], (tf.transpose(batch['uv_unposed'], [0,2,3,1]) + 1) * batch['uv_mask'][:,:,:,tf.newaxis], max_val=2))
|
||||
rfft_loss = 0 #tf.reduce_mean(tf.reduce_sum(tf.math.abs(tf.signal.rfft3d(pred) - tf.signal.rfft3d(batch['uv_unposed'])), axis=[1,2,3]))
|
||||
fft_loss = tf.reduce_sum(tf.math.abs(tf.signal.fft3d(tf.complex(pred, tf.zeros_like(pred))) - tf.signal.fft3d(tf.complex(tf.transpose(batch['uv_unposed' + res_modifier], [0,2,3,1]), tf.zeros_like(tf.transpose(batch['uv_unposed' + res_modifier], [0,2,3,1]))))), axis=[1,2,3])
|
||||
fft_loss_pc, fft_loss_pc_low, fft_loss_pc_high = 0,0,0 #fft_loss_per_channel(pred, batch['uv_unposed'])
|
||||
tv_loss = tf.image.total_variation(pred)
|
||||
l1_loss = tf.reduce_sum(tf.reduce_sum((tf.math.abs(batch['uv_unposed' + res_modifier] - pred)), axis=-1), axis=[1, 2])
|
||||
l2_loss = 1e3 * tf.reduce_mean(tf.reduce_sum(((batch['uv_unposed' + res_modifier] - pred) ** 2), axis=-1), axis=[1, 2])
|
||||
l2_loss_full = 1e3 * tf.reduce_mean(tf.reduce_sum(((batch['uv_unposed'] - pred_full_res) ** 2), axis=-1), axis=[1, 2])
|
||||
if resolution == 32:
|
||||
ms_ssim = tf.image.ssim(pred + 1, batch['uv_unposed' + res_modifier] + 1, max_val=3)
|
||||
ms_ssim_full = tf.image.ssim(pred_full_res + 1, batch['uv_unposed'] + 1, max_val=3)
|
||||
else:
|
||||
ms_ssim = tf.image.ssim_multiscale(pred + 1, batch['uv_unposed' + res_modifier] + 1, max_val=3, power_factors=(0.5, 0.2, 0.1, 0.1, 0.1))
|
||||
|
||||
reconstr_loss = l2_loss
|
||||
reconstr_loss = l2_loss_full
|
||||
reconstr_loss = tf.reduce_mean(reconstr_loss)
|
||||
# logpx_z = -reconstr_loss
|
||||
# logpz = log_normal_pdf(z[:,:model.latent_dim], 0., 0.)
|
||||
# logqz_x = log_normal_pdf(z[:,:model.latent_dim], mean, logvar)
|
||||
# loss = -tf.reduce_mean(logpx_z + balancing_coeff * (logpz - logqz_x))
|
||||
kl = kl_loss(mean, logvar)
|
||||
loss = reconstr_loss + balancing_coeff * kl
|
||||
# loss = reconstr_loss + balancing_coeff * kl
|
||||
ms_ssim = tf.reduce_mean(ms_ssim)
|
||||
ms_ssim_full = tf.reduce_mean(ms_ssim_full)
|
||||
l1_loss = tf.reduce_mean(l1_loss)
|
||||
l2_loss = tf.reduce_mean(l2_loss)
|
||||
fft_loss = tf.reduce_mean(fft_loss)
|
||||
tv_loss = tf.reduce_mean(tv_loss)
|
||||
l2_loss_full = tf.reduce_mean(l2_loss_full)
|
||||
mean = tf.reduce_mean(mean)
|
||||
logvar = tf.reduce_mean(logvar)
|
||||
|
||||
mesh_orig_2 = uv2mesh(batch['uv_unposed' + res_modifier])
|
||||
# mesh_orig_2 = uv2mesh(batch['uv_unposed' + res_modifier])
|
||||
metric = tf.reduce_sum(tf.math.sqrt(tf.reduce_sum(batch['mesh_mask'][:,:,tf.newaxis] * (mesh_orig - mesh_pred) ** 2, axis=-1))) / tf.reduce_sum(batch['mesh_mask'])
|
||||
metric_2 = tf.reduce_sum(tf.math.sqrt(tf.reduce_sum(batch['mesh_mask'][:,:,tf.newaxis] * (mesh_orig_2 - mesh_pred) ** 2, axis=-1))) / tf.reduce_sum(batch['mesh_mask'])
|
||||
# metric_2 = tf.reduce_sum(tf.math.sqrt(tf.reduce_sum(batch['mesh_mask'][:,:,tf.newaxis] * (mesh_orig_2 - mesh_pred) ** 2, axis=-1))) / tf.reduce_sum(batch['mesh_mask'])
|
||||
euclid_posed = 0 # tf.reduce_sum(tf.math.sqrt(tf.reduce_sum(batch['mesh_mask'][:,:,tf.newaxis] * (mesh_skinned - batch['mesh_posed']) ** 2, axis=-1))) / tf.reduce_sum(batch['mesh_mask'])
|
||||
gradients = tape.gradient(loss, model.trainable_variables)
|
||||
# gradients = [tf.clip_by_norm(g, 1.0) for g in gradients]
|
||||
# gradients = [tf.clip_by_value(g, -1.0, 1.0) for g in gradients]
|
||||
optimizer.apply_gradients(zip(gradients, model.trainable_variables))
|
||||
return { 'train/loss': loss, 'train/edge_loss': e_loss, 'train/collision_loss': c_loss, 'train/l1_loss': l1_loss, 'train/euclid_error': metric, 'train/ms_ssim': ms_ssim,
|
||||
'train/fft_loss': fft_loss, 'train/euclid_error_reconst': metric_2, 'train/rfft_loss': rfft_loss, 'train/fft_oc_low': fft_loss_pc_low, 'train/fft_pc_high': fft_loss_pc_high,
|
||||
'train/fft_loss_per_channel': fft_loss_pc, 'train/euclid_error_posed': euclid_posed, 'train/reconstr_loss': reconstr_loss, 'train/tv_loss': tv_loss,
|
||||
'train/mean': mean, 'train/logvar': logvar, 'train/kl_loss': kl, 'train/reconst_loss_norm': reconstr_loss / (2 * (gamma ** 2)), 'train/var': np.e ** logvar,
|
||||
#'train/euclid_error_reconst': metric_2,
|
||||
'train/l2_loss_full_res': l2_loss_full, 'train/ms_ssim_full_res': ms_ssim_full,
|
||||
'train/euclid_error_posed': euclid_posed, 'train/reconstr_loss': reconstr_loss,
|
||||
'train/mean': mean, 'train/logvar': logvar, 'train/kl_loss': kl, 'train/var': np.e ** logvar,
|
||||
'train/reg_coeff': reg_coeff, 'train/l2_loss': l2_loss }
|
||||
|
||||
|
||||
@@ -235,29 +229,36 @@ def plot_everything(batch: dict, type: str):
|
||||
pred, mean, logvar, z = model([batch['uv_unposed' + res_modifier], batch['uv_static' + res_modifier], batch['uv_body_posed' + res_modifier], uv_curvature_low, batch['uv_static'], batch['uv_body_posed'], uv_curvature])
|
||||
# pred = pred * batch['uv_mask' + res_modifier][:,:,:,tf.newaxis]
|
||||
|
||||
mesh_pred = uv2mesh(pred)
|
||||
pred = enhance(upscale_enhancer, pred, batch['uv_mask' + res_modifier], training=False)
|
||||
mesh_pred = uv2mesh(pred).numpy()
|
||||
mesh_orig = batch['mesh_unposed']
|
||||
|
||||
orig_img = tf.transpose(batch['uv_unposed' + res_modifier], [0,2,3,1])
|
||||
uv_static_img = tf.transpose(batch['uv_static' + res_modifier], [0,2,3,1])
|
||||
uv_body_posed_img = tf.transpose(batch['uv_body_posed' + res_modifier], [0,2,3,1])
|
||||
pred_img = pred
|
||||
orig_img = batch['uv_unposed' + res_modifier]
|
||||
uv_static_img = batch['uv_static' + res_modifier]
|
||||
uv_body_posed_img = batch['uv_body_posed' + res_modifier]
|
||||
pred_img = pred.numpy()
|
||||
pred_img[pred_img > 1] = 0
|
||||
pred_img[pred_img < -1] = 0
|
||||
img = tf.concat((uv_static_img, uv_body_posed_img, orig_img, pred_img), axis=2)
|
||||
imgs = [wandb.Image((img[i] + 1) / 2.0) for i in range(4)]
|
||||
|
||||
F = np.load("custom_utils/smpl_faces.npy")
|
||||
mask = batch['mesh_mask'].numpy().astype(bool)
|
||||
garment_unposed, faces = maskFacesBatch(mesh_pred.numpy(), F, mask)
|
||||
gt = [mesh_orig[i].numpy()[mask[i], :] for i in range(pred.shape[0])]
|
||||
|
||||
body = batch['mesh_body_posed'].numpy()
|
||||
mesh_posed = smpl.run_garment(batch['pose_shape'][:, :72], batch['pose_shape'][:, 72:], mesh_pred).numpy()
|
||||
|
||||
shape = batch['pose_shape'][:, 72:]
|
||||
gender = tf.cast(tf.greater_equal(shape[:, 10] , 0.5), tf.int32)
|
||||
shape_offsets = tf.stack([tf.gather(tf.tensordot(shape[i,:10][tf.newaxis, :], smpl.shapedirs[gender[i]], axes=[[1], [2]])[0,:,:], smpl.to_keep, axis=0) for i in range(shape.shape[0])])
|
||||
|
||||
garment_posed = [mesh_posed[i, mask[i], :] + shape_offsets.numpy()[i, mask[i], :] for i in range(body.shape[0])]
|
||||
F = np.load("custom_utils/smpl_faces.npy")
|
||||
mask = batch['mesh_mask'].numpy().astype(bool)
|
||||
garment_unposed, faces = maskFacesBatch(mesh_pred, F, mask)
|
||||
garment_unposed = [garment_unposed[i] + shape_offsets.numpy()[i, mask[i], :] for i in range(mask.shape[0])]
|
||||
gt = [mesh_orig[i].numpy()[mask[i], :] + shape_offsets.numpy()[i, mask[i], :] for i in range(pred.shape[0])]
|
||||
|
||||
for i in range(pred.shape[0]):
|
||||
mesh_pred[i, mask[i], :] += shape_offsets.numpy()[i, mask[i], :]
|
||||
body = batch['mesh_body_posed'].numpy()
|
||||
mesh_posed = smpl.run_garment(batch['pose_shape'][:, :72], batch['pose_shape'][:, 72:], mesh_pred).numpy()
|
||||
|
||||
|
||||
garment_posed = [mesh_posed[i, mask[i], :] for i in range(body.shape[0])]
|
||||
collision = [np.concatenate((body[i], garment_posed[i]), axis=0) for i in range(len(garment_posed))]
|
||||
collision_faces = [np.concatenate((F, faces[i] + 14475), axis=0) for i in range(len(garment_posed))]
|
||||
collision_color = [np.concatenate((np.ones_like(body[i], dtype=np.int32)*100, np.ones_like(garment_posed[i], dtype=np.int32)*230), axis=0) for i in range(len(garment_posed))]
|
||||
@@ -393,6 +394,28 @@ def sample(folder):
|
||||
|
||||
print()
|
||||
|
||||
|
||||
def get_upscale_enhancer(checkpoint, res):
|
||||
upscale_enhancer = Upscaler(512, res)
|
||||
load_model(upscale_enhancer, checkpoint)
|
||||
upscale_enhancer = tf.keras.Sequential([
|
||||
upscale_enhancer.flatten,
|
||||
upscale_enhancer.seq,
|
||||
upscale_enhancer.reshape
|
||||
])
|
||||
upscale_enhancer.trainable = False
|
||||
|
||||
return upscale_enhancer
|
||||
|
||||
|
||||
def enhance(upscale_enhancer, input, mask, training=None):
|
||||
x = input * mask[:,:,:,tf.newaxis]
|
||||
x = upscale_enhancer(x, training=training)
|
||||
x = x * (1 - mask[:,:,:,tf.newaxis])
|
||||
x = x + input
|
||||
return x
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
init_wandb()
|
||||
allow_memory_growth()
|
||||
@@ -404,7 +427,7 @@ if __name__ == '__main__':
|
||||
|
||||
smpl = SMPL()
|
||||
|
||||
resolution = 128
|
||||
resolution = 32
|
||||
res_modifier = ''
|
||||
if resolution != 512:
|
||||
res_modifier = '_' + str(resolution)
|
||||
@@ -412,37 +435,41 @@ if __name__ == '__main__':
|
||||
factory = DatasetFactory()
|
||||
signature_dynamic = { 'id': (),
|
||||
'pose_shape': (72 + 11,),
|
||||
# 'uv_posed': (3, 512, 256,),
|
||||
'uv_body_posed': (3, 512, 256,),
|
||||
'uv_body_posed' + res_modifier: (3, resolution, resolution//2,),
|
||||
# 'uv_posed': (512, 256, 3),
|
||||
'uv_body_posed': (512, 256, 3),
|
||||
'uv_body_posed' + res_modifier: (resolution, resolution//2, 3),
|
||||
'mesh_body_posed': (14475, 3,),
|
||||
'mesh_posed': (14475, 3,),
|
||||
'mesh_unposed': (14475, 3,),
|
||||
'uv_unposed': (3, 512, 256,),
|
||||
'uv_unposed' + res_modifier: (3, resolution, resolution//2,),
|
||||
'uv_unposed': (512, 256, 3),
|
||||
'uv_unposed' + res_modifier: (resolution, resolution//2, 3),
|
||||
'uv_curvature': (512, 256,),
|
||||
'uv_curvature' + res_modifier: (resolution, resolution//2),
|
||||
}
|
||||
signature_static = { 'uv_static': (3, 512, 256,),
|
||||
'uv_static' + res_modifier: (3, resolution, resolution//2,),
|
||||
signature_static = { 'uv_static': (512, 256, 3),
|
||||
'uv_static' + res_modifier: (resolution, resolution//2, 3),
|
||||
# 'mesh_static': (14475, 3,),
|
||||
'mesh_mask': (14475,),
|
||||
'uv_mask' + res_modifier: (resolution, resolution//2,),
|
||||
# 'uv_shaped_body': (3, 512, 256,),
|
||||
'uv_mask': (512, 256,),
|
||||
}
|
||||
|
||||
dataset_train = factory.get_dataset(folder='/home/workspace/local-data/train_100', batch_size=batch_size, signature=signature_dynamic, use_filled=True, resolutions=[512, resolution])
|
||||
static_dataset_train = StaticDataset(folder='/home/workspace/local-data/train_100', signature=signature_static, use_filled=True, resolutions=[512, resolution])
|
||||
dataset_train = factory.get_dataset(folder='/home/workspace/local-data/train_100', batch_size=batch_size, signature=signature_dynamic, use_filled=False, resolutions=[512, resolution])
|
||||
static_dataset_train = StaticDataset(folder='/home/workspace/local-data/train_100', signature=signature_static, use_filled=False, resolutions=[512, resolution])
|
||||
dataset_valid = factory.get_dataset(folder='/home/workspace/local-data/jumpsuit_20/valid', batch_size=batch_size, signature=signature_dynamic)
|
||||
static_dataset_valid = StaticDataset(folder='/home/workspace/local-data/jumpsuit_20/valid', signature=signature_static)
|
||||
|
||||
|
||||
model = CVAE128(#avg_garment_path='custom_data/train_100_no_shape_avg_uv.npy',
|
||||
latent_dim=128, static_model='checkpoints/ae_static_4',
|
||||
body_model='checpoints/ae_body_8',
|
||||
curvature_model='checpoints/ae_curvature_7',
|
||||
model = CVAE(#avg_garment_path='custom_data/train_100_no_shape_avg_uv.npy',
|
||||
size=resolution,
|
||||
latent_dim=128, static_model='checkpoints/ae_static_6_copy',
|
||||
body_model='checkpoints/ae_body_8_copy',
|
||||
curvature_model='checkpoints/ae_curvature_7_copy',
|
||||
freeze_encoders=True,
|
||||
use_full_res_encoders=True)
|
||||
encoder_res=512)
|
||||
|
||||
upscale_enhancer = get_upscale_enhancer('checkpoints/up_2_3', res=resolution)
|
||||
|
||||
|
||||
# lr_schedule = tf.keras.optimizers.schedules.ExponentialDecay(0.0001, decay_steps=30000, decay_rate=0.1, staircase=False)
|
||||
optimizer = tf.optimizers.Adam(learning_rate=0.0001)
|
||||
|
||||
Reference in New Issue
Block a user