445 lines
21 KiB
Python
445 lines
21 KiB
Python
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.abl_all_5_var 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
|
|
from pathlib import Path
|
|
|
|
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 torch.profiler import profile, record_function, ProfilerActivity
|
|
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.utils import text_to_html
|
|
from utils.postprocess import fix_collision
|
|
from losses.losses import collision_loss, normal_loss
|
|
from pytorch_msssim import MS_SSIM
|
|
from models.cvae_model import CVAE
|
|
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():
|
|
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.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_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):
|
|
# with profiler:
|
|
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']
|
|
|
|
# with record_function("forward"):
|
|
model.train()
|
|
pred, mean, logvar = model([uv_orig, batch['uv_static'], batch['uv_body_posed'], batch['uv_normals'], batch['uv_mask']])
|
|
mesh_pred = uv2mesh(pred)
|
|
|
|
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])])
|
|
# shape_offsets = torch.stack([torch.matmul(shape[i, :10], smpl.shapedirs[gender[i]][:, 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
|
|
|
|
|
|
e_loss = torch.mean(edge_loss(mesh_pred, mesh_orig, batch['mesh_mask']))
|
|
c_loss, c_ratio = collision_loss(mesh_pred_posed, batch['mesh_body_posed'], batch['mesh_mask'])
|
|
c_loss, c_ratio = torch.mean(c_loss), torch.mean(c_ratio)
|
|
l2_loss = torch.mean(1e3 * torch.mean(torch.sum(((uv_orig - pred) ** 2), axis=-1), axis=[1, 2]))
|
|
l2_mesh_loss = torch.mean(1e3 * torch.mean(torch.sum(batch['mesh_mask'][:,:,None] * (batch['mesh_posed'] - mesh_pred_posed) ** 2, axis=-1), axis=-1))
|
|
n_loss = normal_loss(mesh_pred_posed, batch['mesh_posed'], batch['mesh_mask'], is_skirt=config['is_skirt'], is_smpl_orig=config['is_cape'])
|
|
kl = kl_loss(mean, logvar)
|
|
|
|
reconstr_loss = l2_loss
|
|
if config['use_extra_losses']:
|
|
reconstr_loss = reconstr_loss + l2_mesh_loss + (e_loss + c_loss + n_loss) * config['reg_loss_coeff']
|
|
|
|
loss = g_balancing_coeff * kl + reconstr_loss
|
|
|
|
# with record_function("backward"):
|
|
optimizer.zero_grad()
|
|
loss.backward()
|
|
optimizer.step()
|
|
|
|
# with record_function("eval"):
|
|
model.eval()
|
|
with torch.inference_mode():
|
|
mean = torch.mean(mean)
|
|
logvar = torch.mean(logvar)
|
|
ms_ssim = torch.mean(_MSSSIM(pred + 1, batch['uv_static'] + 1))
|
|
metric = torch.sum(torch.sqrt(torch.sum(batch['mesh_mask'][:,:,None] * (mesh_orig - mesh_pred.detach()) ** 2, axis=-1))) / torch.sum(batch['mesh_mask'])
|
|
|
|
# profiler.step()
|
|
|
|
|
|
return { 'train/loss': loss,
|
|
'train/edge_loss': e_loss, 'train/collision_loss': c_loss, 'train/euclid_error': metric,
|
|
'train/reconstr_loss': reconstr_loss, 'train/collision_ratio': c_ratio,
|
|
'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/normal_loss': n_loss,
|
|
'train/ms_ssim': ms_ssim,
|
|
}
|
|
|
|
|
|
def valid_step(batch):
|
|
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']
|
|
|
|
model.eval()
|
|
with torch.inference_mode():
|
|
pred, mean, logvar = model([uv_orig, batch['uv_static'], batch['uv_body_posed'], batch['uv_normals'], batch['uv_mask']])
|
|
mesh_pred = uv2mesh(pred)
|
|
|
|
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])])
|
|
# shape_offsets = torch.stack([torch.matmul(shape[i, :10], smpl.shapedirs[gender[i]][:, 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
|
|
|
|
e_loss = torch.mean(edge_loss(mesh_pred, mesh_orig, batch['mesh_mask']))
|
|
c_loss, c_ratio = collision_loss(mesh_pred_posed, batch['mesh_body_posed'], batch['mesh_mask'])
|
|
c_loss, c_ratio = torch.mean(c_loss), torch.mean(c_ratio)
|
|
l2_loss = torch.mean(1e3 * torch.mean(torch.sum(((uv_orig - pred) ** 2), axis=-1), axis=[1, 2]))
|
|
l2_mesh_loss = torch.mean(1e3 * torch.mean(torch.sum(batch['mesh_mask'][:,:,None] * (batch['mesh_posed'] - mesh_pred_posed) ** 2, axis=-1), axis=-1))
|
|
n_loss = normal_loss(mesh_pred_posed, batch['mesh_posed'], batch['mesh_mask'], is_skirt=config['is_skirt'], is_smpl_orig=config['is_cape'])
|
|
kl = kl_loss(mean, logvar)
|
|
|
|
reconstr_loss = l2_loss
|
|
if config['use_extra_losses']:
|
|
reconstr_loss = reconstr_loss + l2_mesh_loss + (e_loss + c_loss + n_loss) * config['reg_loss_coeff']
|
|
|
|
loss = reconstr_loss + g_balancing_coeff * kl
|
|
|
|
mean = torch.mean(mean)
|
|
logvar = torch.mean(logvar)
|
|
ms_ssim = torch.mean(_MSSSIM(pred + 1, batch['uv_static'] + 1))
|
|
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 { 'valid/loss': loss, 'valid/edge_loss': e_loss, 'valid/collision_loss': c_loss, 'valid/euclid_error': metric,
|
|
'valid/reconstr_loss': reconstr_loss, 'valid/l2_mesh_loss': l2_mesh_loss, 'valid/collision_ratio': c_ratio,
|
|
'valid/mean': mean, 'valid/logvar': logvar, 'valid/kl_loss': kl, 'valid/var': np.e ** logvar,
|
|
'valid/normal_loss': n_loss, 'valid/ms_ssim': ms_ssim,
|
|
}
|
|
|
|
|
|
def plot_everything(batch: dict, type: str):
|
|
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():
|
|
pred, mean, logvar = model([uv_orig, batch['uv_static'], batch['uv_body_posed'], batch['uv_normals'], batch['uv_mask']])
|
|
|
|
mesh_pred = uv2mesh(pred).detach().cpu().numpy()
|
|
|
|
orig_img = torch.permute(uv_orig, [0,2,3,1])
|
|
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])
|
|
uv_normals_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, uv_normals_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)
|
|
|
|
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()
|
|
|
|
garment_unposed, faces = maskFacesBatch(mesh_pred, F, mask)
|
|
garment_unposed = [garment_unposed[i] + shape_offsets[i, mask[i], :] for i in range(mask.shape[0])]
|
|
gt = [mesh_orig[i][mask[i], :] + shape_offsets[i, mask[i], :] for i in range(pred.shape[0])]
|
|
|
|
for i in range(mesh_orig.shape[0]):
|
|
mesh_pred[i, mask[i], :] += shape_offsets[i, mask[i], :]
|
|
mesh_posed = smpl(batch['pose_shape'][:, :72], batch['pose_shape'][:, 72:], torch.tensor(mesh_pred, device=config['device']))[0].cpu().numpy()
|
|
else:
|
|
mesh_posed = mesh_pred.cpu().numpy()
|
|
gt = [mesh_orig[i][mask[i], :] for i in range(pred.shape[0])]
|
|
garment_unposed, faces = maskFacesBatch(mesh_pred.cpu().numpy(), F, mask)
|
|
|
|
gt_posed = [batch['mesh_posed'].cpu().numpy()[i, mask[i], :] for i in range(mask.shape[0])]
|
|
|
|
# # plot garment_unposed, gt and mesh_posed next to eachother in plotly subplots
|
|
# from plotly.subplots import make_subplots
|
|
# fig = make_subplots(rows=1, cols=4, specs=[[{'type': 'surface'}, {'type': 'surface'}, {'type': 'surface'}, {'type': 'surface'}]])
|
|
# fig.add_trace(go.Mesh3d(x=gt[0][:,0], y=gt[0][:,2], z=gt[0][:,1], i=faces[0][:,0], j=faces[0][:,1], k=faces[0][:,2], color='red', opacity=0.5), row=1, col=1)
|
|
# fig.add_trace(go.Mesh3d(x=garment_unposed[0][:,0], y=garment_unposed[0][:,2], z=garment_unposed[0][:,1], i=faces[0][:,0], j=faces[0][:,1], k=faces[0][:,2], color='blue', opacity=0.5), row=1, col=2)
|
|
# # add new subplot for gt_posed
|
|
# fig.add_trace(go.Mesh3d(x=gt_posed[0][:,0], y=gt_posed[0][:,2], z=gt_posed[0][:,1], i=faces[0][:,0], j=faces[0][:,1], k=faces[0][:,2], color='red', opacity=0.5), row=1, col=3)
|
|
# fig.add_trace(go.Mesh3d(x=mesh_posed[0][mask[0],0], y=mesh_posed[0][mask[0],2], z=mesh_posed[0][mask[0],1], i=faces[0][:,0], j=faces[0][:,1], k=faces[0][:,2], color='green', opacity=0.5), row=1, col=4)
|
|
# # make each subplot between -1 and 1
|
|
# fig.update_layout(scene_aspectmode='cube', scene2_aspectmode='cube', scene3_aspectmode='cube', scene4_aspectmode='cube')
|
|
# fig.update_layout(scene=dict(xaxis=dict(range=[-1,1]), yaxis=dict(range=[-1,1]), zaxis=dict(range=[-1,1])), scene2=dict(xaxis=dict(range=[-1,1]), yaxis=dict(range=[-1,1]), zaxis=dict(range=[-1,1])), scene3=dict(xaxis=dict(range=[-1,1]), yaxis=dict(range=[-1,1]), zaxis=dict(range=[-1,1])), scene4=dict(xaxis=dict(range=[-1,1]), yaxis=dict(range=[-1,1]), zaxis=dict(range=[-1,1])))
|
|
|
|
# fig.show()
|
|
|
|
mesh_posed_fixed = fix_collision(torch.tensor(mesh_posed, device=config['device']), batch['mesh_body_posed'], torch.tensor(mask, device=config['device'])).cpu().numpy()
|
|
body = batch['mesh_body_posed'].cpu().numpy()
|
|
|
|
garment_posed = [mesh_posed[i, mask[i], :] for i in range(body.shape[0])]
|
|
collision = [np.concatenate((body[i], garment_posed[i]), axis=0) for i in range(len(garment_posed))]
|
|
collision_faces = [np.concatenate((F, faces[i] + config['smpl_res']), axis=0) for i in range(len(garment_posed))]
|
|
collision_color = [np.concatenate((np.ones_like(body[i], dtype=np.int32)*100, np.ones_like(garment_posed[i], dtype=np.int32)*230), axis=0) for i in range(len(garment_posed))]
|
|
|
|
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(garment_posed))]
|
|
collision_gt = [np.concatenate((body[i], gt_posed[i]), axis=0) for i in range(len(garment_posed))]
|
|
|
|
figs = { type + "/garment_" + str(i): plot_3d(gt[i], garment_unposed[i], faces[i], collision[i], collision_faces[i], collision_color[i], flip_xy=(not config['use_skinning'])) for i in range(4) }
|
|
figs_coll = { type + "/garment_" + str(i) + '_collision': plot_3d_collision(collision_gt[i], collision[i], collision_fixed[i], collision_faces[i], collision_color[i], flip_xy=(not config['use_skinning'])) for i in range(4) }
|
|
|
|
mean_hist = wandb.Histogram(sequence=mean.cpu().numpy().mean(axis=0))
|
|
logvar_hist = wandb.Histogram(sequence=logvar.cpu().numpy().mean(axis=0))
|
|
|
|
batch_id = batch['id']
|
|
batch_frame_nr = batch['frame_nr'].cpu().numpy()
|
|
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, **{ f'{type}/batch_info': batch_info }, **{ type + '/images': imgs, type + '/mean_hist': mean_hist, type + '/logvar_hist': logvar_hist } }
|
|
|
|
|
|
|
|
|
|
def sample():
|
|
from data.utils import Frame
|
|
from utils.utils import save_stl
|
|
|
|
def create_temp_frames(folder: str, frame: Frame):
|
|
with open(Path(folder) / 'frames_temp.txt', 'w') as f:
|
|
f.writelines([f'{frame}\n' for _ in range(4)])
|
|
|
|
model.eval()
|
|
load_model(model, f'checkpoints/iccvw/{config["name"]}')
|
|
count = 0
|
|
|
|
frames = ['01852_70_Tshirt']
|
|
frames = [Frame(frame_str=frame) for frame in frames]
|
|
|
|
|
|
|
|
for frame in frames:
|
|
create_temp_frames(config['train_dir'], frame)
|
|
dataset = Dataset(config['train_dir'], config['signature'], device=config['device'], frames_file='frames_temp.txt', use_cache=True, resolutions=[512], is_cape=config['is_cape'])
|
|
dataloader = DataLoader(dataset, batch_size=4, drop_last=True, shuffle=True, )
|
|
batch = next(iter(dataloader))
|
|
|
|
uv_static = batch['uv_static']
|
|
uv_body_posed = batch['uv_body_posed']
|
|
uv_mask = batch['uv_mask']
|
|
uv_normals = batch['uv_normals']
|
|
|
|
batch_size = uv_static.size(0)
|
|
|
|
|
|
for i in range(batch_size):
|
|
counter = 0
|
|
frame = Frame(batch['id'][i], batch['frame_nr'][i], batch['garment'][i])
|
|
fix_data = np.load(Path(dataset_train.folder) / 'mesh_fixed' / f'{frame.id}_{frame.garment}.npz')
|
|
mask = fix_data['mask']
|
|
faces = fix_data['faces']
|
|
|
|
gt = batch['mesh_posed'][i].cpu().numpy()[mask]
|
|
save_stl(Path('temp') / 'sampling' / f'{frame.id}_{frame.frame_nr}_{frame.garment}_gt.stl', gt, faces)
|
|
|
|
uv_static_tiled = uv_static[i][None,:,:,:].repeat(4, 1, 1, 1)
|
|
uv_body_posed_tiled = uv_body_posed[i][None,:,:,:].repeat(4, 1, 1, 1)
|
|
uv_mask_tiled = uv_mask[i][None,:,:].repeat(4, 1, 1)
|
|
uv_normals_tiled = uv_normals[i][None,:,:,:].repeat(4, 1, 1, 1)
|
|
pose_shape = batch['pose_shape'][i][None,:].repeat(4, 1)
|
|
|
|
for _ in range(4):
|
|
with torch.inference_mode():
|
|
pred = model.sample(uv_static_tiled, uv_body_posed_tiled, uv_normals_tiled, uv_mask_tiled)
|
|
|
|
mesh_pred = uv2mesh(pred)
|
|
|
|
shape = 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])])
|
|
|
|
mesh_pred_shaped = mesh_pred + shape_offsets * batch['mesh_mask'][:,:,None]
|
|
mesh_pred_posed = smpl(pose_shape[:, :72], pose_shape[:, 72:], mesh_pred_shaped)[0]
|
|
|
|
for k in range(4):
|
|
posed = mesh_pred_posed.cpu().numpy()[k, mask, :]
|
|
save_stl(Path('temp') / 'sampling' / f'{frame.id}_{frame.frame_nr}_{frame.garment}_{counter}.stl', posed, faces)
|
|
counter += 1
|
|
|
|
pass
|
|
|
|
|
|
if count > 100:
|
|
break
|
|
|
|
|
|
|
|
|
|
|
|
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']:
|
|
# g_balancing_coeff += 1 / 10000
|
|
|
|
if step % 25000 == 0 and not args['debug']:
|
|
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 = CVAE(config)
|
|
|
|
sample()
|
|
exit()
|
|
|
|
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/iccvw/' + config['name'], top_n=10)
|
|
|
|
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)
|
|
|
|
if not args['debug']:
|
|
# model = torch.compile(model)
|
|
wandb.watch(model, log='all', log_freq=10000, log_graph=True)
|
|
|
|
# create a profiler object
|
|
# profiler = torch.profiler.profile(
|
|
# activities=[ProfilerActivity.CPU],
|
|
# schedule=torch.profiler.schedule(wait=2, warmup=1, active=3, repeat=2),
|
|
# on_trace_ready=torch.profiler.tensorboard_trace_handler("log_dir"),
|
|
# )
|
|
|
|
# with profiler:
|
|
# with record_function("model_inference"):
|
|
train()
|
|
|
|
# profiler.stop()
|
|
# print(profiler.key_averages().table(sort_by="cpu_time_total", row_limit=25)) |