Download data_tool/test_generation.py from vegagoto123/gha: direct link, hf CLI and curl.
- Browser
- Download file 14.8 kB
-
https://huggingface.co/vegagoto123/gha/resolve/main/data_tool/test_generation.py
- Command line
-
hf download hf://vegagoto123/gha/data_tool/test_generation.py
-
curl -L -o test_generation.py https://huggingface.co/vegagoto123/gha/resolve/main/data_tool/test_generation.py
14.8 kB
| # | |
| # Copyright (C) 2023, Inria | |
| # GRAPHDECO research group, https://team.inria.fr/graphdeco | |
| # All rights reserved. | |
| # | |
| # This software is free for non-commercial, research and evaluation use | |
| # under the terms of the LICENSE.md file. | |
| # | |
| # For inquiries contact george.drettakis@inria.fr | |
| # | |
| import os | |
| import torch | |
| import time | |
| from random import randint | |
| from utils.loss_utils import l1_loss, ssim | |
| from gaussian_renderer import render, network_gui | |
| import sys | |
| from scene import Scene, GaussianModel, eghuman_dataset, collate_fn, Eghuman | |
| from src.deform_model import Deform_Model | |
| from scene.gaussian_nograd_model import GaussianModel_nograd | |
| from scene.test_data import TestData | |
| from utils.general_utils import safe_state | |
| import uuid | |
| from tqdm import tqdm | |
| import numpy as np | |
| from utils.image_utils import psnr | |
| from argparse import ArgumentParser, Namespace | |
| from arguments import ModelParams, PipelineParams, OptimizationParams | |
| from utils.sh_utils import RGB2SH | |
| from torch.utils.data import DataLoader | |
| import torch.nn.functional as F | |
| import torchvision.models as models | |
| import torch.nn as nn | |
| import torchvision | |
| from simple_knn._C import distCUDA2 | |
| # from torch_geometric.data import Data | |
| # from torch_geometric.transforms import SamplePoints | |
| try: | |
| from torch.utils.tensorboard import SummaryWriter | |
| TENSORBOARD_FOUND = False | |
| except ImportError: | |
| TENSORBOARD_FOUND = False | |
| os.environ["CUDA_VISIBLE_DEVICES"] = "7" | |
| os.environ['CUDA_LAUNCH_BLOCKING'] = '1' | |
| def encoding_position(xyz_sample): | |
| L = 10 | |
| posison_encoding = [] | |
| for i in range(L): | |
| posison_encoding.append(torch.sin(2**i*np.pi*xyz_sample)) | |
| posison_encoding.append(torch.cos(2**i*np.pi*xyz_sample)) | |
| posison_encoding.append(torch.sin(2**L*np.pi*xyz_sample)) | |
| posison_encoding = torch.concat(posison_encoding, -1) | |
| return posison_encoding | |
| def requires_grad(model, flag=True): | |
| for p in model.parameters(): | |
| p.requires_grad = flag | |
| def gs_requires_grad(gs, flag): | |
| for i in gs: | |
| for p in i['params']: | |
| p.requires_grad = flag | |
| # gs._xyz_scale = gs._xyz_scale.detach() | |
| # gs._align_R = gs._align_R.detach() | |
| # gs._align_T = gs._align_T.detach() | |
| # gs._features_dc = gs._features_dc.detach() | |
| # gs._features_rest = gs._features_rest.detach() | |
| # gs._opacity = gs._opacity.detach() | |
| # gs._scaling = gs._scaling.detach() | |
| # gs ._rotation = gs._rotation.detach() | |
| def training(train_loader, dataset, opt, pipe, testing_iterations, saving_iterations, checkpoint_iterations, checkpoint, debug_from): | |
| DeformModel = Deform_Model(dataset.data_device).to(dataset.data_device) | |
| eghuman = Eghuman(opt, dataset.data_device, dataset.use_sh, dataset.sh_degree, dataset.checkpoint_path, dataset.deca_pretain_path, DeformModel.deformNet) | |
| data_tool = TestData(dataset.data_device) | |
| eghuman.feature_net.eval() | |
| eghuman.gs_decoder.eval() | |
| # eghuman.pose_flame.eval() | |
| eghuman.deformNet.eval() | |
| start_iter = eghuman.set_up() | |
| iter = 0 | |
| if dataset.checkpoint_path is not None: | |
| iter = start_iter + 1 | |
| for epoch in range(opt.epoch): | |
| times = [] | |
| for step ,data_train in enumerate(train_loader): | |
| gaussians = data_train[0]['gs'] | |
| scene = data_train[0]['sc'] | |
| dataset = data_train[0]['args'] | |
| data_length = data_train[0]['data_length'] | |
| first_iter = 0 | |
| tb_writer = prepare_output_and_logger(dataset) | |
| if checkpoint: | |
| (model_params, first_iter) = torch.load(checkpoint) | |
| gaussians.restore(model_params, opt) | |
| bg_color = [1, 1, 1] if dataset.white_background else [0, 0, 0] | |
| background = torch.tensor(bg_color, dtype=torch.float32, device=dataset.data_device) | |
| viewpoint_stack = None | |
| first_iter += 1 | |
| # preframe_index = [i for i in range(30, len(scene.getTrainCameras().copy()), 30)] | |
| preframe_index = [2,3,13] | |
| viewpoint_stack = scene.getTrainCameras().copy() | |
| input_img = [] | |
| input_transform = [] | |
| for frame_iter in range(len(preframe_index)): | |
| input_viewpoint = viewpoint_stack[preframe_index[frame_iter]] | |
| input_transform.append(input_viewpoint.full_proj_transform) | |
| input_img.append(input_viewpoint.original_image.to(dataset.data_device)) | |
| input_img = torch.stack(input_img, 0) | |
| flame_input = data_tool.image_crop(input_img[1, ...].permute(1, 2, 0).cpu().numpy()) | |
| for iteration in range(first_iter, opt.iterations + 1): | |
| if network_gui.conn == None: | |
| network_gui.try_connect() | |
| while network_gui.conn != None: | |
| try: | |
| net_image_bytes = None | |
| custom_cam, do_training, pipe.convert_SHs_python, pipe.compute_cov3D_python, keep_alive, scaling_modifer = network_gui.receive() | |
| if custom_cam != None: | |
| net_image = render(custom_cam, gaussians, pipe, background, scaling_modifer)["render"] | |
| net_image_bytes = memoryview((torch.clamp(net_image, min=0, max=1.0) * 255).byte().permute(1, 2, 0).contiguous().cpu().numpy()) | |
| network_gui.send(net_image_bytes, dataset.source_path) | |
| if do_training and ((iteration < int(opt.iterations)) or not keep_alive): | |
| break | |
| except Exception as e: | |
| network_gui.conn = None | |
| # init flame | |
| eghuman.opt.zero_grad() | |
| start_time = time.time() | |
| parameters = eghuman.shape_flame(flame_input.to('cuda:7')) | |
| codedict_shape = data_tool.decompose_code(parameters) | |
| # codedict_pose = eghuman.pose_flame(flame_input, opt.n_eyes, opt.n_jaw, opt.n_neck, opt.n_person) | |
| # codedict = {**codedict_shape, **codedict_pose} | |
| codedict = codedict_shape | |
| codedict['trans_params'] = eghuman.trans_params | |
| DeformModel.example_init(codedict) | |
| # Pick a person time sequeece | |
| if not viewpoint_stack: | |
| viewpoint_stack = scene.getTrainCameras().copy() | |
| gt_viewpoint = viewpoint_stack.pop(randint(0, len(viewpoint_stack)-1)) | |
| # deform gaussians | |
| verts_final, rot_delta, scale_coef, verts_flame = DeformModel.decode(codedict) | |
| end_time = time.time() | |
| execution_time = end_time - start_time | |
| times.append(execution_time) | |
| # print(f"代码段执行时间为: {execution_time} 秒") | |
| if iteration == 1: | |
| gaussians.create_from_verts(verts_flame[0]) | |
| gaussians.update_xyz_rot_scale(verts_flame[0], rot_delta[0], scale_coef[0]) | |
| else: | |
| gaussians.update_xyz_rot_scale(verts_final[0], rot_delta[0], scale_coef[0]) | |
| # decoder gs parameters | |
| point_uv, point_z = eghuman.uv_compute(gaussians.get_xyz, input_transform, input_img, dataset.data_device) | |
| z_embedding = encoding_position(point_z) | |
| feature_map = eghuman.feature_net(input_img.to('cuda:7')) | |
| point_fc2d = eghuman.uv_sample(input_img, feature_map, point_uv) | |
| gs_para = eghuman.gs_decoder(gaussians.get_xyz, point_fc2d, z_embedding) | |
| gaussians._features_dc = gs_para['f_dc'] | |
| gaussians._opacity = gs_para['opacity'] | |
| gaussians._scaling = gs_para['scaling'] | |
| gaussians._rotation = gs_para['rotation'] | |
| if dataset.use_sh: | |
| render_pkg = render(gt_viewpoint, gaussians, pipe, background) | |
| else: | |
| render_pkg = render(gt_viewpoint, gaussians, pipe, background, override_color = gaussians._features_dc) | |
| image_parameter, _, _, _ = render_pkg["render"], render_pkg["viewspace_points"], render_pkg["visibility_filter"], render_pkg["radii"] | |
| torchvision.utils.save_image(image_parameter, os.path.join('/data_160TB/2021/yangkun/gha-gaussian/train_imgs', '{0:05d}'.format(iteration) + "_rgb.png")) | |
| # Loss | |
| gt_image = (gt_viewpoint.original_image).to(dataset.data_device) | |
| torchvision.utils.save_image(gt_image, os.path.join('/data_160TB/2021/yangkun/gha-gaussian/train_imgs', '{0:05d}'.format(iteration) + "_gt.png")) | |
| # with open('/data_160TB/2021/yangkun/gha-gaussian/checkpoints/test/3_view_input/checkpoint_allviews_data_new_2loss_1104_x16/time_log.txt', 'a') as file: | |
| # file.write(f'time: {execution_time}\n') | |
| if (iteration in saving_iterations): | |
| #save | |
| print("\n[ITER {}] Saving FLAME".format(iteration)) | |
| scene.save(iteration, 'ply') | |
| if dataset.type_3d == 'obj': | |
| scene.save(iteration, dataset.type_3d) | |
| if (iteration in checkpoint_iterations): | |
| print("\n[ITER {}] Saving Checkpoint".format(iteration)) | |
| torch.save((gaussians.capture(), iteration), scene.model_path + "/chkpnt" + str(iteration) + ".pth") | |
| times_avg = sum(times) / len(times) | |
| # with open('/data_160TB/2021/yangkun/gha-gaussian/checkpoints/test/3_view_input/checkpoint_allviews_data_new_2loss_1104_x16/time_log.txt', 'a') as file: | |
| # file.write(f'time_avg: {times_avg}\n') | |
| print(times_avg) | |
| def prepare_output_and_logger(args): | |
| if not args.model_path: | |
| if os.getenv('OAR_JOB_ID'): | |
| unique_str=os.getenv('OAR_JOB_ID') | |
| else: | |
| unique_str = str(uuid.uuid4()) | |
| args.model_path = os.path.join("./output/", unique_str[0:10]) | |
| # Set up output folder | |
| print("Output folder: {}".format(args.model_path)) | |
| os.makedirs(args.model_path, exist_ok = True) | |
| with open(os.path.join(args.model_path, "cfg_args"), 'w') as cfg_log_f: | |
| cfg_log_f.write(str(Namespace(**vars(args)))) | |
| # Create Tensorboard writer | |
| tb_writer = None | |
| if TENSORBOARD_FOUND: | |
| tb_writer = SummaryWriter(args.model_path) | |
| else: | |
| print("Tensorboard not available: not logging progress") | |
| return tb_writer | |
| def training_report(tb_writer, iteration, Ll1, loss, l1_loss, elapsed, testing_iterations, scene : Scene, renderFunc, renderArgs): | |
| if tb_writer: | |
| tb_writer.add_scalar('train_loss_patches/l1_loss', Ll1.item(), iteration) | |
| tb_writer.add_scalar('train_loss_patches/total_loss', loss.item(), iteration) | |
| tb_writer.add_scalar('iter_time', elapsed, iteration) | |
| # Report test and samples of training set | |
| if iteration in testing_iterations: | |
| torch.cuda.empty_cache() | |
| validation_configs = ({'name': 'test', 'cameras' : scene.getTestCameras()}, | |
| {'name': 'train', 'cameras' : [scene.getTrainCameras()[idx % len(scene.getTrainCameras())] for idx in range(5, 30, 5)]}) | |
| for config in validation_configs: | |
| if config['cameras'] and len(config['cameras']) > 0: | |
| l1_test = 0.0 | |
| psnr_test = 0.0 | |
| for idx, viewpoint in enumerate(config['cameras']): | |
| image = torch.clamp(renderFunc(viewpoint, scene.gaussians, *renderArgs)["render"], 0.0, 1.0) | |
| gt_image = torch.clamp(viewpoint.original_image.to("cuda:7"), 0.0, 1.0) | |
| if tb_writer and (idx < 5): | |
| tb_writer.add_images(config['name'] + "_view_{}/render".format(viewpoint.image_name), image[None], global_step=iteration) | |
| if iteration == testing_iterations[0]: | |
| tb_writer.add_images(config['name'] + "_view_{}/ground_truth".format(viewpoint.image_name), gt_image[None], global_step=iteration) | |
| l1_test += l1_loss(image, gt_image).mean().double() | |
| psnr_test += psnr(image, gt_image).mean().double() | |
| psnr_test /= len(config['cameras']) | |
| l1_test /= len(config['cameras']) | |
| print("\n[ITER {}] Evaluating {}: L1 {} PSNR {}".format(iteration, config['name'], l1_test, psnr_test)) | |
| if tb_writer: | |
| tb_writer.add_scalar(config['name'] + '/loss_viewpoint - l1_loss', l1_test, iteration) | |
| tb_writer.add_scalar(config['name'] + '/loss_viewpoint - psnr', psnr_test, iteration) | |
| if tb_writer: | |
| tb_writer.add_histogram("scene/opacity_histogram", scene.gaussians.get_opacity, iteration) | |
| tb_writer.add_scalar('total_points', scene.gaussians.get_xyz.shape[0], iteration) | |
| torch.cuda.empty_cache() | |
| if __name__ == "__main__": | |
| # Set up command line argument parser | |
| parser = ArgumentParser(description="Training script parameters") | |
| lp = ModelParams(parser) | |
| op = OptimizationParams(parser) | |
| pp = PipelineParams(parser) | |
| parser.add_argument('--ip', type=str, default="127.0.0.2") | |
| parser.add_argument('--port', type=int, default=6061) | |
| parser.add_argument('--debug_from', type=int, default=-1) | |
| parser.add_argument('--detect_anomaly', action='store_true', default=False) | |
| parser.add_argument("--test_iterations", nargs="+", type=int, default=[]) | |
| parser.add_argument("--save_iterations", nargs="+", type=int, default=[1, 200, 500, 1_000, 2_000, 3_000, 4_000, 5_000, 6_000, 7_000, 8_000, 14_000, 30_000]) | |
| parser.add_argument("--quiet", action="store_true") | |
| parser.add_argument("--checkpoint_iterations", nargs="+", type=int, default=[]) | |
| parser.add_argument("--start_checkpoint", type=str, default = None) | |
| args = parser.parse_args(sys.argv[1:]) | |
| args.save_iterations.append(args.iterations) | |
| print("Optimizing " + args.model_path) | |
| # Initialize system state (RNG) | |
| safe_state(args.quiet) | |
| # Start GUI server, configure and run training | |
| network_gui.init(args.ip, args.port) | |
| torch.autograd.set_detect_anomaly(args.detect_anomaly) | |
| dataset_train = eghuman_dataset(lp.extract(args), train = True) | |
| dataloader_train = DataLoader(dataset=dataset_train, batch_size=1, shuffle=False, num_workers=0, collate_fn=collate_fn) | |
| training(dataloader_train, lp.extract(args), op.extract(args), pp.extract(args), args.test_iterations, args.save_iterations, args.checkpoint_iterations, args.start_checkpoint, args.debug_from) | |
| # All done | |
| print("\nTraining complete.") | |