commit all

This commit is contained in:
2023-01-25 12:25:59 +00:00
parent 1bf224841f
commit 7470ca9fb6
139 changed files with 82069 additions and 811 deletions
+141 -165
View File
@@ -1,5 +1,8 @@
import os
os.environ["CUDA_VISIBLE_DEVICES"] = "1"
import sys
from configs.config_cvae_curv import config
os.environ["CUDA_VISIBLE_DEVICES"] = config['gpu']
import tensorflow as tf
gpus = tf.config.experimental.list_physical_devices('GPU')
@@ -21,9 +24,10 @@ import random
import cmapy as cm
import numpy as np
import scipy as sp
from custom_utils.custom_utils import UV2Mesh, UV2MeshLabel, maskFacesBatch, _maskFaces
from custom_utils.custom_utils import UV2Mesh, UV2MeshLabel, maskFacesBatch, _maskFaces, load_model, get_summary_html, get_summary_str
import plotly.graph_objects as go
import plotly.express as ex
from plotly.subplots import make_subplots
from PIL import Image
from tf_utils import check_tf_version, allow_memory_growth
@@ -33,31 +37,31 @@ from dataset import DatasetFactory, StaticDataset
from custom_utils.custom_utils import batch_to_dict
from custom_utils.smpl import SMPL
from models.cvae_curv_model import CVAE
from losses import kl_loss
name='cvae_curv_3'
def init_wandb():
run = wandb.init(project='vae', name=name,
notes='learn offsets. smaller flattened latent vectors. with 25-85k pretraining. smaller batchsize. new implementation for kl loss. \
no lr schedule. 25 jumpsuits, average reconst_loss before calculation, offsets over average unposed garment. gamma balancing. remove global \
orientation (in posed body input and in pose_shape parameters.. r lower kl coeff to 0.1. fixed plotting colors\
addent MLP for lowering conditional Z diemnsion\
higher starting kl coeff (0.1)\
train on 100 garments')
run = wandb.init(project='ablation', name=config['name'], notes=config['notes'], dir='/wandb')
artifact = wandb.Artifact('code', type='code')
artifact.add_file('cvae_curv.py')
artifact.add_file('models/cvae_curv_model.py')
artifact.add_file('dataset.py')
artifact.add_file('losses.py')
artifact.add_file('models/base.py')
artifact.add_file('models/cond_encoder.py')
artifact.add_file('dataset.py')
artifact.add_file('convnext/models/convnext_tf.py')
config_file_names = [key for key in sys.modules.keys() if key.startswith('configs.')]
for config_file_name in config_file_names:
artifact.add_file('/'.join(config_file_name.split('.')) + '.py')
run.log_artifact(artifact)
uv2mesh = UV2MeshLabel(res=256)
def plot_3d(curv_gt, curv_pred, faces, mesh):
mesh_2 = mesh.copy()
mesh_2[:,1] += 1
def plot_3d(curv_gt, curv_pred, faces, mesh):
colors = np.array([cm.color('jet', 1 - i) for i in np.linspace(0, 1, 6+1)])
v_color_1 = np.zeros((mesh.shape[0], 3))
v_color_2 = np.zeros((mesh.shape[0], 3))
@@ -65,58 +69,50 @@ def plot_3d(curv_gt, curv_pred, faces, mesh):
v_color_1[curv_gt == i, :] = colors[i]
v_color_2[curv_pred == i, :] = colors[i]
fig = go.Figure(data=[
go.Mesh3d(
# 8 vertices of a cube
x=mesh[:,0],
y=mesh[:,1],
z=mesh[:,2],
# i, j and k give the vertices of triangles
i = faces[:,0],
j = faces[:,1],
k = faces[:,2],
vertexcolor=v_color_1,
text='gt'
),
go.Mesh3d(
# 8 vertices of a cube
x=mesh_2[:,0],
y=mesh_2[:,1],
z=mesh_2[:,2],
# i, j and k give the vertices of triangles
i = faces[:,0],
j = faces[:,1],
k = faces[:,2],
vertexcolor=v_color_2,
text='pred'
)
])
fig = make_subplots(rows=1, cols=2, start_cell="top-left", specs = [ [{ 'type': 'scene' } for _ in range(2)] ])
fig.update_layout(scene_aspectmode='manual',
scene_aspectratio=dict(x=1, y=2, z=1))
fig.update_layout(
scene = dict(
xaxis = dict(nticks=4, range=[-1,1],),
yaxis = dict(nticks=4, range=[-1,3],),
zaxis = dict(nticks=4, range=[-1,1],),)
fig.add_trace(go.Mesh3d(
# 8 vertices of a cube
x=mesh[:,0],
y=mesh[:,1],
z=mesh[:,2],
# i, j and k give the vertices of triangles
i = faces[:,0],
j = faces[:,1],
k = faces[:,2],
vertexcolor=v_color_1,
text='gt'
),
row=1, col=1)
fig.add_trace(go.Mesh3d(
# 8 vertices of a cube
x=mesh[:,0],
y=mesh[:,1],
z=mesh[:,2],
# i, j and k give the vertices of triangles
i = faces[:,0],
j = faces[:,1],
k = faces[:,2],
vertexcolor=v_color_2,
text='pred'
),
row=1, col=2)
fig.update_layout(scene_aspectmode='manual', scene_aspectratio=dict(x=1, y=1, z=1),
scene2_aspectmode='manual', scene2_aspectratio=dict(x=1, y=1, z=1),
)
helper = dict(xaxis = dict(nticks=4, range=[-1,1],),
yaxis = dict(nticks=4, range=[-1,1],),
zaxis = dict(nticks=4, range=[-1,1],),)
fig.update_layout(scene = helper,
scene2 = helper,
)
return fig
def log_normal_pdf(sample, mean, logvar, raxis=1):
log2pi = tf.math.log(2. * np.pi)
res = tf.reduce_sum(-.5 * ((sample - mean) ** 2. * tf.exp(-logvar) + logvar + log2pi), axis=raxis)
return res
def kl_loss(mean, logvar):
kl_loss = 1 + logvar - tf.square(mean) - tf.exp(logvar)
kl_loss = tf.reduce_mean(kl_loss)
kl_loss *= -0.5
return kl_loss
g_mean_iou = tf.keras.metrics.MeanIoU(num_classes=7)
def get_mean_iou(y_true, y_pred):
@@ -157,83 +153,89 @@ def dice_dense(prediction, ground_truth, weight_map=None):
@tf.function
def train_step(batch):
with tf.GradientTape() as tape:
uv_curvature = tf.one_hot(batch['uv_curvature'], 7)
pred, mean, logvar, z = model([batch['uv_static'], batch['uv_body_posed'], uv_curvature, batch['uv_mask']])
pred, mean, logvar = model([batch['uv_static'], batch['uv_body_posed'], batch['uv_curvature'], batch['uv_mask']])
ce_uv_loss = scce(batch['uv_curvature'], pred)
ms_ssim = tf.reduce_mean(tf.image.ssim(pred, uv_curvature, max_val=1))
ce_uv_loss = scce(tf.math.argmax(batch['uv_curvature'], axis=-1), pred)
dice = dice_dense(pred, batch['uv_curvature'])
reconstr_loss = ce_uv_loss
mesh_pred = uv2mesh(pred) * batch['mesh_mask'][:,:,tf.newaxis]
mesh_orig = tf.cast(uv2mesh(tf.math.argmax(batch['uv_curvature'], axis=-1, output_type=tf.int32)), tf.float32) * batch['mesh_mask']
ce_mesh_loss = scce(mesh_orig, mesh_pred)
reconstr_loss = ce_uv_loss + ce_mesh_loss
# reconstr_loss = 1 - dice
reconstr_loss = tf.reduce_mean(reconstr_loss)
kl = kl_loss(mean, logvar)
loss = reconstr_loss + balancing_coeff * kl
ms_ssim = tf.reduce_mean(ms_ssim)
loss = reconstr_loss + g_balancing_coeff * kl
mean = tf.reduce_mean(mean)
logvar = tf.reduce_mean(logvar)
# mesh_pred = uv2mesh(tf.tile(tf.math.argmax(pred, axis=-1, output_type=tf.dtypes.int32)[:,:,:,tf.newaxis], [1,1,1,3]))[:,:,0]
# mesh_orig = tf.one_hot(batch['mesh_curvature'] + tf.cast(batch['mesh_mask'], tf.int32), 7)
# ce_mesh_loss = scce(mesh_orig, mesh_pred)
mean_iou = get_mean_iou(tf.math.argmax(batch['uv_curvature'], axis=-1), tf.math.argmax(pred, axis=-1))
mean_iou = get_mean_iou(batch['uv_curvature'], tf.math.argmax(pred, axis=-1))
dice = dice_dense(pred, uv_curvature)
gradients = tape.gradient(loss, model.trainable_variables)
optimizer.apply_gradients(zip(gradients, model.trainable_variables))
return { 'train/loss': loss, 'train/ce_uv_loss': ce_uv_loss, 'train/ssim': ms_ssim, 'train/mean_iou': mean_iou, 'train/dice': dice, #'ce_mesh_loss': ce_mesh_loss
'train/reconstr_loss': reconstr_loss,
'train/mean': mean, 'train/logvar': logvar, 'train/kl_loss': kl, 'train/reconst_loss_norm': reconstr_loss / (2 * (gamma ** 2)), 'train/var': np.e ** logvar,
'train/reg_coeff': reg_coeff}
return { 'train/loss': loss, 'train/ce_uv_loss': ce_uv_loss, 'train/mean_iou': mean_iou, 'train/dice': dice,
'train/reconstr_loss': reconstr_loss, 'train/ce_mesh_loss': ce_mesh_loss,
'train/mean': mean, 'train/logvar': logvar, 'train/kl_loss': kl,'train/var': np.e ** logvar,
}
@tf.function
def valid_step(batch):
uv_curvature = tf.one_hot(batch['uv_curvature'], 7)
pred, mean, logvar = model([batch['uv_static'], batch['uv_body_posed'], batch['uv_curvature'], batch['uv_mask']])
pred, mean, logvar, z = model([batch['uv_static'], batch['uv_body_posed'], uv_curvature, batch['uv_mask']])
ce_uv_loss = scce(batch['uv_curvature'], pred)
ms_ssim = tf.reduce_mean(tf.image.ssim(pred, uv_curvature, max_val=1))
ce_uv_loss = scce(tf.math.argmax(batch['uv_curvature'], axis=-1), pred)
loss = ce_uv_loss
mean_iou = get_mean_iou(batch['uv_curvature'], tf.math.argmax(pred, axis=-1))
dice = dice_dense(pred, uv_curvature)
mean_iou = get_mean_iou(tf.math.argmax(batch['uv_curvature'], axis=-1), tf.math.argmax(pred, axis=-1))
dice = dice_dense(pred, batch['uv_curvature'])
reconstr_loss = tf.reduce_mean(ce_uv_loss)
reconstr_loss = ce_uv_loss
# reconstr_loss = 1 - dice
reconstr_loss = tf.reduce_mean(reconstr_loss)
kl = kl_loss(mean, logvar)
loss = reconstr_loss + balancing_coeff * kl
ms_ssim = tf.reduce_mean(ms_ssim)
loss = reconstr_loss + g_balancing_coeff * kl
mean = tf.reduce_mean(mean)
logvar = tf.reduce_mean(logvar)
return { 'valid/loss': loss, 'valid/ce_uv_loss': ce_uv_loss, 'valid/ssim': ms_ssim, 'valid/mean_iou': mean_iou, 'valid/dice': dice,
'valid/ms_ssim': ms_ssim, 'valid/reconstr_loss': reconstr_loss,
mesh_pred = uv2mesh(pred) * batch['mesh_mask'][:,:,tf.newaxis]
mesh_orig = tf.cast(uv2mesh(tf.math.argmax(batch['uv_curvature'], axis=-1, output_type=tf.int32)), tf.float32) * batch['mesh_mask']
ce_mesh_loss = scce(mesh_orig, mesh_pred)
return { 'valid/loss': loss, 'valid/ce_uv_loss': ce_uv_loss, 'valid/mean_iou': mean_iou, 'valid/dice': dice,
'valid/reconstr_loss': reconstr_loss, 'valid/ce_mesh_loss': ce_mesh_loss,
'valid/mean': mean, 'valid/logvar': logvar, 'valid/kl_loss': kl, 'valid/var': np.e ** logvar }
def plot_everything(batch: dict, type: str):
uv_curvature = tf.one_hot(batch['uv_curvature'], 7)
pred, mean, logvar, z = model([batch['uv_static'], batch['uv_body_posed'], uv_curvature, batch['uv_mask']])
pred, mean, logvar = model([batch['uv_static'], batch['uv_body_posed'], batch['uv_curvature'], batch['uv_mask']])
pred = np.argmax(pred.numpy(), axis=-1)
mesh_pred = uv2mesh(pred)
mesh_orig = batch['mesh_curvature']
mesh_orig = uv2mesh(tf.math.argmax(batch['uv_curvature'], axis=-1)) # batch['mesh_curvature']
mesh_base = batch['mesh_posed']
orig_img = batch['uv_curvature']
pred_img = pred
img = tf.concat((orig_img, pred_img), axis=2)
img = tf.concat((tf.math.argmax(orig_img, axis=-1), pred_img), axis=2)
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]
imgs = [wandb.Image(img[i].numpy().astype(np.float32) / 6.0) for i in range(4)]
color_img = [wandb.Image(color_img[i]) for i in range(4)]
F = np.load("custom_utils/smpl_faces.npy")
mask = batch['mesh_mask'].numpy().astype(bool)
_, faces = maskFacesBatch(np.zeros((4, 14475, 3)), F, mask)
gt_curv = [mesh_orig[i].numpy()[mask[i]] + 1 for i in range(pred.shape[0])]
gt_curv = [mesh_orig[i].numpy()[mask[i]] for i in range(pred.shape[0])]
pred_curv = [mesh_pred[i].numpy()[mask[i]] for i in range(pred.shape[0])]
mesh = [mesh_base[i].numpy()[mask[i]] for i in range(pred.shape[0])]
@@ -242,14 +244,9 @@ def plot_everything(batch: dict, type: str):
mean_hist = wandb.Histogram(sequence=mean.numpy().mean(axis=0), num_bins=model.latent_dim)
logvar_hist = wandb.Histogram(sequence=logvar.numpy().mean(axis=0), num_bins=model.latent_dim)
return { **figs, **{ type + '/images': imgs, type + '/mean_hist': mean_hist, type + '/logvar_hist': logvar_hist } }
return { **figs, **{ type + '/images': imgs, type + '/images_color': color_img, type + '/mean_hist': mean_hist, type + '/logvar_hist': logvar_hist } }
def load_model(model, checkpoint):
ckpt = tf.train.Checkpoint(model=model)
manager = tf.train.CheckpointManager(ckpt, checkpoint, max_to_keep=1)
ckpt.restore(manager.latest_checkpoint)
def sample(folder):
load_model(model,folder)
@@ -335,101 +332,80 @@ def sample(folder):
if __name__ == '__main__':
init_wandb()
allow_memory_growth()
parser = argparse.ArgumentParser(description='')
parser.add_argument('--name', type=str)
args = vars(parser.parse_args())
batch_size = 4
smpl = SMPL()
skirt_modifier = '_skirt' if config['is_skirt'] else ''
scce = tf.keras.losses.SparseCategoricalCrossentropy()
factory = DatasetFactory()
signature_dynamic = { 'id': (),
'pose_shape': (72 + 11,),
# 'uv_posed': (3, 512, 256,),
'uv_body_posed': (3, 512, 256,),
'mesh_body_posed': (14475, 3,),
'mesh_posed': (14475, 3,),
# 'mesh_unposed': (14475, 3,),
# 'uv_unposed': (3, 512, 256,),
'uv_curvature': (512, 256),
'mesh_curvature': (14475)
}
signature_static = { 'uv_static': (3, 512, 256,),
# 'mesh_static': (14475, 3,),
'mesh_mask': (14475,),
'uv_mask': (512, 256,),
# 'uv_shaped_body': (3, 512, 256,),
}
dataset_train = factory.get_dataset(folder='/home/workspace/local-data/train_100', batch_size=batch_size, signature=signature_dynamic, use_filled=False, resolutions=[512])
static_dataset_train = StaticDataset(folder='/home/workspace/local-data/train_100', signature=signature_static, use_filled=False, resolutions=[512])
dataset_valid = factory.get_dataset(folder='/home/workspace/local-data/jumpsuit_20/valid', batch_size=batch_size, signature=signature_dynamic)
static_dataset_valid = StaticDataset(folder='/home/workspace/local-data/jumpsuit_20/valid', signature=signature_static)
dataset_train = factory.get_dataset(folder=config['train_dir'],
batch_size=config['batch_size'],
signature=config['signature_dynamic'],
resolutions=[config['resolution']],
in_memory=config['dataset_in_memory'],
use_one_hot=False,
use_no_orient=True,
frames_file=config['frames_file'] if 'frames_file' in config.keys() else None)
static_dataset_train = StaticDataset(folder=config['train_dir'],
signature=config['signature_static'],
resolutions=[config['resolution']],
in_memory=True)
dataset_valid = factory.get_dataset(folder=config['valid_dir'],
batch_size=config['batch_size'],
signature=config['signature_dynamic'],
resolutions=[config['resolution']],
in_memory=config['dataset_in_memory'],
use_one_hot=False,
use_no_orient=True)
static_dataset_valid = StaticDataset(folder=config['valid_dir'],
signature=config['signature_static'],
resolutions=[config['resolution']],
in_memory=True)
model = CVAE(latent_dim=128, static_model='checkpoints/ae_static_5',
body_model='checpoints/ae_body_8',)
model = CVAE(config)
# lr_schedule = tf.keras.optimizers.schedules.ExponentialDecay(0.0001, decay_steps=30000, decay_rate=0.1, staircase=False)
optimizer = tf.optimizers.Adam(learning_rate=0.0001)
balancing_coeff = 0.1
reg_coeff = 1
optimizer = tf.optimizers.Adam(learning_rate=config['lr']) #0.0001
g_balancing_coeff = config['starting_balancing_coeff']
folder = 'models/ae_logs/'
valid_iterator = iter(dataset_valid)
gamma = 1
balancing_activated_step = 0
# sample('checkpoints/cvae_curv_2')
ckpt = tf.train.Checkpoint(model=model)
manager = tf.train.CheckpointManager(ckpt, 'checkpoints/' + name, max_to_keep=20)
manager = tf.train.CheckpointManager(ckpt, 'checkpoints/' + config['name'], max_to_keep=20)
if config['pretrained_model'] != '':
load_model(model, config['pretrained_model'], iteration=config['pretrained_model_iteration'])
step = 0
for batch in dataset_train:
batch = static_dataset_train.expand_batch(batch_to_dict(batch, signature_dynamic))
batch = static_dataset_train.expand_batch(batch_to_dict(batch, config['signature_dynamic']))
train_loss = train_step(batch)
# data_valid = valid_iterator.get_next()
# data_valid = static_dataset_valid.expand_batch(batch_to_dict(data_valid, signature_dynamic))
# valid_loss = valid_step(data_valid)
valid_loss = {}
data_valid = valid_iterator.get_next()
data_valid = static_dataset_valid.expand_batch(batch_to_dict(data_valid, config['signature_dynamic']))
valid_loss = valid_step(data_valid)
to_log = { **train_loss, **valid_loss, **{ 'current_step': step} }
if step % 2500 == 0:
if step % 5000 == 0 or (step < 5000 and step % 500 == 0):
train_figs = plot_everything(batch, 'train')
# valid_figs = plot_everything(data_valid, 'valid')
valid_figs = {}
valid_figs = plot_everything(data_valid, 'valid')
to_log = { **to_log, **train_figs, **valid_figs }
if step % 25000 == 0:
if step % 10000 == 0:
manager.save(checkpoint_number=step)
if step == 0:
to_log = { **to_log, **{ 'model/summary': wandb.Html(get_summary_html(model)) } }
if step > 25000:
# if train_loss['train/euclid_error'] < 0.01:
balancing_coeff = balancing_coeff + 1 / 20000
# if train_loss['train/euclid_error'] < 0.015:
# reg_coeff = reg_coeff + 100 / 15000
if step > 40000:
g_balancing_coeff = g_balancing_coeff + 1 / 20000
# if step > 15000 and balancing_coeff <= 1e-3:
# balancing_coeff = 1e-2
# if step > 20000 and balancing_coeff <= 1e-3:
# balancing_coeff = 1e-2
# if step > 25000 and balancing_coeff <= 1e-2:
# balancing_coeff = 1e-1
# if step > 30000 and balancing_coeff <= 1e-1:
# balancing_coeff = 1
# gamma = 0.99 * gamma + 0.01 * train_loss['train/reconstr_loss']
to_log = { **to_log, **{ 'train/balancing_coeff': balancing_coeff, 'train/gamma': gamma } }
to_log = { **to_log, **{ 'train/g_balancing_coeff': g_balancing_coeff } }
wandb.log(to_log, step = step)