import os import time import argparse import wandb import random import numpy as np import scipy as sp import tensorflow as tf from custom_utils.custom_utils import UV2Mesh, maskFacesBatch from tensorboardX import SummaryWriter import plotly.graph_objects as go import plotly.express as ex 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 convnext.models.convnext_tf import ConvNeXt, ConvNeXtReverse, Block from stylegan2_ae.generator import Generator from custom_utils.graph_utils import Reconstructor_V4_Decoder as GNNDecoder, sparse_to_tensor from custom_utils.graph_utils import Reconstructor_v2 as SimpleReconstructor from dataset import DatasetFactory, StaticDataset from custom_utils.custom_utils import batch_to_dict, plot_3d from custom_utils.smpl import SMPL name='vae_11' os.environ["CUDA_VISIBLE_DEVICES"] = "1" run = wandb.init(project='vae', name=name, notes='vae, ms_ssim with range 3. with l1 loss, larger latent_dim=1024. 4 dowscaling steps, 4 upscaling, the image resize for final resolution. upscale from 256*128') artifact = wandb.Artifact('code', type='code') artifact.add_file('vae.py') artifact.add_file('dataset.py') artifact.add_file('losses.py') artifact.add_file('convnext/models/convnext_tf.py') run.log_artifact(artifact) uv2mesh = UV2Mesh(res=256) class Bottleneck(tf.keras.Model): def __init__(self, dim): super(Bottleneck, self).__init__() self.bottleneck = tf.keras.Sequential( [Block(dim=dim, drop_path=0, layer_scale_init_value=1e-6, prefix=f'bottleneck{j}') for j in range(5)] ) def call(self, inputs, training=None): x = inputs x = self.bottleneck(x, training=training) return x class Encoder(tf.keras.Model): def __init__(self, latent_dim): super(Encoder, self).__init__() self.encoder = ConvNeXt(depths=[3, 3, 9, 3], dims=[32, 64, 128, 128], include_top=False) self.flatten = tf.keras.layers.Flatten() self.mean = tf.keras.layers.Dense(latent_dim) self.log_var = tf.keras.layers.Dense(latent_dim) def call(self, inputs, training=None): x = inputs x = self.encoder(x) x = self.flatten(x) mean = self.mean(x) log_var = self.log_var(x) return mean, log_var class Decoder(tf.keras.Model): def __init__(self): super(Decoder, self).__init__() self.dense = tf.keras.layers.Dense(8 * 4 * 512) self.reshape = tf.keras.layers.Reshape((8, 4, 512)) self.decoder = ConvNeXtReverse(depths=list(reversed([3, 3, 9, 3])), dims=list(reversed([128, 128, 64, 16]))) def call(self, inputs, training=None): x = inputs x = self.dense(x) x = self.reshape(x) x = self.decoder(x) return x class VAE(tf.keras.Model): def __init__(self, latent_dim=1024): super(VAE, self).__init__() self.encoder = Encoder(latent_dim) self.decoder = Decoder() @tf.function def sample(self, eps=None): if eps is None: eps = tf.random.normal(shape=(4, self.latent_dim)) return self.decode(eps, apply_sigmoid=True) def reparameterize(self, mean, logvar): eps = tf.random.normal(shape=mean.shape) return eps * tf.exp(logvar * .5) + mean def decode(self, z, apply_sigmoid=False): logits = self.decoder(z) if apply_sigmoid: probs = tf.sigmoid(logits) return probs return logits def call(self, inputs, training=None): x, uv_mask = inputs x = tf.transpose(x, [0,2,3,1]) mean, logvar = self.encoder(x) z = self.reparameterize(mean, logvar) x = self.decoder(z) # x = tf.transpose(x, [0,3,1,2]) # x = x * uv_mask[:,tf.newaxis,:,:] x = tf.image.resize(x, (512, 256), tf.image.ResizeMethod.LANCZOS5) x = x * uv_mask[:,:,:,tf.newaxis] return x, mean, logvar, z def log_normal_pdf(sample, mean, logvar, raxis=1): log2pi = tf.math.log(2. * np.pi) res = tf.reduce_sum(-.5 * ((sample - mean) ** 2. * tf.exp(-logvar) + logvar + log2pi), axis=raxis) return res @tf.function def train_step(batch): with tf.GradientTape() as tape: pred, mean, logvar, z = model([batch['uv_unposed'], batch['uv_mask']]) mesh_pred = uv2mesh(tf.transpose(pred, [0,3,1,2])) mesh_orig = batch['mesh_unposed'] e_loss = 1e-3 * tf.reduce_mean(edge_loss(mesh_pred, mesh_orig, batch['mesh_mask'])) c_loss = 1e-3 * tf.reduce_mean(collision_penalty(mesh_pred, batch['mesh_body_posed'], batch['mesh_mask'])) l1_loss = tf.reduce_sum(tf.reduce_sum((tf.math.abs(tf.transpose(batch['uv_unposed'], [0,2,3,1]) - pred)), axis=-1) * batch['uv_mask'], 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'], [0,2,3,1]) + 1, max_val=3) # 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'], [0,2,3,1]), tf.zeros_like(tf.transpose(batch['uv_unposed'], [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) reconstr_loss = l1_loss logpx_z = -reconstr_loss logpz = log_normal_pdf(z, 0., 0.) logqz_x = log_normal_pdf(z, mean, logvar) loss = -tf.reduce_mean(logpx_z + logpz - logqz_x) ms_ssim = tf.reduce_mean(ms_ssim) l1_loss = tf.reduce_mean(l1_loss) fft_loss = tf.reduce_mean(fft_loss) reconstr_loss = tf.reduce_mean(reconstr_loss) tv_loss = tf.reduce_mean(tv_loss) mesh_orig_2 = uv2mesh(batch['uv_unposed']) 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']) 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 } @tf.function def valid_step(batch): pred, mean, logvar, z = model([batch['uv_unposed'], batch['uv_mask']]) mesh_pred = uv2mesh(tf.transpose(pred, [0,3,1,2])) mesh_orig = batch['mesh_unposed'] e_loss = 1e-2 * tf.reduce_mean(edge_loss(mesh_pred, mesh_orig, batch['mesh_mask'])) c_loss = 1e-2 * tf.reduce_mean(collision_penalty(mesh_pred, batch['mesh_body_posed'], batch['mesh_mask'])) l1_loss = tf.reduce_sum(tf.reduce_sum((tf.math.abs(tf.transpose(batch['uv_unposed'], [0,2,3,1]) - pred)), axis=-1) * batch['uv_mask'], axis=[1, 2]) b_loss = 0 #1e-3 * bend_loss(mesh_pred, smpl_faces, laplacian_loss, batch['mesh_mask']) # 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'], [0,2,3,1]) + 1, max_val=3) fft_loss = 0 #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'], [0,2,3,1]), tf.zeros_like(tf.transpose(batch['uv_unposed'], [0,2,3,1]))))), axis=[1,2,3]) # mesh_orig_2 = uv2mesh(batch['uv_unposed']) 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 = 0 #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']) reconstr_loss = l1_loss logpx_z = -reconstr_loss logpz = log_normal_pdf(z, 0., 0.) logqz_x = log_normal_pdf(z, mean, logvar) loss = -tf.reduce_mean(logpx_z + logpz - logqz_x) ms_ssim = tf.reduce_mean(ms_ssim) l1_loss = tf.reduce_mean(l1_loss) fft_loss = tf.reduce_mean(fft_loss) b_loss = tf.reduce_mean(b_loss) reconstr_loss = tf.reduce_mean(reconstr_loss) return { 'valid/loss': loss, 'valid/edge_loss': e_loss, 'valid/collision_loss': c_loss, 'valid/l1_loss': l1_loss, 'valid/euclid_error': metric, 'valid/ms_ssim': ms_ssim, 'valid/fft_loss': fft_loss, 'valid/euclid_error_reconst': metric_2, 'train/bend_loss': b_loss, 'train/reconstr_loss': reconstr_loss } def plot_everything(batch: dict, type: str): pred, mean, logvar, z = model([batch['uv_unposed'], batch['uv_mask']]) mesh_pred = uv2mesh(tf.transpose(pred, [0,3,1,2])) mesh_orig = batch['mesh_unposed'] orig_img = tf.transpose(batch['uv_unposed'], [0,2,3,1]) 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.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() 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) } return { **figs, **{ type + '/images': imgs } } def repeat_faces(faces, times): idx_offset = np.linspace(0, 14475 * (times-1), times).astype(np.int32) idx_offset = np.repeat(idx_offset, faces.shape[0], axis=0) merged = np.tile(faces, [times,1]) merged += idx_offset[:, np.newaxis] return merged def repeat_laplacian(L, times): idx = np.repeat(np.mat([L.row, L.col]), repeats=times, axis=1) idx_offset = np.linspace(0, L.shape[0] * (times-1), times).astype(np.int32) idx_offset = np.repeat(idx_offset, L.row.shape[0], axis=0) idx += idx_offset[np.newaxis,:] data = np.repeat(L.data, repeats=times, axis=0) shape = (L.shape[0] * times, L.shape[1] * times) return sp.sparse.coo_matrix((data, (np.squeeze(np.asarray(idx[0,:])), np.squeeze(np.asarray(idx[1,:])))), shape) if __name__ == '__main__': allow_memory_growth() parser = argparse.ArgumentParser(description='') parser.add_argument('--name', type=str) args = vars(parser.parse_args()) batch_size = 8 smpl_faces = np.load('custom_utils/smpl_faces.npy') faces_loss_single = smpl_faces faces_loss = repeat_faces(smpl_faces, batch_size) laplacian_loss = sp.sparse.load_npz("custom_utils/laplacian/laplacian0.npz").todense().astype(np.float32) # edges = np.stack(np.nonzero(laplacian_loss.todense())).transpose() # laplacian_loss = sparse_to_tensor(laplacian_loss) # laplacian_loss = sparse_to_tensor(repeat_laplacian(laplacian_loss, batch_size)) smpl = SMPL() factory = DatasetFactory() signature_dynamic = { 'id': (), 'pose_shape': (72 + 11,), # 'uv_posed': (3, 512, 256,), # 'uv_body_posed': (3, 512, 256,), 'mesh_body_posed': (14475, 3,), 'mesh_posed': (14475, 3,), 'mesh_unposed': (14475, 3,), 'uv_unposed': (3, 512, 256,) } signature_static = { #'uv_static': (3, 512, 256,), # 'mesh_static': (14475, 3,), 'mesh_mask': (14475,), 'uv_mask': (512, 256,), # 'uv_shaped_body': (3, 512, 256,), } dataset_train = factory.get_dataset(folder='/home/workspace/local-data/jumpsuit_20/train', batch_size=batch_size, signature=signature_dynamic) static_dataset_train = StaticDataset(folder='/home/workspace/local-data/jumpsuit_20/train', signature=signature_static) 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 = VAE() lr_schedule = tf.keras.optimizers.schedules.ExponentialDecay(0.0001, decay_steps=30000, decay_rate=0.1, staircase=False) optimizer = tf.optimizers.Adam(learning_rate=lr_schedule) folder = 'models/ae_logs/' valid_iterator = iter(dataset_valid) step = 0 for batch in dataset_train: batch = static_dataset_train.expand_batch(batch_to_dict(batch, signature_dynamic)) # _, masked_faces = maskFacesBatch(batch['mesh_unposed'].numpy(), smpl_faces, batch['mesh_mask'].numpy().astype(bool)) # # batch['mesh_masked_verts'] = masked_verts # batch['mesh_masked_faces'] = [masked_faces[i].astype(np.int32) for i in range(batch_size)] # batch['mesh_mask_bool'] = batch['mesh_mask'].numpy().astype(bool) # batch['laplacian'] = [sparse_to_tensor(sp.sparse.coo_matrix(laplacian_loss[batch['mesh_mask_bool'][i], :][:, batch['mesh_mask_bool'][i]])) for i in range(batch_size)] # batch['laplacian'] = [tf.sparse.to_dense(sparse_to_tensor(sp.sparse.coo_matrix(laplacian_loss[batch['mesh_mask_bool'][i], :][:, batch['mesh_mask_bool'][i]]))) for i in range(batch_size)] # batch['laplacian'] = [sp.sparse.coo_matrix(laplacian_loss[batch['mesh_mask_bool'][i], :][:, batch['mesh_mask_bool'][i]]) for i in range(batch_size)] train_loss = train_step(batch) data_valid = valid_iterator.get_next() data_valid = static_dataset_valid.expand_batch(batch_to_dict(data_valid, signature_dynamic)) valid_loss = valid_step(data_valid) if step % 500 == 0: train_figs = plot_everything(batch, 'train') valid_figs = plot_everything(data_valid, 'valid') wandb.log({ **train_loss, **valid_loss, **{ 'current_step': step}, **train_figs, **valid_figs }, step=step) else: wandb.log({ **train_loss, **valid_loss, **{ 'current_step': step} }, step=step) print(step) step += 1