import os import time import argparse import wandb import random import numpy as np import tensorflow as tf os.environ["CUDA_VISIBLE_DEVICES"] = "0" from custom_utils.custom_utils import UV2Mesh, maskFacesBatch import plotly.graph_objects as go import plotly.express as ex from tf_utils import check_tf_version, allow_memory_growth from losses import collision_loss as collision_penalty from convnext.models.convnext_tf import ConvNeXt, ConvNeXtReverse, Block, ConvNeXtReverseLabels from dataset import DatasetFactory, StaticDataset from custom_utils.custom_utils import batch_to_dict from custom_utils.smpl import SMPL name='ae_curvature_7_2' testing = False def init_wandb(): if not testing: run = wandb.init(project='vae', name=name, notes='convnext + convnext, 16*8*32, ce loss. flattened latent dim of 128. trained on 100 garments. same as 7') artifact = wandb.Artifact('code', type='code') artifact.add_file('auto_encoder_curv.py') artifact.add_file('dataset.py') artifact.add_file('losses.py') artifact.add_file('stylegan2_ae/layers/mapping_block.py') artifact.add_file('convnext/models/convnext_tf.py') run.log_artifact(artifact) uv2mesh = UV2Mesh(res=256) class DatasetSimple(tf.data.Dataset): def _generator(folder): # Opening the file folder = folder.decode("utf-8") uv_folder = os.path.join(folder, 'uv_posed') frames = os.listdir(uv_folder) random.shuffle(frames) for frame in frames: id, frame_nr = frame.split('.')[0].split('_') mesh_mask = np.load(os.path.join(folder, 'mesh_mask', id + '.npy')); mesh_mask = mesh_mask.astype(np.float32) uv_mask = np.load(os.path.join(folder, 'uv_mask', id + '.npz')); uv_mask=uv_mask['uv_mask']; uv_mask = uv_mask.astype(np.float32) mesh_unposed = np.load(os.path.join(folder, 'mesh_unposed', id + '_' + frame_nr + '.npz')); mesh_unposed = mesh_unposed['mesh_unposed'] uv_unposed = np.load(os.path.join(folder, 'uv_unposed', id + '_' + frame_nr + '.npz')); uv_unposed = uv_unposed['uv_unposed']; uv_unposed = np.transpose(uv_unposed, [2, 0, 1]) yield uv_unposed, mesh_unposed, uv_mask, mesh_mask def __new__(cls, folder, res=256): return tf.data.Dataset.from_generator( cls._generator, output_signature = (tf.TensorSpec(shape = (3, res * 2, res,), dtype = tf.float32), tf.TensorSpec(shape = (14475, 3,), dtype = tf.float32), tf.TensorSpec(shape = (res * 2, res,), dtype = tf.float32), tf.TensorSpec(shape = (14475,), dtype = tf.float32), ), args=(folder, ) ) def filter_resolutions_featuremaps(resolutions, featuremaps, res): index = resolutions.index(res) filtered_resolutions = resolutions[:index + 1] filtered_featuremaps = featuremaps[:index + 1] return filtered_resolutions, filtered_featuremaps def plot_3d(mesh_gt, mesh_pred, faces): mesh_pred[:,1] += 2 fig = go.Figure(data=[ go.Mesh3d( # 8 vertices of a cube x=mesh_gt[:,0], y=mesh_gt[:,1], z=mesh_gt[:,2], # i, j and k give the vertices of triangles i = faces[:,0], j = faces[:,1], k = faces[:,2] ), go.Mesh3d( # 8 vertices of a cube x=mesh_pred[:,0], y=mesh_pred[:,1], z=mesh_pred[:,2], # i, j and k give the vertices of triangles i = faces[:,0], j = faces[:,1], k = faces[:,2], ) ]) fig.update_layout(scene_aspectmode='manual', scene_aspectratio=dict(x=1, y=2, z=1)) fig.update_layout( scene = dict( xaxis = dict(nticks=4, range=[-1,1],), yaxis = dict(nticks=4, range=[-1,3],), zaxis = dict(nticks=4, range=[-1,1],),) ) return fig class Bottleneck(tf.keras.Model): def __init__(self, dim, latent_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)] ) self.flatten = tf.keras.layers.Flatten() self.dense = tf.keras.layers.Dense(latent_dim) def call(self, inputs, training=None): x = inputs x = self.bottleneck(x) x = self.flatten(x) x = self.dense(x) return x class Decoder(tf.keras.Model): def __init__(self, bottleneck_size, latent_dim): super(Decoder, self).__init__() self.dense = tf.keras.layers.Dense(16 * 8 * bottleneck_size) self.reshape = tf.keras.layers.Reshape((16, 8, bottleneck_size)) self.decoder = ConvNeXtReverseLabels(depths=list(reversed([3, 3, 9, 3])), dims=list(reversed([bottleneck_size, 128, 64, 16])), nr_of_classes=7) def call(self, inputs, training=None): x = inputs x = self.dense(x) x = self.reshape(x) x = self.decoder(x) return x class AutoEncoder(tf.keras.Model): def __init__(self): super(AutoEncoder, self).__init__() bottleneck_size = 32 latent_dim = 128 self.decoder = Decoder(bottleneck_size, latent_dim) self.bottleneck = Bottleneck(bottleneck_size, latent_dim) self.encoder = ConvNeXt(depths=[3, 3, 9, 3], dims=[32, 64, 128, bottleneck_size], include_top=False) def call(self, inputs, training=None): x, uv_mask = inputs # x = tf.transpose(x, [0,2,3,1]) x = self.encoder(x, training=training) x = self.bottleneck(x, training=training) x = self.decoder(x, training=training) # x = tf.transpose(x, [0,3,1,2]) # x = x * uv_mask[:,:, tf.newaxis] # x = x * uv_mask[:,tf.newaxis,:,:] x = x * uv_mask[:,:,:,tf.newaxis] return x g_mean_iou = tf.keras.metrics.MeanIoU(num_classes=7) def get_mean_iou(y_true, y_pred): g_mean_iou.reset_state() g_mean_iou.update_state(y_true, y_pred) return g_mean_iou.result() # https://github.com/NifTK/NiftyNet/blob/dev/niftynet/layer/loss_segmentation.py def dice_dense(prediction, ground_truth, weight_map=None): """ Computing mean-class Dice similarity. :param prediction: last dimension should have ``num_classes`` :param ground_truth: segmentation ground truth (encoded as a binary matrix) last dimension should be ``num_classes`` :param weight_map: :return: ``1.0 - mean(Dice similarity per class)`` """ if weight_map is not None: raise NotImplementedError prediction = tf.cast(prediction, dtype=tf.float32) ground_truth = tf.cast(ground_truth, dtype=tf.float32) ground_truth = tf.reshape(ground_truth, prediction.shape) # computing Dice over the spatial dimensions reduce_axes = list(range(len(prediction.shape) - 1)) dice_numerator = 2.0 * tf.reduce_sum( prediction * ground_truth, axis=reduce_axes) dice_denominator = \ tf.reduce_sum(tf.square(prediction), axis=reduce_axes) + \ tf.reduce_sum(tf.square(ground_truth), axis=reduce_axes) epsilon = 0.00001 dice_score = (dice_numerator + epsilon) / (dice_denominator + epsilon) return tf.reduce_mean(dice_score) @tf.function def train_step(batch): with tf.GradientTape() as tape: uv_curvature = tf.one_hot(batch['uv_curvature'], 7) pred = model([uv_curvature, batch['uv_mask']]) ce_uv_loss = scce(batch['uv_curvature'], pred) ms_ssim = tf.reduce_mean(tf.image.ssim(pred, uv_curvature, max_val=1)) # ms_ssim = tf.reduce_mean(tf.image.ssim_multiscale(tf.math.argmax(pred, axis=-1, output_type=tf.dtypes.int32)[:,:,:,tf.newaxis], batch['uv_curvature'][:,:,:,tf.newaxis], max_val=7*2)) # loss = 1e3 * (1 - ms_ssim) loss = ce_uv_loss # mesh_pred = uv2mesh(tf.tile(tf.math.argmax(pred, axis=-1, output_type=tf.dtypes.int32)[:,:,:,tf.newaxis], [1,1,1,3]))[:,:,0] # mesh_orig = tf.one_hot(batch['mesh_curvature'] + tf.cast(batch['mesh_mask'], tf.int32), 7) # ce_mesh_loss = scce(mesh_orig, mesh_pred) mean_iou = get_mean_iou(batch['uv_curvature'], tf.math.argmax(pred, axis=-1)) dice = dice_dense(pred, uv_curvature) gradients = tape.gradient(loss, model.trainable_variables) optimizer.apply_gradients(zip(gradients, model.trainable_variables)) return { 'train/loss': loss, 'train/ce_uv_loss': ce_uv_loss, 'train/ssim': ms_ssim, 'train/mean_iou': mean_iou, 'train/dice': dice #'ce_mesh_loss': ce_mesh_loss } @tf.function def valid_step(batch): uv_curvature = tf.one_hot(batch['uv_curvature'], 7) pred = model([uv_curvature, batch['uv_mask']]) ce_uv_loss = scce(batch['uv_curvature'], pred) ms_ssim = tf.reduce_mean(tf.image.ssim(pred, uv_curvature, max_val=1)) loss = ce_uv_loss mean_iou = get_mean_iou(batch['uv_curvature'], tf.math.argmax(pred, axis=-1)) dice = dice_dense(pred, uv_curvature) return { 'valid/loss': loss, 'valid/ce_uv_loss': ce_uv_loss, 'valid/ssim': ms_ssim, 'valid/mean_iou': mean_iou, 'valid/dice': dice #'ce_mesh_loss': ce_mesh_loss } def train(): step = 0 for batch in dataset_train: batch = static_dataset_train.expand_batch(batch_to_dict(batch, 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, signature_dynamic)) valid_loss = {}#valid_step(data_valid) data_valid = batch to_log = { **train_loss, **valid_loss} if step % 2500 == 0: uv_curvature = tf.one_hot(data_valid['uv_curvature'], 7) pred = model([uv_curvature, data_valid['uv_mask']]) orig_img = data_valid['uv_curvature'] pred_img = tf.math.argmax(pred, axis=-1, output_type=tf.dtypes.int32) img = tf.concat((orig_img, pred_img), axis=2).numpy() # imgs = { 'valid/images': [wandb.Image(img[i,:,:,np.newaxis] / 6.0) for i in range(4)] } imgs = { 'train/images': [wandb.Image(img[i,:,:,np.newaxis] / 6.0) for i in range(4)] } to_log = { **to_log, **imgs} wandb.log(to_log, step=step) print(step) if step % 2500 == 0: manager.save(checkpoint_number=step) step += 1 def test(): ckpt.restore(manager.latest_checkpoint) for batch in dataset_train: batch = static_dataset_train.expand_batch(batch_to_dict(batch, signature_dynamic)) uv_curvature = tf.one_hot(batch['uv_curvature'], 7) pred = model([uv_curvature, batch['uv_mask']]) orig_img = batch['uv_curvature'] pred_img = tf.math.argmax(pred, axis=-1, output_type=tf.dtypes.int32) img = tf.concat((orig_img, pred_img), axis=2).numpy() ex.imshow(img[0] / 6.0).show() print() if __name__ == '__main__': init_wandb() allow_memory_growth() parser = argparse.ArgumentParser(description='') parser.add_argument('--name', type=str) args = vars(parser.parse_args()) smpl = SMPL() scce = tf.keras.losses.SparseCategoricalCrossentropy() 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,) 'uv_curvature': (512, 256), 'mesh_curvature': (14475) } 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/train_100', batch_size=8, signature=signature_dynamic, use_filled=False) static_dataset_train = StaticDataset(folder='/home/workspace/local-data/train_100', signature=signature_static, use_filled=False) dataset_valid = factory.get_dataset(folder='/home/workspace/local-data/jumpsuit_20/valid', batch_size=8, signature=signature_dynamic) static_dataset_valid = StaticDataset(folder='/home/workspace/local-data/jumpsuit_20/valid', signature=signature_static) valid_iterator = iter(dataset_valid) model = AutoEncoder() # optimizer = tf.optimizers.Adam(learning_rate=0.002, beta_1=0.0, beta_2=0.99, epsilon=1e-8) lr_schedule = tf.keras.optimizers.schedules.ExponentialDecay(0.001, decay_steps=10000, decay_rate=0.1, staircase=False) optimizer = tf.optimizers.Adam(learning_rate=lr_schedule) folder = 'models/ae_logs/' ckpt = tf.train.Checkpoint(model=model) manager = tf.train.CheckpointManager(ckpt, 'checkpoints/' + name, max_to_keep=5) if testing: test() else: train()