diff --git a/configs/ae_norm_1.py b/configs/ae_norm_1.py new file mode 100644 index 0000000..0eea21c --- /dev/null +++ b/configs/ae_norm_1.py @@ -0,0 +1,73 @@ +from utils.convnext_utils import CNBlockConfig + +config = dict() + +config['gpu'] = '0' +config['name'] = 'norm_torch_2' +config['notes'] = ' ' +config['tags'] = ['torch', 'norm'] +config['script'] = 'scripts/ae_norm_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'] = False +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.0001 +config['cond_ae']['upscale_output'] = False + +config['signature'] = { 'id', + 'frame_nr', + 'uv_mask', + 'uv_normals', + 'mesh_mask', + 'mesh_normals', + } \ No newline at end of file diff --git a/data/calculate_normals.py b/data/calculate_normals.py new file mode 100644 index 0000000..a978384 --- /dev/null +++ b/data/calculate_normals.py @@ -0,0 +1,112 @@ +import os +import sys +import numpy as np +import trimesh as tm +import scipy.io as sio +import plotly.graph_objects as go +import plotly.express as px +from tqdm import tqdm +import torch +from scipy.spatial.transform import Rotation as R +import argparse + +sys.path.append(os.path.dirname(os.path.abspath(__file__)) + '/..') + +from data.cloth3d_io import readOBJ, readPC2 +from data.utils import Frame +from smpl.smpl_torch import SMPL + + +def calculate_normals(vertices, mesh_file, poses): + _, faces, _, _ = readOBJ(mesh_file) + rodr = smpl.rodrigues(torch.tensor(poses.T.reshape(-1, 1, 3), dtype=torch.float32)).numpy().reshape(vertices.shape[0], -1, 3, 3) + + normals = [] + for i in range(vertices.shape[0]): + r = R.from_matrix(rodr[i, 0, :, :]) + # assert r.as_matrix() == rodr[frame, 0, :, :] + out = r.apply(vertices[i], inverse=True) + + # create a plotly mesh plot of out and vertices [i] + # fig = go.Figure(data=[ + # go.Mesh3d( + # x=out[:, 0], y=out[:, 2], z=out[:, 1], + # # i, j and k give the vertices of triangles + # i=faces[:, 0], j=faces[:, 1], k=faces[:, 2], + # name='y', + # showscale=False + # ), + # go.Mesh3d( + # x=vertices[i][:, 0], y=vertices[i][:, 1], z=vertices[i][:, 2], + # # i, j and k give the vertices of triangles + # i=faces[:, 0], j=faces[:, 1], k=faces[:, 2], + # name='x', + # showscale=False + # ) + # ]) + # fig.show() + + mesh = tm.Trimesh(vertices=out, faces=faces, process=False, validate=False) + normals.append(mesh.vertex_normals) + return np.stack(normals) + + +def get_frames(folder): + uv_static_folder = os.path.join(folder, 'pose_shape') + frames = sorted(os.listdir(uv_static_folder)) + + frames = [frame.split('.')[0] for frame in frames] # .split('_')[0] + frames = [Frame(frame.split('_')[0], frame.split('_')[1]) for frame in frames] + return frames + + +if __name__ == '__main__': + parser = argparse.ArgumentParser() + parser.add_argument("-f", "--folder", help = "end of range", default='') + parser.add_argument("-f_obj", "--folder_object", help = "end of range", default='/') + parser.add_argument("-s", "--start", help = "start of range", default=0) + parser.add_argument("-e", "--end", help = "end of range", default=10) + parser.add_argument("-n", "--name", help = "end of range", default='lhunor') + args = parser.parse_args() + + obj_folder = args.folder_object # '/data-net/dataset/cloth3d/train' + folder = args.folder #'/data-local/127/train' + + os.makedirs(os.path.join(folder, 'mesh_normals'), exist_ok=True) + frames = get_frames(folder) + smpl = SMPL('cpu', 'smpl') + + ids = {frame.id for frame in frames} + ids = sorted(list(ids))[int(args.start):int(args.end)] + + for id in tqdm(ids): + # find obj files in the folder + garment_obj_folder = os.path.join(obj_folder, id[:5]) + garments = [file.split('.')[0] for file in os.listdir(garment_obj_folder) if file.endswith('.obj')] + + if len(id) == 5: + garment = garments[0] + elif len(id) == 6: + garment = garments[1] + else: + raise ValueError('Invalid frame id') + + mesh_file = os.path.join(garment_obj_folder, f'{garment}.obj') + vertices =readPC2(os.path.join(garment_obj_folder, f'{garment}.pc16'), True)['V'] + poses = sio.loadmat(os.path.join(garment_obj_folder, f'info.mat'))['poses'] + normals = calculate_normals(vertices, mesh_file, poses) + + map = sio.loadmat(os.path.join(garment_obj_folder, f'{garment}_map.mat'))['map'][0] + mask = np.load(os.path.join(folder, 'mesh_mask', f'{id}.npy')) + + mesh_normals = normals[:,map,:] + mesh_normals = mesh_normals * mask[None,:, None] + + for i in range(vertices.shape[0]): + # np.savez(os.path.join(folder, 'mesh_normals', f'{id}_{i}.npz'), mesh_normals=mesh_normals) + np.savez_compressed(os.path.join(folder, 'mesh_normals', f'{id}_{i}.npz'), mesh_normals=mesh_normals[i]) + + # pass + + # print(frame.id, frame.frame_nr) + diff --git a/data/dataset.py b/data/dataset.py index f85c5ad..99aa5e8 100644 --- a/data/dataset.py +++ b/data/dataset.py @@ -175,6 +175,9 @@ class Dataset(Dataset): if 'mesh_curvature' in self.signature: mesh_curvature = np.load(os.path.join(self.folder, 'mesh_curvature', frame.id + separator + frame.frame_nr + '.npz')); mesh_curvature = mesh_curvature['mesh_curvature'] item['mesh_curvature'] = mesh_curvature.astype(np.int32) + if 'mesh_normals' in self.signature: + mesh_normals = np.load(os.path.join(self.folder, 'mesh_normals', frame.id + separator + frame.frame_nr + '.npz')); mesh_normals = mesh_normals['mesh_normals'] + item['mesh_normals'] = mesh_normals for res in self.resolutions: res_string = '' @@ -203,6 +206,10 @@ class Dataset(Dataset): uv_posed = np.load(os.path.join(self.folder, 'uv_posed_no_orient' + res_string, frame.id + separator + frame.frame_nr + '.npz')); uv_posed = uv_posed['uv_posed_no_orient'] item['uv_posed' + res_string] = uv_posed + if 'uv_normals' + res_string in self.signature: + uv_normals = np.load(os.path.join(self.folder, 'uv_normals' + res_string, frame.id + separator + frame.frame_nr + '.npz')); uv_normals = uv_normals['uv_normals'] + item['uv_normals' + res_string] = uv_normals + data = { key: (torch.from_numpy(value) if not (type(value) == str or type(value) == torch.Tensor) else value) for key, value in item.items()} diff --git a/docker/docker-compose.yml b/docker/docker-compose.yml index e19132c..ac5fd5e 100644 --- a/docker/docker-compose.yml +++ b/docker/docker-compose.yml @@ -34,6 +34,7 @@ services: - '/data-net/guest/lhunor/data:/data-net' - '/data-fast/126-data1/lhunor/data:/data-local/126' - '/data-fast/127-data1/lhunor/data:/data-local/127' + - '/data-fast/127-data2/lhunor/data:/data-local/127_2' - '/data-fast/128-data1/lhunor/data:/data-local/128' deploy: resources: diff --git a/run_parallel.py b/run_parallel.py index 834de78..da12a64 100644 --- a/run_parallel.py +++ b/run_parallel.py @@ -4,24 +4,27 @@ import os if __name__ == '__main__': - folder = '/home/workspace/data/dataset/cloth3d/train' + # folder = '/home/workspace/data/dataset/cloth3d/train' # folder = '/home/workspace/local-data/cape_processed/train/male' # folder = '/home/workspace/local-data/valid_skirt' # folder = '/home/workspace/local-data/valid' # ids = os.listdir(folder) # ids = os.listdir(folder + '/mesh_posed_no_orient')#[280000:] skirt = 0 + obj_folder = '/data-net/dataset/cloth3d/train' + folder = '/data-local/127/train' - count = int(500 * 1e3) - step = 10000 + count = 0 + step = 100 # !!!!!!! change skirt parameter in script - while count < 510 * 1e3: + while count <1200: # os.system('nohup python convert_to_uv_cape.py -f ' + folder + ' -s ' + str(count) + ' -e ' + str(count + step) + ' -n ' + 'to_uv_2_cape_train_male_' + str(count) + '_' + str(count+step) + ' > nohup/to_uv_2_cape_train_male_' + str(count) + '_' + str(count+step) + '.out' + ' 2>&1 &') # os.system('nohup python convert_to_uv.py -f ' + folder + ' -s ' + str(count) + ' -e ' + str(count + step) + ' -n ' + 'to_uv_train_unposed_onehot_' + str(count) + '_' + str(count+step) + ' > nohup/to_uv_train_unposed_onehot_' + str(count) + '_' + str(count+step) + '.out' + ' 2>&1 &') # os.system('nohup python convert_to_uv_local.py -f ' + folder + ' -s ' + str(count) + ' -e ' + str(count + step) + ' -n ' + 'to_uv_train_local_unposed_onehot_' + str(count) + '_' + str(count+step) + ' > nohup/to_uv_train_local_unposed_onehot_' + str(count) + '_' + str(count+step) + '.out' + ' 2>&1 &') - os.system('nohup python data/convert_to_uv.py -f ' + folder + ' -s ' + str(count) + ' -e ' + str(count + step) + ' -n ' + 'to_uv_train_2_' + str(count) + '_' + str(count+step) + ' > nohup/to_uv/train_2_' + str(count) + '_' + str(count+step) + '_again.out' + ' 2>&1 &') + # os.system('nohup python data/convert_to_uv.py -f ' + folder + ' -s ' + str(count) + ' -e ' + str(count + step) + ' -n ' + 'to_uv_train_2_' + str(count) + '_' + str(count+step) + ' > nohup/to_uv/train_2_' + str(count) + '_' + str(count+step) + '_again.out' + ' 2>&1 &') + os.system(f'nohup python data/calculate_normals.py -f {folder} -f_obj {obj_folder} -s {count} -e {(count+step)} -n normals_train_calc_{count}_{(count+step)} > nohup/normals/normals_train_calc_{count}_{(count+step)}.out' + ' 2>&1 &') # os.system('nohup python convert_to_uv_local_single.py -f ' + folder + ' -s ' + str(count) + ' -e ' + str(count + step) + ' -n ' + 'to_uv_train_skirt_local_unposed_onehot_3_' + str(count) + '_' + str(count+step) + ' > nohup/to_uv_train_skirt_local_unposed_onehot_3_' + str(count) + '_' + str(count+step) + '.out' + ' 2>&1 &') # os.system('nohup python convert_to_uv_local_single.py -f ' + folder + ' -s ' + str(count) + ' -e ' + str(count + step) + ' -n ' + 'to_uv_valid_skirt_local_unposed_onehot_3_' + str(count) + '_' + str(count+step) + ' > nohup/to_uv_valid_skirt_local_unposed_onehot_' + str(count) + '_' + str(count+step) + '.out' + ' 2>&1 &') # os.system('nohup python downscale.py -f ' + folder + ' -s ' + str(count) + ' -e ' + str(count + step) + ' -n ' + 'downscale_valid_posed_no_orient_' + str(count) + '_' + str(count+step) + ' > nohup/downscale_valid_posed_no_orient_' + str(count) + '_' + str(count+step) + '.out' + ' 2>&1 &') diff --git a/scripts/ae_norm_train.py b/scripts/ae_norm_train.py new file mode 100644 index 0000000..621b493 --- /dev/null +++ b/scripts/ae_norm_train.py @@ -0,0 +1,218 @@ +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) +parser.add_argument('--debug', action='store_true') +args = vars(parser.parse_args()) + +config_module = importlib.import_module(args['config']) +config = config_module.config +if args['debug']: + from configs.ae_norm_1 import config +os.environ["CUDA_DEVICE_ORDER"]="PCI_BUS_ID" +os.environ["CUDA_VISIBLE_DEVICES"] = config['gpu'] +if args['debug']: + os.environ["CUDA_LAUNCH_BLOCKING"] = '1' + +import time +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, 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_2/temp', tags=config['tags']) + artifact = wandb.Artifact('code', type='code') + artifact.add_file('scripts/ae_norm_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_normals'], batch['uv_mask']]) * 1.1 + + ms_ssim = torch.mean(_MSSSIM(pred + 1.1, batch['uv_normals'] + 1.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_normals'] + l1_loss = torch.mean(torch.sum((torch.abs(batch['uv_normals'] - pred)), axis=1)) + metric = torch.mean(torch.sqrt(torch.sum(batch['mesh_mask'][:,:,None] * (mesh_orig - mesh_pred) ** 2, axis=-1))) + + return { 'train/loss': 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_normals'], batch['uv_mask']]) * 1.1 + + mesh_pred = uv2mesh(pred) + mesh_orig = batch['mesh_normals'] + + l1_loss = torch.mean(torch.sum((torch.abs(batch['uv_normals'] - pred)), axis=1)) + ms_ssim = torch.mean(_MSSSIM(pred + 1.1, batch['uv_normals'] + 1.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/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_normals'], batch['uv_mask']]).detach() * 1.1 + + # mesh_pred = uv2mesh(pred) + # mesh_orig = batch['mesh_normals'] + + orig_img = torch.permute(batch['uv_normals'], [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.1) / 2.2) 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) } + figs = {} + + 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)) } } + + if not args['debug']: + 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, scaler=None) + ckpt_saver_dec(model.decoder, step, optimizer, scaler=None) + + step += 1 + + +class Scale(torch.nn.Module): + def __init__(self, scale_factor): + super().__init__() + self.scale_factor = scale_factor + + def forward(self, x): + return x * self.scale_factor + + +if __name__ == '__main__': + if not args['debug']: + init_wandb() + + skirt_modifier = '_skirt' if config['is_skirt'] else '' + + dataset_train = Dataset(config['train_dir'], config['signature'], device=config['device'], frames_file=config['train_frames'], use_cache=config['dataset_in_memory'], is_cape=config['is_cape']) + dataset_valid = Dataset(config['valid_dir'], config['signature'], device=config['device'], frames_file=config['valid_frames'], use_cache=config['dataset_in_memory'], is_cape=config['is_cape']) + 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.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/torch/' + config['name'] + '_enc', top_n=5) + ckpt_saver_dec = CheckpointSaver('checkpoints/iccv/torch/' + config['name'] + '_dec', top_n=5) + + run_name = config['name'] + print(f'started training: {run_name}') + + if not args['debug']: + # model = torch.compile(model) + wandb.watch(model, log='all', log_freq=10000, log_graph=True) + + train() + + +