update cvae_low version

This commit is contained in:
2022-09-26 12:54:03 +00:00
parent fdf36b27e7
commit 83294bc00c
3 changed files with 53 additions and 129 deletions
+22 -2
View File
@@ -1,7 +1,7 @@
from configs.config_base import config from configs.config_base import config
config['gpu'] = '3' config['gpu'] = '0'
config['name'] = 'cvae_19' config['name'] = 'cvae_19_2'
config['notes'] = '\ config['notes'] = '\
offsets over average unposed garment. remove global orientation (in posed body input and in pose_shape parameters. \ offsets over average unposed garment. remove global orientation (in posed body input and in pose_shape parameters. \
retrained body encoder with deoriented bodies \ retrained body encoder with deoriented bodies \
@@ -11,8 +11,16 @@ remove shape from unposed garment\
training on 100 garments with offsets over the average of these\ training on 100 garments with offsets over the average of these\
fixed autoencoders!!!!!!!!!\ fixed autoencoders!!!!!!!!!\
cvae only loads encoders instead AEs\ cvae only loads encoders instead AEs\
with edge and collision loss\
' '
# config['resolution'] = 32
if config['resolution'] != 512:
config['notes'] += '\
using custom enhancer for upscaling, using not filled versions\
'
config['lr'] = 0.0001 config['lr'] = 0.0001
config['starting_balancing_coeff'] = 0.0001 config['starting_balancing_coeff'] = 0.0001
@@ -31,7 +39,19 @@ config['signature_static'] = { 'uv_static': (512, 256, 3),
'uv_mask': (512, 256,), 'uv_mask': (512, 256,),
} }
if config['resolution'] != 512:
res_modifier = '_' + str(config['resolution'])
config['signature_dynamic']['uv_body_posed' + res_modifier] = (config['resolution'], config['resolution']//2, 3)
config['signature_dynamic']['uv_unposed' + res_modifier] = (config['resolution'], config['resolution']//2, 3)
config['signature_dynamic']['uv_curvature' + res_modifier] = (config['resolution'], config['resolution']//2)
config['signature_static']['uv_static' + res_modifier] = (config['resolution'], config['resolution']//2, 3)
config['signature_static']['uv_mask' + res_modifier] = (config['resolution'], config['resolution']//2)
if config['resolution'] == 512:
config['avg_garment_path'] = 'custom_data/train_100_no_shape_avg_uv.npy' config['avg_garment_path'] = 'custom_data/train_100_no_shape_avg_uv.npy'
else:
config['avg_garment_path'] = ''
config['static_model'] = 'checkpoints/ae_static_7_2_x' config['static_model'] = 'checkpoints/ae_static_7_2_x'
config['body_model'] = 'checkpoints/ae_body_9_x' config['body_model'] = 'checkpoints/ae_body_9_x'
config['curvature_model'] = 'checkpoints/ae_curv_9_x' config['curvature_model'] = 'checkpoints/ae_curv_9_x'
+5 -3
View File
@@ -87,21 +87,23 @@ def train_step(batch):
mesh_pred_shaped = mesh_pred + shape_offsets * batch['mesh_mask'][:,:,tf.newaxis] mesh_pred_shaped = mesh_pred + shape_offsets * batch['mesh_mask'][:,:,tf.newaxis]
mesh_pred_posed = smpl.run_garment(batch['pose_shape'][:, :72], batch['pose_shape'][:, 72:], mesh_pred_shaped) mesh_pred_posed = smpl.run_garment(batch['pose_shape'][:, :72], batch['pose_shape'][:, 72:], mesh_pred_shaped)
e_loss = tf.reduce_mean(edge_loss(mesh_pred, mesh_orig, batch['mesh_mask'])) e_loss = edge_loss(mesh_pred, mesh_orig, batch['mesh_mask'])
c_loss = tf.reduce_mean(collision_penalty(mesh_pred_posed, batch['mesh_body_posed'], batch['mesh_mask'])) c_loss = collision_penalty(mesh_pred_posed, batch['mesh_body_posed'], batch['mesh_mask'])
l1_loss = tf.reduce_sum(tf.reduce_sum((tf.math.abs(batch['uv_unposed'] - pred)), axis=-1) * batch['uv_mask'], axis=[1, 2]) l1_loss = tf.reduce_sum(tf.reduce_sum((tf.math.abs(batch['uv_unposed'] - pred)), axis=-1) * batch['uv_mask'], axis=[1, 2])
l2_loss = 1e3 * tf.reduce_mean(tf.reduce_sum(((batch['uv_unposed'] - pred) ** 2), axis=-1) * batch['uv_mask'], axis=[1, 2]) l2_loss = 1e3 * tf.reduce_mean(tf.reduce_sum(((batch['uv_unposed'] - pred) ** 2), axis=-1) * batch['uv_mask'], axis=[1, 2])
# ms_ssim = tf.image.ssim_multiscale(tf.transpose(pred, [0,2,3,1]) + 1, tf.transpose(batch['uv_unposed'], [0,2,3,1]) + 1, max_val=2) # ms_ssim = tf.image.ssim_multiscale(tf.transpose(pred, [0,2,3,1]) + 1, tf.transpose(batch['uv_unposed'], [0,2,3,1]) + 1, max_val=2)
ms_ssim = tf.image.ssim_multiscale(pred + 1, batch['uv_unposed'] + 1, max_val=3, power_factors=(0.5, 0.2, 0.1, 0.1, 0.1)) ms_ssim = tf.image.ssim_multiscale(pred + 1, batch['uv_unposed'] + 1, max_val=3, power_factors=(0.5, 0.2, 0.1, 0.1, 0.1))
# ms_ssim = tf.reduce_mean(tf.image.ssim_multiscale((tf.transpose(pred, [0,2,3,1]) + 1) * batch['uv_mask'][:,:,:,tf.newaxis], (tf.transpose(batch['uv_unposed'], [0,2,3,1]) + 1) * batch['uv_mask'][:,:,:,tf.newaxis], max_val=2)) # ms_ssim = tf.reduce_mean(tf.image.ssim_multiscale((tf.transpose(pred, [0,2,3,1]) + 1) * batch['uv_mask'][:,:,:,tf.newaxis], (tf.transpose(batch['uv_unposed'], [0,2,3,1]) + 1) * batch['uv_mask'][:,:,:,tf.newaxis], max_val=2))
reconstr_loss = l2_loss reconstr_loss = l2_loss + e_loss + c_loss
reconstr_loss = tf.reduce_mean(reconstr_loss) reconstr_loss = tf.reduce_mean(reconstr_loss)
kl = kl_loss(mean, logvar) kl = kl_loss(mean, logvar)
loss = reconstr_loss + balancing_coeff * kl loss = reconstr_loss + balancing_coeff * kl
ms_ssim = tf.reduce_mean(ms_ssim) ms_ssim = tf.reduce_mean(ms_ssim)
l1_loss = tf.reduce_mean(l1_loss) l1_loss = tf.reduce_mean(l1_loss)
l2_loss = tf.reduce_mean(l2_loss) l2_loss = tf.reduce_mean(l2_loss)
e_loss = tf.reduce_mean(e_loss)
c_loss = tf.reduce_mean(c_loss)
mean = tf.reduce_mean(mean) mean = tf.reduce_mean(mean)
logvar = tf.reduce_mean(logvar) logvar = tf.reduce_mean(logvar)
+25 -123
View File
@@ -1,5 +1,6 @@
import os import os
os.environ["CUDA_VISIBLE_DEVICES"] = "1" from configs.config_cvae import config
os.environ["CUDA_VISIBLE_DEVICES"] = config['gpu']
import tensorflow as tf import tensorflow as tf
gpus = tf.config.experimental.list_physical_devices('GPU') gpus = tf.config.experimental.list_physical_devices('GPU')
@@ -29,86 +30,29 @@ from tf_utils import check_tf_version, allow_memory_growth, split_gpu_for_testin
from losses import d_logistic, d_logistic_r1_reg, g_logistic_non_saturating, g_logistic_ns_pathreg, edge_loss, uv_mask_loss, bend_loss from losses import d_logistic, d_logistic_r1_reg, g_logistic_non_saturating, g_logistic_ns_pathreg, edge_loss, uv_mask_loss, bend_loss
# from losses import collision_penalty as collision_penalty # from losses import collision_penalty as collision_penalty
from losses import collision_loss as collision_penalty from losses import collision_loss as collision_penalty
from custom_utils.custom_utils import batch_to_dict, load_model from custom_utils.custom_utils import batch_to_dict, load_model, plot_3d
from dataset import DatasetFactory, StaticDataset from dataset import DatasetFactory, StaticDataset
from custom_utils.smpl import SMPL from custom_utils.smpl import SMPL
from models.cvae_model import CVAE#, CVAE128, CVAE32 from models.cvae_model import CVAE
from models.upscaler import UpscalerBasic as Upscaler from models.upscaler import UpscalerBasic as Upscaler
name='cvae_low_4_2_d32'
def init_wandb(): def init_wandb():
run = wandb.init(project='vae', name=name, run = wandb.init(project='vae', name=config['name'], notes=config['notes'])
notes='learn offsets. smaller flattened latent vectors. with 25-85k pretraining. smaller batchsize. fixed balancing of reconst and kl loss for baseline. \
new implementation for kl loss. no lr schedule. 25 jumpsuits, average reconst_loss before calculation, linearly increasing balancing, up to 1 from 0.1. \
offsets over average unposed garment. remove global orientation (in posed body input and in pose_shape parameters. \
retrained body encoder with deoriented bodies \
use mean l2 loss. small batch. l2 * 1000, balancing to 1 from 0.01\
fixed gender issue and retrained body encoder\
remove shape from unposed garment\
training on 100 garments , absolute, not offsets\
using custom enhancer for upscaling, using not filled versions\
calculating loss at full res')
artifact = wandb.Artifact('code', type='code') artifact = wandb.Artifact('code', type='code')
artifact.add_file('cvae.py') artifact.add_file('cvae_low.py')
artifact.add_file('models/cvae_model.py') artifact.add_file('models/cvae_model.py')
artifact.add_file('dataset.py')
artifact.add_file('losses.py') artifact.add_file('losses.py')
artifact.add_file('configs/config_base.py')
artifact.add_file('configs/config_cvae.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') artifact.add_file('convnext/models/convnext_tf.py')
run.log_artifact(artifact) run.log_artifact(artifact)
uv2mesh = UV2Mesh(res=256) uv2mesh = UV2Mesh(res=256)
def plot_3d(mesh_gt, mesh_pred_unposed, faces, collision, collision_faces, collision_color):
mesh_pred_unposed[:,2] += 1
collision[:,2] += 2
fig = go.Figure(data=[
go.Mesh3d(
# 8 vertices of a cube
x=mesh_gt[:,0],
y=mesh_gt[:,2],
z=mesh_gt[:,1],
# i, j and k give the vertices of triangles
i = faces[:,0],
j = faces[:,1],
k = faces[:,2]
),
go.Mesh3d(
# 8 vertices of a cube
x=mesh_pred_unposed[:,0],
y=mesh_pred_unposed[:,2],
z=mesh_pred_unposed[:,1],
# i, j and k give the vertices of triangles
i = faces[:,0],
j = faces[:,1],
k = faces[:,2],
),
go.Mesh3d(
# 8 vertices of a cube
x=collision[:,0],
y=collision[:,2],
z=collision[:,1],
# i, j and k give the vertices of triangles
i = collision_faces[:,0],
j = collision_faces[:,1],
k = collision_faces[:,2],
vertexcolor=collision_color
)
])
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],),)
)
return fig
def log_normal_pdf(sample, mean, logvar, raxis=1): def log_normal_pdf(sample, mean, logvar, raxis=1):
log2pi = tf.math.log(2. * np.pi) log2pi = tf.math.log(2. * np.pi)
@@ -131,11 +75,10 @@ def train_step(batch):
uv_curvature_low = tf.one_hot(batch['uv_curvature' + res_modifier], 7) uv_curvature_low = tf.one_hot(batch['uv_curvature' + res_modifier], 7)
pred, mean, logvar, z = model([batch['uv_unposed' + res_modifier], batch['uv_static' + res_modifier], batch['uv_body_posed' + res_modifier], uv_curvature_low, pred, mean, logvar, z = model([batch['uv_unposed' + res_modifier], batch['uv_static' + res_modifier], batch['uv_body_posed' + res_modifier], uv_curvature_low,
batch['uv_mask' + res_modifier], batch['uv_static'], batch['uv_body_posed'], uv_curvature, batch['uv_mask']], use_mask=True) batch['uv_mask' + res_modifier], batch['uv_static'], batch['uv_body_posed'], uv_curvature, batch['uv_mask']], use_mask=True)
# pred = pred * batch['uv_mask' + res_modifier][:,:,:,tf.newaxis]
pred_enhanced = enhance(upscale_enhancer, pred, batch['uv_mask' + res_modifier], training=False) pred_enhanced = enhance(upscale_enhancer, pred, batch['uv_mask' + res_modifier], training=False)
pred_full_res = tf.image.resize(pred_enhanced, size=(512, 256), method=tf.image.ResizeMethod.LANCZOS5) pred_full_res = tf.image.resize(pred_enhanced, size=(512, 256), method=tf.image.ResizeMethod.LANCZOS5)
mesh_pred = uv2mesh(pred_enhanced) mesh_pred = uv2mesh(pred_full_res)
mesh_orig = batch['mesh_unposed'] mesh_orig = batch['mesh_unposed']
shape = batch['pose_shape'][:, 72:] shape = batch['pose_shape'][:, 72:]
@@ -153,7 +96,7 @@ def train_step(batch):
ms_ssim = tf.image.ssim(pred + 1, batch['uv_unposed' + res_modifier] + 1, max_val=3) ms_ssim = tf.image.ssim(pred + 1, batch['uv_unposed' + res_modifier] + 1, max_val=3)
ms_ssim_full = tf.image.ssim(pred_full_res + 1, batch['uv_unposed'] + 1, max_val=3) ms_ssim_full = tf.image.ssim(pred_full_res + 1, batch['uv_unposed'] + 1, max_val=3)
else: else:
ms_ssim = tf.image.ssim_multiscale(pred + 1, batch['uv_unposed' + res_modifier] + 1, max_val=3, power_factors=(0.5, 0.2, 0.1, 0.1, 0.1)) ms_ssim = tf.image.ssim_multiscale(pred + 1, batch['uv_unposed' + res_modifier] + 1, max_val=3, power_factors=(0.5, 0.3, 0.1, 0.1))
reconstr_loss = l2_loss_full reconstr_loss = l2_loss_full
reconstr_loss = tf.reduce_mean(reconstr_loss) reconstr_loss = tf.reduce_mean(reconstr_loss)
@@ -167,18 +110,12 @@ def train_step(batch):
mean = tf.reduce_mean(mean) mean = tf.reduce_mean(mean)
logvar = tf.reduce_mean(logvar) logvar = tf.reduce_mean(logvar)
# mesh_orig_2 = uv2mesh(batch['uv_unposed' + res_modifier])
metric = tf.reduce_sum(tf.math.sqrt(tf.reduce_sum(batch['mesh_mask'][:,:,tf.newaxis] * (mesh_orig - mesh_pred) ** 2, axis=-1))) / tf.reduce_sum(batch['mesh_mask']) metric = tf.reduce_sum(tf.math.sqrt(tf.reduce_sum(batch['mesh_mask'][:,:,tf.newaxis] * (mesh_orig - mesh_pred) ** 2, axis=-1))) / tf.reduce_sum(batch['mesh_mask'])
# metric_2 = tf.reduce_sum(tf.math.sqrt(tf.reduce_sum(batch['mesh_mask'][:,:,tf.newaxis] * (mesh_orig_2 - mesh_pred) ** 2, axis=-1))) / tf.reduce_sum(batch['mesh_mask'])
euclid_posed = 0 # tf.reduce_sum(tf.math.sqrt(tf.reduce_sum(batch['mesh_mask'][:,:,tf.newaxis] * (mesh_skinned - batch['mesh_posed']) ** 2, axis=-1))) / tf.reduce_sum(batch['mesh_mask'])
gradients = tape.gradient(loss, model.trainable_variables) gradients = tape.gradient(loss, model.trainable_variables)
# gradients = [tf.clip_by_norm(g, 1.0) for g in gradients]
# gradients = [tf.clip_by_value(g, -1.0, 1.0) for g in gradients]
optimizer.apply_gradients(zip(gradients, model.trainable_variables)) optimizer.apply_gradients(zip(gradients, model.trainable_variables))
return { 'train/loss': loss, 'train/edge_loss': e_loss, 'train/collision_loss': c_loss, 'train/l1_loss': l1_loss, 'train/euclid_error': metric, 'train/ms_ssim': ms_ssim, return { 'train/loss': loss, 'train/edge_loss': e_loss, 'train/collision_loss': c_loss, 'train/l1_loss': l1_loss, 'train/euclid_error': metric, 'train/ms_ssim': ms_ssim,
#'train/euclid_error_reconst': metric_2,
'train/l2_loss_full_res': l2_loss_full, 'train/ms_ssim_full_res': ms_ssim_full, 'train/l2_loss_full_res': l2_loss_full, 'train/ms_ssim_full_res': ms_ssim_full,
'train/euclid_error_posed': euclid_posed, 'train/reconstr_loss': reconstr_loss, 'train/reconstr_loss': reconstr_loss,
'train/mean': mean, 'train/logvar': logvar, 'train/kl_loss': kl, 'train/var': np.e ** logvar, 'train/mean': mean, 'train/logvar': logvar, 'train/kl_loss': kl, 'train/var': np.e ** logvar,
'train/reg_coeff': reg_coeff, 'train/l2_loss': l2_loss } 'train/reg_coeff': reg_coeff, 'train/l2_loss': l2_loss }
@@ -226,8 +163,8 @@ def valid_step(batch):
def plot_everything(batch: dict, type: str): def plot_everything(batch: dict, type: str):
uv_curvature = tf.one_hot(batch['uv_curvature'], 7) uv_curvature = tf.one_hot(batch['uv_curvature'], 7)
uv_curvature_low = tf.one_hot(batch['uv_curvature' + res_modifier], 7) uv_curvature_low = tf.one_hot(batch['uv_curvature' + res_modifier], 7)
pred, mean, logvar, z = model([batch['uv_unposed' + res_modifier], batch['uv_static' + res_modifier], batch['uv_body_posed' + res_modifier], uv_curvature_low, batch['uv_static'], batch['uv_body_posed'], uv_curvature]) pred, mean, logvar, z = model([batch['uv_unposed' + res_modifier], batch['uv_static' + res_modifier], batch['uv_body_posed' + res_modifier], uv_curvature_low,
# pred = pred * batch['uv_mask' + res_modifier][:,:,:,tf.newaxis] batch['uv_mask' + res_modifier], batch['uv_static'], batch['uv_body_posed'], uv_curvature, batch['uv_mask']], use_mask=True)
pred = enhance(upscale_enhancer, pred, batch['uv_mask' + res_modifier], training=False) pred = enhance(upscale_enhancer, pred, batch['uv_mask' + res_modifier], training=False)
mesh_pred = uv2mesh(pred).numpy() mesh_pred = uv2mesh(pred).numpy()
@@ -433,64 +370,31 @@ if __name__ == '__main__':
res_modifier = '_' + str(resolution) res_modifier = '_' + str(resolution)
factory = DatasetFactory() factory = DatasetFactory()
signature_dynamic = { 'id': (),
'pose_shape': (72 + 11,),
# 'uv_posed': (512, 256, 3),
'uv_body_posed': (512, 256, 3),
'uv_body_posed' + res_modifier: (resolution, resolution//2, 3),
'mesh_body_posed': (14475, 3,),
'mesh_posed': (14475, 3,),
'mesh_unposed': (14475, 3,),
'uv_unposed': (512, 256, 3),
'uv_unposed' + res_modifier: (resolution, resolution//2, 3),
'uv_curvature': (512, 256,),
'uv_curvature' + res_modifier: (resolution, resolution//2),
}
signature_static = { 'uv_static': (512, 256, 3),
'uv_static' + res_modifier: (resolution, resolution//2, 3),
# 'mesh_static': (14475, 3,),
'mesh_mask': (14475,),
'uv_mask' + res_modifier: (resolution, resolution//2,),
'uv_mask': (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, resolution]) dataset_train = factory.get_dataset(folder=config['train_dir'], batch_size=config['batch_size'], signature=config['signature_dynamic'], use_filled=config['use_filled'], resolutions=[512, config['resolution']])
static_dataset_train = StaticDataset(folder='/home/workspace/local-data/train_100', signature=signature_static, use_filled=False, resolutions=[512, resolution]) static_dataset_train = StaticDataset(folder=config['train_dir'], signature=config['signature_static'], use_filled=config['use_filled'], resolutions=[512, config['resolution']])
dataset_valid = factory.get_dataset(folder='/home/workspace/local-data/jumpsuit_20/valid', batch_size=batch_size, signature=signature_dynamic) dataset_valid = factory.get_dataset(folder=config['valid_dir'], batch_size=config['batch_size'], signature=config['signature_dynamic'])
static_dataset_valid = StaticDataset(folder='/home/workspace/local-data/jumpsuit_20/valid', signature=signature_static) static_dataset_valid = StaticDataset(folder=config['valid_dir'], signature=config['signature_static'])
model = CVAE(config)
model = CVAE(#avg_garment_path='custom_data/train_100_no_shape_avg_uv.npy',
size=resolution,
latent_dim=128, static_model='checkpoints/ae_static_6_copy',
body_model='checkpoints/ae_body_8_copy',
curvature_model='checkpoints/ae_curvature_7_copy',
freeze_encoders=True,
encoder_res=512)
upscale_enhancer = get_upscale_enhancer('checkpoints/up_2_3', res=resolution) upscale_enhancer = get_upscale_enhancer('checkpoints/up_2_3', res=resolution)
optimizer = tf.optimizers.Adam(learning_rate=config['lr'])
# lr_schedule = tf.keras.optimizers.schedules.ExponentialDecay(0.0001, decay_steps=30000, decay_rate=0.1, staircase=False) balancing_coeff = config['starting_balancing_coeff']
optimizer = tf.optimizers.Adam(learning_rate=0.0001)
balancing_coeff = 0.0001
reg_coeff = 1 reg_coeff = 1
folder = 'models/ae_logs/'
valid_iterator = iter(dataset_valid) valid_iterator = iter(dataset_valid)
gamma = 1 gamma = 1
balancing_activated_step = 0 balancing_activated_step = 0
# avg_jumpsuit = np.load('custom_data/jumpsuit_20_avg_uv.npy')
# sample('checkpoints/cvae_13') # sample('checkpoints/cvae_13')
ckpt = tf.train.Checkpoint(model=model) ckpt = tf.train.Checkpoint(model=model)
manager = tf.train.CheckpointManager(ckpt, 'checkpoints/' + name, max_to_keep=3) manager = tf.train.CheckpointManager(ckpt, 'checkpoints/' + config['name'], max_to_keep=3)
step = 0 step = 0
for batch in dataset_train: 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) train_loss = train_step(batch)
@@ -514,8 +418,6 @@ if __name__ == '__main__':
balancing_activated_step = step balancing_activated_step = step
balancing_coeff = balancing_coeff + 1 / 15000 balancing_coeff = balancing_coeff + 1 / 15000
# 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/balancing_coeff': balancing_coeff, 'train/gamma': gamma } }
wandb.log(to_log, step = step) wandb.log(to_log, step = step)