215 lines
8.6 KiB
Python
215 lines
8.6 KiB
Python
import os
|
|
import sys
|
|
sys.path.append(os.path.dirname(os.path.abspath(__file__)) + '/..')
|
|
|
|
import argparse
|
|
import importlib
|
|
|
|
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.ae_body_cape_m 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 wandb
|
|
import random
|
|
import numpy as np
|
|
import torch
|
|
import cv2
|
|
# from torchmetrics import MultiScaleStructuralSimilarityIndexMeasure as MSSSIM
|
|
from custom_utils.custom_utils import UV2Mesh, get_summary_html, maskFacesBatch, get_summary_str
|
|
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 custom_utils.custom_utils import plot_3d
|
|
from models.cond_encoder import AutoEncoder
|
|
from utils.checkpoints import CheckpointSaver, load_model
|
|
from custom_utils.custom_utils import Accumulator
|
|
from utils.utils import InfiniteDataLoader as DataLoader
|
|
|
|
from pytorch_msssim import MS_SSIM
|
|
|
|
|
|
def init_wandb():
|
|
run = wandb.init(project='ae', name=config['name'], notes=config['notes'], dir='/data-local/127/temp', tags=config['tags'])
|
|
artifact = wandb.Artifact('code', type='code')
|
|
artifact.add_file('scripts/ae_body_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()
|
|
pred = model([batch['uv_body_posed'], uv_mask_body])
|
|
|
|
ms_ssim = torch.mean(_MSSSIM(pred + 1, batch['uv_body_posed'] + 1))
|
|
loss = 1e3 * (1 - ms_ssim)
|
|
|
|
optimizer.zero_grad()
|
|
loss.backward()
|
|
optimizer.step()
|
|
|
|
model.eval()
|
|
with torch.inference_mode():
|
|
mesh_pred = uv2mesh(pred)
|
|
mesh_orig = batch['mesh_body_posed']
|
|
l1_loss = torch.mean(torch.sum((torch.abs(batch['uv_body_posed'] - pred)), axis=1))
|
|
e_loss = 1e-2 * torch.mean(edge_loss(mesh_pred, mesh_orig, torch.ones((pred.shape[0], 3638 if config['is_cape'] else 14475), device=pred.get_device())))
|
|
metric = torch.mean(torch.sqrt(torch.sum(batch['mesh_mask'][:,:,None] * (mesh_orig - mesh_pred) ** 2, axis=-1)))
|
|
|
|
return { 'train/loss': loss, 'train/edge_loss': e_loss, 'train/l1_loss': l1_loss, 'train/euclid_error': metric, 'train/ms_ssim': ms_ssim, }
|
|
|
|
|
|
def valid_step(batch):
|
|
model.eval()
|
|
|
|
with torch.inference_mode():
|
|
pred = model([batch['uv_body_posed'], uv_mask_body])
|
|
|
|
mesh_pred = uv2mesh(pred)
|
|
mesh_orig = batch['mesh_body_posed']
|
|
|
|
e_loss = 1e-2 * torch.mean(edge_loss(mesh_pred, mesh_orig, torch.ones((pred.shape[0], 3638 if config['is_cape'] else 14475), device=pred.get_device())))
|
|
l1_loss = torch.mean(torch.sum((torch.abs(batch['uv_body_posed'] - pred)), axis=1))
|
|
ms_ssim = torch.mean(_MSSSIM(pred + 1, batch['uv_body_posed'] + 1))
|
|
loss = 1e3 * (1 - ms_ssim)
|
|
|
|
metric = torch.mean(torch.sqrt(torch.sum(batch['mesh_mask'][:,:,None] * (mesh_orig - mesh_pred) ** 2, axis=-1)))
|
|
|
|
return { 'valid/loss': loss, 'valid/edge_loss': e_loss, 'valid/l1_loss': l1_loss, 'valid/euclid_error': metric, 'valid/ms_ssim': ms_ssim, }
|
|
|
|
|
|
def plot_everything(batch: dict, type: str):
|
|
model.eval()
|
|
pred = model([batch['uv_body_posed'], uv_mask_body]).detach()
|
|
|
|
mesh_pred = uv2mesh(pred)
|
|
mesh_orig = batch['mesh_body_posed']
|
|
|
|
orig_img = torch.permute(batch['uv_body_posed'], [0,2,3,1])
|
|
pred_img = torch.permute(pred, [0,2,3,1])
|
|
img = torch.concat((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")
|
|
garment_unposed, faces = mesh_pred.cpu().numpy(), F
|
|
gt = [mesh_orig[i].cpu().numpy() for i in range(pred.shape[0])]
|
|
|
|
body = uv2mesh(batch['uv_body_posed']).cpu().numpy()
|
|
garment_posed = garment_unposed
|
|
collision = [np.concatenate((body[i], garment_posed[i]), axis=0) for i in range(len(garment_posed))]
|
|
collision_faces = [np.concatenate((F, faces + (3638 if config['is_cape'] else 14475)), 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))]
|
|
|
|
figs = { type + "/garment_" + str(i): plot_3d(gt[i], garment_unposed[i], faces, collision[i], collision_faces[i], collision_color[i]) for i in range(4) }
|
|
|
|
return { **figs, **{ 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=None)
|
|
ckpt_saver_dec(model.decoder, step, optimizer, scaler=None)
|
|
|
|
step += 1
|
|
|
|
|
|
if __name__ == '__main__':
|
|
if not args['debug']:
|
|
init_wandb()
|
|
|
|
skirt_modifier = '_skirt' if config['is_skirt'] else ''
|
|
|
|
uv_mask_body = np.load('custom_utils/mask_256x512' + ('_skirt' if config['is_skirt'] else '') + '.npy')
|
|
uv_mask_body = cv2.dilate(uv_mask_body.astype(np.float32), cv2.getStructuringElement(cv2.MORPH_RECT, (2 * 2 + 1, 2 * 2 + 1), (2, 2)), iterations=2)
|
|
uv_mask_body = torch.from_numpy(uv_mask_body).float().to(config['device'])
|
|
|
|
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 : AutoEncoder = AutoEncoder(config['cond_ae'])
|
|
optimizer = optim.Adam(model.parameters(), lr=config['lr'])
|
|
|
|
# _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=1000, log_graph=True)
|
|
|
|
train()
|
|
|
|
|
|
|