316 lines
15 KiB
Python
316 lines
15 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())
|
|
|
|
config_module = importlib.import_module(args['config'])
|
|
config = config_module.config
|
|
if args['debug']:
|
|
from configs.direct_7 import config
|
|
# from configs.ae_static_orig_2 import config
|
|
os.environ["CUDA_DEVICE_ORDER"]="PCI_BUS_ID"
|
|
os.environ["CUDA_VISIBLE_DEVICES"] = config['gpu']
|
|
if args['debug']:
|
|
os.environ["CUDA_LAUNCH_BLOCKING"] = '1'
|
|
|
|
import time
|
|
import argparse
|
|
import wandb
|
|
import random
|
|
import numpy as np
|
|
import torch
|
|
# from torchmetrics import MultiScaleStructuralSimilarityIndexMeasure as MSSSIM
|
|
from custom_utils.custom_utils import UV2Mesh, get_summary_html, maskFacesBatch, plot_3d_collision
|
|
import plotly.graph_objects as go
|
|
import plotly.express as ex
|
|
import torch.optim as optim
|
|
|
|
if config['is_skirt']:
|
|
from losses.losses import edge_loss_skirt as edge_loss
|
|
else:
|
|
from losses.losses import edge_loss
|
|
|
|
from data.dataset import Dataset
|
|
# from torch.utils.data import DataLoader
|
|
from losses.losses import collision_loss, normal_loss
|
|
from utils.postprocess import fix_collision
|
|
from custom_utils.custom_utils import plot_3d
|
|
from utils.checkpoints import CheckpointSaver, load_model
|
|
from custom_utils.custom_utils import Accumulator
|
|
from utils.utils import InfiniteDataLoader as DataLoader
|
|
from models.cond_encoder import AutoEncoder as Model
|
|
from smpl.smpl_torch import SMPL
|
|
|
|
from pytorch_msssim import MS_SSIM
|
|
|
|
|
|
def init_wandb():
|
|
run = wandb.init(project='iccv', name=config['name'], notes=config['notes'], dir='/data-local/127_2/temp', tags=config['tags'])
|
|
artifact = wandb.Artifact('code', type='code')
|
|
artifact.add_file('scripts/direct_train.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('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 train_step(batch):
|
|
model.train()
|
|
# with torch.autocast(device_type='cuda', dtype=torch.float16, enabled=use_amp):
|
|
if config['use_curvature']:
|
|
input = torch.cat([batch['uv_curvature'], batch['uv_static']], axis=1)
|
|
elif config['use_normals']:
|
|
input = torch.cat([batch['uv_normals'], batch['uv_body_posed'], batch['uv_static']], axis=1)
|
|
else:
|
|
input = torch.cat([batch['uv_body_posed'], batch['uv_static']], axis=1)
|
|
pred = model([input, batch['uv_mask']])
|
|
|
|
mesh_pred = uv2mesh(pred)
|
|
if config['use_skinning']:
|
|
mesh_orig = batch['mesh_unposed']
|
|
uv_orig = batch['uv_unposed']
|
|
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])])
|
|
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_orig = batch['mesh_posed']
|
|
uv_orig = batch['uv_posed']
|
|
mesh_pred_posed = mesh_pred
|
|
|
|
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))
|
|
|
|
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(((batch['uv_unposed'] - pred) ** 2), axis=-1), axis=[1, 2]))
|
|
n_loss = normal_loss(mesh_pred_posed, batch['mesh_posed'], batch['mesh_mask'], is_skirt=config['is_skirt'], is_smpl_orig=config['is_cape'])
|
|
|
|
|
|
ms_ssim = torch.mean(_MSSSIM(pred + 1, uv_orig + 1))
|
|
loss = l2_mesh_loss + (1 - ms_ssim) * 1e3 + (e_loss + c_loss + n_loss) * config['reg_loss_coeff']
|
|
|
|
optimizer.zero_grad()
|
|
loss.backward()
|
|
optimizer.step()
|
|
# scaler.scale(loss).backward()
|
|
# scaler.step(optimizer)
|
|
# scaler.update()
|
|
# optimizer.zero_grad()
|
|
|
|
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/edge_loss': e_loss, 'train/euclid_error': metric, 'train/collision_ratio': c_ratio,
|
|
'train/ms_ssim': ms_ssim, 'train/collision_loss': c_loss, 'train/l2_mesh_loss': l2_mesh_loss,
|
|
'train/normal_loss': n_loss }
|
|
|
|
|
|
def valid_step(batch):
|
|
model.eval()
|
|
|
|
with torch.inference_mode():
|
|
if config['use_curvature']:
|
|
input = torch.cat([batch['uv_curvature'], batch['uv_static']], axis=1)
|
|
elif config['use_normals']:
|
|
input = torch.cat([batch['uv_normals'], batch['uv_body_posed'], batch['uv_static']], axis=1)
|
|
else:
|
|
input = torch.cat([batch['uv_body_posed'], batch['uv_static']], axis=1)
|
|
|
|
pred = model([input, batch['uv_mask']])
|
|
mesh_pred = uv2mesh(pred)
|
|
if config['use_skinning']:
|
|
mesh_orig = batch['mesh_unposed']
|
|
uv_orig = batch['uv_unposed']
|
|
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])])
|
|
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_orig = batch['mesh_posed']
|
|
uv_orig = batch['uv_posed']
|
|
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(((batch['uv_unposed'] - 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'])
|
|
|
|
ms_ssim = torch.mean(_MSSSIM(pred + 1, uv_orig + 1))
|
|
loss = l2_mesh_loss + (1 - ms_ssim) * 1e3 + (e_loss + c_loss + n_loss) * config['reg_loss_coeff']
|
|
|
|
metric = torch.sum(torch.sqrt(torch.sum(batch['mesh_mask'][:,:,None] * (mesh_orig - mesh_pred) ** 2, axis=-1))) / torch.sum(batch['mesh_mask'])
|
|
|
|
return { 'valid/loss': loss, 'valid/edge_loss': e_loss, 'valid/euclid_error': metric, 'valid/collision_ratio': c_ratio,
|
|
'valid/ms_ssim': ms_ssim, 'valid/collision_loss': c_loss, 'valid/l2_mesh_loss': l2_mesh_loss,
|
|
'valid/normal_loss': n_loss }
|
|
|
|
|
|
def plot_everything(batch: dict, type: str):
|
|
model.eval()
|
|
with torch.inference_mode():
|
|
if config['use_curvature']:
|
|
input = torch.cat([batch['uv_curvature'], batch['uv_static']], axis=1)
|
|
elif config['use_normals']:
|
|
input = torch.cat([batch['uv_normals'], batch['uv_body_posed'], batch['uv_static']], axis=1)
|
|
else:
|
|
input = torch.cat([batch['uv_body_posed'], batch['uv_static']], axis=1)
|
|
pred = model([input, batch['uv_mask']]).detach()
|
|
|
|
mesh_pred = uv2mesh(pred).cpu().numpy()
|
|
if config['use_skinning']:
|
|
mesh_orig = batch['mesh_unposed'].cpu().numpy()
|
|
uv_orig = batch['uv_unposed']
|
|
else:
|
|
mesh_orig = batch['mesh_posed'].cpu().numpy()
|
|
uv_orig = batch['uv_posed']
|
|
|
|
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:
|
|
garment_unposed, faces = maskFacesBatch(mesh_pred, F, mask)
|
|
mesh_posed = mesh_pred
|
|
gt = [mesh_orig[i][mask[i], :] for i in range(pred.shape[0])]
|
|
|
|
gt_posed = [batch['mesh_posed'].cpu().numpy()[i, mask[i], :] for i in range(mask.shape[0])]
|
|
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_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))]
|
|
|
|
# faces_ = np.load('/data-net/dataset/00761/faces/00761.npy')
|
|
# faces = [faces_ 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))]
|
|
|
|
figs = { type + "/garment_" + str(i): plot_3d(gt[i], garment_unposed[i], faces[i], collision[i], collision_faces[i], collision_color[i]) for i in range(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]) for i in range(4) }
|
|
|
|
return { **figs, **figs_coll, **{ type + '/images': imgs, } }
|
|
|
|
|
|
def train():
|
|
valid_iterator = iter(valid_dataloader)
|
|
|
|
step = 0
|
|
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 step % 10000 == 0:
|
|
ckpt_saver_enc(model.encoder, step, optimizer, scaler)
|
|
ckpt_saver_dec(model.decoder, step, optimizer, scaler)
|
|
|
|
step += 1
|
|
|
|
|
|
if __name__ == '__main__':
|
|
if not args['debug']:
|
|
init_wandb()
|
|
|
|
use_amp = True
|
|
skirt_modifier = '_skirt' if config['is_skirt'] else ''
|
|
|
|
# dataset = Dataset('/data-local/127/train', config['signature'], resolutions=[512], device=device, frames_file='frames_jumpsuit.txt')
|
|
dataset_train = Dataset(config['train_dir'], config['signature'], device=config['device'], frames_file=config['train_frames'], use_cache=config['dataset_in_memory'], 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'], 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 : Model = Model(config)
|
|
optimizer = optim.Adam(model.parameters(), lr=config['lr'])
|
|
scaler = torch.cuda.amp.GradScaler(enabled=use_amp)
|
|
smpl = SMPL(orig_smpl=config['is_cape'], path='smpl', device=config['device'])
|
|
|
|
# _MSSSIM = MSSSIM(data_range=2).to(config['device'])
|
|
_MSSSIM = MS_SSIM(data_range=2, size_average=True, channel=3)
|
|
|
|
if config['pretrained_model'] != '':
|
|
load_model(model.encoder, config['pretrained_model'] + '_enc')
|
|
load_model(model.decoder, config['pretrained_model'] + '_dec')
|
|
|
|
ckpt_saver_enc = CheckpointSaver('checkpoints/iccv/torch/' + config['name'] + '_enc', top_n=5)
|
|
ckpt_saver_dec = CheckpointSaver('checkpoints/iccv/torch/' + config['name'] + '_dec', top_n=5)
|
|
|
|
run_name = config['name']
|
|
print(f'started training: {run_name}')
|
|
|
|
if not args['debug']:
|
|
# model = torch.compile(model)
|
|
wandb.watch(model, log='all', log_freq=10000, log_graph=True)
|
|
|
|
train()
|
|
|
|
|
|
|