571 lines
27 KiB
Python
571 lines
27 KiB
Python
import os
|
|
import sys
|
|
from configs.config_abl_overfit_jumpsuit_2 import config
|
|
|
|
os.environ["CUDA_VISIBLE_DEVICES"] = config['gpu']
|
|
import tensorflow as tf
|
|
|
|
gpus = tf.config.experimental.list_physical_devices('GPU')
|
|
if gpus:
|
|
try:
|
|
# Currently, memory growth needs to be the same across GPUs
|
|
for gpu in gpus:
|
|
tf.config.experimental.set_memory_growth(gpu, True)
|
|
logical_gpus = tf.config.experimental.list_logical_devices('GPU')
|
|
print(len(gpus), "Physical GPUs,", len(logical_gpus), "Logical GPUs")
|
|
except RuntimeError as e:
|
|
# Memory growth must be set before GPUs have been initialized
|
|
print(e)
|
|
|
|
import time
|
|
import argparse
|
|
import wandb
|
|
import tqdm
|
|
import random
|
|
import numpy as np
|
|
import plotly.graph_objects as go
|
|
import plotly.express as ex
|
|
from PIL import Image
|
|
from postprocessing import fix_collision
|
|
|
|
if config['is_skirt']:
|
|
from losses import edge_loss_skirt as edge_loss
|
|
else:
|
|
from losses import edge_loss
|
|
|
|
|
|
|
|
from losses import collision_ratio, kl_loss, normal_loss #, concept_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, plot_3d, UV2Mesh, get_summary_html, maskFacesBatch, _maskFaces, plot_3d_collision
|
|
from dataset import DatasetFactory, StaticDataset
|
|
from custom_utils.smpl import SMPL
|
|
from models.cvae_model import CVAE
|
|
|
|
|
|
def init_wandb():
|
|
run = wandb.init(project='ablation', name=config['name'], notes=config['notes'], dir='/wandb')
|
|
artifact = wandb.Artifact('code', type='code')
|
|
artifact.add_file('cvae.py')
|
|
artifact.add_file('models/cvae_model.py')
|
|
artifact.add_file('losses.py')
|
|
# artifact.add_file('configs/config_base.py')
|
|
# artifact.add_file('configs/config_cvae.py')
|
|
artifact.add_file('models/base.py')
|
|
artifact.add_file('models/cond_encoder.py')
|
|
artifact.add_file('dataset.py')
|
|
artifact.add_file('convnext/models/convnext_tf.py')
|
|
config_file_names = [key for key in sys.modules.keys() if key.startswith('configs.')]
|
|
for config_file_name in config_file_names:
|
|
artifact.add_file('/'.join(config_file_name.split('.')) + '.py')
|
|
run.log_artifact(artifact)
|
|
|
|
uv2mesh = UV2Mesh(res=256, is_skirt=config['is_skirt'], is_adaptive=False, is_smpl_orig=config['is_cape'])
|
|
|
|
|
|
def kl_loss(mean, logvar):
|
|
kl_loss = 1 + logvar - tf.square(mean) - tf.exp(logvar)
|
|
kl_loss = tf.reduce_mean(kl_loss)
|
|
kl_loss *= -0.5
|
|
return kl_loss
|
|
|
|
|
|
# 3d loss on posed !!!!!!!!!!!!
|
|
|
|
# @tf.function
|
|
def train_step(batch):
|
|
|
|
with tf.GradientTape() as tape:
|
|
if config['use_skinning']:
|
|
mesh_orig, uv_orig = batch['mesh_unposed'], batch['uv_unposed']
|
|
else:
|
|
mesh_orig, uv_orig = batch['mesh_posed'], batch['uv_posed']
|
|
|
|
pred, mean, logvar = model([uv_orig, batch['uv_static'], batch['uv_body_posed'], batch['uv_curvature'], batch['uv_mask']], training=True)
|
|
|
|
mesh_pred = uv2mesh(pred)
|
|
|
|
if config['use_skinning']:
|
|
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_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)
|
|
else:
|
|
mesh_pred_posed = mesh_pred
|
|
|
|
# is the output already masked?
|
|
|
|
e_loss = tf.reduce_mean(edge_loss(mesh_pred, mesh_orig, batch['mesh_mask']))
|
|
c_loss, c_ratio = collision_penalty(mesh_pred_posed, batch['mesh_body_posed'], batch['mesh_mask'])
|
|
c_loss, c_ratio = tf.reduce_mean(c_loss), tf.reduce_mean(c_ratio)
|
|
l2_loss = tf.reduce_mean(1e3 * tf.reduce_mean(tf.reduce_sum(((uv_orig - pred) ** 2), axis=-1), axis=[1, 2]))
|
|
l2_mesh_loss = tf.reduce_mean(1e3 * tf.reduce_mean(tf.reduce_sum(batch['mesh_mask'][:,:,tf.newaxis] * (batch['mesh_posed'] - mesh_pred_posed) ** 2, axis=-1), axis=-1))
|
|
n_loss = normal_loss(mesh_pred_posed, batch['mesh_posed'], batch['mesh_mask'], is_skirt=config['is_skirt'], is_smpl_orig=config['is_cape'])
|
|
# conc_loss = concept_loss(pred, batch['uv_unposed'])
|
|
kl = kl_loss(mean, logvar)
|
|
|
|
reconstr_loss = l2_loss
|
|
if config['use_extra_losses']:
|
|
if 'block_collision_loss' in config.keys() and config['block_collision_loss'] == True:
|
|
reconstr_loss = reconstr_loss + l2_mesh_loss + (e_loss) * config['reg_loss_coeff']
|
|
else:
|
|
reconstr_loss = reconstr_loss + l2_mesh_loss + (e_loss + c_loss) * config['reg_loss_coeff']
|
|
if config['use_norm_loss'] and step > 2000:
|
|
reconstr_loss = reconstr_loss + n_loss * config['reg_loss_coeff']
|
|
|
|
loss = reconstr_loss + g_balancing_coeff * kl
|
|
|
|
mean = tf.reduce_mean(mean)
|
|
logvar = tf.reduce_mean(logvar)
|
|
|
|
# ms_ssim = tf.reduce_mean(tf.image.ssim_multiscale(pred + 5, batch['uv_unposed'] + 5, max_val=10, power_factors=(0.5, 0.2, 0.1, 0.1, 0.1)))
|
|
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'])
|
|
gradients = tape.gradient(loss, model.trainable_variables)
|
|
optimizer.apply_gradients(zip(gradients, model.trainable_variables))
|
|
return { 'train/loss': loss, 'train/edge_loss': e_loss, 'train/collision_loss': c_loss, 'train/euclid_error': metric,
|
|
'train/reconstr_loss': reconstr_loss, 'train/collision_ratio': c_ratio,
|
|
'train/mean': mean, 'train/logvar': logvar, 'train/kl_loss': kl, 'train/var': np.e ** logvar,
|
|
'train/l2_loss': l2_loss, 'train/l2_mesh_loss': l2_mesh_loss, 'train/normal_loss': n_loss,
|
|
# 'train/ms_ssim': ms_ssim,
|
|
}
|
|
|
|
|
|
@tf.function
|
|
def valid_step(batch):
|
|
if config['use_skinning']:
|
|
mesh_orig, uv_orig = batch['mesh_unposed'], batch['uv_unposed']
|
|
else:
|
|
mesh_orig, uv_orig = batch['mesh_posed'], batch['uv_posed']
|
|
|
|
pred, mean, logvar = model([uv_orig, batch['uv_static'], batch['uv_body_posed'], batch['uv_curvature'], batch['uv_mask']], training=False)
|
|
|
|
mesh_pred = uv2mesh(pred)
|
|
|
|
if config['use_skinning']:
|
|
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_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)
|
|
else:
|
|
mesh_pred_posed = mesh_pred
|
|
|
|
# is the output already masked?
|
|
|
|
e_loss = tf.reduce_mean(edge_loss(mesh_pred, mesh_orig, batch['mesh_mask']))
|
|
c_loss, c_ratio = collision_penalty(mesh_pred_posed, batch['mesh_body_posed'], batch['mesh_mask'])
|
|
c_loss, c_ratio = tf.reduce_mean(c_loss), tf.reduce_mean(c_ratio)
|
|
l2_loss = tf.reduce_mean(1e3 * tf.reduce_mean(tf.reduce_sum(((uv_orig - pred) ** 2), axis=-1), axis=[1, 2]))
|
|
l2_mesh_loss = tf.reduce_mean(1e3 * tf.reduce_mean(tf.reduce_sum(batch['mesh_mask'][:,:,tf.newaxis] * (batch['mesh_posed'] - mesh_pred_posed) ** 2, axis=-1), axis=-1))
|
|
n_loss = normal_loss(mesh_pred_posed, batch['mesh_posed'], batch['mesh_mask'], is_skirt=config['is_skirt'], is_smpl_orig=config['is_cape'])
|
|
# conc_loss = concept_loss(pred, batch['uv_unposed'])
|
|
kl = kl_loss(mean, logvar)
|
|
|
|
reconstr_loss = l2_loss
|
|
if config['use_extra_losses']:
|
|
reconstr_loss = reconstr_loss + l2_mesh_loss + (e_loss + c_loss) * config['reg_loss_coeff']
|
|
if config['use_norm_loss']:
|
|
reconstr_loss = reconstr_loss + n_loss * config['reg_loss_coeff']
|
|
|
|
loss = reconstr_loss + g_balancing_coeff * kl
|
|
|
|
mean = tf.reduce_mean(mean)
|
|
logvar = tf.reduce_mean(logvar)
|
|
|
|
# ms_ssim = tf.reduce_mean(tf.image.ssim_multiscale(pred + 5, batch['uv_unposed'] + 5, max_val=10, power_factors=(0.5, 0.2, 0.1, 0.1, 0.1)))
|
|
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'])
|
|
# c_ratio = tf.reduce_mean(collision_ratio(mesh_pred_posed, batch['mesh_body_posed'], batch['mesh_mask']))
|
|
|
|
return { 'valid/loss': loss, 'valid/edge_loss': e_loss, 'valid/collision_loss': c_loss, 'valid/euclid_error': metric,
|
|
'valid/reconstr_loss': reconstr_loss, 'valid/l2_mesh_loss': l2_mesh_loss, 'valid/collision_ratio': c_ratio,
|
|
'valid/mean': mean, 'valid/logvar': logvar, 'valid/kl_loss': kl, 'valid/var': np.e ** logvar,
|
|
'valid/normal_loss': n_loss,# 'valid/ms_ssim': ms_ssim,
|
|
}
|
|
|
|
|
|
@tf.function
|
|
def test_step(batch):
|
|
if config['use_skinning']:
|
|
mesh_orig, uv_orig = batch['mesh_unposed'], batch['uv_unposed']
|
|
else:
|
|
mesh_orig, uv_orig = batch['mesh_posed'], batch['uv_posed']
|
|
|
|
pred, mean, logvar = model([uv_orig, batch['uv_static'], batch['uv_body_posed'], batch['uv_curvature'], batch['uv_mask']], training=False)
|
|
|
|
mesh_pred = uv2mesh(pred)
|
|
|
|
if config['use_skinning']:
|
|
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_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)
|
|
mesh_orig_shaped = mesh_orig + shape_offsets * batch['mesh_mask'][:,:,tf.newaxis]
|
|
mesh_orig_posed = smpl.run_garment(batch['pose_shape'][:, :72], batch['pose_shape'][:, 72:], mesh_orig_shaped)
|
|
else:
|
|
mesh_pred_posed = mesh_pred
|
|
mesh_orig_posed = mesh_orig
|
|
|
|
mesh_pred_posed_fixed = fix_collision(mesh_pred_posed, batch['mesh_body_posed'], batch['mesh_mask'])
|
|
|
|
|
|
# is the output already masked?
|
|
|
|
e_loss = tf.reduce_mean(edge_loss(mesh_pred, mesh_orig, batch['mesh_mask']))
|
|
c_loss, c_ratio = collision_penalty(mesh_pred_posed, batch['mesh_body_posed'], batch['mesh_mask'])
|
|
c_loss, c_ratio = tf.reduce_mean(c_loss), tf.reduce_mean(c_ratio)
|
|
l2_loss = tf.reduce_mean(1e3 * tf.reduce_mean(tf.reduce_sum(((uv_orig - pred) ** 2), axis=-1), axis=[1, 2]))
|
|
l2_mesh_loss = tf.reduce_mean(1e3 * tf.reduce_mean(tf.reduce_sum(batch['mesh_mask'][:,:,tf.newaxis] * (mesh_orig - mesh_pred) ** 2, axis=-1), axis=-1))
|
|
# conc_loss = concept_loss(pred, batch['uv_unposed'])
|
|
kl = kl_loss(mean, logvar)
|
|
|
|
reconstr_loss = l2_loss
|
|
if config['use_extra_losses']:
|
|
reconstr_loss = reconstr_loss + l2_mesh_loss + (e_loss + c_loss) * config['reg_loss_coeff']
|
|
|
|
loss = reconstr_loss + g_balancing_coeff * kl
|
|
|
|
mean = tf.reduce_mean(mean)
|
|
logvar = tf.reduce_mean(logvar)
|
|
|
|
ms_ssim = tf.reduce_mean(tf.image.ssim_multiscale(pred + 5, uv_orig + 5, max_val=10, power_factors=(0.5, 0.2, 0.1, 0.1, 0.1)))
|
|
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'])
|
|
euclid_posed = tf.reduce_sum(tf.math.sqrt(tf.reduce_sum(batch['mesh_mask'][:,:,tf.newaxis] * (mesh_orig_posed - mesh_pred_posed) ** 2, axis=-1))) / tf.reduce_sum(batch['mesh_mask'])
|
|
euclid_posed_fixed = tf.reduce_sum(tf.math.sqrt(tf.reduce_sum(batch['mesh_mask'][:,:,tf.newaxis] * (mesh_orig_posed - mesh_pred_posed_fixed) ** 2, axis=-1))) / tf.reduce_sum(batch['mesh_mask'])
|
|
|
|
return { 'test/loss': loss, 'test/edge_loss': e_loss, 'test/collision_loss': c_loss, 'test/euclid_error': metric, 'test/ms_ssim': ms_ssim,
|
|
'test/reconstr_loss': reconstr_loss, 'test/collision_ratio': c_ratio, 'test/l2_mesh_loss': l2_mesh_loss,
|
|
'test/mean': mean, 'test/logvar': logvar, 'test/kl_loss': kl, 'test/var': np.e ** logvar,
|
|
'test/euclid_posed': euclid_posed, 'test/euclid_posed_fixed': euclid_posed_fixed }
|
|
|
|
|
|
def plot_everything(batch: dict, type: str):
|
|
if config['use_skinning']:
|
|
mesh_orig, uv_orig = batch['mesh_unposed'], batch['uv_unposed']
|
|
else:
|
|
mesh_orig, uv_orig = batch['mesh_posed'], batch['uv_posed']
|
|
|
|
pred, mean, logvar = model([uv_orig, batch['uv_static'], batch['uv_body_posed'], batch['uv_curvature'], batch['uv_mask']], training=False)
|
|
|
|
mesh_pred = uv2mesh(pred).numpy()
|
|
|
|
orig_img = uv_orig
|
|
uv_static_img = batch['uv_static']
|
|
uv_body_posed_img = batch['uv_body_posed']
|
|
pred_img = pred
|
|
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" + skirt_modifier + ("_orig" if config['is_cape'] else "") + ".npy")
|
|
mask = batch['mesh_mask'].numpy().astype(bool)
|
|
|
|
if config['use_skinning']:
|
|
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_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(mesh_orig.shape[0]):
|
|
mesh_pred[i, mask[i], :] += shape_offsets.numpy()[i, mask[i], :]
|
|
mesh_posed = smpl.run_garment(batch['pose_shape'][:, :72], batch['pose_shape'][:, 72:], mesh_pred).numpy()
|
|
else:
|
|
mesh_posed = mesh_pred
|
|
gt = [mesh_orig[i].numpy()[mask[i], :] for i in range(pred.shape[0])]
|
|
garment_unposed, faces = maskFacesBatch(mesh_pred, F, mask)
|
|
|
|
gt_posed = [batch['mesh_posed'].numpy()[i, mask[i], :] for i in range(mask.shape[0])]
|
|
|
|
|
|
body = batch['mesh_body_posed'].numpy()
|
|
mesh_posed_fixed = fix_collision(mesh_posed, body, mask).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] + config['smpl_res']), 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))]
|
|
|
|
garment_posed_fixed = [mesh_posed_fixed[i, mask[i], :] for i in range(body.shape[0])]
|
|
collision_fixed = [np.concatenate((body[i], garment_posed_fixed[i]), axis=0) for i in range(len(garment_posed))]
|
|
collision_gt = [np.concatenate((body[i], gt_posed[i]), axis=0) for i in range(len(garment_posed))]
|
|
|
|
figs = { type + "/garment_" + str(i): plot_3d(gt[i], garment_unposed[i], faces[i], collision[i], collision_faces[i], collision_color[i], flip_xy=(not config['use_skinning'] and config['remove_global_orientation'])) for i in range(4) }
|
|
figs_coll = { type + "/garment_" + str(i) + '_collision': plot_3d_collision(collision_gt[i], collision[i], collision_fixed[i], collision_faces[i], collision_color[i], flip_xy=(not config['use_skinning'] and config['remove_global_orientation'])) for i in range(4) }
|
|
|
|
mean_hist = wandb.Histogram(sequence=mean.numpy().mean(axis=0))
|
|
logvar_hist = wandb.Histogram(sequence=logvar.numpy().mean(axis=0))
|
|
|
|
return { **figs, **figs_coll, **{ type + '/images': imgs, type + '/mean_hist': mean_hist, type + '/logvar_hist': logvar_hist } }
|
|
|
|
|
|
def sample(folder):
|
|
# run = wandb.init(project='vae_plots', name=folder.split('/')[-1])
|
|
load_model(model,folder)
|
|
count = 0
|
|
for batch in dataset_train:
|
|
batch = static_dataset_train.expand_batch(batch_to_dict(batch, config['signature_dynamic']))
|
|
uv_curvature = tf.one_hot(batch['uv_curvature'], 7)
|
|
nr_of_samples=2
|
|
|
|
pred = model.sample_single(batch['uv_static'][0], batch['uv_body_posed'][0], uv_curvature[0], batch['uv_mask'][0], nr_of_samples=nr_of_samples)
|
|
pose, shape = batch['pose_shape'][0, :72], batch['pose_shape'][0, 72:]
|
|
pose, shape = tf.tile(pose[tf.newaxis,:], [nr_of_samples,1]), tf.tile(shape[tf.newaxis,:], [nr_of_samples,1])
|
|
|
|
mesh_pred = uv2mesh(pred)
|
|
mesh_posed = smpl.run_garment(pose, shape, mesh_pred).numpy()
|
|
mesh_orig = batch['mesh_posed'][0].numpy()
|
|
mesh_orig_reposed = smpl.run_garment(pose[:1], shape[:1], batch['mesh_unposed'][:1]).numpy()[0]
|
|
|
|
body = batch['mesh_body_posed'][0].numpy()
|
|
body_color = np.ones_like(body, dtype=np.int32)*100
|
|
|
|
F = np.load("custom_utils/smpl_faces.npy")
|
|
mask = batch['mesh_mask'].numpy().astype(bool)[0]
|
|
_, faces = _maskFaces(np.ones((config['smpl_res'], 3)), F, mask)
|
|
|
|
pred_zero = model.sample_single(batch['uv_static'][0], batch['uv_body_posed'][0], uv_curvature[0], batch['uv_mask'][0], nr_of_samples=nr_of_samples, zero_latent=True)
|
|
mesh_pred_zero = uv2mesh(pred_zero)
|
|
mesh_posed_zero = smpl.run_garment(pose, shape, mesh_pred_zero).numpy()
|
|
|
|
|
|
meshes = []
|
|
meshes.append(go.Mesh3d(
|
|
# 8 vertices of a cube
|
|
x=mesh_orig_reposed[mask,0],
|
|
y=mesh_orig_reposed[mask,2],
|
|
z=mesh_orig_reposed[mask,1],
|
|
# i, j and k give the vertices of triangles
|
|
i = faces[:,0],
|
|
j = faces[:,1],
|
|
k = faces[:,2]
|
|
))
|
|
|
|
for i in range(nr_of_samples):
|
|
x = mesh_posed[i][mask, :].copy()
|
|
# x[:, 2] += 1 * (i + 1)
|
|
x[:, 2] += 1
|
|
meshes.append(go.Mesh3d(
|
|
# 8 vertices of a cube
|
|
x=x[:,0],
|
|
y=x[:,2],
|
|
z=x[:,1],
|
|
# i, j and k give the vertices of triangles
|
|
i = faces[:,0],
|
|
j = faces[:,1],
|
|
k = faces[:,2]
|
|
))
|
|
|
|
|
|
for i in range(nr_of_samples):
|
|
x = mesh_posed_zero[i][mask, :].copy()
|
|
# x[:, 2] += 1 * (i + 1)
|
|
x[:, 2] += 2
|
|
meshes.append(go.Mesh3d(
|
|
# 8 vertices of a cube
|
|
x=x[:,0],
|
|
y=x[:,2],
|
|
z=x[:,1],
|
|
# i, j and k give the vertices of triangles
|
|
i = faces[:,0],
|
|
j = faces[:,1],
|
|
k = faces[:,2]
|
|
))
|
|
|
|
# for i in range(5):
|
|
# x = body.copy()
|
|
# x[:, 2] += 1 * i
|
|
# meshes.append(go.Mesh3d(
|
|
# # 8 vertices of a cube
|
|
# x=x[:,0],
|
|
# y=x[:,2],
|
|
# z=x[:,1],
|
|
# # i, j and k give the vertices of triangles
|
|
# i = F[:,0],
|
|
# j = F[:,1],
|
|
# k = F[:,2],
|
|
# vertexcolor=body_color
|
|
# ))
|
|
|
|
|
|
fig = go.Figure(data=meshes)
|
|
|
|
fig.update_layout(scene_aspectmode='manual', scene_aspectratio=dict(x=1, y=2, z=1))
|
|
# fig.update_layout(scene_aspectmode='manual', scene_aspectratio=dict(x=1, y=nr_of_samples-1, z=1))
|
|
fig.update_layout(
|
|
scene = dict(
|
|
xaxis = dict(nticks=4, range=[-1,1],),
|
|
# yaxis = dict(nticks=4, range=[-1,nr_of_samples+1],),
|
|
yaxis = dict(nticks=4, range=[-1,3],),
|
|
zaxis = dict(nticks=4, range=[-1,1],),)
|
|
)
|
|
|
|
# wandb.log({'plot_' + str(count): fig})
|
|
fig.show()
|
|
|
|
pred = pred.numpy()
|
|
frames = [Image.fromarray(((pred[i] + 1) * 128).astype(np.int8), mode='RGB') for i in range(pred.shape[0])]
|
|
frames[0].save("temp/garment_1.gif", format="GIF", append_images=frames[1:],
|
|
save_all=True, duration=500, loop=0)
|
|
|
|
|
|
if count > 10:
|
|
break
|
|
|
|
print(count)
|
|
count += 1
|
|
|
|
print()
|
|
|
|
|
|
|
|
|
|
|
|
def test():
|
|
str_split = config['name'].split('_')
|
|
test_idx = str_split.index('test')
|
|
checkpoint_name = '_'.join(str_split[:test_idx])
|
|
load_model(model, 'checkpoints/' + checkpoint_name)
|
|
|
|
dataset_test = factory.get_dataset(folder=config['test_dir'], batch_size=config['batch_size'], signature=config['signature_dynamic'], use_filled=config['use_filled'], resolutions=[config['resolution']], in_memory=False, do_repeat=False)
|
|
static_dataset_test = StaticDataset(folder=config['test_dir'], signature=config['signature_static'], use_filled=config['use_filled'], resolutions=[config['resolution']], in_memory=False)
|
|
|
|
step = 0
|
|
losses = []
|
|
|
|
for batch in tqdm.tqdm(dataset_test):
|
|
batch = static_dataset_test.expand_batch(batch_to_dict(batch, config['signature_dynamic']))
|
|
|
|
test_loss = test_step(batch)
|
|
losses.append(test_loss)
|
|
|
|
to_log = { **{ 'current_step': step }, **test_loss }
|
|
if step % 1000 == 0:
|
|
figs = plot_everything(batch, 'test')
|
|
to_log = { **to_log, **figs }
|
|
|
|
wandb.log(to_log, step = step)
|
|
|
|
# print(step)
|
|
step += 1
|
|
|
|
# averages = dict()
|
|
path_to_plotly_html = "temp/plotly_figure.html"
|
|
|
|
histograms = dict()
|
|
for key in test_loss.keys():
|
|
accumulated = [losses[i][key].numpy() for i in range(len(losses))]
|
|
fig = ex.histogram(accumulated, title='Average: ' + str(np.asarray(accumulated).mean()))
|
|
fig.write_html(path_to_plotly_html, auto_play = False)
|
|
|
|
histograms['all/' + key.split('/')[-1] + '_hist'] = wandb.Html(path_to_plotly_html)
|
|
# averages['all/' + key.split('/')[-1] + '_avg'] = np.asarray(accumulated).mean()
|
|
|
|
|
|
|
|
wandb.log({ **histograms }, step = step)
|
|
wandb.finish()
|
|
pass
|
|
|
|
|
|
|
|
if __name__ == '__main__':
|
|
# init_wandb()
|
|
parser = argparse.ArgumentParser(description='')
|
|
parser.add_argument('--name', type=str)
|
|
args = vars(parser.parse_args())
|
|
|
|
smpl = SMPL(orig_smpl=config['is_cape'])
|
|
skirt_modifier = '_skirt' if config['is_skirt'] else ''
|
|
|
|
factory = DatasetFactory()
|
|
|
|
dataset_train = factory.get_dataset(folder=config['train_dir'],
|
|
batch_size=config['batch_size'],
|
|
signature=config['signature_dynamic'],
|
|
resolutions=[config['resolution']],
|
|
in_memory=config['dataset_in_memory'],
|
|
use_one_hot=config['use_one_hot'],
|
|
use_no_orient=config['remove_global_orientation'],
|
|
frames_file=config['frames_file'] if 'frames_file' in config.keys() else None,
|
|
is_cape=config['is_cape'])
|
|
static_dataset_train = StaticDataset(folder=config['train_dir'],
|
|
signature=config['signature_static'],
|
|
resolutions=[config['resolution']],
|
|
in_memory=True,
|
|
is_cape=config['is_cape'])
|
|
|
|
dataset_valid = factory.get_dataset(folder=config['valid_dir'],
|
|
batch_size=config['batch_size'],
|
|
signature=config['signature_dynamic'],
|
|
resolutions=[config['resolution']],
|
|
in_memory=config['dataset_in_memory'],
|
|
use_one_hot=config['use_one_hot'],
|
|
use_no_orient=config['remove_global_orientation'],
|
|
frames_file=config['frames_file_valid'] if 'frames_file_valid' in config.keys() else None,
|
|
is_cape=config['is_cape'])
|
|
static_dataset_valid = StaticDataset(folder=config['valid_dir'],
|
|
signature=config['signature_static'],
|
|
resolutions=[config['resolution']],
|
|
in_memory=True,
|
|
is_cape=config['is_cape'])
|
|
|
|
model = CVAE(config)
|
|
|
|
optimizer = tf.optimizers.Adam(learning_rate=config['lr'])
|
|
balancing_activated_step = 0
|
|
g_balancing_coeff = config['starting_balancing_coeff']
|
|
|
|
# sample('checkpoints/cvae_13')
|
|
# test()
|
|
|
|
ckpt = tf.train.Checkpoint(model=model)
|
|
manager = tf.train.CheckpointManager(ckpt, 'checkpoints/post/' + config['name'], max_to_keep=20)
|
|
|
|
|
|
if config['pretrained_model'] != '':
|
|
load_model(model, config['pretrained_model'])
|
|
|
|
# load_model(model, 'checkpoints/' + config['name'])
|
|
|
|
valid_iterator = iter(dataset_valid)
|
|
step = 0
|
|
for batch in dataset_train:
|
|
batch = static_dataset_train.expand_batch(batch_to_dict(batch, config['signature_dynamic']))
|
|
|
|
train_loss = train_step(batch)
|
|
|
|
data_valid = valid_iterator.get_next()
|
|
data_valid = static_dataset_valid.expand_batch(batch_to_dict(data_valid, config['signature_dynamic']))
|
|
valid_loss = valid_step(data_valid)
|
|
|
|
to_log = { **train_loss, **valid_loss, **{ 'current_step': step} }
|
|
if step % 5000 == 0 or (step < 5000 and step % 500 == 0):
|
|
train_figs = plot_everything(batch, 'train')
|
|
valid_figs = plot_everything(data_valid, 'valid')
|
|
to_log = { **to_log, **train_figs, **valid_figs }
|
|
|
|
if step % 5000 == 0:
|
|
manager.save(checkpoint_number=step)
|
|
if step == 0:
|
|
to_log = { **to_log, **{ 'model/summary': wandb.Html(get_summary_html(model)) } }
|
|
|
|
if train_loss['train/euclid_error'] < (config['balancing_activation_limit'] if 'balancing_activation_limit' in config.keys() else 0.017):
|
|
if balancing_activated_step == 0:
|
|
balancing_activated_step = step
|
|
g_balancing_coeff = g_balancing_coeff + 1 / 10000
|
|
|
|
to_log = { **to_log, **{ 'train/balancing_coeff': g_balancing_coeff } }
|
|
|
|
wandb.log(to_log, step = step)
|
|
|
|
print(step)
|
|
|
|
step += 1
|
|
|