ae body training
This commit is contained in:
@@ -0,0 +1,72 @@
|
||||
from utils.convnext_utils import CNBlockConfig
|
||||
|
||||
config = dict()
|
||||
|
||||
config['gpu'] = '1'
|
||||
config['name'] = 'body_torch_1'
|
||||
config['notes'] = ' '
|
||||
config['tags'] = ['torch', 'body']
|
||||
|
||||
config['pretrained_model'] = ''
|
||||
|
||||
config['batch_size'] = 4
|
||||
config['train_dir'] = '/data-local/127/train'
|
||||
config['valid_dir'] = '/data-local/127/valid'
|
||||
config['test_dir'] = '/data-net/dataset/test_ready'
|
||||
config['train_frames'] = None
|
||||
config['valid_frames'] = None
|
||||
|
||||
config['resolution'] = 512
|
||||
config['is_skirt'] = False
|
||||
config['dataset_in_memory'] = False
|
||||
config['is_cape'] = False
|
||||
config['remove_global_orientation'] = True
|
||||
config['device'] = 'cuda'
|
||||
|
||||
config['smpl_res'] = 14475
|
||||
if config['is_cape']:
|
||||
config['smpl_res'] = 3638
|
||||
|
||||
config['latent_dim'] = 128
|
||||
|
||||
config['bottleneck_scale'] = 2
|
||||
|
||||
config['cond_ae'] = dict()
|
||||
config['cond_ae']['device'] = config['device']
|
||||
config['cond_ae']['is_label'] = False
|
||||
config['cond_ae']['latent_dim'] = config['latent_dim']
|
||||
config['cond_ae']['kernel_size'] = 7
|
||||
config['cond_ae']['bottleneck_size'] = 16 * config['bottleneck_scale']
|
||||
|
||||
block_setting = [
|
||||
CNBlockConfig(16, 32, 3),
|
||||
CNBlockConfig(32, 64, 3),
|
||||
CNBlockConfig(64, 128, 9),
|
||||
CNBlockConfig(128, config['cond_ae']['bottleneck_size'], 9),
|
||||
CNBlockConfig(config['cond_ae']['bottleneck_size'], None, 3),
|
||||
]
|
||||
|
||||
block_setting_reverse = [
|
||||
CNBlockConfig(config['cond_ae']['bottleneck_size'], 128, 3),
|
||||
CNBlockConfig(128, 64, 9),
|
||||
CNBlockConfig(64, 32, 9),
|
||||
CNBlockConfig(32, 16, 3),
|
||||
CNBlockConfig(16, 3, 3),
|
||||
# CNBlockConfig(3, 3, 3),
|
||||
]
|
||||
|
||||
config['cond_ae']['encoder_block_settings'] = block_setting
|
||||
config['cond_ae']['decoder_block_settings'] = block_setting_reverse
|
||||
config['cond_ae']['activation'] = 'tanh'
|
||||
|
||||
|
||||
config['lr'] = 0.0001
|
||||
config['cond_ae']['upscale_output'] = False
|
||||
|
||||
config['signature'] = { 'id',
|
||||
'frame_nr',
|
||||
'pose_shape',
|
||||
'uv_body_posed',
|
||||
'mesh_mask',
|
||||
'mesh_body_posed',
|
||||
}
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
import torch
|
||||
from torch import nn
|
||||
from models.convnext import ConvNeXt, CNBlock, CNBlockConfig
|
||||
from models.convnext_orig import ConvNeXt, CNBlock, CNBlockConfig
|
||||
from typing import Any, Callable, List, Optional, Sequence
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,203 @@
|
||||
import os
|
||||
import sys
|
||||
sys.path.append(os.path.dirname(os.path.abspath(__file__)) + '/..')
|
||||
|
||||
from configs.ae_body_1 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
|
||||
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)) } }
|
||||
|
||||
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=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/' + 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()
|
||||
|
||||
|
||||
|
||||
Reference in New Issue
Block a user