commit all
This commit is contained in:
@@ -0,0 +1,202 @@
|
||||
import os
|
||||
import string
|
||||
from configs.config_cvae 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
|
||||
import scipy as sp
|
||||
from custom_utils.custom_utils import UV2Mesh, get_summary_html, maskFacesBatch, _maskFaces
|
||||
import plotly.graph_objects as go
|
||||
import plotly.express as ex
|
||||
from PIL import Image
|
||||
|
||||
if config['is_skirt']:
|
||||
from losses import edge_loss_skirt as edge_loss
|
||||
else:
|
||||
from losses import edge_loss
|
||||
|
||||
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 collision_ratio, uv_mask_loss, bend_loss, kl_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
|
||||
from dataset import DatasetFactory, StaticDataset
|
||||
from custom_utils.smpl import SMPL
|
||||
from custom_utils.supersmpl_io import writeOBJ
|
||||
from models.cvae_model import CVAE
|
||||
|
||||
|
||||
def init_wandb():
|
||||
run = wandb.init(project='cvae', name=config['name'], notes=config['notes'])
|
||||
artifact = wandb.Artifact('code', type='code')
|
||||
artifact.add_file('cvae.py')
|
||||
artifact.add_file('cvae_evaluate.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')
|
||||
run.log_artifact(artifact)
|
||||
|
||||
uv2mesh = UV2Mesh(res=256, is_skirt=config['is_skirt'])
|
||||
|
||||
|
||||
@tf.function
|
||||
def inference_step(batch):
|
||||
pred = model.sample(batch['uv_static'], batch['uv_body_posed'], batch['uv_curvature'], batch['uv_mask'])
|
||||
|
||||
mesh_pred = uv2mesh(pred)
|
||||
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_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)
|
||||
|
||||
# is the output already masked?
|
||||
|
||||
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']))
|
||||
# c_ratio = tf.reduce_mean(collision_ratio(mesh_pred_posed, batch['mesh_body_posed'], batch['mesh_mask']))
|
||||
l2_loss = tf.reduce_mean(1e3 * tf.reduce_mean(tf.reduce_sum(((batch['uv_unposed'] - pred) ** 2), axis=-1), axis=[1, 2]))
|
||||
|
||||
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)))
|
||||
euclid_error = 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 { 'test/l2_loss': l2_loss, 'test/edge_loss': e_loss, 'test/collision_loss': c_loss, 'test/euclid_error': euclid_error, 'test/ms_ssim': ms_ssim,
|
||||
}
|
||||
|
||||
|
||||
|
||||
def plot_everything(batch: dict, type: str):
|
||||
pred = model.sample(batch['uv_static'], batch['uv_body_posed'], batch['uv_curvature'], batch['uv_mask'])
|
||||
|
||||
mesh_pred = uv2mesh(pred).numpy()
|
||||
mesh_orig = batch['mesh_unposed']
|
||||
|
||||
orig_img = batch['uv_unposed']
|
||||
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)]
|
||||
|
||||
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])])
|
||||
|
||||
F = np.load("custom_utils/smpl_faces" + skirt_modifier + ".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])]
|
||||
|
||||
body = batch['mesh_body_posed'].numpy()
|
||||
for i in range(body.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()
|
||||
|
||||
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))]
|
||||
|
||||
figs = { type + "/garment_" + str(i): plot_3d(gt[i], garment_unposed[i], faces[i], collision[i], collision_faces[i], collision_color[i]) for i in range(4) }
|
||||
|
||||
for i in range(4):
|
||||
temp_file = 'temp/' + config['name'] + '_' + batch['id'][i].numpy().decode('UTF-8') + '_' + ''.join(random.choice(string.ascii_lowercase) for _ in range(4))
|
||||
writeOBJ(temp_file + '_garment.obj', garment_posed[i], faces[i].astype(np.int32))
|
||||
writeOBJ(temp_file + '_body.obj', body[i], F[i].astype(np.int32))
|
||||
|
||||
|
||||
return { **figs, **{ type + '/images': imgs } }
|
||||
|
||||
|
||||
|
||||
def test():
|
||||
load_model(model, 'checkpoints/' + config['name'].split('_')[0])
|
||||
|
||||
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 dataset_test:
|
||||
batch = static_dataset_test.expand_batch(batch_to_dict(batch, config['signature_dynamic']))
|
||||
|
||||
inference_loss = inference_step(batch)
|
||||
losses.append(inference_loss)
|
||||
|
||||
to_log = { **{ 'current_step': step }, **inference_loss }
|
||||
if step % 100 == 0:
|
||||
figs = plot_everything(batch, 'test')
|
||||
to_log = { **to_log, **figs }
|
||||
|
||||
wandb.log(to_log, step = step)
|
||||
|
||||
if step > 300:
|
||||
break
|
||||
|
||||
print(step)
|
||||
step += 1
|
||||
|
||||
# averages = dict()
|
||||
path_to_plotly_html = "temp/plotly_figure.html"
|
||||
|
||||
histograms = dict()
|
||||
for key in inference_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'] = fig # 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()
|
||||
skirt_modifier = '_skirt' if config['is_skirt'] else ''
|
||||
|
||||
factory = DatasetFactory()
|
||||
|
||||
model = CVAE(config)
|
||||
|
||||
g_balancing_coeff = config['starting_balancing_coeff']
|
||||
|
||||
test()
|
||||
Reference in New Issue
Block a user