Compare commits
2
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
cada175296 | ||
|
|
52e5658dcc |
@@ -0,0 +1,73 @@
|
|||||||
|
from utils.convnext_utils import CNBlockConfig
|
||||||
|
|
||||||
|
config = dict()
|
||||||
|
|
||||||
|
config['gpu'] = '2'
|
||||||
|
config['name'] = 'curv_torch_1'
|
||||||
|
config['notes'] = ' '
|
||||||
|
config['tags'] = ['torch', 'curv']
|
||||||
|
config['script'] = 'scripts/ae_curv_train.py'
|
||||||
|
|
||||||
|
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'] = True
|
||||||
|
config['cond_ae']['latent_dim'] = config['latent_dim']
|
||||||
|
config['cond_ae']['kernel_size'] = 7
|
||||||
|
config['cond_ae']['bottleneck_size'] = 40 * 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.001
|
||||||
|
config['cond_ae']['upscale_output'] = False
|
||||||
|
|
||||||
|
config['signature'] = { 'id',
|
||||||
|
'frame_nr',
|
||||||
|
'uv_curvature',
|
||||||
|
'mesh_curvature',
|
||||||
|
'mesh_mask',
|
||||||
|
'uv_mask',
|
||||||
|
}
|
||||||
@@ -40,7 +40,7 @@ class UV2Mesh(nn.Module):
|
|||||||
|
|
||||||
|
|
||||||
def uv_to_mesh(self, uv):
|
def uv_to_mesh(self, uv):
|
||||||
if uv.shape[1] == 3:
|
if uv.shape[1] == 3 or uv.shape[1] == 7:
|
||||||
uv = torch.permute(uv, [0,2,3,1])
|
uv = torch.permute(uv, [0,2,3,1])
|
||||||
if uv.shape[1] != 512:
|
if uv.shape[1] != 512:
|
||||||
uv = Resize(uv[:,:,None], size=(512, 256), interpolation=InterpolationMode.BILINEAR)
|
uv = Resize(uv[:,:,None], size=(512, 256), interpolation=InterpolationMode.BILINEAR)
|
||||||
@@ -65,7 +65,7 @@ class UV2Mesh(nn.Module):
|
|||||||
# p1 = tf.stack((x1, y1, z1), axis=-1)
|
# p1 = tf.stack((x1, y1, z1), axis=-1)
|
||||||
# p2 = tf.stack((x2, y2, z2), axis=-1)
|
# p2 = tf.stack((x2, y2, z2), axis=-1)
|
||||||
|
|
||||||
mesh = torch.mean(uv[:, self.uv_pixels[:,:,0], self.uv_pixels[:,:,1]], dim=2)
|
mesh = torch.mean(uv[:, self.uv_pixels[:,:,0], self.uv_pixels[:,:,1]].float(), dim=2)
|
||||||
return mesh
|
return mesh
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
+2
-2
@@ -186,7 +186,7 @@ class Dataset(Dataset):
|
|||||||
uv_curvature = uv_curvature['uv_curvature']
|
uv_curvature = uv_curvature['uv_curvature']
|
||||||
else:
|
else:
|
||||||
uv_curvature = uv_curvature['curvature_uv']
|
uv_curvature = uv_curvature['curvature_uv']
|
||||||
uv_curvature = torch.nn.functional.one_hot(torch.tensor(uv_curvature, device=self.device, dtype=torch.long), 7).to(self.device)
|
uv_curvature = torch.nn.functional.one_hot(torch.tensor(uv_curvature, device=self.device, dtype=torch.long), 7).float().to(self.device)
|
||||||
item['uv_curvature' + res_string] = uv_curvature
|
item['uv_curvature' + res_string] = uv_curvature
|
||||||
|
|
||||||
if 'uv_unposed' + res_string in self.signature:
|
if 'uv_unposed' + res_string in self.signature:
|
||||||
@@ -206,7 +206,7 @@ class Dataset(Dataset):
|
|||||||
data = { key: (torch.from_numpy(value) if not (type(value) == str or type(value) == torch.Tensor) else value) for key, value in item.items()}
|
data = { key: (torch.from_numpy(value) if not (type(value) == str or type(value) == torch.Tensor) else value) for key, value in item.items()}
|
||||||
|
|
||||||
for key, value in data.items():
|
for key, value in data.items():
|
||||||
if key.startswith('uv_') and value.shape[-1] == 3:
|
if key.startswith('uv_') and (value.shape[-1] == 3 or value.shape[-1] == 7):
|
||||||
data[key] = torch.permute(value, [2,0,1])
|
data[key] = torch.permute(value, [2,0,1])
|
||||||
|
|
||||||
if self.cache is not None:
|
if self.cache is not None:
|
||||||
|
|||||||
+5
-5
@@ -33,10 +33,10 @@ class VariationalEncoder(nn.Module):
|
|||||||
|
|
||||||
class AEEncoder(nn.Module):
|
class AEEncoder(nn.Module):
|
||||||
|
|
||||||
def __init__(self, block_setting: CNBlockConfig, kernel_size: int = 7, activation='tanh', device='cuda'):
|
def __init__(self, block_setting: CNBlockConfig, kernel_size: int = 7, activation='tanh', is_label=False, nr_of_labels=None, device='cuda'):
|
||||||
super(AEEncoder, self).__init__()
|
super(AEEncoder, self).__init__()
|
||||||
|
|
||||||
self.encoder = ConvNeXt(block_setting=block_setting, kernel_size=kernel_size, device=device)
|
self.encoder = ConvNeXt(block_setting=block_setting, kernel_size=kernel_size, is_label=is_label, nr_of_labels=nr_of_labels, device=device)
|
||||||
if activation == 'tanh':
|
if activation == 'tanh':
|
||||||
self.act = nn.Tanh()
|
self.act = nn.Tanh()
|
||||||
elif activation == 'sigmoid':
|
elif activation == 'sigmoid':
|
||||||
@@ -81,10 +81,10 @@ class Decoder(nn.Module):
|
|||||||
x = self.decoder(x)
|
x = self.decoder(x)
|
||||||
|
|
||||||
if self.is_label:
|
if self.is_label:
|
||||||
x = x * mask[:,:,:,None]
|
x = x * mask[:,None,:,:]
|
||||||
|
|
||||||
background = torch.ones((mask.shape[0],512,256,1), device=mask.get_device()) * (1 - mask[:,:,:,None])
|
background = torch.ones((mask.shape[0],1,512,256), device=mask.get_device()) * (1 - mask[:,None,:,:])
|
||||||
x = torch.concat((background, x), axis=-1)
|
x = torch.concat((background, x), dim=1)
|
||||||
x = self.softmax(x)
|
x = self.softmax(x)
|
||||||
|
|
||||||
if len(inputs) == 2:
|
if len(inputs) == 2:
|
||||||
|
|||||||
@@ -8,8 +8,8 @@ class AutoEncoder(nn.Module):
|
|||||||
def __init__(self, config):
|
def __init__(self, config):
|
||||||
super(AutoEncoder, self).__init__()
|
super(AutoEncoder, self).__init__()
|
||||||
|
|
||||||
self.encoder : AEEncoder = AEEncoder(config['encoder_block_settings'], config['kernel_size'], config['activation'], device=config['device'])
|
self.encoder : AEEncoder = AEEncoder(config['encoder_block_settings'], config['kernel_size'], config['activation'], is_label=config['is_label'], device=config['device'], nr_of_labels=7)
|
||||||
self.decoder : Decoder = Decoder(config['decoder_block_settings'], kernel_size=config['kernel_size'], is_label=config['is_label'], device=config['device'])
|
self.decoder : Decoder = Decoder(config['decoder_block_settings'], kernel_size=config['kernel_size'], is_label=config['is_label'], device=config['device'], nr_of_classes=6)
|
||||||
|
|
||||||
|
|
||||||
def forward(self, input):
|
def forward(self, input):
|
||||||
|
|||||||
@@ -64,6 +64,8 @@ class ConvNeXtBase(nn.Module):
|
|||||||
norm_layer: Optional[Callable[..., nn.Module]] = None,
|
norm_layer: Optional[Callable[..., nn.Module]] = None,
|
||||||
device: str = 'cuda',
|
device: str = 'cuda',
|
||||||
kernel_size: int = 7,
|
kernel_size: int = 7,
|
||||||
|
is_label: bool = False,
|
||||||
|
nr_of_labels: Optional[int] = None,
|
||||||
) -> None:
|
) -> None:
|
||||||
super().__init__()
|
super().__init__()
|
||||||
|
|
||||||
@@ -83,7 +85,7 @@ class ConvNeXtBase(nn.Module):
|
|||||||
# Stem
|
# Stem
|
||||||
firstconv_output_channels = block_setting[0].input_channels
|
firstconv_output_channels = block_setting[0].input_channels
|
||||||
self.stem = Conv2dNormActivation(
|
self.stem = Conv2dNormActivation(
|
||||||
3,
|
3 if not is_label else nr_of_labels,
|
||||||
firstconv_output_channels,
|
firstconv_output_channels,
|
||||||
kernel_size=4,
|
kernel_size=4,
|
||||||
stride=4,
|
stride=4,
|
||||||
@@ -234,7 +236,7 @@ def _convnext(
|
|||||||
if reversed:
|
if reversed:
|
||||||
model = ConvNeXtReverseBase(block_setting, stochastic_depth_prob=stochastic_depth_prob, is_label=is_label, nr_of_labels=nr_of_labels, kernel_size=kernel_size, device=device, **kwargs)
|
model = ConvNeXtReverseBase(block_setting, stochastic_depth_prob=stochastic_depth_prob, is_label=is_label, nr_of_labels=nr_of_labels, kernel_size=kernel_size, device=device, **kwargs)
|
||||||
else:
|
else:
|
||||||
model = ConvNeXtBase(block_setting, stochastic_depth_prob=stochastic_depth_prob, kernel_size=kernel_size, device=device, **kwargs)
|
model = ConvNeXtBase(block_setting, stochastic_depth_prob=stochastic_depth_prob, kernel_size=kernel_size, is_label=is_label, nr_of_labels=nr_of_labels, device=device, **kwargs)
|
||||||
|
|
||||||
|
|
||||||
return model
|
return model
|
||||||
|
|||||||
@@ -1,6 +1,13 @@
|
|||||||
import os
|
import os
|
||||||
import sys
|
import sys
|
||||||
from configs.ae_body_1 import config
|
from configs.ae_curv_1 import config
|
||||||
|
import argparse
|
||||||
|
|
||||||
|
parser = argparse.ArgumentParser(description='')
|
||||||
|
parser.add_argument('--debug', action='store_true')
|
||||||
|
args = vars(parser.parse_args())
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
if __name__ == '__main__':
|
if __name__ == '__main__':
|
||||||
# import wandb
|
# import wandb
|
||||||
@@ -9,5 +16,8 @@ if __name__ == '__main__':
|
|||||||
script = config['script']
|
script = config['script']
|
||||||
config = [key for key in sys.modules.keys() if key.startswith('configs.')][-1]
|
config = [key for key in sys.modules.keys() if key.startswith('configs.')][-1]
|
||||||
current_file = '/'.join(__file__.split('/')[-2:])
|
current_file = '/'.join(__file__.split('/')[-2:])
|
||||||
# os.system(f'nohup python scripts/ae_static_train.py --name lhunor_{name} > nohup/torch/{name}.out 2>&1 &')
|
|
||||||
os.system(f'nohup python {script} --name lhunor_{name} --config {config} > nohup/torch/{name}.out 2>&1 &')
|
if args['debug']:
|
||||||
|
os.system(f'python {script} --name lhunor_{name} --config {config}')
|
||||||
|
else:
|
||||||
|
os.system(f'nohup python {script} --name lhunor_{name} --config {config} > nohup/torch/{name}.out 2>&1 &')
|
||||||
@@ -0,0 +1,221 @@
|
|||||||
|
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()
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
Reference in New Issue
Block a user