import os import sys sys.path.append(os.path.dirname(os.path.abspath(__file__)) + '/..') import importlib import argparse parser = argparse.ArgumentParser(description='') parser.add_argument('--name', type=str) parser.add_argument('--config', type=str) parser.add_argument('--debug', action='store_true') args = vars(parser.parse_args()) config_module = importlib.import_module(args['config']) config = config_module.config if args['debug']: from configs.cvae_norm_1 import config os.environ["CUDA_DEVICE_ORDER"]="PCI_BUS_ID" os.environ["CUDA_VISIBLE_DEVICES"] = config['gpu'] if args['debug']: os.environ["CUDA_LAUNCH_BLOCKING"] = '1' import time import argparse import wandb import tqdm import random import numpy as np import plotly.graph_objects as go import plotly.express as ex from PIL import Image if config['is_skirt']: from losses.losses import edge_loss_skirt as edge_loss else: from losses.losses import edge_loss import torch import torch.nn as nn import torch.optim as optim from data.dataset import Dataset from models.cond_encoder import AutoEncoder from utils.checkpoints import CheckpointSaver, load_model from utils.utils import InfiniteDataLoader as DataLoader from utils.postprocess import fix_collision from losses.losses import collision_loss, normal_loss from pytorch_msssim import MS_SSIM from models.cvae_norm_model import CVAENorm from smpl.smpl_torch import SMPL from custom_utils.custom_utils import UV2Mesh, Accumulator, plot_3d, get_summary_html, maskFacesBatch, get_summary_str, plot_3d_collision def init_wandb(): run = wandb.init(project='iccv', name=config['name'], notes=config['notes'], dir='/data-local/127/temp', tags=config['tags']) artifact = wandb.Artifact('code', type='code') artifact.add_file('scripts/cvae_norm.py') artifact.add_file('losses/losses.py') artifact.add_file('models/base.py') artifact.add_file('models/cond_encoder.py') artifact.add_file('models/convnext.py') artifact.add_file('models/cvae_norm_model.py') artifact.add_file('data/dataset.py') config_file_names = [key for key in sys.modules.keys() if key.startswith('configs.')] for config_file_name in config_file_names: file_name = '/'.join(config_file_name.split('.')) + '.py' if os.path.exists(file_name): artifact.add_file(file_name) run.log_artifact(artifact) uv2mesh = UV2Mesh(res=256, is_skirt=config['is_skirt'], is_smpl_orig=config['is_cape']) def kl_loss(mean: torch.Tensor, logvar: torch.Tensor) -> torch.Tensor: kl_loss = 1 + logvar - torch.square(mean) - torch.exp(logvar) kl_loss = torch.mean(kl_loss) kl_loss *= -0.5 return kl_loss def train_step(batch): model.train() pred, mean, logvar = model([batch['uv_normals'], batch['uv_static'], batch['uv_body_posed'], batch['uv_mask']]) pred = pred * 1.1 mesh_pred = uv2mesh(pred) l2_loss = torch.mean(1e3 * torch.mean(torch.sum(((batch['uv_normals'] - pred) ** 2), axis=-1), axis=[1, 2])) l2_mesh_loss = torch.mean(1e3 * torch.mean(torch.sum(batch['mesh_mask'][:,:,None] * (batch['mesh_normals'] - mesh_pred) ** 2, axis=-1), axis=-1)) ms_ssim = torch.mean(_MSSSIM(pred + 1.1, batch['uv_normals'] + 1.1)) kl = kl_loss(mean, logvar) reconstr_loss = l2_loss + l2_mesh_loss + (1 - ms_ssim) loss = reconstr_loss + g_balancing_coeff * kl optimizer.zero_grad() loss.backward() optimizer.step() model.eval() with torch.inference_mode(): mean = torch.mean(mean) logvar = torch.mean(logvar) metric = torch.sum(torch.sqrt(torch.sum(batch['mesh_mask'][:,:,None] * (batch['mesh_normals'] - mesh_pred.detach()) ** 2, axis=-1))) / torch.sum(batch['mesh_mask']) return { 'train/loss': loss, 'train/euclid_error': metric, 'train/reconstr_loss': reconstr_loss, 'train/mean': mean, 'train/logvar': logvar, 'train/kl_loss': kl, 'train/var': np.e ** logvar, 'train/l2_loss': l2_loss, 'train/l2_mesh_loss': l2_mesh_loss, 'train/ms_ssim': ms_ssim, } def valid_step(batch): model.eval() with torch.inference_mode(): pred, mean, logvar = model([batch['uv_normals'], batch['uv_static'], batch['uv_body_posed'], batch['uv_mask']]) pred = pred * 1.1 mesh_pred = uv2mesh(pred) l2_loss = torch.mean(1e3 * torch.mean(torch.sum(((batch['uv_normals'] - pred) ** 2), axis=-1), axis=[1, 2])) l2_mesh_loss = torch.mean(1e3 * torch.mean(torch.sum(batch['mesh_mask'][:,:,None] * (mesh_pred - batch['mesh_normals']) ** 2, axis=-1), axis=-1)) ms_ssim = torch.mean(_MSSSIM(pred + 1.1, batch['uv_static'] + 1.1)) kl = kl_loss(mean, logvar) reconstr_loss = l2_loss + l2_mesh_loss + (1 - ms_ssim) loss = reconstr_loss + g_balancing_coeff * kl mean = torch.mean(mean) logvar = torch.mean(logvar) metric = torch.sum(torch.sqrt(torch.sum(batch['mesh_mask'][:,:,None] * (batch['mesh_normals'] - mesh_pred.detach()) ** 2, axis=-1))) / torch.sum(batch['mesh_mask']) return { 'valid/loss': loss, 'valid/euclid_error': metric, 'valid/reconstr_loss': reconstr_loss, 'valid/l2_mesh_loss': l2_mesh_loss, 'valid/mean': mean, 'valid/logvar': logvar, 'valid/kl_loss': kl, 'valid/var': np.e ** logvar, 'valid/ms_ssim': ms_ssim, } def plot_everything(batch: dict, type: str): model.eval() with torch.inference_mode(): pred, mean, logvar = model([batch['uv_normals'], batch['uv_static'], batch['uv_body_posed'], batch['uv_mask']]) pred = pred * 1.1 # mesh_pred = uv2mesh(pred).detach().cpu().numpy() uv_static_img = torch.permute(batch['uv_static'], [0,2,3,1]) uv_body_posed_img = torch.permute(batch['uv_body_posed'], [0,2,3,1]) orig_img = (torch.permute(batch['uv_normals'], [0,2,3,1]) + 1.1) / 2.2 pred_img = torch.permute(pred, [0,2,3,1]) img = torch.concat((uv_static_img, uv_body_posed_img, orig_img, pred_img), axis=2) imgs = [wandb.Image((img[i].cpu().numpy() + 1) / 2.0) for i in range(4)] # F = np.load("smpl/smpl_faces" + skirt_modifier + ("_orig" if config['is_cape'] else "") + ".npy") # mask = batch['mesh_mask'].cpu().numpy().astype(bool) mean_hist = wandb.Histogram(sequence=mean.cpu().numpy().mean(axis=0)) logvar_hist = wandb.Histogram(sequence=logvar.cpu().numpy().mean(axis=0)) return { **{ type + '/images': imgs, type + '/mean_hist': mean_hist, type + '/logvar_hist': logvar_hist } } def sample(folder): # run = wandb.init(project='vae_plots', name=folder.split('/')[-1]) load_model(model,folder) count = 0 for batch in dataset_train: batch = static_dataset_train.expand_batch(batch_to_dict(batch, config['signature_dynamic'])) uv_normals = tf.one_hot(batch['uv_normals'], 7) nr_of_samples=2 pred = model.sample_single(batch['uv_static'][0], batch['uv_body_posed'][0], uv_normals[0], batch['uv_mask'][0], nr_of_samples=nr_of_samples) pose, shape = batch['pose_shape'][0, :72], batch['pose_shape'][0, 72:] pose, shape = tf.tile(pose[tf.newaxis,:], [nr_of_samples,1]), tf.tile(shape[tf.newaxis,:], [nr_of_samples,1]) mesh_pred = uv2mesh(pred) mesh_posed = smpl.run_garment(pose, shape, mesh_pred).numpy() mesh_orig = batch['mesh_posed'][0].numpy() mesh_orig_reposed = smpl.run_garment(pose[:1], shape[:1], batch['mesh_unposed'][:1]).numpy()[0] body = batch['mesh_body_posed'][0].numpy() body_color = np.ones_like(body, dtype=np.int32)*100 F = np.load("custom_utils/smpl_faces.npy") mask = batch['mesh_mask'].numpy().astype(bool)[0] _, faces = _maskFaces(np.ones((config['smpl_res'], 3)), F, mask) pred_zero = model.sample_single(batch['uv_static'][0], batch['uv_body_posed'][0], uv_normals[0], batch['uv_mask'][0], nr_of_samples=nr_of_samples, zero_latent=True) mesh_pred_zero = uv2mesh(pred_zero) mesh_posed_zero = smpl.run_garment(pose, shape, mesh_pred_zero).numpy() meshes = [] meshes.append(go.Mesh3d( # 8 vertices of a cube x=mesh_orig_reposed[mask,0], y=mesh_orig_reposed[mask,2], z=mesh_orig_reposed[mask,1], # i, j and k give the vertices of triangles i = faces[:,0], j = faces[:,1], k = faces[:,2] )) for i in range(nr_of_samples): x = mesh_posed[i][mask, :].copy() # x[:, 2] += 1 * (i + 1) x[:, 2] += 1 meshes.append(go.Mesh3d( # 8 vertices of a cube x=x[:,0], y=x[:,2], z=x[:,1], # i, j and k give the vertices of triangles i = faces[:,0], j = faces[:,1], k = faces[:,2] )) for i in range(nr_of_samples): x = mesh_posed_zero[i][mask, :].copy() # x[:, 2] += 1 * (i + 1) x[:, 2] += 2 meshes.append(go.Mesh3d( # 8 vertices of a cube x=x[:,0], y=x[:,2], z=x[:,1], # i, j and k give the vertices of triangles i = faces[:,0], j = faces[:,1], k = faces[:,2] )) # for i in range(5): # x = body.copy() # x[:, 2] += 1 * i # meshes.append(go.Mesh3d( # # 8 vertices of a cube # x=x[:,0], # y=x[:,2], # z=x[:,1], # # i, j and k give the vertices of triangles # i = F[:,0], # j = F[:,1], # k = F[:,2], # vertexcolor=body_color # )) fig = go.Figure(data=meshes) fig.update_layout(scene_aspectmode='manual', scene_aspectratio=dict(x=1, y=2, z=1)) # fig.update_layout(scene_aspectmode='manual', scene_aspectratio=dict(x=1, y=nr_of_samples-1, z=1)) fig.update_layout( scene = dict( xaxis = dict(nticks=4, range=[-1,1],), # yaxis = dict(nticks=4, range=[-1,nr_of_samples+1],), yaxis = dict(nticks=4, range=[-1,3],), zaxis = dict(nticks=4, range=[-1,1],),) ) # wandb.log({'plot_' + str(count): fig}) fig.show() pred = pred.numpy() frames = [Image.fromarray(((pred[i] + 1) * 128).astype(np.int8), mode='RGB') for i in range(pred.shape[0])] frames[0].save("temp/garment_1.gif", format="GIF", append_images=frames[1:], save_all=True, duration=500, loop=0) if count > 10: break print(count) count += 1 print() def test(): str_split = config['name'].split('_') test_idx = str_split.index('test') checkpoint_name = '_'.join(str_split[:test_idx]) load_model(model, 'checkpoints/' + checkpoint_name) 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 tqdm.tqdm(dataset_test): batch = static_dataset_test.expand_batch(batch_to_dict(batch, config['signature_dynamic'])) test_loss = test_step(batch) losses.append(test_loss) to_log = { **{ 'current_step': step }, **test_loss } if step % 1000 == 0: figs = plot_everything(batch, 'test') to_log = { **to_log, **figs } wandb.log(to_log, step = step) # print(step) step += 1 # averages = dict() path_to_plotly_html = "temp/plotly_figure.html" histograms = dict() for key in test_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'] = wandb.Html(path_to_plotly_html) # averages['all/' + key.split('/')[-1] + '_avg'] = np.asarray(accumulated).mean() wandb.log({ **histograms }, step = step) wandb.finish() pass def train(): global g_balancing_coeff global step valid_iterator = iter(valid_dataloader) for batch in train_dataloader: train_loss = train_step(batch) train_accumulator.update(train_loss) if step % 25 == 0: data_valid = next(valid_iterator) valid_loss = valid_step(data_valid) valid_accumulator.update(valid_loss) if step % 1000 == 0 or (step < 1000 and step % 100 == 0): to_log = dict({ **train_loss, **valid_loss, **{ 'current_step': step } }) if step % 5000 == 0 or (step < 5000 and step % 1000 == 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)) } } if not args['debug']: wandb.log(to_log, step=step) train_accumulator.reset() valid_accumulator.reset() print(step) if train_loss['train/euclid_error'] < (config['balancing_activation_limit'] if 'balancing_activation_limit' in config.keys() else 0.017): g_balancing_coeff += 1 / 10000 if step % 10000 == 0: ckpt_saver(model, step, optimizer, None) step += 1 if __name__ == '__main__': if not args['debug']: init_wandb() smpl = SMPL(orig_smpl=config['is_cape'], path='smpl', device=config['device']) skirt_modifier = '_skirt' if config['is_skirt'] else '' dataset_train = Dataset(config['train_dir'], config['signature'], device=config['device'], frames_file=config['train_frames'], use_cache=config['dataset_in_memory']) dataset_valid = Dataset(config['valid_dir'], config['signature'], device=config['device'], frames_file=config['valid_frames'], use_cache=config['dataset_in_memory']) train_dataloader = DataLoader(dataset_train, batch_size=4, drop_last=True, shuffle=True, ) valid_dataloader = DataLoader(dataset_valid, batch_size=4, drop_last=True, shuffle=True) train_accumulator = Accumulator() valid_accumulator = Accumulator() model = CVAENorm(config) optimizer = optim.Adam(model.parameters(), lr=config['lr']) _MSSSIM = MS_SSIM(data_range=2, size_average=True, channel=3) g_balancing_coeff = config['starting_balancing_coeff'] ckpt_saver = CheckpointSaver('checkpoints/iccv/' + config['name'], top_n=5) step = 0 if config['pretrained_model'] != '': step = load_model(model, config['pretrained_model']) if not args['debug']: # model = torch.compile(model) wandb.watch(model, log='all', log_freq=10000, log_graph=True) train()