219 lines
9.5 KiB
Python
219 lines
9.5 KiB
Python
import os
|
|
from configs.config_ae_static 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 random
|
|
import numpy as np
|
|
from custom_utils.custom_utils import UV2Mesh, get_summary_html, load_model, maskFacesBatch, get_summary_str
|
|
import plotly.graph_objects as go
|
|
import plotly.express as ex
|
|
|
|
if config['is_skirt']:
|
|
from losses import edge_loss_skirt as edge_loss
|
|
else:
|
|
from losses import edge_loss
|
|
|
|
from tf_utils import check_tf_version, allow_memory_growth
|
|
from dataset import DatasetFactory, StaticDataset
|
|
from custom_utils.custom_utils import batch_to_dict, plot_3d
|
|
from models.cond_encoder import AutoEncoder
|
|
|
|
|
|
def init_wandb():
|
|
run = wandb.init(project='ae', name=config['name'], notes=config['notes'], dir='/home/workspace/local-data/temp')
|
|
artifact = wandb.Artifact('code', type='code')
|
|
artifact.add_file('auto_encoder_static.py')
|
|
artifact.add_file('losses.py')
|
|
artifact.add_file('configs/config_base.py')
|
|
artifact.add_file('configs/config_ae_static.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')
|
|
run.log_artifact(artifact)
|
|
|
|
uv2mesh = UV2Mesh(res=256, is_skirt=config['is_skirt'], is_smpl_orig=config['is_cape'])
|
|
|
|
|
|
|
|
@tf.function
|
|
def train_step(batch):
|
|
with tf.GradientTape() as tape:
|
|
pred = model([batch['uv_static'], batch['uv_mask']], training=True)
|
|
|
|
mesh_pred = uv2mesh(pred)
|
|
mesh_orig = batch['mesh_static']
|
|
|
|
e_loss = 1e-2 * tf.reduce_mean(edge_loss(mesh_pred, mesh_orig, batch['mesh_mask']))
|
|
l1_loss = tf.reduce_mean(tf.reduce_sum((tf.math.abs(batch['uv_static'] - pred)), axis=1))
|
|
ms_ssim = tf.reduce_mean(tf.image.ssim_multiscale(pred + 1, batch['uv_static'] + 1, max_val=2, power_factors=(0.5, 0.2, 0.1, 0.1, 0.1)))
|
|
loss = 1e3 * (1 - ms_ssim)
|
|
|
|
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/l1_loss': l1_loss, 'train/euclid_error': metric, 'train/ms_ssim': ms_ssim, }
|
|
|
|
|
|
|
|
@tf.function
|
|
def valid_step(batch):
|
|
pred = model([batch['uv_static'], batch['uv_mask']], training=False)
|
|
|
|
mesh_pred = uv2mesh(pred)
|
|
mesh_orig = batch['mesh_static']
|
|
|
|
e_loss = 1e-2 * tf.reduce_mean(edge_loss(mesh_pred, mesh_orig, batch['mesh_mask']))
|
|
l1_loss = tf.reduce_mean(tf.reduce_sum((tf.math.abs(batch['uv_static'] - pred)), axis=1))
|
|
ms_ssim = tf.reduce_mean(tf.image.ssim_multiscale(pred + 1, batch['uv_static'] + 1, max_val=2, power_factors=(0.5, 0.2, 0.1, 0.1, 0.1)))
|
|
loss = 1e3 * (1 - ms_ssim)
|
|
|
|
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'])
|
|
return { 'valid/loss': loss, 'valid/edge_loss': e_loss, 'valid/l1_loss': l1_loss, 'valid/euclid_error': metric, 'valid/ms_ssim': ms_ssim, }
|
|
|
|
|
|
|
|
def plot_everything(batch: dict, type: str):
|
|
pred = model([batch['uv_static'], batch['uv_mask']], training=False)
|
|
|
|
mesh_pred = uv2mesh(pred)
|
|
mesh_orig = batch['mesh_static']
|
|
|
|
orig_img = batch['uv_static']
|
|
pred_img = pred
|
|
img = tf.concat((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)
|
|
garment_static, faces = maskFacesBatch(mesh_pred.numpy(), F, mask)
|
|
gt = [mesh_orig[i].numpy()[mask[i], :] for i in range(pred.shape[0])]
|
|
|
|
body = gt
|
|
garment_posed = garment_static
|
|
collision = [np.concatenate((body[i], garment_posed[i]), axis=0) for i in range(len(garment_posed))]
|
|
collision_faces = [np.concatenate((faces[i], faces[i] + np.sum(mask[i])), 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))]
|
|
|
|
figs = { type + "/garment_" + str(i): plot_3d(gt[i], garment_static[i], faces[i], collision[i], collision_faces[i], collision_color[i]) for i in range(4) }
|
|
|
|
return { **figs, **{ type + '/images': imgs } }
|
|
|
|
|
|
def train():
|
|
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 = dict({ **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 == 0:
|
|
to_log = { **to_log, **{ 'model/summary': wandb.Html(get_summary_html(model)) } }
|
|
|
|
|
|
wandb.log(to_log, step=step)
|
|
|
|
if step % 10000 == 0:
|
|
manager_enc.save(checkpoint_number=step)
|
|
manager_dec.save(checkpoint_number=step)
|
|
|
|
print(step)
|
|
|
|
step += 1
|
|
|
|
|
|
def test():
|
|
load_model(model.encoder, 'checkpoints/' + config['name'] + '_enc')
|
|
load_model(model.decoder, 'checkpoints/' + config['name'] + '_dec')
|
|
|
|
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)
|
|
|
|
avg_error = 0
|
|
count = 0
|
|
|
|
for batch in dataset_test:
|
|
batch = static_dataset_test.expand_batch(batch_to_dict(batch, config['signature_dynamic']))
|
|
|
|
pred = model([batch['uv_static'], batch['uv_mask']], training=False)
|
|
# orig_img = batch['uv_static']
|
|
# pred_img = pred
|
|
# img = tf.concat((orig_img, pred_img), axis=2).numpy()
|
|
|
|
# ex.imshow((img[0] + 1) / 2).show()
|
|
|
|
|
|
|
|
mesh_pred = uv2mesh(pred)
|
|
mesh_orig = batch['mesh_static']
|
|
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'])
|
|
|
|
avg_error += metric
|
|
count += 1
|
|
|
|
print(count)
|
|
|
|
print()
|
|
|
|
|
|
if __name__ == '__main__':
|
|
init_wandb()
|
|
allow_memory_growth()
|
|
parser = argparse.ArgumentParser(description='')
|
|
parser.add_argument('--name', type=str)
|
|
args = vars(parser.parse_args())
|
|
|
|
# TODO: different resolutions not working yet, model should be ready though
|
|
|
|
resolution_modifier = ''
|
|
if config['resolution'] != 512:
|
|
resolution_modifier = '_' + str(config['resolution'])
|
|
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'], use_filled=config['use_filled'], resolutions=[config['resolution']], in_memory=config['dataset_in_memory'], is_cape=config['is_cape'])
|
|
static_dataset_train = StaticDataset(folder=config['train_dir'], signature=config['signature_static'], use_filled=config['use_filled'], 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'], use_filled=config['use_filled'], resolutions=[config['resolution']], in_memory=config['dataset_in_memory'], is_cape=config['is_cape'])
|
|
static_dataset_valid = StaticDataset(folder=config['valid_dir'], signature=config['signature_static'], use_filled=config['use_filled'], resolutions=[config['resolution']], in_memory=True, is_cape=config['is_cape'])
|
|
|
|
model : AutoEncoder = AutoEncoder(config['cond_ae'])
|
|
optimizer = tf.optimizers.Adam(learning_rate=config['lr'])
|
|
|
|
if config['pretrained_model'] != '':
|
|
load_model(model.encoder, config['pretrained_model'] + '_enc')
|
|
load_model(model.decoder, config['pretrained_model'] + '_dec')
|
|
|
|
ckpt_enc = tf.train.Checkpoint(model=model.encoder)
|
|
manager_enc = tf.train.CheckpointManager(ckpt_enc, 'checkpoints/' + config['name'] + '_enc', max_to_keep=20)
|
|
ckpt_dec = tf.train.Checkpoint(model=model.decoder)
|
|
manager_dec = tf.train.CheckpointManager(ckpt_dec, 'checkpoints/' + config['name'] + '_dec', max_to_keep=20)
|
|
|
|
# test()
|
|
train() |