import os import time import argparse import wandb import random import numpy as np import tensorflow as tf import scipy.interpolate as spi from custom_utils.custom_utils import UV2Mesh, maskFacesBatch from tensorboardX import SummaryWriter import plotly.graph_objects as go import plotly.express as ex from plotly.subplots import make_subplots 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 # 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, ConvNeXtReverseWithSkip, ConvNeXtWithSkip from stylegan2_ae.generator import Generator from custom_utils.graph_utils import Reconstructor_V4_Decoder as GNNDecoder from custom_utils.graph_utils import Reconstructor_v2 as SimpleReconstructor from dataset import DatasetFactory, StaticDataset from custom_utils.custom_utils import batch_to_dict from custom_utils.smpl import SMPL name='convunext_7' os.environ["CUDA_VISIBLE_DEVICES"] = "6" run = wandb.init(config=tf.compat.v1.flags.FLAGS, sync_tensorboard=True, project='stylegan', name=name, notes='basic pyramid. more balanced levels. take ssim (not ms-ssim) loss at each level. higher lr. on on jumpsuits. \ uv maps filled with nearest enighbour, up/downscaling with lanczos. only take loss at final level') artifact = wandb.Artifact('code', type='code') artifact.add_file('auto_encoder.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) # 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 def plot_3d(mesh_gt, mesh_pred_unposed, faces, collision, collision_faces, collision_color): mesh_pred_unposed[:,1] += 1 collision[:,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_unposed[:,0], y=mesh_pred_unposed[:,1], z=mesh_pred_unposed[:,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=collision[:,0], y=collision[:,1], z=collision[:,2], # i, j and k give the vertices of triangles i = collision_faces[:,0], j = collision_faces[:,1], k = collision_faces[:,2], vertexcolor=collision_color ) ]) 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 def plot_3d_levels(mesh_levels, faces): levels = len(mesh_levels) plot_levels = mesh_levels.copy() #[mesh_levels[i][0] for i in range(levels)] for i in range(levels): plot_levels[i][:,1] = plot_levels[i][:,1] + i * 2 meshes = [go.Mesh3d( # 8 vertices of a cube x=mesh[:,0], y=mesh[:,1], z=mesh[:,2], # i, j and k give the vertices of triangles i = faces[:,0], j = faces[:,1], k = faces[:,2] ) for mesh in mesh_levels] fig = go.Figure(data= meshes) fig.update_layout(scene_aspectmode='manual', scene_aspectratio=dict(x=1, y=levels, z=1)) fig.update_layout( scene = dict( xaxis = dict(nticks=4, range=[-1,1],), yaxis = dict(nticks=4, range=[-1,levels*2],), zaxis = dict(nticks=4, range=[-1,1],),) ) return fig 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 PyramidLevel(tf.keras.Model): def __init__(self, depths=[3, 3, 9, 3], dims=[64, 128, 256, 256]): super(PyramidLevel, self).__init__() # reverse_dims = list(reversed(dims[:-1] + [16])) # reverse_dims = dims[:-1] + [16] reverse_dims = [16] + dims[:-1] self.encoder = ConvNeXtWithSkip(depths=depths, dims=dims) self.bottleneck = Bottleneck(dims[-1]) self.decoder = ConvNeXtReverseWithSkip(depths=depths, dims=reverse_dims) def call(self, inputs, training=None): x = inputs x, skip_features = self.encoder(x, training=training) x = self.bottleneck(x, training=training) x = self.decoder([x, skip_features], training=training) return x def downscale(img, uv_mask=None): # img = tf.transpose(tf.squeeze(batch['uv_posed']), [1,2,0]).numpy() # coords = np.transpose(np.stack(np.nonzero((1 - batch['uv_mask'][0]).numpy().astype(bool))), (1,0)) # img_idx = np.transpose(np.stack(np.nonzero((batch['uv_mask'][0]).numpy().astype(bool))), (1,0)) # img_data = img[img_idx[:,0], img_idx[:,1], :] # interpolator = spi.NearestNDInterpolator(x=img_idx, y=img_data) # img_2 = interpolator(coords) # res = np.zeros((512,256,3)) # res[coords[:,0], coords[:,1], :] = img_2 # res[img_idx[:,0], img_idx[:,1], :] = img_data results = [img] if uv_mask is not None: masks = [uv_mask] for i in range(4): # print(np.array(img.shape[:2]) / (2 ** (i + 1))) results.append(tf.image.resize(img, size=np.array(img.shape[1:3]) / (2 ** (i + 1)), method=tf.image.ResizeMethod.LANCZOS5, antialias=True, preserve_aspect_ratio=True)) if uv_mask is not None: masks.append(tf.image.resize(uv_mask[:,:,:,tf.newaxis], size=np.array(uv_mask.shape[1:]) / (2 ** (i + 1)), method=tf.image.ResizeMethod.NEAREST_NEIGHBOR, antialias=False)[:,:,:,0]) if uv_mask is not None: return results, masks return results def upscale(imgs): results = [] for img in imgs: results.append(tf.image.resize(img, size=(512, 256), method=tf.image.ResizeMethod.LANCZOS5)) return results class Pyramid(tf.keras.Model): def __init__(self): super(Pyramid, self).__init__() self.level_1 = PyramidLevel(depths=[27], dims=[512]) self.level_2 = PyramidLevel(depths=[9, 27], dims=[256, 256]) self.level_3 = PyramidLevel(depths=[9, 9, 27], dims=[64, 128, 256]) self.level_4 = PyramidLevel(depths=[3, 9, 27, 3], dims=[32, 64, 128, 256]) self.level_5 = PyramidLevel(depths=[3, 3, 9, 27, 9], dims=[32, 64, 128, 256, 256]) self.levels = [self.level_5, self.level_4, self.level_3, self.level_2, self.level_1] def call(self, inputs, training=None): x, uv_mask, uv_shaped_body = inputs x = tf.transpose(x, [0,2,3,1]) x_levels = downscale(x) output = self.levels[-1](x_levels[-1]) output_levels = [output] for i in reversed(range(len(x_levels)-1)): level_out = self.levels[i](x_levels[i]) output = tf.image.resize(output, size=(output.shape[1] * 2, output.shape[2] * 2), method=tf.image.ResizeMethod.LANCZOS5) + level_out output_levels.append(output) x = output x = tf.transpose(x, [0,3,1,2]) # x = x * uv_mask[:,tf.newaxis,:,:] return x, output_levels class AutoEncoder(tf.keras.Model): def __init__(self): super(AutoEncoder, self).__init__() # bottleneck_size = 256 # self.decoder = ConvNeXtReverseWithSkip(depths=list(reversed([3, 3, 9, 3])), dims=list(reversed([bottleneck_size, 128, 64, 16]))) # self.bottleneck = Bottleneck(bottleneck_size) # self.encoder = ConvNeXtWithSkip(depths=[3, 3, 9, 3], dims=[64, 128, 256, bottleneck_size]) self.level = PyramidLevel(depths=[3, 3, 3, 3], dims=[64, 128]) def call(self, inputs, training=None): x, uv_mask, uv_shaped_body = inputs x = tf.transpose(x, [0,2,3,1]) x = tf.image.resize(x, size=(256, 128)) # x, skip_features = self.encoder(x, training=training) # x = self.bottleneck(x, training=training) # x = self.decoder([x, skip_features], training=training) x = self.level(x) x = x + tf.transpose(uv_shaped_body, [0,2,3,1]) x = tf.transpose(x, [0,3,1,2]) # x = x * uv_mask[:,:, tf.newaxis] # x = x * uv_mask[:,tf.newaxis,:,:] return x @tf.function def train_step(batch): with tf.GradientTape() as tape: pred, levels_pred = model([tf.concat((batch['uv_static'], batch['uv_body_posed']), axis=1), batch['uv_mask'], batch['uv_shaped_body']]) # pred = (pred + zero_body) * batch['mesh_mask'][:,:,tf.newaxis] mesh_pred = uv2mesh(pred) # mesh_pred = pred mesh_orig = batch['mesh_unposed'] # uv_unposed_levels, uv_mask_levels = downscale(tf.transpose(batch['uv_unposed'], [0,2,3,1]), batch['uv_mask']) ms_ssim_levels = 0 #tf.reduce_mean([tf.reduce_mean(tf.image.ssim((levels_pred[i] + 1) * uv_mask_levels[len(levels_pred) - i - 1][:,:,:,tf.newaxis], (uv_unposed_levels[len(levels_pred) - i - 1] + 1) * uv_mask_levels[len(levels_pred) - i - 1][:,:,:,tf.newaxis], max_val=10)) for i in range(len(levels_pred))]) 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_mean(tf.reduce_sum((tf.math.abs(batch['uv_unposed'] - pred)), axis=1) * batch['uv_mask']) 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=10)) fft_loss = tf.reduce_mean(tf.reduce_sum(tf.math.abs(tf.signal.fft3d(tf.complex(pred * batch['uv_mask'][:,tf.newaxis,:,:], tf.zeros_like(pred))) - tf.signal.fft3d(tf.complex(batch['uv_unposed'] * batch['uv_mask'][:,tf.newaxis,:,:], tf.zeros_like(batch['uv_unposed'])))), axis=[1,2,3])) # loss = fft_loss_pc # + e_loss + c_loss loss = 1e3 * (1 - ms_ssim) mesh_orig_2 = uv2mesh(batch['uv_unposed']) # mesh_skinned = smpl.run_garment(batch['pose_shape'][:, :72], batch['pose_shape'][:, 72:], mesh_pred) 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) optimizer.apply_gradients(zip(gradients, model.trainable_variables)) return { 'loss': loss, 'edge_loss': e_loss, 'collision_loss': c_loss, 'l1_loss': l1_loss, 'euclid_error': metric, 'ms_ssim': ms_ssim, 'fft_loss': fft_loss, 'euclid_error_reconst': metric_2, 'euclid_error_posed': euclid_posed, 'ms_ssim_levels': ms_ssim_levels } @tf.function def valid_step(batch): pred, levels_pred = model([tf.concat((batch['uv_static'], batch['uv_body_posed']), axis=1), batch['uv_mask'], batch['uv_shaped_body']]) mesh_pred = uv2mesh(pred) mesh_orig = batch['mesh_unposed'] # uv_unposed_levels, uv_mask_levels = downscale(tf.transpose(batch['uv_unposed'], [0,2,3,1]), batch['uv_mask']) ms_ssim_levels = 0#tf.reduce_mean([tf.reduce_mean(tf.image.ssim(levels_pred[i] + 1, uv_unposed_levels[len(levels_pred) - i - 1] + 1, max_val=10)) for i in range(len(levels_pred))]) 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_mean(tf.reduce_sum((tf.math.abs(batch['uv_unposed'] - pred)), axis=1) * batch['uv_mask']) 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=10)) fft_loss = tf.reduce_mean(tf.reduce_sum(tf.math.abs(tf.signal.fft3d(tf.complex(pred * batch['uv_mask'][:,tf.newaxis,:,:], tf.zeros_like(pred))) - tf.signal.fft3d(tf.complex(batch['uv_unposed'] * batch['uv_mask'][:,tf.newaxis,:,:], tf.zeros_like(batch['uv_unposed'])))), axis=[1,2,3])) loss = 1e3 * (1 - ms_ssim) 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']) return { 'loss': loss, 'edge_loss': e_loss, 'collision_loss': c_loss, 'l1_loss': l1_loss, 'euclid_error': metric, 'ms_ssim': ms_ssim, 'fft_loss': fft_loss, 'euclid_error_reconst': metric_2, 'ms_ssim_levels': ms_ssim_levels } def plot_everything(writer, batch: dict, type: str): pred, levels = model([tf.concat((batch['uv_static'], batch['uv_body_posed']), axis=1), batch['uv_mask'], batch['uv_shaped_body']]) mesh_pred = uv2mesh(pred) mesh_orig = batch['mesh_unposed'] orig_img = tf.transpose(batch['uv_unposed'], [0,2,3,1]) pred_img = tf.transpose(pred, [0,2,3,1]) img = tf.concat((orig_img, pred_img), axis=2) levels = upscale(levels) mesh_pred_levels = [uv2mesh(tf.transpose(levels[i], [0,3,1,2])) for i in range(len(levels))] with writer.as_default(): tf.summary.image('images', img, step=step, max_outputs=4) tf.summary.image('levels', tf.concat(levels, axis=2) , step=step, max_outputs=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() mesh_posed_levels = [smpl.run_garment(batch['pose_shape'][:, :72], batch['pose_shape'][:, 72:], mesh_pred_levels[i]).numpy() for i in range(len(levels))] mesh_posed_levels = [mesh_posed_levels[j][0, mask[0], :] for j in range(len(levels))] 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))] fig_levels = plot_3d_levels(mesh_posed_levels, faces[0]) 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(pred.shape[0]) } # fig = plot_3d(gt[i], garment_unposed[i], faces[i], collision[i], collision_faces[i], collision_color[i]) wandb.log( { **figs, **{ type + '/levels_garments': fig_levels } } ) if __name__ == '__main__': allow_memory_growth() parser = argparse.ArgumentParser(description='') parser.add_argument('--name', type=str) args = vars(parser.parse_args()) smpl = SMPL() # R = smpl.run_rodrigues((np.zeros((8,72), dtype=np.float32))) # zero_body = smpl.run(R, np.zeros((8, 11), dtype=np.float32))[0] 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=8, 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=8, signature=signature_dynamic) static_dataset_valid = StaticDataset(folder='/home/workspace/local-data/jumpsuit_20/valid', signature=signature_static) # model = AutoEncoder() model = Pyramid() # 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=30000, decay_rate=0.1, staircase=False) optimizer = tf.optimizers.Adam(learning_rate=lr_schedule) folder = 'models/ae_logs/' train_summary_writer = tf.summary.create_file_writer(folder + name + '/train') valid_summary_writer = tf.summary.create_file_writer(folder + name + '/valid') valid_iterator = iter(dataset_valid) step = 0 for batch in dataset_train: # batch = batch_to_dict(batch, signature_dynamic) batch = static_dataset_train.expand_batch(batch_to_dict(batch, signature_dynamic)) train_loss = train_step(batch) for key in train_loss.keys(): with train_summary_writer.as_default(): tf.summary.scalar(key, train_loss[key], step=step) # data_valid = 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) for key in valid_loss.keys(): with valid_summary_writer.as_default(): tf.summary.scalar(key, valid_loss[key], step=step) if step % 500 == 0: plot_everything(train_summary_writer, batch, 'train') plot_everything(valid_summary_writer, data_valid, 'valid') # fig = make_subplots(rows=1, cols=5, start_cell="top-left") # for i, l in enumerate(levels): # fig.add_trace(ex.imshow((l[0] + 1) * 128).data[0], row=1, col=i+1) print(step) step += 1