static encoder runs, but doesn't work yet
This commit is contained in:
@@ -0,0 +1,197 @@
|
||||
import os
|
||||
import sys
|
||||
sys.path.append(os.path.dirname(os.path.abspath(__file__)) + '/..')
|
||||
|
||||
from configs.ae_static import config
|
||||
os.environ["CUDA_DEVICE_ORDER"]="PCI_BUS_ID"
|
||||
os.environ["CUDA_VISIBLE_DEVICES"] = config['gpu']
|
||||
|
||||
|
||||
import time
|
||||
import argparse
|
||||
import wandb
|
||||
import random
|
||||
import numpy as np
|
||||
import torch
|
||||
from torch import nn
|
||||
from torchmetrics import MultiScaleStructuralSimilarityIndexMeasure as MSSSIM
|
||||
from custom_utils.custom_utils import UV2Mesh, get_summary_html, load_model, 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 batch_to_dict, plot_3d
|
||||
from models.cond_encoder import AutoEncoder
|
||||
from utils.checkpoints import CheckpointSaver
|
||||
from custom_utils.custom_utils import Accumulator
|
||||
|
||||
|
||||
def init_wandb():
|
||||
run = wandb.init(project='ae', name=config['name'], notes=config['notes'], dir='/data-local/127/temp/wandb', tags=config['tags'])
|
||||
artifact = wandb.Artifact('code', type='code')
|
||||
artifact.add_file('scripts/ae_static_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_static'], batch['uv_mask']])
|
||||
|
||||
mesh_pred = uv2mesh(pred)
|
||||
mesh_orig = batch['mesh_static']
|
||||
|
||||
e_loss = 1e-2 * torch.mean(edge_loss(mesh_pred, mesh_orig, batch['mesh_mask']))
|
||||
l1_loss = torch.mean(torch.sum((torch.abs(batch['uv_static'] - pred)), axis=1))
|
||||
ms_ssim = torch.mean(_MSSSIM(pred + 1, batch['uv_static'] + 1))
|
||||
loss = 1e3 * (1 - ms_ssim)
|
||||
|
||||
optimizer.zero_grad()
|
||||
loss.backward()
|
||||
optimizer.step()
|
||||
|
||||
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/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_static'], batch['uv_mask']])
|
||||
|
||||
mesh_pred = uv2mesh(pred)
|
||||
mesh_orig = batch['mesh_static']
|
||||
|
||||
e_loss = 1e-2 * torch.mean(edge_loss(mesh_pred, mesh_orig, batch['mesh_mask']))
|
||||
l1_loss = torch.mean(torch.sum((torch.abs(batch['uv_static'] - pred)), axis=1))
|
||||
ms_ssim = torch.mean(_MSSSIM(pred + 1, batch['uv_static'] + 1))
|
||||
loss = 1e3 * (1 - ms_ssim)
|
||||
|
||||
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/l1_loss': l1_loss, 'valid/euclid_error': metric, 'valid/ms_ssim': ms_ssim, }
|
||||
|
||||
|
||||
def plot_everything(batch: dict, type: str):
|
||||
pred = model([batch['uv_static'], batch['uv_mask']]).detach()
|
||||
|
||||
mesh_pred = uv2mesh(pred)
|
||||
mesh_orig = batch['mesh_static']
|
||||
|
||||
orig_img = torch.permute(batch['uv_static'], [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")
|
||||
mask = batch['mesh_mask'].cpu().numpy().astype(bool)
|
||||
garment_static, faces = maskFacesBatch(mesh_pred.detach().cpu().numpy(), F, mask)
|
||||
gt = [mesh_orig[i].cpu().numpy()[mask[i], :] for i in range(pred.shape[0])]
|
||||
|
||||
body = gt
|
||||
garment_posed = garment_static
|
||||
collision = [np.concatenate((body[i], garment_posed[i]), axis=0) for i in range(len(garment_posed))]
|
||||
collision_faces = [np.concatenate((faces[i], faces[i] + np.sum(mask[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))]
|
||||
|
||||
figs = { type + "/garment_" + str(i): plot_3d(gt[i], garment_static[i], faces[i], 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)) } }
|
||||
|
||||
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)
|
||||
|
||||
print(step)
|
||||
|
||||
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 ''
|
||||
|
||||
# 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'])
|
||||
dataset_valid = Dataset(config['valid_dir'], config['signature'], device=config['device'], frames_file=config['valid_frames'])
|
||||
train_dataloader = DataLoader(dataset_train, batch_size=4, drop_last=True, shuffle=False)
|
||||
valid_dataloader = DataLoader(dataset_valid, batch_size=4, drop_last=True, shuffle=False)
|
||||
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'])
|
||||
|
||||
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=20)
|
||||
ckpt_saver_dec = CheckpointSaver('checkpoints/iccv/' + config['name'] + '_dec', top_n=20)
|
||||
|
||||
run_name = config['name']
|
||||
print(f'started training: {run_name}')
|
||||
train()
|
||||
|
||||
|
||||
|
||||
Reference in New Issue
Block a user