222 lines
8.5 KiB
Python
222 lines
8.5 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)
|
|
args = vars(parser.parse_args())
|
|
|
|
config_module = importlib.import_module(args['config'])
|
|
config = config_module.config
|
|
# from configs.ae_curv_1 import config
|
|
os.environ["CUDA_DEVICE_ORDER"]="PCI_BUS_ID"
|
|
os.environ["CUDA_VISIBLE_DEVICES"] = config['gpu']
|
|
|
|
|
|
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
|
|
import cmapy as cm
|
|
|
|
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 torchmetrics.classification import MulticlassJaccardIndex
|
|
from torchmetrics import Dice
|
|
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_curv_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_curvature'], batch['uv_mask']])
|
|
gt_dense = torch.argmax(batch['uv_curvature'], dim=1)
|
|
|
|
ce_uv_loss = _ce_uv(pred, gt_dense)
|
|
mesh_pred = uv2mesh(pred) * batch['mesh_mask'][:,:,None]
|
|
mesh_orig = uv2mesh(gt_dense) * batch['mesh_mask']
|
|
ce_mesh_loss = _ce_mesh(torch.transpose(mesh_pred, 1, 2), mesh_orig.long())
|
|
|
|
loss = ce_uv_loss + ce_mesh_loss
|
|
|
|
optimizer.zero_grad()
|
|
loss.backward()
|
|
optimizer.step()
|
|
|
|
model.eval()
|
|
with torch.inference_mode():
|
|
ms_ssim = torch.mean(_MSSSIM(torch.argmax(pred, dim=1)[:,None,:,:].float(), gt_dense[:,None,:,:].float()))
|
|
mean_iou = _mean_iou(pred, gt_dense)
|
|
dice = _dice(pred, gt_dense)
|
|
|
|
return { 'train/loss': loss, 'train/ce_uv_loss': ce_uv_loss, 'train/ssim': ms_ssim, 'train/mean_iou': mean_iou,
|
|
'train/dice': dice, 'train/ce_mesh_loss': ce_mesh_loss }
|
|
|
|
|
|
def valid_step(batch):
|
|
model.eval()
|
|
|
|
with torch.inference_mode():
|
|
pred = model([batch['uv_curvature'], batch['uv_mask']])
|
|
gt_dense = torch.argmax(batch['uv_curvature'], dim=1)
|
|
|
|
ce_uv_loss = _ce_uv(pred, gt_dense)
|
|
mesh_pred = uv2mesh(pred) * batch['mesh_mask'][:,:,None]
|
|
mesh_orig = uv2mesh(gt_dense) * batch['mesh_mask']
|
|
ce_mesh_loss = _ce_mesh(torch.transpose(mesh_pred, 1, 2), mesh_orig.long())
|
|
|
|
loss = ce_uv_loss + ce_mesh_loss
|
|
|
|
ms_ssim = torch.mean(_MSSSIM(torch.argmax(pred, dim=1)[:,None,:,:].float(), gt_dense[:,None,:,:].float()))
|
|
mean_iou = _mean_iou(pred, gt_dense)
|
|
dice = _dice(pred, gt_dense)
|
|
|
|
return { 'valid/loss': loss, 'valid/ce_uv_loss': ce_uv_loss, 'valid/ssim': ms_ssim, 'valid/mean_iou': mean_iou,
|
|
'valid/dice': dice, 'valid/ce_mesh_loss': ce_mesh_loss }
|
|
|
|
|
|
def plot_everything(batch: dict, type: str):
|
|
model.eval()
|
|
pred = model([batch['uv_curvature'], batch['uv_mask']])
|
|
# gt_dense = torch.argmax(batch['uv_curvature'], dim=1)
|
|
|
|
# mesh_pred = uv2mesh(pred) * batch['mesh_mask'][:,:,None]
|
|
# mesh_orig = uv2mesh(gt_dense) * batch['mesh_mask']
|
|
|
|
orig_img = torch.argmax(batch['uv_curvature'], dim=1)
|
|
pred_img = torch.argmax(pred, dim=1)
|
|
img = torch.concat((orig_img, pred_img), axis=2).cpu().numpy()
|
|
imgs = [wandb.Image((img[i] + 1) / 2.0) for i in range(4)]
|
|
|
|
colors = np.array([cm.color('jet', 1 - i) for i in np.linspace(0, 1, 6+1)])
|
|
color_img = np.zeros((img.shape[0], img.shape[1], img.shape[2], 3), np.uint8)
|
|
for i in range(7):
|
|
color_img[img == i, :] = colors[i]
|
|
color_img = [wandb.Image(color_img[i]) for i in range(4)]
|
|
|
|
imgs = { type + '/images': [wandb.Image(img[i,:,:,np.newaxis] / 6.0) for i in range(img.shape[0])], type + '/color_images': color_img }
|
|
|
|
return 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)) } }
|
|
|
|
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)
|
|
ckpt_saver_dec(model.decoder, step, optimizer)
|
|
|
|
step += 1
|
|
|
|
|
|
if __name__ == '__main__':
|
|
init_wandb()
|
|
# device = "cuda" if torch.cuda.is_available() else "cpu"
|
|
|
|
# parser = argparse.ArgumentParser(description='')
|
|
# parser.add_argument('--name', type=str)
|
|
# args = vars(parser.parse_args())
|
|
|
|
resolution_modifier = ''
|
|
if config['resolution'] != 512:
|
|
resolution_modifier = '_' + str(config['resolution'])
|
|
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'])
|
|
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 : 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=1)
|
|
_mean_iou = MulticlassJaccardIndex(num_classes=7).to(config['device'])
|
|
_dice = Dice(average='macro', num_classes=7).to(config['device'])
|
|
_ce_uv = torch.nn.CrossEntropyLoss()
|
|
_ce_mesh = torch.nn.CrossEntropyLoss()
|
|
|
|
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/' + config['name'] + '_enc', top_n=5)
|
|
ckpt_saver_dec = CheckpointSaver('checkpoints/iccv/' + config['name'] + '_dec', top_n=5)
|
|
|
|
run_name = config['name']
|
|
print(f'started training: {run_name}')
|
|
train()
|
|
|
|
|
|
|