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_reg_e2e 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 torchvision.transforms import Resize from torchvision.transforms.functional import InterpolationMode 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_e2e.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] if res != 512: pred = resizer(pred) * batch['uv_mask'][:,None,:,:] l2_loss = torch.mean(1e3 * torch.mean(torch.sum(((uv_orig - pred) ** 2), dim=-1), dim=[1, 2])) kl = kl_loss(mean, logvar) if config['use_extra_losses']: 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 + n_loss * config['reg_loss_coeff'] output = { **output, **{ 'train/edge_loss' + res_modifier: e_loss, 'train/collision_loss' + res_modifier: c_loss, '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/l2_mesh_loss': l2_mesh_loss, 'train/collision_ratio': c_ratio } } else: reconstr_loss_total = reconstr_loss_total + config['pyramid']['loss_weights'][i] * (l2_loss) kl_total += kl model.eval() with torch.inference_mode(): mean = torch.mean(mean) logvar = torch.mean(logvar) loss: torch.Tensor = reconstr_loss_total + g_balancing_coeff * kl_total optimizer.zero_grad() loss.backward() optimizer.step() model.eval() with torch.inference_mode(): 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] if res != 512: pred = resizer(pred) * batch['uv_mask'][:,None,:,:] mean = torch.mean(mean) logvar = torch.mean(logvar) if not config['use_extra_losses']: 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']) output = { **output, **{ 'train/edge_loss' + res_modifier: e_loss, 'train/collision_loss' + res_modifier: c_loss, '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/l2_mesh_loss': l2_mesh_loss, 'train/collision_ratio': c_ratio } } ms_ssim = torch.mean(_MSSSIM(pred + 1, uv_orig + 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/euclid_error' + res_modifier: metric, 'train/ms_ssim' + res_modifier: ms_ssim } } 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] if res != 512: pred = resizer(pred) * batch['uv_mask'][:,None,:,:] 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(((uv_orig - 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 mean = torch.mean(mean) logvar = torch.mean(logvar) ms_ssim = torch.mean(_MSSSIM(pred + 1, uv_orig + 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/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' + res_modifier: metric, 'valid/l2_mesh_loss': l2_mesh_loss, 'valid/ms_ssim' + res_modifier: ms_ssim, } } # loss = reconstr_loss_total + g_balancing_coeff * kl_total 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 % 5000 == 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']) 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=50) scaler = torch.cuda.amp.GradScaler(enabled=use_amp) resizer = Resize(size=(512, 256), interpolation=InterpolationMode.BILINEAR).to(config['device']) g_balancing_coeff = config['starting_balancing_coeff'] config['pyramid']['loss_weights'] = [1,2,3,4,5] step = 0 if 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, iteration=config['pretrained_model_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].upscale_enhancer.parameters(): param.requires_grad = False train()