From 57b7aed4bae9b0dc059cd7c59fbc8b1d51f1b207 Mon Sep 17 00:00:00 2001 From: Hunor Laczko Date: Sat, 8 Jul 2023 11:54:21 +0200 Subject: [PATCH] small updates --- custom_utils/custom_utils.py | 24 +- data/dataset_cape.py | 51 +-- data/utils.py | 4 +- docker/Dockerfile2 | 1 + docker/docker-compose.yml | 42 +++ models/pyramid_level.py | 88 +---- models/pyramid_model.py | 7 +- scripts/cvae.py | 5 +- scripts/cvae_norm.py | 82 ++--- scripts/cvae_pyramid.py | 32 +- scripts/cvae_pyramid_fine.py | 557 +++++++++++++++++++++++++++++ scripts/cvae_pyramid_speed_test.py | 160 +++++++++ scripts/generate_results.py | 47 ++- utils/generate_figures.py | 3 +- utils/postprocess.py | 2 +- 15 files changed, 884 insertions(+), 221 deletions(-) create mode 100644 scripts/cvae_pyramid_fine.py create mode 100644 scripts/cvae_pyramid_speed_test.py diff --git a/custom_utils/custom_utils.py b/custom_utils/custom_utils.py index b41c681..c47a39b 100644 --- a/custom_utils/custom_utils.py +++ b/custom_utils/custom_utils.py @@ -35,32 +35,14 @@ class UV2Mesh(nn.Module): self.uv_pixels = self.uv_map_discreet[m2uv] self.smpl_res = 14475 if not is_smpl_orig else 3638 + self.resizer = Resize(size=(512, 256), interpolation=InterpolationMode.BILINEAR) + def uv_to_mesh(self, uv): if uv.shape[1] == 3 or uv.shape[1] == 7: uv = torch.permute(uv, [0,2,3,1]) if uv.shape[1] != 512: - uv = Resize(uv[:,:,None], size=(512, 256), interpolation=InterpolationMode.BILINEAR) - - # batch_size = uv.shape[0] - - # x1_ind = tf.concat((tf.tile(self.uv_pixels[:, 0, :][tf.newaxis, :, :], [batch_size, 1, 1]), tf.zeros((batch_size, self.smpl_res, 1), dtype=tf.int32)), axis=-1) - # y1_ind = tf.concat((tf.tile(self.uv_pixels[:, 0, :][tf.newaxis, :, :], [batch_size, 1, 1]), tf.ones((batch_size, self.smpl_res, 1), dtype=tf.int32)), axis=-1) - # z1_ind = tf.concat((tf.tile(self.uv_pixels[:, 0, :][tf.newaxis, :, :], [batch_size, 1, 1]), tf.ones((batch_size, self.smpl_res, 1), dtype=tf.int32) * 2), axis=-1) - # x2_ind = tf.concat((tf.tile(self.uv_pixels[:, 1, :][tf.newaxis, :, :], [batch_size, 1, 1]), tf.zeros((batch_size, self.smpl_res, 1), dtype=tf.int32)), axis=-1) - # y2_ind = tf.concat((tf.tile(self.uv_pixels[:, 1, :][tf.newaxis, :, :], [batch_size, 1, 1]), tf.ones((batch_size, self.smpl_res, 1), dtype=tf.int32)), axis=-1) - # z2_ind = tf.concat((tf.tile(self.uv_pixels[:, 1, :][tf.newaxis, :, :], [batch_size, 1, 1]), tf.ones((batch_size, self.smpl_res, 1), dtype=tf.int32) * 2), axis=-1) - - - # x1 = tf.gather_nd(uv, x1_ind, batch_dims=1) - # y1 = tf.gather_nd(uv, y1_ind, batch_dims=1) - # z1 = tf.gather_nd(uv, z1_ind, batch_dims=1) - # x2 = tf.gather_nd(uv, x2_ind, batch_dims=1) - # y2 = tf.gather_nd(uv, y2_ind, batch_dims=1) - # z2 = tf.gather_nd(uv, z2_ind, batch_dims=1) - - # p1 = tf.stack((x1, y1, z1), axis=-1) - # p2 = tf.stack((x2, y2, z2), axis=-1) + uv = torch.permute(self.resizer(torch.permute(uv, [0,3,1,2])), [0,2,3,1]) mesh = torch.mean(uv[:, self.uv_pixels[:,:,0], self.uv_pixels[:,:,1]].float(), dim=2) return mesh diff --git a/data/dataset_cape.py b/data/dataset_cape.py index ef6c9d6..1680741 100644 --- a/data/dataset_cape.py +++ b/data/dataset_cape.py @@ -29,7 +29,7 @@ def read_frames(folder, shuffle=True, is_cape=False, testing=False, frames_file= if is_cape: frames = ['.'.join(frame.split('.')[:-1]) for frame in frames] # .split('_')[0] - frames = [Frame(frame.split('.')[0], frame.split('.')[1]) for frame in frames] + frames = [Frame(frame.split('.')[0], frame.split('.')[1], 'cape') for frame in frames] else: frames = [frame.split('.')[0] for frame in frames] # .split('_')[0] frames = [Frame(frame.split('_')[0], frame.split('_')[1]) for frame in frames] @@ -91,11 +91,10 @@ class StaticCache(): if 'mesh_static' in self.signature: mesh_static = np.load(os.path.join(self.folder, 'mesh_static', id + '.npz')); mesh_static = mesh_static['mesh_static']; data['mesh_static'] = mesh_static.astype(np.float32) - if 'mesh_mask' in self.signature: - if self.is_cape: - data['mesh_mask'] = np.ones((3638), np.float32) - else: - mesh_mask = np.load(os.path.join(self.folder, 'mesh_mask', id + '.npy')); mesh_mask = mesh_mask.astype(np.float32); data['mesh_mask'] = mesh_mask + if self.is_cape: + data['mesh_mask'] = np.ones((3638), np.float32) + else: + mesh_mask = np.load(os.path.join(self.folder, 'mesh_mask', id + '.npy')); mesh_mask = mesh_mask.astype(np.float32); data['mesh_mask'] = mesh_mask # if 'uv_shaped_body' in self.signature: # uv_shaped_body = np.load(os.path.join(self.folder, 'uv_shaped_body', id + '.npz')); uv_shaped_body = uv_shaped_body['uv_shaped_body']; data['uv_shaped_body'] = uv_shaped_body @@ -198,7 +197,12 @@ class DatasetCape(torch.utils.data.Dataset): item['uv_posed' + res_string] = uv_posed.astype(np.float32) if 'uv_normals' + res_string in self.signature: - uv_normals = np.load(os.path.join(self.folder, 'uv_normals' + res_string, frame.id + separator + frame.frame_nr + '.npz')); uv_normals = uv_normals['uv_normals'] + try: + uv_normals = np.load(os.path.join(self.folder, 'uv_normals' + res_string, frame.id + separator + frame.frame_nr + '.npz')); uv_normals = uv_normals['uv_normals'] + except: + print('Warning: uv_normals not found for frame ' + frame.id + separator + frame.frame_nr + '.npz') + uv_normals = np.zeros((res, int(res/2), 3), dtype=np.float32) + item['uv_normals' + res_string] = uv_normals @@ -223,27 +227,28 @@ if __name__ == '__main__': signature = { 'id', 'frame_nr', - 'pose_shape', - 'uv_posed', - 'uv_body_posed', - 'mesh_body_posed', - 'mesh_posed', - 'mesh_unposed', - 'uv_unposed', - 'uv_curvature', - 'mesh_curvature', - 'uv_static', - 'mesh_static', - 'mesh_mask', - 'uv_mask', - 'uv_shaped_body', + # 'pose_shape', + # 'uv_posed', + # 'uv_body_posed', + # 'mesh_body_posed', + # 'mesh_posed', + # 'mesh_unposed', + # 'uv_unposed', + 'uv_normals', + # 'mesh_curvature', + # 'uv_static', + # 'mesh_static', + # 'mesh_mask', + # 'uv_mask', + # 'uv_shaped_body', } - dataset = Dataset('/data-local/127/train', signature, resolutions=[512], device=device, frames_file='frames_jumpsuit.txt') + dataset = DatasetCape('/data-local/127_2/cape_processed/train/female', signature, resolutions=[512, 256, 128, 64], device=device, frames_file=None, is_cape=True) train_dataloader = DataLoader(dataset, batch_size=4, drop_last=True, shuffle=False) - for batch in train_dataloader: + for i, batch in enumerate(train_dataloader): batch + print(i) pass pass diff --git a/data/utils.py b/data/utils.py index 1e1596b..2dde4cd 100644 --- a/data/utils.py +++ b/data/utils.py @@ -11,7 +11,9 @@ class Frame: def __eq__(self, other): return (self.id, self.frame_nr, self.garment) == (other.id, other.frame_nr, self.garment) - + + def __str__(self): + return f'{self.id}_{self.frame_nr}_{self.garment}' def save_to_h5file(h5file, id, frame_nr, garment, data, name, type): filters = tb.Filters(complevel=9, complib='blosc2') diff --git a/docker/Dockerfile2 b/docker/Dockerfile2 index ef8570c..13752ff 100644 --- a/docker/Dockerfile2 +++ b/docker/Dockerfile2 @@ -42,6 +42,7 @@ COPY requirements.txt /tmp/ RUN pip install torch-cluster -f https://data.pyg.org/whl/torch-2.0.0+cu117.html RUN pip install --requirement /tmp/requirements.txt +RUN pip install pyvista flask==2.1.2 pyinstaller==5.1 sphinx ipyvtklink pythreejs tqdm imageio imageio-ffmpeg matplotlib cmocean # defining the volumes that will be mounted VOLUME [ "/data-net" ] diff --git a/docker/docker-compose.yml b/docker/docker-compose.yml index dfb7030..76d69ab 100644 --- a/docker/docker-compose.yml +++ b/docker/docker-compose.yml @@ -48,6 +48,48 @@ services: container_name: lhunor_iccvw_pt2.0.1 ipc: host tty: true + ulimits: + memlock: -1 + stack: 67108864 + volumes: + - '/home-net/lhunor:/home-net' + - '/data-net/guest/lhunor/data:/data-net' + - '/data-fast/126-data1/lhunor/data:/data-local/126' + - '/data-fast/127-data1/lhunor/data:/data-local/127' + - '/data-fast/127-data2/lhunor/data:/data-local/127_2' + - '/data-fast/128-data1/lhunor/data:/data-local/128' + deploy: + resources: + reservations: + devices: + - capabilities: [gpu] + + lhunor_iccvw_2: + image: lhunor_iccvw:pt2.0.1 + container_name: lhunor_iccvw_2_pt2.0.1 + ipc: host + tty: true + ulimits: + memlock: -1 + stack: 67108864 + volumes: + - '/home-net/lhunor:/home-net' + - '/data-net/guest/lhunor/data:/data-net' + - '/data-fast/126-data1/lhunor/data:/data-local/126' + - '/data-fast/127-data1/lhunor/data:/data-local/127' + - '/data-fast/127-data2/lhunor/data:/data-local/127_2' + - '/data-fast/128-data1/lhunor/data:/data-local/128' + deploy: + resources: + reservations: + devices: + - capabilities: [gpu] + + lhunor_iccvw_pv: + image: lhunor_iccvw:pt2.0.1_pv + container_name: lhunor_iccvw_pt2.0.1_pv + ipc: host + tty: true ulimits: memlock: -1 stack: 67108864 diff --git a/models/pyramid_level.py b/models/pyramid_level.py index b8abeb1..d5cfda9 100644 --- a/models/pyramid_level.py +++ b/models/pyramid_level.py @@ -13,91 +13,6 @@ from models.base import AEEncoder, VariationalEncoder, Decoder from models.upscaler import Upscaler - -# class PyramidLevel(nn.Module): - -# def __init__(self, config): -# super(PyramidLevel, self).__init__() -# self.latent_dim = config['latent_dim'] -# self.size = config['resolution'] - -# self.encoder: VariationalEncoder = VariationalEncoder(config['encoder_block_settings'], config['input_features'], kernel_size=config['kernel_size']) -# self.decoder: Decoder = Decoder(config['decoder_block_settings'], config['kernel_size']) - -# self.upscale_enhancer = None -# if config['upscale_enhancer'] != '': -# k_size = config['upscale_enhancer_kernel_size'] -# self.upscale_enhancer = Upscaler(config['resolution'], kernel_size=k_size) -# load_model(self.upscale_enhancer, config['upscale_enhancer']) -# for param in self.upscale_enhancer.parameters(): param.requires_grad = False - -# if config['avg_garment_path'] != '': -# self.avg_garment = np.load(config['avg_garment_path']) -# else: -# self.avg_garment = None - - -# def enhance(self, low, mask, training=None): -# x = self.upscale_enhancer([low, mask], training=training) -# return x - - -# def sample(self, z_cond, uv_mask, noise=None): -# if noise is None: -# eps = torch.normal(shape=(uv_mask.shape[0], self.latent_dim)) -# else: -# eps = noise - -# z = torch.concat([eps, z_cond], dim=-1) - -# x = self.decoder(z) - -# if self.avg_garment is not None: -# x = x + self.avg_garment[None,:,:,:] - -# x = x * uv_mask[:,None,:,:] - -# return x - - -# def reparameterize(self, mean, logvar, training, fix_noise=False): -# if training == True: -# if not fix_noise: -# eps = torch.normal(mean=0.0, std=1.0, size=mean.shape) -# else: -# eps = torch.normal(mean=0.0, std=1.0, size=mean.shape) -# eps = torch.tile(eps, [mean.shape[0],1]) -# out = eps * torch.exp(logvar * .5) + mean -# else: -# out = torch.exp(logvar * .5) + mean -# return out - - -# def call(self, inputs, z_cond, training=None): -# uv_unposed, uv_template, uv_body_posed, uv_curv, uv_mask, uv_mask_high = inputs - -# x = torch.concat([uv_unposed, uv_template, uv_body_posed, uv_curv], dim=1) -# mean, logvar = self.encoder(x, training=training) -# z = self.reparameterize(mean, logvar, training) - -# z = torch.concat([z, z_cond], dim=-1) -# x = self.decoder(z, training=training) - -# if self.avg_garment is not None: -# x = x + self.avg_garment[None,:,:,:] - -# x = x * uv_mask[:,None,:,:] - -# # if self.upscale_enhancer is not None: -# # pred_low = self.enhance(x, uv_mask, training=training) -# # x = tf.image.resize(pred_low, (512, 256), tf.image.ResizeMethod.LANCZOS5) - -# # x = x * uv_mask_high[:,:,:,tf.newaxis] - -# return x, mean, logvar - - - class PyramidLevel(nn.Module): def __init__(self, config, use_normals=True): @@ -115,6 +30,7 @@ class PyramidLevel(nn.Module): for param in self.upscale_enhancer.parameters(): param.requires_grad = False self.use_normals = use_normals + self.scaling = 1.0 if 'scaling' not in config else config['scaling'] def enhance(self, low, mask): x = self.upscale_enhancer([low, mask]) @@ -175,4 +91,6 @@ class PyramidLevel(nn.Module): # x = x * uv_mask_high[:,:,:,tf.newaxis] + x = x * self.scaling + return x, mean, logvar \ No newline at end of file diff --git a/models/pyramid_model.py b/models/pyramid_model.py index 447aab5..1996ecd 100644 --- a/models/pyramid_model.py +++ b/models/pyramid_model.py @@ -66,8 +66,8 @@ class Pyramid(nn.Module): # pred = pred + levels_input[0][2] # uv_body_posed_32 if 1 != len(self.levels): pred = self.levels[0].enhance(pred, levels_input[0][-2]) # levels_input[i][-2]=uv_mask_res - pred = self.resizers[self.levels[1].size](pred) out_levels.append([pred, mean, logvar]) + pred = self.resizers[self.levels[1].size](pred) pred = pred * levels_input[1][-2][:,None,:,:] else: pred = self.levels[0].enhance(pred, levels_input[0][-2]) # levels_input[i][-2]=uv_mask_res @@ -86,8 +86,9 @@ class Pyramid(nn.Module): pred = self.resizers[self.levels[i+1].size](pred) pred = pred * levels_input[i+1][-2][:,None,:,:] else: - pred = self.levels[-1].enhance(pred, levels_input[-1][-2]) - pred = self.resizers[512](pred) + if self.levels[-1].size != 512: + pred = self.levels[-1].enhance(pred, levels_input[-1][-2]) + pred = self.resizers[512](pred) pred = pred * levels_input[-1][-1][:,None,:,:] # full res uv mask out_levels.append([pred, mean, logvar]) diff --git a/scripts/cvae.py b/scripts/cvae.py index 948e6bf..3bfcb35 100644 --- a/scripts/cvae.py +++ b/scripts/cvae.py @@ -509,7 +509,10 @@ if __name__ == '__main__': step = 0 if config['pretrained_model'] != '': - step = load_model(model, config['pretrained_model'], optimizer) + if 'ignore_saved_optimizer' in config.keys() and config['ignore_saved_optimizer']: + step = load_model(model, config['pretrained_model']) + else: + step = load_model(model, config['pretrained_model'], optimizer=optimizer) if not args['debug']: # model = torch.compile(model) diff --git a/scripts/cvae_norm.py b/scripts/cvae_norm.py index c749ad3..2a305dc 100644 --- a/scripts/cvae_norm.py +++ b/scripts/cvae_norm.py @@ -10,10 +10,12 @@ 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 + from configs.iccvw.cvae_norm_1 import config +else: + config_module = importlib.import_module(args['config']) + config = config_module.config os.environ["CUDA_DEVICE_ORDER"]="PCI_BUS_ID" os.environ["CUDA_VISIBLE_DEVICES"] = config['gpu'] @@ -51,7 +53,8 @@ from custom_utils.custom_utils import UV2Mesh, Accumulator, plot_3d, get_summary def init_wandb(): - run = wandb.init(project='iccv', name=config['name'], notes=config['notes'], dir='/data-local/127/temp', tags=config['tags']) + wandb.login(host='https://wandb2.lnrweb.com', key='local-2a78b434e9bc51e9f12625f8321a9e3ee34af16d', relogin=True, force=True) + run = wandb.init(project='iccvw', 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') @@ -80,13 +83,13 @@ def kl_loss(mean: torch.Tensor, logvar: torch.Tensor) -> torch.Tensor: 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 + pred = pred * 1.4 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)) + ms_ssim = torch.mean(_MSSSIM(pred + 1.4, batch['uv_normals'] + 1.4)) kl = kl_loss(mean, logvar) reconstr_loss = l2_loss + l2_mesh_loss + (1 - ms_ssim) @@ -114,12 +117,12 @@ 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 + pred = pred * 1.4 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)) + ms_ssim = torch.mean(_MSSSIM(pred + 1.4, batch['uv_static'] + 1.4)) kl = kl_loss(mean, logvar) reconstr_loss = l2_loss + l2_mesh_loss + (1 - ms_ssim) @@ -142,12 +145,12 @@ def plot_everything(batch: dict, type: str): 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 + pred = pred * 1.4 # 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 + orig_img = (torch.permute(batch['uv_normals'], [0,2,3,1]) + 1.4) / 2.8 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)] @@ -281,54 +284,6 @@ def sample(folder): -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 @@ -358,10 +313,10 @@ def train(): 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): + if train_loss['train/euclid_error'] < config['balancing_activation_limit']: g_balancing_coeff += 1 / 10000 - if step % 10000 == 0: + if step % 20000 == 0: ckpt_saver(model, step, optimizer, None) step += 1 @@ -387,11 +342,14 @@ if __name__ == '__main__': _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) + ckpt_saver = CheckpointSaver('checkpoints/iccvw/' + config['name'], top_n=25) step = 0 if config['pretrained_model'] != '': - step = load_model(model, config['pretrained_model']) + if 'ignore_saved_optimizer' in config.keys() and config['ignore_saved_optimizer']: + step = load_model(model, config['pretrained_model']) + else: + step = load_model(model, config['pretrained_model'], optimizer=optimizer) if not args['debug']: # model = torch.compile(model) diff --git a/scripts/cvae_pyramid.py b/scripts/cvae_pyramid.py index 762b81d..f2b99fc 100644 --- a/scripts/cvae_pyramid.py +++ b/scripts/cvae_pyramid.py @@ -11,7 +11,7 @@ parser.add_argument('--debug', action='store_true') args = vars(parser.parse_args()) if args['debug']: - from configs.iccvw.pyr_64_reg import config + from configs.iccvw.pyr_64_128_256_512_cape_f import config else: config_module = importlib.import_module(args['config']) config = config_module.config @@ -217,6 +217,9 @@ def plot_3d(mesh_gt, mesh_pred_unposed_levels, faces, mesh_posed, collision, col def train_step(batch): + if config['is_cape']: + batch['mesh_fix'] = {'mesh_mask': batch['mesh_mask']} + model.train() # with torch.autocast(device_type='cuda', dtype=torch.float16, enabled=use_amp): levels_input, conds = group_inputs_for_levels(batch, config) @@ -313,6 +316,9 @@ def train_step(batch): def valid_step(batch): + if config['is_cape']: + batch['mesh_fix'] = {'mesh_mask': batch['mesh_mask']} + model.eval() with torch.inference_mode(): levels_input, conds = group_inputs_for_levels(batch, config) @@ -384,6 +390,9 @@ def valid_step(batch): def plot_everything(batch: dict, type: str): + if config['is_cape']: + batch['mesh_fix'] = {'mesh_mask': batch['mesh_mask']} + if config['use_skinning']: mesh_orig, uv_orig = batch['mesh_unposed'].cpu().numpy(), batch['uv_unposed'] else: @@ -394,7 +403,7 @@ def plot_everything(batch: dict, type: str): levels_input = group_inputs_for_levels(batch, config) output_levels = model(levels_input) - mesh_pred_levels = [uv2mesh(output_levels[i][0]).detach().cpu() for i in range(len(output_levels))] + mesh_pred_levels = [uv2mesh(output_levels[i][0]).cpu() for i in range(len(output_levels))] mesh_orig_posed = batch['mesh_posed'].cpu() body = batch['mesh_body_posed'].cpu().numpy() @@ -406,16 +415,16 @@ def plot_everything(batch: dict, type: str): uv_static_img = (torch.permute(batch['uv_static'], [0,2,3,1]) + 1) / 2 uv_body_posed_img = (torch.permute(batch['uv_body_posed'], [0,2,3,1]) + 1) / 2 uv_normals = (torch.permute(batch['uv_normals'], [0,2,3,1]) + 1.4) / 2.8 - pred_img = torch.concatenate([torch.permute(model.resizers[512](output_levels[i][0]), [0,2,3,1]) for i in range(len(output_levels))], dim=3) + pred_img = torch.concatenate([torch.permute(model.resizers[512](output_levels[i][0]), [0,2,3,1]) for i in range(len(output_levels))], dim=2) # pred_img = (pred_img - pred_img.min(axis=(1,2,3))[:,np.newaxis,np.newaxis,np.newaxis]) / (pred_img.max(axis=(1,2,3))[:,np.newaxis,np.newaxis,np.newaxis] - pred_img.min(axis=(1,2,3))[:,np.newaxis,np.newaxis,np.newaxis]) pred_img = (pred_img - pred_img.flatten().reshape(pred_img.shape[0], -1).min(1)[0][:,None,None,None]) / (pred_img.flatten().reshape(pred_img.shape[0], -1).max(1)[0][:,None,None,None] - pred_img.flatten().reshape(pred_img.shape[0], -1).min(1)[0][:,None,None,None]) - img = torch.concat((uv_static_img, uv_body_posed_img, uv_normals, orig_img, pred_img), axis=2) + img = torch.concat((uv_static_img, uv_body_posed_img, uv_normals, orig_img, pred_img), dim=2) imgs = [wandb.Image(img[i].cpu().numpy()) for i in range(4)] _F = np.load("smpl/smpl_faces" + skirt_modifier + ("_orig" if config['is_cape'] else "") + ".npy") mask = batch['mesh_fix']['mesh_mask'].cpu().numpy().astype(bool) - if 'mesh_fix' in batch: + if 'mesh_fix' in batch and not config['is_cape']: faces = [np.load( (dataset_train if type == 'train' else dataset_valid).folder + "/mesh_fixed/" + batch['id'][i] + '_' + batch['garment'][i] + ".npz" )['faces'] for i in range(len(batch['id']))] else: _, faces = maskFacesBatch(np.ones_like(mesh_orig), _F, mask) @@ -553,7 +562,7 @@ if __name__ == '__main__': optimizer = optim.Adam(model.parameters(), lr=config['lr']) _MSSSIM = MS_SSIM(data_range=2, size_average=True, channel=3) - ckpt_saver = CheckpointSaver('checkpoints/iccvw/' + config['name'], top_n=20) + ckpt_saver = CheckpointSaver('checkpoints/iccvw/' + config['name'], top_n=50) scaler = torch.cuda.amp.GradScaler(enabled=use_amp) g_balancing_coeff = config['starting_balancing_coeff'] @@ -561,13 +570,10 @@ if __name__ == '__main__': step = 0 if config['pretrained_model'] != '': - # assert len(config['pyramid']['resolutions']) == 1 - step = load_model(model, config['pretrained_model'], optimizer=optimizer, scaler=scaler, iteration=config['pretrained_model_iteration']) - - # if not args['debug']: - # model = torch.compile(model) - # wandb.watch(model, log='all', log_freq=1000, log_graph=True) - + if 'ignore_saved_optimizer' in config.keys() and config['ignore_saved_optimizer']: + step = load_model(model, config['pretrained_model']) + else: + step = load_model(model, config['pretrained_model'], optimizer=optimizer, iteration=config['pretrained_model_iteration']) if len(config['pyramid']['resolutions']) == 1: for param in model.static_enc.parameters(): param.requires_grad = False diff --git a/scripts/cvae_pyramid_fine.py b/scripts/cvae_pyramid_fine.py new file mode 100644 index 0000000..4ae3158 --- /dev/null +++ b/scripts/cvae_pyramid_fine.py @@ -0,0 +1,557 @@ +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()) + +if args['debug']: + from configs.iccvw.pyr_64_128_256_512_cape_f import config +else: + config_module = importlib.import_module(args['config']) + config = config_module.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 +import torch.nn.functional as F +from data.dataset import Dataset +from utils.checkpoints import CheckpointSaver, load_model +from utils.utils import InfiniteDataLoader as DataLoader +from utils.utils import text_to_html +from utils.postprocess import fix_collision +from losses.losses import collision_loss, normal_loss, kl_loss +from pytorch_msssim import MS_SSIM +from custom_utils.custom_utils import UV2Mesh, Accumulator, plot_3d, get_summary_html, maskFacesBatch, get_summary_str, plot_3d_collision, group_inputs_for_levels +from smpl.smpl_torch import SMPL +from plotly.subplots import make_subplots +from models.pyramid_model import Pyramid + + +def init_wandb(): + wandb.login(host='https://wandb2.lnrweb.com', key='local-2a78b434e9bc51e9f12625f8321a9e3ee34af16d', relogin=True, force=True) + run = wandb.init(project='iccvw', 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_pyramid.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/pyramid_model.py') + artifact.add_file('models/pyramid_level.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 plot_3d(mesh_gt, mesh_pred_unposed_levels, faces, mesh_posed, collision, collision_faces, collision_color): + fig = make_subplots(rows=1, cols=1+len(mesh_pred_unposed_levels)+1+1, start_cell="top-left", specs = [ [{ 'type': 'scene' } for _ in range(1+len(mesh_pred_unposed_levels)+1+1)] ]) + + fig.add_trace(go.Mesh3d( + x=mesh_gt[:,0], + y=mesh_gt[:,2], + z=mesh_gt[:,1], + i = faces[:,0], + j = faces[:,1], + k = faces[:,2], + text="Ground Truth" + ), + row=1, col=1) + + for i, mesh in enumerate(mesh_pred_unposed_levels): + fig.add_trace(go.Mesh3d( + x=mesh[:,0], + y=mesh[:,2], + z=mesh[:,1], + i = faces[:,0], + j = faces[:,1], + k = faces[:,2], + text='Unposed level_' + str(i) + ), + row=1, col=i+2) + + fig.add_trace(go.Mesh3d( + x=mesh_posed[:,0], + y=mesh_posed[:,2], + z=mesh_posed[:,1], + i = faces[:,0], + j = faces[:,1], + k = faces[:,2], + text='Posed GT' + ), + row=1, col=1+len(mesh_pred_unposed_levels)+1) + + fig.add_trace(go.Mesh3d( + x=collision[:,0], + y=collision[:,2], + z=collision[:,1], + i = collision_faces[:,0], + j = collision_faces[:,1], + k = collision_faces[:,2], + vertexcolor=collision_color, + text='Posed output on body' + ), + row=1, col=1+len(mesh_pred_unposed_levels)+1+1) + + if len(mesh_pred_unposed_levels) == 1: + fig.update_layout(scene_aspectmode='manual', scene_aspectratio=dict(x=1, y=1, z=1), + scene2_aspectmode='manual', scene2_aspectratio=dict(x=1, y=1, z=1), + scene3_aspectmode='manual', scene3_aspectratio=dict(x=1, y=1, z=1), + scene4_aspectmode='manual', scene4_aspectratio=dict(x=1, y=1, z=1), + ) + helper = dict(xaxis = dict(nticks=4, range=[-1,1],), + yaxis = dict(nticks=4, range=[-1,1],), + zaxis = dict(nticks=4, range=[-1,1],),) + fig.update_layout(scene = helper, + scene2 = helper, + scene3 = helper, + scene4 = helper, + ) + if len(mesh_pred_unposed_levels) == 2: + fig.update_layout(scene_aspectmode='manual', scene_aspectratio=dict(x=1, y=1, z=1), + scene2_aspectmode='manual', scene2_aspectratio=dict(x=1, y=1, z=1), + scene3_aspectmode='manual', scene3_aspectratio=dict(x=1, y=1, z=1), + scene4_aspectmode='manual', scene4_aspectratio=dict(x=1, y=1, z=1), + scene5_aspectmode='manual', scene5_aspectratio=dict(x=1, y=1, z=1), + ) + helper = dict(xaxis = dict(nticks=4, range=[-1,1],), + yaxis = dict(nticks=4, range=[-1,1],), + zaxis = dict(nticks=4, range=[-1,1],),) + fig.update_layout(scene = helper, + scene2 = helper, + scene3 = helper, + scene4 = helper, + scene5 = helper, + ) + if len(mesh_pred_unposed_levels) == 3: + fig.update_layout(scene_aspectmode='manual', scene_aspectratio=dict(x=1, y=1, z=1), + scene2_aspectmode='manual', scene2_aspectratio=dict(x=1, y=1, z=1), + scene3_aspectmode='manual', scene3_aspectratio=dict(x=1, y=1, z=1), + scene4_aspectmode='manual', scene4_aspectratio=dict(x=1, y=1, z=1), + scene5_aspectmode='manual', scene5_aspectratio=dict(x=1, y=1, z=1), + scene6_aspectmode='manual', scene6_aspectratio=dict(x=1, y=1, z=1,) + ) + helper = dict(xaxis = dict(nticks=4, range=[-1,1],), + yaxis = dict(nticks=4, range=[-1,1],), + zaxis = dict(nticks=4, range=[-1,1],),) + fig.update_layout(scene = helper, + scene2 = helper, + scene3 = helper, + scene4 = helper, + scene5 = helper, + scene6 = helper, + ) + if len(mesh_pred_unposed_levels) == 4: + fig.update_layout(scene_aspectmode='manual', scene_aspectratio=dict(x=1, y=1, z=1), + scene2_aspectmode='manual', scene2_aspectratio=dict(x=1, y=1, z=1), + scene3_aspectmode='manual', scene3_aspectratio=dict(x=1, y=1, z=1), + scene4_aspectmode='manual', scene4_aspectratio=dict(x=1, y=1, z=1), + scene5_aspectmode='manual', scene5_aspectratio=dict(x=1, y=1, z=1), + scene6_aspectmode='manual', scene6_aspectratio=dict(x=1, y=1, z=1,), + scene7_aspectmode='manual', scene7_aspectratio=dict(x=1, y=1, z=1,), + ) + helper = dict(xaxis = dict(nticks=4, range=[-1,1],), + yaxis = dict(nticks=4, range=[-1,1],), + zaxis = dict(nticks=4, range=[-1,1],),) + fig.update_layout(scene = helper, + scene2 = helper, + scene3 = helper, + scene4 = helper, + scene5 = helper, + scene6 = helper, + scene7 = helper, + ) + if len(mesh_pred_unposed_levels) == 5: + fig.update_layout(scene_aspectmode='manual', scene_aspectratio=dict(x=1, y=1, z=1), + scene2_aspectmode='manual', scene2_aspectratio=dict(x=1, y=1, z=1), + scene3_aspectmode='manual', scene3_aspectratio=dict(x=1, y=1, z=1), + scene4_aspectmode='manual', scene4_aspectratio=dict(x=1, y=1, z=1), + scene5_aspectmode='manual', scene5_aspectratio=dict(x=1, y=1, z=1), + scene6_aspectmode='manual', scene6_aspectratio=dict(x=1, y=1, z=1,), + scene7_aspectmode='manual', scene7_aspectratio=dict(x=1, y=1, z=1,), + scene8_aspectmode='manual', scene8_aspectratio=dict(x=1, y=1, z=1,), + ) + helper = dict(xaxis = dict(nticks=4, range=[-1,1],), + yaxis = dict(nticks=4, range=[-1,1],), + zaxis = dict(nticks=4, range=[-1,1],),) + fig.update_layout(scene = helper, + scene2 = helper, + scene3 = helper, + scene4 = helper, + scene5 = helper, + scene6 = helper, + scene7 = helper, + scene8 = helper, + ) + return fig + + +def train_step(batch): + if config['is_cape']: + batch['mesh_fix'] = {'mesh_mask': batch['mesh_mask']} + + model.train() + # with torch.autocast(device_type='cuda', dtype=torch.float16, enabled=use_amp): + levels_input, conds = group_inputs_for_levels(batch, config) + + out_levels = model([levels_input, conds]) + + if config['use_skinning']: + mesh_orig, uv_orig = batch['mesh_unposed'], batch['uv_unposed'] + else: + mesh_orig, uv_orig = batch['mesh_posed'], batch['uv_posed'] + + output = dict() + reconstr_loss_total = 0 + kl_total = 0 + posed_or_not = 'unposed' if config['use_skinning'] else 'posed' + + for i, res in enumerate(config['pyramid']['resolutions']): + # i = -1 + res = config['pyramid']['resolutions'][i] + res_modifier = '_' + str(res) if res != 512 else '' + pred, mean, logvar = out_levels[i] + + l2_loss = torch.mean(1e3 * torch.mean(torch.sum(((levels_input[i][0] - pred) ** 2), dim=-1), dim=[1, 2])) # levels_input[i][0] = uv_orig + kl = kl_loss(mean, logvar) + + mesh_pred = uv2mesh(pred) + + if config['use_skinning']: + shape = batch['pose_shape'][:, 72:] + gender = torch.greater_equal(shape[:, 10] , 0.5).to(dtype=torch.int64) + shape_offsets = torch.stack([torch.tensordot(shape[i,:10][None, :], smpl.shapedirs[gender[i]], dims=[[1], [2]])[0,smpl.to_keep,:] for i in range(shape.shape[0])]) + + mesh_pred_shaped = mesh_pred + shape_offsets * batch['mesh_fix']['mesh_mask'][:,:,None] + mesh_pred_posed = smpl(batch['pose_shape'][:, :72], batch['pose_shape'][:, 72:], mesh_pred_shaped)[0] + else: + mesh_pred_posed = mesh_pred + + e_loss = torch.mean(edge_loss(mesh_pred, mesh_orig, batch['mesh_fix']['mesh_mask'])) + c_loss, c_ratio = collision_loss(mesh_pred_posed, batch['mesh_body_posed'], batch['mesh_fix']['mesh_mask']) + c_loss, c_ratio = torch.mean(c_loss), torch.mean(c_ratio) + n_loss = normal_loss(mesh_pred_posed, batch['mesh_posed'], batch['mesh_fix']['mesh_mask'], is_skirt=config['is_skirt'], is_smpl_orig=config['is_cape']) + l2_mesh_loss = torch.mean(1e3 * torch.mean(torch.sum(batch['mesh_fix']['mesh_mask'][:,:,None] * (batch['mesh_posed'] - mesh_pred_posed) ** 2, dim=-1), dim=-1)) + + reconstr_loss_total = reconstr_loss_total + config['pyramid']['loss_weights'][i] * (l2_loss + l2_mesh_loss) + if not config['is_cape']: + reconstr_loss_total = reconstr_loss_total + config['pyramid']['loss_weights'][i] * (e_loss + c_loss) * config['reg_loss_coeff'] + if config['use_norm_loss'] and step > 2000: + reconstr_loss_total = reconstr_loss_total + config['pyramid']['loss_weights'][i] * n_loss * config['reg_loss_coeff'] + + kl_total += kl + loss: torch.Tensor = reconstr_loss_total + g_balancing_coeff * kl_total + + optimizer.zero_grad() + loss.backward() + optimizer.step() + + model.eval() + with torch.inference_mode(): + mean = torch.mean(mean) + logvar = torch.mean(logvar) + + ms_ssim = torch.mean(_MSSSIM(pred + 1, levels_input[i][0] + 1)) + metric = torch.sum(torch.sqrt(torch.sum(batch['mesh_fix']['mesh_mask'][:,:,None] * (mesh_orig - mesh_pred.detach()) ** 2, axis=-1))) / torch.sum(batch['mesh_fix']['mesh_mask']) + + output = { **output, **{ 'train/edge_loss' + res_modifier: e_loss, 'train/collision_loss' + res_modifier: c_loss,'train/euclid_error' + res_modifier: metric, + 'train/mean' + res_modifier: mean, 'train/logvar' + res_modifier: logvar, 'train/kl_loss' + res_modifier: kl, + 'train/var' + res_modifier: np.e ** logvar, 'train/l2_loss' + res_modifier: l2_loss, 'train/normal_loss': n_loss, + 'train/euclid_error': metric, 'train/l2_mesh_loss': l2_mesh_loss, 'train/ms_ssim' + res_modifier: ms_ssim, + 'train/collision_ratio': c_ratio } } # + + + return { **{ 'train/loss': loss, 'train/reconstr_loss_total': reconstr_loss_total, 'train/kl_total': kl_total }, **output } + + +def valid_step(batch): + if config['is_cape']: + batch['mesh_fix'] = {'mesh_mask': batch['mesh_mask']} + + model.eval() + with torch.inference_mode(): + levels_input, conds = group_inputs_for_levels(batch, config) + + out_levels = model([levels_input, conds]) + + if config['use_skinning']: + mesh_orig, uv_orig = batch['mesh_unposed'], batch['uv_unposed'] + else: + mesh_orig, uv_orig = batch['mesh_posed'], batch['uv_posed'] + + output = dict() + reconstr_loss_total = 0 + kl_total = 0 + + for i, res in enumerate(config['pyramid']['resolutions']): + # i = -1 + res = config['pyramid']['resolutions'][i] + res_modifier = '_' + str(res) if res != 512 else '' + pred, mean, logvar = out_levels[i] + + mesh_pred = uv2mesh(pred) + + if config['use_skinning']: + shape = batch['pose_shape'][:, 72:] + gender = torch.greater_equal(shape[:, 10] , 0.5).to(dtype=torch.int64) + shape_offsets = torch.stack([torch.tensordot(shape[i,:10][None, :], smpl.shapedirs[gender[i]], dims=[[1], [2]])[0,smpl.to_keep,:] for i in range(shape.shape[0])]) + + mesh_pred_shaped = mesh_pred + shape_offsets * batch['mesh_fix']['mesh_mask'][:,:,None] + mesh_pred_posed = smpl(batch['pose_shape'][:, :72], batch['pose_shape'][:, 72:], mesh_pred_shaped)[0] + else: + mesh_pred_posed = mesh_pred + + e_loss = torch.mean(edge_loss(mesh_pred, mesh_orig, batch['mesh_fix']['mesh_mask'])) + c_loss, c_ratio = collision_loss(mesh_pred_posed, batch['mesh_body_posed'], batch['mesh_fix']['mesh_mask']) + c_loss, c_ratio = torch.mean(c_loss), torch.mean(c_ratio) + l2_mesh_loss = torch.mean(1e3 * torch.mean(torch.sum(batch['mesh_fix']['mesh_mask'][:,:,None] * (batch['mesh_posed'] - mesh_pred_posed) ** 2, dim=-1), dim=-1)) + n_loss = normal_loss(mesh_pred_posed, batch['mesh_posed'], batch['mesh_fix']['mesh_mask'], is_skirt=config['is_skirt'], is_smpl_orig=config['is_cape']) + l2_loss = torch.mean(1e3 * torch.mean(torch.sum(((levels_input[i][0] - pred) ** 2), dim=-1), dim=[1, 2])) + + kl = kl_loss(mean, logvar) + + if config['use_extra_losses']: + reconstr_loss_total = reconstr_loss_total + config['pyramid']['loss_weights'][i] * (l2_loss + l2_mesh_loss) + if not config['is_cape']: + reconstr_loss_total = reconstr_loss_total + config['pyramid']['loss_weights'][i] * (e_loss + c_loss) * config['reg_loss_coeff'] + if config['use_norm_loss'] and step > 2000: + reconstr_loss_total = reconstr_loss_total + config['pyramid']['loss_weights'][i] * n_loss * config['reg_loss_coeff'] + else: + reconstr_loss_total = reconstr_loss_total + config['pyramid']['loss_weights'][i] * (l2_loss) + + kl_total += kl + loss = reconstr_loss_total + g_balancing_coeff * kl_total + + mean = torch.mean(mean) + logvar = torch.mean(logvar) + + ms_ssim = torch.mean(_MSSSIM(pred + 1, levels_input[i][0] + 1)) + metric = torch.sum(torch.sqrt(torch.sum(batch['mesh_fix']['mesh_mask'][:,:,None] * (mesh_orig - mesh_pred) ** 2, axis=-1))) / torch.sum(batch['mesh_fix']['mesh_mask']) + + output = { **output, **{ 'valid/edge_loss' + res_modifier: e_loss, 'valid/collision_loss' + res_modifier: c_loss,'valid/euclid_error' + res_modifier: metric, + 'valid/mean' + res_modifier: mean, 'valid/logvar' + res_modifier: logvar, 'valid/kl_loss' + res_modifier: kl, + 'valid/var' + res_modifier: np.e ** logvar, 'valid/l2_loss' + res_modifier: l2_loss, 'valid/normal_loss': n_loss, + 'valid/euclid_error': metric, 'valid/l2_mesh_loss': l2_mesh_loss, 'valid/ms_ssim' + res_modifier: ms_ssim, } } # + + + + return { **{ 'valid/loss': loss, 'valid/reconstr_loss_total': reconstr_loss_total, 'valid/kl_total': kl_total }, **output } + + +def plot_everything(batch: dict, type: str): + if config['is_cape']: + batch['mesh_fix'] = {'mesh_mask': batch['mesh_mask']} + + if config['use_skinning']: + mesh_orig, uv_orig = batch['mesh_unposed'].cpu().numpy(), batch['uv_unposed'] + else: + mesh_orig, uv_orig = batch['mesh_posed'].cpu().numpy(), batch['uv_posed'] + + model.eval() + with torch.inference_mode(): + levels_input = group_inputs_for_levels(batch, config) + output_levels = model(levels_input) + + mesh_pred_levels = [uv2mesh(output_levels[i][0]).cpu() for i in range(len(output_levels))] + mesh_orig_posed = batch['mesh_posed'].cpu() + body = batch['mesh_body_posed'].cpu().numpy() + + # mesh_pred = torch.cat((mesh_pred[:, :, 0:1], -mesh_pred[:, :, 2:3], mesh_pred[:, :, 1:2]), dim=2) + # mesh_pred_levels = [torch.cat((mesh_pred_levels[i][:, :, 0:1], -mesh_pred_levels[i][:, :, 2:3], mesh_pred_levels[i][:, :, 1:2]), dim=2).numpy() for i in range(len(mesh_pred_levels))] + # mesh_orig_posed = torch.cat((mesh_orig_posed[:, :, 0:1], -mesh_orig_posed[:, :, 2:3], mesh_orig_posed[:, :, 1:2]), dim=2).numpy() + + orig_img = (torch.permute(uv_orig, [0,2,3,1]) + 1) / 2 + uv_static_img = (torch.permute(batch['uv_static'], [0,2,3,1]) + 1) / 2 + uv_body_posed_img = (torch.permute(batch['uv_body_posed'], [0,2,3,1]) + 1) / 2 + uv_normals = (torch.permute(batch['uv_normals'], [0,2,3,1]) + 1.4) / 2.8 + pred_img = torch.concatenate([torch.permute(model.resizers[512](output_levels[i][0]), [0,2,3,1]) for i in range(len(output_levels))], dim=2) + # pred_img = (pred_img - pred_img.min(axis=(1,2,3))[:,np.newaxis,np.newaxis,np.newaxis]) / (pred_img.max(axis=(1,2,3))[:,np.newaxis,np.newaxis,np.newaxis] - pred_img.min(axis=(1,2,3))[:,np.newaxis,np.newaxis,np.newaxis]) + pred_img = (pred_img - pred_img.flatten().reshape(pred_img.shape[0], -1).min(1)[0][:,None,None,None]) / (pred_img.flatten().reshape(pred_img.shape[0], -1).max(1)[0][:,None,None,None] - pred_img.flatten().reshape(pred_img.shape[0], -1).min(1)[0][:,None,None,None]) + + img = torch.concat((uv_static_img, uv_body_posed_img, uv_normals, orig_img, pred_img), dim=2) + imgs = [wandb.Image(img[i].cpu().numpy()) for i in range(4)] + + _F = np.load("smpl/smpl_faces" + skirt_modifier + ("_orig" if config['is_cape'] else "") + ".npy") + mask = batch['mesh_fix']['mesh_mask'].cpu().numpy().astype(bool) + if 'mesh_fix' in batch and not config['is_cape']: + faces = [np.load( (dataset_train if type == 'train' else dataset_valid).folder + "/mesh_fixed/" + batch['id'][i] + '_' + batch['garment'][i] + ".npz" )['faces'] for i in range(len(batch['id']))] + else: + _, faces = maskFacesBatch(np.ones_like(mesh_orig), _F, mask) + + if config['use_skinning']: + shape = batch['pose_shape'][:, 72:] + gender = torch.greater_equal(shape[:, 10] , 0.5).to(torch.long) + shape_offsets = torch.stack([torch.tensordot(shape[i,:10][None, :], smpl.shapedirs[gender[i]], dims=[[1], [2]])[0,smpl.to_keep,:] for i in range(shape.shape[0])]).cpu().numpy() + + gt = [mesh_orig[i][mask[i], :] + shape_offsets[i, mask[i], :] for i in range(mask.shape[0])] + + mesh_unposed_shaped_levels = [[] for _ in range(mask.shape[0])] + for i in range(len(output_levels)): + mesh_unposed_shaped = [mesh_pred_levels[i][j, mask[j], :] + shape_offsets[j, mask[j]] for j in range(mask.shape[0])] + for k in range(mask.shape[0]): + mesh_unposed_shaped_levels[k].append(mesh_unposed_shaped[k]) + + # full res version + mesh_unposed_shaped_full = np.zeros((mask.shape[0], config['smpl_res'], 3), dtype=np.float32) + for i in range(mask.shape[0]): + mesh_unposed_shaped_full[i, mask[i], :] = mesh_unposed_shaped[i] + mesh_posed = smpl(batch['pose_shape'][:, :72], batch['pose_shape'][:, 72:], torch.tensor(mesh_unposed_shaped_full, device=config['device']))[0].cpu().numpy() + + # rotate gt 180 degrees along z axis + # gt = [np.matmul(gt[i], np.array([[np.cos(np.pi), -np.sin(np.pi), 0], [np.sin(np.pi), np.cos(np.pi), 0], [0, 0, 1]])) for i in range(mask.shape[0])] + + # gt_full = np.zeros((mask.shape[0], config['smpl_res'], 3), dtype=np.float32) + # for i in range(mask.shape[0]): + # gt_full[i, mask[i], :] = gt[i] + # mesh_orig_posed = smpl(batch['pose_shape'][:, :72], batch['pose_shape'][:, 72:], torch.tensor(np.stack(gt_full, axis=0), device=config['device'], dtype=torch.float32))[0].cpu().numpy() + else: + mesh_posed = mesh_pred_levels[-1] + gt = [mesh_orig[i][mask[i], :] for i in range(mesh_posed.shape[0])] + mesh_unposed_shaped_levels = [[mesh_pred_levels[i][j, mask[j], :] for i in range(len(output_levels))] for j in range(mask.shape[0])] + + + gt_posed = [mesh_orig_posed[i, mask[i], :] for i in range(mask.shape[0])] + mesh_posed_fixed = fix_collision(torch.Tensor(mesh_posed).to('cuda'), torch.Tensor(body).to('cuda'), torch.Tensor(mask).to('cuda')).cpu().numpy() + + mesh_posed = [mesh_posed[j, mask[j], :] for j in range(mask.shape[0])] + + if config['is_cape']: + collision = mesh_posed + collision_faces = faces + collision_color = [np.ones_like(mesh_posed[i], dtype=np.int32)*230 for i in range(len(mesh_posed))] + else: + collision = [np.concatenate((body[i], mesh_posed[i]), axis=0) for i in range(len(mesh_posed))] + collision_faces = [np.concatenate((_F, faces[i] + config['smpl_res']), axis=0) for i in range(len(mesh_posed))] + collision_color = [np.concatenate((np.ones_like(body[i], dtype=np.int32)*100, np.ones_like(mesh_posed[i], dtype=np.int32)*230), axis=0) for i in range(len(mesh_posed))] + + figs = { type + "/garment_" + str(i): plot_3d(gt[i], mesh_unposed_shaped_levels[i], faces[i], gt_posed[i], collision[i], collision_faces[i], collision_color[i]) for i in range(4) } + + if config['is_cape']: + figs_coll = dict() + else: + garment_posed_fixed = [mesh_posed_fixed[i, mask[i], :] for i in range(body.shape[0])] + collision_fixed = [np.concatenate((body[i], garment_posed_fixed[i]), axis=0) for i in range(len(mesh_posed))] + gt_posed = [batch['mesh_posed'].cpu().numpy()[i, mask[i], :] for i in range(mask.shape[0])] + collision_gt = [np.concatenate((body[i], gt_posed[i]), axis=0) for i in range(len(gt_posed))] + figs_coll = { type + "/garment_" + str(i) + '_collision': plot_3d_collision(collision_gt[i], collision[i], collision_fixed[i], collision_faces[i], collision_color[i]) for i in range(4) } + + batch_id = batch['id'] + batch_frame_nr = batch['frame_nr'] + batch_garment = batch['garment'] + batch_info = [f'batch_info: id: {batch_id[i]}, frame_nr: {batch_frame_nr[i]}, garment: {batch_garment[i]}' for i in range(len(batch_id))] + batch_info = text_to_html(batch_info) + batch_info = wandb.Html(batch_info) + + return { **figs, **figs_coll, **{ type + '/images': imgs, }, **{ f'{type}/batch_info': batch_info }, } + + +def speed_step(levels_input, conds): + + return model.sample([levels_input, conds], training=False) + + + +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) + + 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']: + g_balancing_coeff += 1 / 50000 + + if step % 10000 == 0 and not args['debug']: + ckpt_saver(model, step, optimizer, None) + + step += 1 + + +if __name__ == '__main__': + if not args['debug']: + init_wandb() + + use_amp = True + smpl = SMPL(orig_smpl=config['is_cape'], path='smpl', device=config['device']) + skirt_modifier = '_skirt' if config['is_skirt'] else '' + dataset_resolutions = config['pyramid']['resolutions'].copy() + if 512 not in dataset_resolutions: + dataset_resolutions.append(512) + + dataset_train = Dataset(config['train_dir'], config['signature'], device=config['device'], frames_file=config['train_frames'], use_cache=config['dataset_in_memory'], resolutions=dataset_resolutions, is_cape=config['is_cape']) + dataset_valid = Dataset(config['valid_dir'], config['signature'], device=config['device'], frames_file=config['valid_frames'], use_cache=config['dataset_in_memory'], resolutions=dataset_resolutions, is_cape=config['is_cape']) + 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: Pyramid = Pyramid(config) + + optimizer = optim.Adam(model.parameters(), lr=config['lr'] * 0.05) + _MSSSIM = MS_SSIM(data_range=2, size_average=True, channel=3) + ckpt_saver = CheckpointSaver('checkpoints/iccvw/' + config['name'] + '_fine_2', top_n=50) + scaler = torch.cuda.amp.GradScaler(enabled=use_amp) + + g_balancing_coeff = config['starting_balancing_coeff'] + config['pyramid']['loss_weights'] = [1,3,5,10,25] + + step = load_model(model, f'checkpoints/iccvw/{config["name"]}', iteration='25000') + + for param in model.static_enc.parameters(): param.requires_grad = False + for param in model.body_enc.parameters(): param.requires_grad = False + for param in model.norm_enc.parameters(): param.requires_grad = False + for i in range(len(model.levels)-1): + for param in model.levels[i].upscale_enhancer.parameters(): param.requires_grad = False + + train() \ No newline at end of file diff --git a/scripts/cvae_pyramid_speed_test.py b/scripts/cvae_pyramid_speed_test.py new file mode 100644 index 0000000..ef5c6b2 --- /dev/null +++ b/scripts/cvae_pyramid_speed_test.py @@ -0,0 +1,160 @@ +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()) + + +from configs.iccvw.pyr_64_2 import config + +os.environ["CUDA_DEVICE_ORDER"]="PCI_BUS_ID" +os.environ["CUDA_VISIBLE_DEVICES"] = '5' +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 + + +import torch +import torch.nn as nn +import torch.optim as optim +import torch.nn.functional as F +from torch.profiler import profile, record_function, ProfilerActivity +from data.dataset import Dataset +from utils.checkpoints import load_model +from utils.utils import InfiniteDataLoader as DataLoader +from losses.losses import kl_loss +from custom_utils.custom_utils import UV2Mesh, Accumulator, group_inputs_for_levels +from smpl.smpl_torch import SMPL +from models.pyramid_model import Pyramid + + + +uv2mesh = UV2Mesh(res=256, is_skirt=config['is_skirt'], is_smpl_orig=config['is_cape']) + +def train_step(batch): + model.train() + # with torch.autocast(device_type='cuda', dtype=torch.float16, enabled=use_amp): + levels_input, conds = group_inputs_for_levels(batch, config) + + out_levels = model([levels_input, conds]) + + if config['use_skinning']: + mesh_orig, uv_orig = batch['mesh_unposed'], batch['uv_unposed'] + else: + mesh_orig, uv_orig = batch['mesh_posed'], batch['uv_posed'] + + reconstr_loss_total = 0 + kl_total = 0 + + #for i, res in enumerate(config['pyramid']['resolutions']): + i = -1 + pred, mean, logvar = out_levels[i] + + mesh_pred = uv2mesh(pred) + + if config['use_skinning']: + shape = batch['pose_shape'][:, 72:] + gender = torch.greater_equal(shape[:, 10] , 0.5).to(dtype=torch.int64) + shape_offsets = torch.stack([torch.tensordot(shape[i,:10][None, :], smpl.shapedirs[gender[i]], dims=[[1], [2]])[0,smpl.to_keep,:] for i in range(shape.shape[0])]) + + mesh_pred_shaped = mesh_pred + shape_offsets * batch['mesh_mask'][:,:,None] + mesh_pred_posed = smpl(batch['pose_shape'][:, :72], batch['pose_shape'][:, 72:], mesh_pred_shaped)[0] + else: + mesh_pred_posed = mesh_pred + + + kl = kl_loss(mean, logvar) + + loss: torch.Tensor = g_balancing_coeff * kl + + optimizer.zero_grad() + loss.backward() + optimizer.step() + + model.eval() + with torch.inference_mode(): + metric = torch.sum(torch.sqrt(torch.sum(batch['mesh_mask'][:,:,None] * (mesh_orig - mesh_pred.detach()) ** 2, axis=-1))) / torch.sum(batch['mesh_mask']) + + + return { **{ 'train/loss': loss, 'train/reconstr_loss_total': reconstr_loss_total, 'train/kl_total': kl_total } } + + +def train(): + global g_balancing_coeff + global step + + for batch in train_dataloader: + train_step(batch) + + step += 1 + print(step) + profiler.step() + + if step > 300: + break + + + +if __name__ == '__main__': + smpl = SMPL(orig_smpl=config['is_cape'], path='smpl', device=config['device']) + skirt_modifier = '_skirt' if config['is_skirt'] else '' + dataset_resolutions = config['pyramid']['resolutions'].copy() + if 512 not in dataset_resolutions: + dataset_resolutions.append(512) + + dataset_train = Dataset(config['train_dir'], config['signature'], device=config['device'], frames_file='frames_single.txt', use_cache=True, resolutions=dataset_resolutions, is_cape=config['is_cape']) + train_dataloader = DataLoader(dataset_train, batch_size=4, drop_last=True, shuffle=True, ) + train_accumulator = Accumulator() + + model: Pyramid = Pyramid(config) + + optimizer = optim.Adam(model.parameters(), lr=config['lr']) + + g_balancing_coeff = config['starting_balancing_coeff'] + reg_coeff = 1 + + step = 0 + if config['pretrained_model'] != '': + # assert len(config['pyramid']['resolutions']) == 1 + load_model(model, config['pretrained_model'], optimizer=optimizer, iteration=config['pretrained_model_iteration']) + + if len(config['pyramid']['resolutions']) == 1: + for param in model.static_enc.parameters(): param.requires_grad = False + for param in model.body_enc.parameters(): param.requires_grad = False + for param in model.norm_enc.parameters(): param.requires_grad = False + else: + load_model(model, config['pyramid']['pretrained_pyramid'], iteration=config['pyramid']['pretrained_pyramid_iteration']) + for param in model.static_enc.parameters(): param.requires_grad = False + for param in model.body_enc.parameters(): param.requires_grad = False + for param in model.norm_enc.parameters(): param.requires_grad = False + + for i in range(len(model.levels)-1): + for param in model.levels[i].parameters(): param.requires_grad = False + + # create a profiler object + profiler = torch.profiler.profile( + activities=[ProfilerActivity.CPU, ProfilerActivity.CUDA], + schedule=torch.profiler.schedule(wait=2, warmup=5, active=3, repeat=2), + on_trace_ready=torch.profiler.tensorboard_trace_handler("log_dir"), + ) + + with profiler: + train() + + profiler.stop() + print(profiler.key_averages().table(sort_by="cpu_time_total", row_limit=25)) \ No newline at end of file diff --git a/scripts/generate_results.py b/scripts/generate_results.py index a57d483..4d0042c 100644 --- a/scripts/generate_results.py +++ b/scripts/generate_results.py @@ -7,17 +7,19 @@ import argparse parser = argparse.ArgumentParser(description='') parser.add_argument('--name', type=str) parser.add_argument('--config', type=str) +parser.add_argument('--iteration', type=str, default='') parser.add_argument('--debug', action='store_true') +parser.add_argument('-g', '--gpu', type=str) args = vars(parser.parse_args()) if args['debug']: - from configs.iccvw.pyr_64 import config + from configs.iccvw.pyr_64_128_cape_f_2 import config else: config_module = importlib.import_module(args['config']) config = config_module.config os.environ["CUDA_DEVICE_ORDER"]="PCI_BUS_ID" -os.environ["CUDA_VISIBLE_DEVICES"] = config['gpu'] +os.environ["CUDA_VISIBLE_DEVICES"] = args['gpu'] if args['debug']: os.environ["CUDA_LAUNCH_BLOCKING"] = '1' @@ -70,7 +72,10 @@ def step_pyramid(batch): shape_offsets = torch.stack([torch.tensordot(shape[i,:10][None, :], smpl.shapedirs[gender[i]], dims=[[1], [2]])[0,smpl.to_keep,:] for i in range(shape.shape[0])]) mesh_pred_shaped = mesh_pred + shape_offsets * batch['mesh_mask'][:,:,None] - mesh_pred_posed = smpl(batch['pose_shape'][:, :72], batch['pose_shape'][:, 72:], mesh_pred_shaped)[0] + if not config['is_cape']: + mesh_pred_posed = smpl(batch['pose_shape'][:, :72], batch['pose_shape'][:, 72:], mesh_pred_shaped)[0] + else: + mesh_pred_posed = mesh_pred_shaped else: mesh_pred_posed = mesh_pred @@ -102,15 +107,32 @@ def step(batch): def generate(): for batch in tqdm(test_dataloader): - if is_pyramid: - mesh_pred = step_pyramid(batch) - else: - mesh_pred = step(batch) + with torch.inference_mode(): + if is_pyramid: + mesh_pred = step_pyramid(batch) + else: + mesh_pred = step(batch) ids = batch['id'] frame_nrs = batch['frame_nr'] garments = batch['garment'] + # import plotly.graph_objects as go + # mesh_pred = mesh_pred.cpu().numpy() + # mask = batch['mesh_mask'].cpu().numpy() + # i = 3 + # fig = go.Figure(data=[go.Scatter3d(x=mesh_pred[i,mask[i],0], y=mesh_pred[i,mask[i],2], z=mesh_pred[i,mask[i],1], mode='markers', marker=dict(size=1))]) + # fig.update_layout(scene_aspectmode='cube') + # fig.show() + + # import plotly.graph_objects as go + # mesh_pred = mesh_pred.cpu().numpy() + # i = 3 + # fig = go.Figure(data=[go.Scatter3d(x=mesh_pred[i,:,0], y=mesh_pred[i,:,2], z=mesh_pred[i,:,1], mode='markers', marker=dict(size=1))]) + # fig.update_layout(scene_aspectmode='cube') + # fig.update_layout(scene=dict(xaxis=dict(range=[-1,1]), yaxis=dict(range=[-1,1]), zaxis=dict(range=[-1,1]))) + # fig.show() + for i in range(len(ids)): np.savez_compressed(f'{out_folder}/{ids[i]}_{frame_nrs[i]}_{garments[i]}', mesh_pred[i].cpu().numpy()) @@ -121,11 +143,17 @@ if __name__ == '__main__': smpl = SMPL(orig_smpl=config['is_cape'], path='smpl', device=config['device']) skirt_modifier = '_skirt' if config['is_skirt'] else '' - dataset_resolutions = config['pyramid']['resolutions'].copy() + dataset_resolutions = [] + if 'pyramid' in config: + dataset_resolutions = config['pyramid']['resolutions'].copy() if 512 not in dataset_resolutions: dataset_resolutions.append(512) + # remove all values from config['signature] that start with mesh_ + config['signature'] = set([x for x in config['signature'] if not x.startswith('mesh_')]) + dataset_test = Dataset(config['test_dir'], config['signature'], device=config['device'], frames_file=config['test_frames'], use_cache=config['dataset_in_memory'], resolutions=dataset_resolutions, is_cape=config['is_cape']) + # dataset_test = Dataset(config['test_dir'], config['signature'], device=config['device'], frames_file='frames_temp.txt', use_cache=config['dataset_in_memory'], resolutions=dataset_resolutions, is_cape=config['is_cape']) test_dataloader = DataLoader(dataset_test, batch_size=4, drop_last=True, shuffle=True, ) is_pyramid = config['name'].startswith('pyr') @@ -135,7 +163,8 @@ if __name__ == '__main__': else: model: CVAE = CVAE(config) - it = load_model(model, 'checkpoints/iccv/torch/' + config['name']) + it = load_model(model, 'checkpoints/iccvw/' + config['name'], iteration=args['iteration']) + model.eval() # it = load_model(model, 'checkpoints/iccvw/' + config['name']) name = config['name'] + '_' + str(it) diff --git a/utils/generate_figures.py b/utils/generate_figures.py index bd22685..3fe0bc5 100644 --- a/utils/generate_figures.py +++ b/utils/generate_figures.py @@ -5,12 +5,11 @@ sys.path.append(os.path.dirname(os.path.abspath(__file__)) + '/..') import numpy as np import cmapy as cm -from utils import remove_long_edges from custom_utils.custom_utils import save_stl, write_obj from data.cloth3d_io import readPC2Frame from data.utils import Frame -from custom_utils.custom_utils import _maskFaces +from custom_utils.custom_utils import _maskFaces, remove_long_edges import plotly.graph_objects as go import plotly.express as ex from plotly.subplots import make_subplots diff --git a/utils/postprocess.py b/utils/postprocess.py index ebeaacb..294e379 100644 --- a/utils/postprocess.py +++ b/utils/postprocess.py @@ -14,7 +14,7 @@ import plotly.graph_objects as go import plotly.express as ex from pytorch3d.structures import Meshes -from custom_utils.custom_utils import _maskFaces +from custom_utils.custom_utils import _maskFaces, remove_long_edges from losses.losses import _nearest_neighbour