From bb7c7f9a9491f4d2d85290d4040e672c358adb1b Mon Sep 17 00:00:00 2001 From: Justin Kerr Date: Wed, 18 Oct 2023 09:33:27 -0700 Subject: [PATCH] quality improvements, param changes, camera optimization support, misc updates --- nerfstudio/cameras/camera_optimizers.py | 13 +- nerfstudio/configs/method_configs.py | 21 +- .../datamanagers/full_images_datamanager.py | 42 ++-- nerfstudio/engine/optimizers.py | 21 ++ nerfstudio/engine/trainer.py | 41 ++-- nerfstudio/model_components/losses.py | 16 ++ nerfstudio/models/gaussian_splatting.py | 187 +++++++++++------- nerfstudio/pipelines/base_pipeline.py | 7 +- .../viewer_beta/render_state_machine.py | 2 +- 9 files changed, 228 insertions(+), 122 deletions(-) diff --git a/nerfstudio/cameras/camera_optimizers.py b/nerfstudio/cameras/camera_optimizers.py index fbf01d664..19b4b8606 100644 --- a/nerfstudio/cameras/camera_optimizers.py +++ b/nerfstudio/cameras/camera_optimizers.py @@ -45,10 +45,10 @@ class CameraOptimizerConfig(InstantiateConfig): mode: Literal["off", "SO3xR3", "SE3"] = "off" """Pose optimization strategy to use. If enabled, we recommend SO3xR3.""" - trans_l2_penalty: float = 1e-2 + trans_l2_penalty: float = 1e-4 """L2 penalty on translation parameters.""" - rot_l2_penalty: float = 1e-3 + rot_l2_penalty: float = 1e-4 """L2 penalty on rotation parameters.""" optimizer: Optional[OptimizerConfig] = field(default=None) @@ -150,9 +150,12 @@ class CameraOptimizer(nn.Module): def apply_to_camera(self, camera: Cameras) -> None: """Apply the pose correction to the raybundle""" if self.config.mode != "off": - correction_matrices = self(raybundle.camera_indices.squeeze()) # type: ignore - raybundle.origins = raybundle.origins + correction_matrices[:, :3, 3] - raybundle.directions = torch.bmm(correction_matrices[:, :3, :3], raybundle.directions[..., None]).squeeze() + assert camera.metadata is not None, "Must provide id of camera in its metadata" + assert "cam_idx" in camera.metadata, "Must provide id of camera in its metadata" + camera_idx = camera.metadata["cam_idx"] + adj = self([camera_idx]) # type: ignore + adj = torch.cat([adj, torch.Tensor([0, 0, 0, 1])[None, None].to(adj)], dim=1) + camera.camera_to_worlds = torch.bmm(camera.camera_to_worlds, adj) def get_loss_dict(self, loss_dict: dict) -> None: """Add regularization""" diff --git a/nerfstudio/configs/method_configs.py b/nerfstudio/configs/method_configs.py index 8e57546ba..3e5939eed 100644 --- a/nerfstudio/configs/method_configs.py +++ b/nerfstudio/configs/method_configs.py @@ -597,7 +597,8 @@ method_configs["neus-facto"] = TrainerConfig( viewer=ViewerConfig(num_rays_per_chunk=1 << 15), vis="viewer", ) - +from dataclasses import field +from collections import defaultdict method_configs["gaussian-splatting"] = TrainerConfig( method_name="gaussian-splatting", steps_per_eval_image=10, @@ -606,7 +607,7 @@ method_configs["gaussian-splatting"] = TrainerConfig( steps_per_eval_all_images=1000000, # set to a very large model so we don't eval with all images max_num_iterations=30000, mixed_precision=False, - gradient_accumulation_steps=1, + gradient_accumulation_steps = {'camera_opt': 100}, pipeline=VanillaPipelineConfig( datamanager=FullImageDatamanagerConfig( dataparser=ColmapDataParserConfig(load_3D_points=True), @@ -618,7 +619,7 @@ method_configs["gaussian-splatting"] = TrainerConfig( "optimizer": AdamOptimizerConfig(lr=1.6e-4, eps=1e-15), "scheduler": ExponentialDecaySchedulerConfig( lr_final=1.6e-6, - max_steps=15000, + max_steps=30000, ), }, "color": { @@ -641,17 +642,15 @@ method_configs["gaussian-splatting"] = TrainerConfig( }, "scaling": { "optimizer": AdamOptimizerConfig(lr=0.005, eps=1e-15), - "scheduler": ExponentialDecaySchedulerConfig( - lr_final=1e-3, - max_steps=15000, - ), + "scheduler": None }, "rotation": { "optimizer": AdamOptimizerConfig(lr=0.001, eps=1e-15), - "scheduler": ExponentialDecaySchedulerConfig( - lr_final=1e-4, - max_steps=15000, - ), + "scheduler": None + }, + "camera_opt": { + "optimizer": AdamOptimizerConfig(lr=1e-3, eps=1e-15), + "scheduler": ExponentialDecaySchedulerConfig(lr_final=5e-5, max_steps=30000), }, }, viewer=ViewerConfig(num_rays_per_chunk=1 << 15), diff --git a/nerfstudio/data/datamanagers/full_images_datamanager.py b/nerfstudio/data/datamanagers/full_images_datamanager.py index e170e0961..72f936ea2 100644 --- a/nerfstudio/data/datamanagers/full_images_datamanager.py +++ b/nerfstudio/data/datamanagers/full_images_datamanager.py @@ -141,22 +141,26 @@ class FullImageDatamanager(DataManager, Generic[TDataset]): 0, ] ) - newK,roi = cv2.getOptimalNewCameraMatrix(K,distortion_params,(image.shape[1],image.shape[0]),0) + newK, roi = cv2.getOptimalNewCameraMatrix(K, distortion_params, (image.shape[1], image.shape[0]), 0) image = cv2.undistort(image, K, distortion_params, None, newK) - #crop the image and update the intrinsics accordingly - x,y,w,h = roi - image = image[y:y+h,x:x+w] + # crop the image and update the intrinsics accordingly + x, y, w, h = roi + image = image[y : y + h, x : x + w] K = newK - #update the width, height + # update the width, height self.train_dataset.cameras.width[i] = w self.train_dataset.cameras.height[i] = h - + elif camera.camera_type.item() == CameraType.FISHEYE.value: distortion_params = np.array( [distortion_params[0], distortion_params[1], distortion_params[2], distortion_params[3]] ) - newK = cv2.fisheye.estimateNewCameraMatrixForUndistortRectify(K, distortion_params, (image.shape[1],image.shape[0]), np.eye(3), balance=0) - map1, map2 = cv2.fisheye.initUndistortRectifyMap(K, distortion_params, np.eye(3), newK, (image.shape[1],image.shape[0]), cv2.CV_32FC1) + newK = cv2.fisheye.estimateNewCameraMatrixForUndistortRectify( + K, distortion_params, (image.shape[1], image.shape[0]), np.eye(3), balance=0 + ) + map1, map2 = cv2.fisheye.initUndistortRectifyMap( + K, distortion_params, np.eye(3), newK, (image.shape[1], image.shape[0]), cv2.CV_32FC1 + ) # and then remap: image = cv2.remap(image, map1, map2, interpolation=cv2.INTER_LINEAR, borderMode=cv2.BORDER_CONSTANT) K = newK @@ -204,21 +208,25 @@ class FullImageDatamanager(DataManager, Generic[TDataset]): 0, ] ) - newK,roi = cv2.getOptimalNewCameraMatrix(K,distortion_params,(image.shape[1],image.shape[0]),0) + newK, roi = cv2.getOptimalNewCameraMatrix(K, distortion_params, (image.shape[1], image.shape[0]), 0) image = cv2.undistort(image, K, distortion_params, None, newK) - #crop the image and update the intrinsics accordingly - x,y,w,h = roi - image = image[y:y+h,x:x+w] + # crop the image and update the intrinsics accordingly + x, y, w, h = roi + image = image[y : y + h, x : x + w] K = newK - #update the width, height + # update the width, height self.train_dataset.cameras.width[i] = w self.train_dataset.cameras.height[i] = h elif camera.camera_type.item() == CameraType.FISHEYE.value: distortion_params = np.array( [distortion_params[0], distortion_params[1], distortion_params[2], distortion_params[3]] ) - newK = cv2.fisheye.estimateNewCameraMatrixForUndistortRectify(K, distortion_params, (image.shape[1],image.shape[0]), np.eye(3), balance=0) - map1, map2 = cv2.fisheye.initUndistortRectifyMap(K, distortion_params, np.eye(3), newK, (image.shape[1],image.shape[0]), cv2.CV_32FC1) + newK = cv2.fisheye.estimateNewCameraMatrixForUndistortRectify( + K, distortion_params, (image.shape[1], image.shape[0]), np.eye(3), balance=0 + ) + map1, map2 = cv2.fisheye.initUndistortRectifyMap( + K, distortion_params, np.eye(3), newK, (image.shape[1], image.shape[0]), cv2.CV_32FC1 + ) # and then remap: image = cv2.remap(image, map1, map2, interpolation=cv2.INTER_LINEAR, borderMode=cv2.BORDER_CONSTANT) K = newK @@ -325,10 +333,12 @@ class FullImageDatamanager(DataManager, Generic[TDataset]): data = deepcopy(self.cached_train[image_idx]) data["image"] = data["image"].to(self.device) - data['cam_idx'] = torch.tensor(image_idx).to(self.device) assert len(self.train_dataset.cameras.shape) == 1, "Assumes single batch dimension" camera = self.train_dataset.cameras[image_idx : image_idx + 1].to(self.device) + if camera.metadata is None: + camera.metadata = {} + camera.metadata["cam_idx"] = image_idx return camera, data def next_eval(self, step: int) -> Tuple[Cameras, Dict]: diff --git a/nerfstudio/engine/optimizers.py b/nerfstudio/engine/optimizers.py index 9b8d48dba..5e35808c8 100644 --- a/nerfstudio/engine/optimizers.py +++ b/nerfstudio/engine/optimizers.py @@ -135,6 +135,12 @@ class Optimizers: for _, optimizer in self.optimizers.items(): optimizer.zero_grad() + def zero_grad_some(self,param_groups: List[str]) -> None: + """Zero the gradients for the given parameter groups.""" + for param_group in param_groups: + optimizer = self.optimizers[param_group] + optimizer.zero_grad() + def optimizer_scaler_step_all(self, grad_scaler: GradScaler) -> None: """Take an optimizer step using a grad scaler. @@ -149,6 +155,21 @@ class Optimizers: if any(any(p.grad is not None for p in g["params"]) for g in optimizer.param_groups): grad_scaler.step(optimizer) + def optimizer_scaler_step_some(self, grad_scaler: GradScaler, param_groups: List[str]) -> None: + """Take an optimizer step using a grad scaler ONLY on the specified param groups. + + Args: + grad_scaler: GradScaler to use + """ + for param_group in param_groups: + optimizer = self.optimizers[param_group] + max_norm = self.config[param_group]["optimizer"].max_norm + if max_norm is not None: + grad_scaler.unscale_(optimizer) + torch.nn.utils.clip_grad_norm_(self.parameters[param_group], max_norm) + if any(any(p.grad is not None for p in g["params"]) for g in optimizer.param_groups): + grad_scaler.step(optimizer) + def optimizer_step_all(self) -> None: """Run step for all optimizers.""" for param_group, optimizer in self.optimizers.items(): diff --git a/nerfstudio/engine/trainer.py b/nerfstudio/engine/trainer.py index fe4aa85ce..a8da3f935 100644 --- a/nerfstudio/engine/trainer.py +++ b/nerfstudio/engine/trainer.py @@ -24,8 +24,8 @@ import time from dataclasses import dataclass, field from pathlib import Path from threading import Lock -from typing import Dict, List, Literal, Optional, Tuple, Type, cast - +from typing import Dict, List, Literal, Optional, Tuple, Type, cast,Union,Dict,DefaultDict +from collections import defaultdict import torch from nerfstudio.configs.experiment_config import ExperimentConfig from nerfstudio.data.datamanagers.base_datamanager import VanillaDataManager @@ -81,8 +81,8 @@ class TrainerConfig(ExperimentConfig): """Path to checkpoint file.""" log_gradients: bool = False """Optionally log gradients during training""" - gradient_accumulation_steps: int = 1 - """Number of steps to accumulate gradients over.""" + gradient_accumulation_steps: Dict = field(default_factory=lambda: {}) + """Number of steps to accumulate gradients over. Contains a mapping of {param_group:num}""" class Trainer: @@ -119,7 +119,8 @@ class Trainer: self.mixed_precision: bool = self.config.mixed_precision self.use_grad_scaler: bool = self.mixed_precision or self.config.use_grad_scaler self.training_state: Literal["training", "paused", "completed"] = "training" - self.gradient_accumulation_steps: int = self.config.gradient_accumulation_steps + self.gradient_accumulation_steps: DefaultDict = defaultdict(lambda: 1) + self.gradient_accumulation_steps.update(self.config.gradient_accumulation_steps) if self.device == "cpu": self.mixed_precision = False @@ -462,18 +463,26 @@ class Trainer: step: Current training step. """ - self.optimizers.zero_grad_all() + needs_zero = [group for group in self.optimizers.parameters.keys() if step % self.gradient_accumulation_steps[group] == 0] + self.optimizers.zero_grad_some(needs_zero) cpu_or_cuda_str: str = self.device.split(":")[0] - assert ( - self.gradient_accumulation_steps > 0 - ), f"gradient_accumulation_steps must be > 0, not {self.gradient_accumulation_steps}" - for _ in range(self.gradient_accumulation_steps): - with torch.autocast(device_type=cpu_or_cuda_str, enabled=self.mixed_precision): - _, loss_dict, metrics_dict = self.pipeline.get_train_loss_dict(step=step) - loss = functools.reduce(torch.add, loss_dict.values()) - loss /= self.gradient_accumulation_steps - self.grad_scaler.scale(loss).backward() # type: ignore - self.optimizers.optimizer_scaler_step_all(self.grad_scaler) + # assert ( + # self.gradient_accumulation_steps > 0 + # ), f"gradient_accumulation_steps must be > 0, not {self.gradient_accumulation_steps}" + # for _ in range(self.gradient_accumulation_steps): + # with torch.autocast(device_type=cpu_or_cuda_str, enabled=self.mixed_precision): + # _, loss_dict, metrics_dict = self.pipeline.get_train_loss_dict(step=step) + # loss = functools.reduce(torch.add, loss_dict.values()) + # loss /= self.gradient_accumulation_steps + # self.grad_scaler.scale(loss).backward() # type: ignore + # self.optimizers.optimizer_scaler_step_all(self.grad_scaler) + + with torch.autocast(device_type=cpu_or_cuda_str, enabled=self.mixed_precision): + _, loss_dict, metrics_dict = self.pipeline.get_train_loss_dict(step=step) + loss = functools.reduce(torch.add, loss_dict.values()) + self.grad_scaler.scale(loss).backward() # type: ignore + needs_step = [group for group in self.optimizers.parameters.keys() if step % self.gradient_accumulation_steps[group] == self.gradient_accumulation_steps[group]-1] + self.optimizers.optimizer_scaler_step_some(self.grad_scaler,needs_step) if self.config.log_gradients: total_grad = 0 diff --git a/nerfstudio/model_components/losses.py b/nerfstudio/model_components/losses.py index e90ec8e61..ff7ab1774 100644 --- a/nerfstudio/model_components/losses.py +++ b/nerfstudio/model_components/losses.py @@ -567,6 +567,22 @@ def scale_gradients_by_distance_squared( out[key], _ = cast(Tuple[Tensor, Tensor], _GradientScaler.apply(value, scaling)) return out +def scale_gauss_gradients_by_distance_squared( + gauss_outs: torch.nn.Parameter, + gauss_depths: Float[Tensor,"n_gauss 1"], + padding_eps: float = .1, + far_dist: float = 1, +) -> torch.nn.Parameter: + """ + Scale gradients by the gaussian distance to the pixel + + """ + scaling = (torch.square(gauss_depths/far_dist) + padding_eps).clamp(0, 1) + num_dims_to_add = len(gauss_outs.shape) - 1 + scaling = scaling.view(-1, *([1] * num_dims_to_add)) + out, _ = cast(Tuple[Tensor, Tensor], _GradientScaler.apply(gauss_outs, scaling)) + return out + def depth_ranking_loss(rendered_depth, gt_depth): """ diff --git a/nerfstudio/models/gaussian_splatting.py b/nerfstudio/models/gaussian_splatting.py index 9f8951042..2ce0f9d01 100644 --- a/nerfstudio/models/gaussian_splatting.py +++ b/nerfstudio/models/gaussian_splatting.py @@ -36,8 +36,10 @@ import math import numpy as np from sklearn.neighbors import NearestNeighbors import viser.transforms as vtf +from nerfstudio.model_components.losses import scale_gauss_gradients_by_distance_squared +from nerfstudio.cameras.camera_optimizers import CameraOptimizer, CameraOptimizerConfig - +from torchmetrics.image import StructuralSimilarityIndexMeasure from gsplat.rasterize import RasterizeGaussians from gsplat.project_gaussians import ProjectGaussians from gsplat.sh import SphericalHarmonics, num_sh_bases @@ -63,7 +65,7 @@ def RGB2SH(rgb): return (rgb - 0.5) / C0 -def projection_matrix(znear, zfar, fovx, fovy, **kwargs): +def projection_matrix(znear, zfar, fovx, fovy, device="cpu"): t = znear * math.tan(0.5 * fovy) b = -t r = znear * math.tan(0.5 * fovx) @@ -77,7 +79,7 @@ def projection_matrix(znear, zfar, fovx, fovy, **kwargs): [0.0, 0.0, (f + n) / (f - n), -1.0 * f * n / (f - n)], [0.0, 0.0, 1.0, 0.0], ], - **kwargs, + device=device, ) @@ -86,17 +88,17 @@ class GaussianSplattingModelConfig(ModelConfig): """Gaussian Splatting Model Config""" _target: Type = field(default_factory=lambda: GaussianSplattingModel) - warmup_length: int = 1000 + warmup_length: int = 500 """period of steps where refinement is turned off""" refine_every: int = 100 """period of steps where gaussians are culled and densified""" - resolution_schedule: int = 200 + resolution_schedule: int = 250 """training starts at 1/d resolution, every n steps this is doubled""" num_downscales: int = 2 """at the beginning, resolution is 1/2^d, where d is this number""" cull_alpha_thresh: float = 0.01 """threshold of opacity for culling gaussians""" - cull_scale_thresh: float = 0.5 + cull_scale_thresh: float = 0.1 """threshold of scale for culling gaussians""" reset_alpha_every: int = 30 """Every this many refinement steps, reset the alpha""" @@ -104,18 +106,26 @@ class GaussianSplattingModelConfig(ModelConfig): """threshold of positional gradient norm for densifying gaussians""" densify_size_thresh: float = 0.01 """below this size, gaussians are *duplicated*, otherwise split""" - sh_degree_interval: int = 500 + n_split_samples: int = 2 + """number of samples to split gaussians into""" + sh_degree_interval: int = 1000 """every n intervals turn on another sh degree""" - max_screen_size: int = 150 - """maximum screen size of a gaussian, in pixels""" + cull_screen_size: int = 150 + """if a gaussian is more than this many pixels, cull it""" + split_screen_size: int = 50 + """if a gaussian is more than this many pixels, split it""" random_init: bool = False """whether to initialize the positions uniformly randomly (not SFM points)""" + extra_points: int = 0 + """number of extra points to add to the model in addition to sfm points, randomly distributed""" ssim_lambda: float = 0.2 """weight of ssim loss""" stop_split_at: int = 25000 """stop splitting at this step""" sh_degree: int = 4 """maximum degree of spherical harmonics to use""" + camera_optimizer: CameraOptimizerConfig = CameraOptimizerConfig(mode="off") + """camera optimizer config""" class GaussianSplattingModel(Model): @@ -136,9 +146,10 @@ class GaussianSplattingModel(Model): def populate_modules(self): if self.seed_pts is not None and not self.config.random_init: - self.means = torch.nn.Parameter(self.seed_pts[0]) # (Location, Color) + extra_means = (torch.rand((self.config.extra_points, 3)) - 0.5) * 20 + self.means = torch.nn.Parameter(torch.cat([self.seed_pts[0],extra_means])) # (Location, Color) else: - self.means = torch.nn.Parameter((torch.rand((100000, 3)) - 0.5) * 2) + self.means = torch.nn.Parameter((torch.rand((500000, 3)) - 0.5) * 20) self.xys_grad_norm = None self.max_2Dsize = None distances, _ = self.k_nearest_sklearn(self.means.data, 3) @@ -146,7 +157,6 @@ class GaussianSplattingModel(Model): # find the average of the three nearest neighbors for each point and use that as the scale avg_dist = distances.mean(dim=-1, keepdim=True) self.scales = torch.nn.Parameter(torch.log(avg_dist.repeat(1, 3))) - self.quats = torch.nn.Parameter(random_quat_tensor(self.num_points)) dim_sh = num_sh_bases(self.config.sh_degree) @@ -155,6 +165,10 @@ class GaussianSplattingModel(Model): shs = torch.zeros((fused_color.shape[0], 3, dim_sh)).float().cuda() shs[:, :3, 0] = fused_color shs[:, 3:, 1:] = 0.0 + #concat on extra_points amount of random ones at the end + extra_shs = torch.rand((self.config.extra_points, 3, dim_sh)).float().cuda() + extra_shs[:,:,1:] = 0.0#zero out the higher freq + shs = torch.cat([shs, extra_shs]) self.colors = torch.nn.Parameter(shs[:, :, 0:1]) self.shs_rest = torch.nn.Parameter(shs[:, :, 1:]) else: @@ -164,7 +178,6 @@ class GaussianSplattingModel(Model): self.opacities = torch.nn.Parameter(torch.logit(0.1 * torch.ones(self.num_points, 1))) # metrics self.psnr = PeakSignalNoiseRatio(data_range=1.0) - from torchmetrics.image import StructuralSimilarityIndexMeasure self.ssim = StructuralSimilarityIndexMeasure() self.lpips = LearnedPerceptualImagePatchSimilarity(normalize=True) @@ -172,6 +185,10 @@ class GaussianSplattingModel(Model): self.crop_box: Optional[OrientedBox] = None self.back_color = torch.zeros(3) + self.camera_optimizer: CameraOptimizer = self.config.camera_optimizer.setup( + num_cameras=self.num_train_data, device="cpu" + ) + @property def get_colors(self): color = self.colors @@ -213,7 +230,7 @@ class GaussianSplattingModel(Model): def remove_from_optim(self, optimizer, deleted_mask, new_params): """removes the deleted_mask from the optimizer provided""" assert len(new_params) == 1 - assert isinstance(optimizer, torch.optim.Adam), "Only works with Adam" + # assert isinstance(optimizer, torch.optim.Adam), "Only works with Adam" param = optimizer.param_groups[0]["params"][0] param_state = optimizer.state[param] @@ -266,7 +283,7 @@ class GaussianSplattingModel(Model): # update the max screen size if self.max_2Dsize is None: self.max_2Dsize = torch.zeros_like(self.radii) - newradii = self.radii[visible_mask] + newradii = self.radii.detach()[visible_mask] self.max_2Dsize[visible_mask] = torch.maximum(self.max_2Dsize[visible_mask], newradii) def set_crop(self, crop_box: OrientedBox): @@ -277,7 +294,7 @@ class GaussianSplattingModel(Model): self.back_color = back_color def refinement_after(self, optimizers: Optimizers, step): - if self.step > self.config.warmup_length: + if self.step >= self.config.warmup_length: with torch.no_grad(): if self.step < self.config.stop_split_at: # then we densify @@ -286,8 +303,9 @@ class GaussianSplattingModel(Model): ) high_grads = (avg_grad_norm > self.config.densify_grad_thresh).squeeze() splits = (self.scales.exp().max(dim=-1).values > self.config.densify_size_thresh).squeeze() + splits |= (self.max_2Dsize > self.config.split_screen_size).squeeze() splits &= high_grads - nsamps = 2 + nsamps = self.config.n_split_samples ( split_means, split_colors, @@ -314,12 +332,12 @@ class GaussianSplattingModel(Model): dim=0, ) split_idcs = torch.where(splits)[0] - param_groups = self.get_param_groups() + param_groups = self.get_gaussian_param_groups() for group, param in param_groups.items(): self.dup_in_optim(optimizers.optimizers[group], split_idcs, param, n=nsamps) dup_idcs = torch.where(dups)[0] - param_groups = self.get_param_groups() + param_groups = self.get_gaussian_param_groups() for group, param in param_groups.items(): self.dup_in_optim(optimizers.optimizers[group], dup_idcs, param, 1) @@ -328,11 +346,11 @@ class GaussianSplattingModel(Model): if self.step % reset_interval > self.num_train_data: # then cull deleted_mask = self.cull_gaussians() - param_groups = self.get_param_groups() + param_groups = self.get_gaussian_param_groups() for group, param in param_groups.items(): self.remove_from_optim(optimizers.optimizers[group], deleted_mask, param) - if self.step // self.config.refine_every % self.config.reset_alpha_every == 0: + if (self.step - 1) // self.config.refine_every % self.config.reset_alpha_every == 0: reset_value = 0.01 self.opacities.data = torch.full_like( self.opacities.data, torch.logit(torch.tensor(reset_value)).item() @@ -358,8 +376,9 @@ class GaussianSplattingModel(Model): # cull huge ones toobigs = (torch.exp(self.scales).max(dim=-1).values > self.config.cull_scale_thresh).squeeze() culls = culls | toobigs - # cull big screen space - culls = culls | (self.max_2Dsize > self.config.max_screen_size).squeeze() + if self.step < self.config.stop_split_at: + # cull big screen space + culls = culls | (self.max_2Dsize > self.config.cull_screen_size).squeeze() self.means = Parameter(self.means[~culls].detach()) self.scales = Parameter(self.scales[~culls].detach()) self.quats = Parameter(self.quats[~culls].detach()) @@ -392,8 +411,9 @@ class GaussianSplattingModel(Model): # step 3, sample new opacities new_opacities = self.opacities[split_mask].repeat(samps, 1) # step 4, sample new scales - new_scales = torch.log(torch.exp(self.scales[split_mask]) / 1.6).repeat(samps, 1) - self.scales[split_mask] = torch.log(torch.exp(self.scales[split_mask]) / 1.6) + size_fac = 1.6 + new_scales = torch.log(torch.exp(self.scales[split_mask]) / size_fac).repeat(samps, 1) + self.scales[split_mask] = torch.log(torch.exp(self.scales[split_mask]) / size_fac) # step 5, sample new quats new_quats = self.quats[split_mask].repeat(samps, 1) return new_means, new_colors, new_shs, new_opacities, new_scales, new_quats @@ -441,12 +461,7 @@ class GaussianSplattingModel(Model): def step_cb(self, step): self.step = step - def get_param_groups(self) -> Dict[str, List[Parameter]]: - """Obtain the parameter groups for the optimizers - - Returns: - Mapping of different parameter groups - """ + def get_gaussian_param_groups(self) -> Dict[str, List[Parameter]]: return { "xyz": [self.means], "color": [self.colors], @@ -456,6 +471,17 @@ class GaussianSplattingModel(Model): "rotation": [self.quats], } + def get_param_groups(self) -> Dict[str, List[Parameter]]: + """Obtain the parameter groups for the optimizers + + Returns: + Mapping of different parameter groups + """ + gps = self.get_gaussian_param_groups() + # add camera optimizer param groups + self.camera_optimizer.get_param_groups(gps) + return gps + def _get_downscale_factor(self): return 2 ** max((self.config.num_downscales - self.step // self.config.resolution_schedule), 0) @@ -475,6 +501,9 @@ class GaussianSplattingModel(Model): assert camera.shape[0] == 1, "Only one camera at a time" # dont mutate the input camera = deepcopy(camera) + if self.training: + #currently relies on the branch vickie/camera-grads + self.camera_optimizer.apply_to_camera(camera) if self.training: d = self._get_downscale_factor() camera.rescale_output_resolution(1 / d) @@ -483,18 +512,19 @@ class GaussianSplattingModel(Model): if crop_ids.sum() == 0: return {"rgb": torch.full((camera.height.item(), camera.width.item(), 3), 0.5, device=self.device)} else: - crop_ids = torch.ones_like(self.means[:, 0], dtype=torch.bool) + crop_ids = None # shift the camera to center of scene looking at center - R = camera.camera_to_worlds[..., :3, :3] # 1 x 3 x 3 - T = camera.camera_to_worlds[..., :3, 3:4] # 1 x 3 x 1 - R = vtf.SO3.from_matrix(R.cpu().squeeze().numpy()) - R = R @ vtf.SO3.from_x_radians(np.pi) - R = torch.from_numpy(R.as_matrix()[None, ...]).to(self.device, torch.float32) - viewmat = torch.cat([R, T], dim=2) - # add a row of zeros and a 1 to the bottom of the viewmat - viewmat = torch.cat([viewmat, torch.tensor([[[0, 0, 0, 1]]], device=self.device)], dim=1) - # invert it - viewmat = torch.inverse(viewmat) + R = camera.camera_to_worlds[0, :3, :3] # 3 x 3 + T = camera.camera_to_worlds[0, :3, 3:4] # 3 x 1 + # flip the z axis to align with gsplat conventions + R_edit = torch.tensor(vtf.SO3.from_x_radians(np.pi).as_matrix(), device=R.device, dtype=R.dtype) + R = R @ R_edit + # analytic matrix inverse to get world2camera matrix + R_inv = R.T + T_inv = -R_inv @ T + viewmat = torch.eye(4, device=R.device, dtype=R.dtype) + viewmat[:3, :3] = R_inv + viewmat[:3, 3:4] = T_inv # calculate the FOV of the camera given fx and fy, width and height cx = camera.cx.item() cy = camera.cy.item() @@ -502,7 +532,7 @@ class GaussianSplattingModel(Model): fovy = 2 * math.atan(camera.height / (2 * camera.fy)) W, H = camera.width.item(), camera.height.item() self.last_size = (H, W) - projmat = projection_matrix(0.001, 1000, fovx, fovy).to(self.device) + projmat = projection_matrix(0.001, 1000, fovx, fovy, device=self.device) BLOCK_X, BLOCK_Y = 16, 16 tile_bounds = ( (W + BLOCK_X - 1) // BLOCK_X, @@ -514,14 +544,24 @@ class GaussianSplattingModel(Model): else: background = self.back_color - opacities_crop = self.opacities[crop_ids] - means_crop = self.means[crop_ids] - colors_crop = self.get_colors[crop_ids] + + if crop_ids is not None: + opacities_crop = self.opacities[crop_ids] + means_crop = self.means[crop_ids] + colors_crop = self.get_colors[crop_ids] + scales_crop = self.scales[crop_ids] + quats_crop = self.quats[crop_ids] + else: + opacities_crop = self.opacities + means_crop = self.means + colors_crop = self.get_colors + scales_crop = self.scales + quats_crop = self.quats self.xys, depths, self.radii, conics, num_tiles_hit, cov3d = ProjectGaussians.apply( - self.means[crop_ids], - torch.exp(self.scales[crop_ids]), + means_crop, + torch.exp(scales_crop), 1, - self.quats[crop_ids], + quats_crop / quats_crop.norm(dim=-1, keepdim=True), viewmat.squeeze()[:3, :], projmat.squeeze() @ viewmat.squeeze(), camera.fx.item(), @@ -532,45 +572,50 @@ class GaussianSplattingModel(Model): W, tile_bounds, ) + # if self.training: + # # experimental gradient scaling for floater removal + # depths_de = depths.detach() + # opacities_crop = scale_gauss_gradients_by_distance_squared(opacities_crop,depths_de,far_dist=.5,padding_eps=.05) # Important to allow xys grads to populate properly if self.training: self.xys.retain_grad() - rend_mask = self.radii > 0 if self.config.sh_degree > 0: - viewdirs = means_crop[rend_mask].detach() - camera.camera_to_worlds[..., :3, 3] # (N, 3) + viewdirs = means_crop.detach() - camera.camera_to_worlds.detach()[..., :3, 3] # (N, 3) viewdirs = viewdirs / viewdirs.norm(dim=-1, keepdim=True) n = min(self.step // self.config.sh_degree_interval, self.config.sh_degree) n_coeffs = num_sh_bases(n) - coeffs = colors_crop.permute(0, 2, 1)[rend_mask, :n_coeffs, :] + coeffs = colors_crop.permute(0, 2, 1)[:, :n_coeffs, :] rgbs = SphericalHarmonics.apply(n, viewdirs, coeffs) rgbs = torch.clamp(rgbs + 0.5, 0.0, 1.0) else: - rgbs = self.get_colors.squeeze()[rend_mask] # (N, 3) + rgbs = self.get_colors.squeeze() # (N, 3) rgbs = torch.sigmoid(rgbs) rgb = RasterizeGaussians.apply( - self.xys[rend_mask], - depths[rend_mask], - self.radii[rend_mask], - conics[rend_mask], - num_tiles_hit[rend_mask], + self.xys, + depths, + self.radii, + conics, + num_tiles_hit, rgbs, - torch.sigmoid(opacities_crop[rend_mask]), + torch.sigmoid(opacities_crop), H, W, background, ) - depth_im = RasterizeGaussians.apply( - self.xys[rend_mask], - depths[rend_mask], - self.radii[rend_mask], - conics[rend_mask], - num_tiles_hit[rend_mask], - depths[rend_mask, None].repeat(1, 3), - torch.sigmoid(opacities_crop[rend_mask]), - H, - W, - torch.ones(3, device=self.device) * 10, - )[..., 0:1] + depth_im = None + if not self.training: + depth_im = RasterizeGaussians.apply( + self.xys, + depths, + self.radii, + conics, + num_tiles_hit, + depths[:, None].repeat(1, 3), + torch.sigmoid(opacities_crop), + H, + W, + torch.ones(3, device=self.device) * 10, + )[..., 0:1] return {"rgb": rgb, "depth": depth_im} def get_metrics_dict(self, outputs, batch) -> Dict[str, torch.Tensor]: diff --git a/nerfstudio/pipelines/base_pipeline.py b/nerfstudio/pipelines/base_pipeline.py index 9cf86dc86..493954721 100644 --- a/nerfstudio/pipelines/base_pipeline.py +++ b/nerfstudio/pipelines/base_pipeline.py @@ -261,10 +261,13 @@ class VanillaPipeline(Pipeline): ) # TODO make cleaner seed_pts = None - if hasattr(self.datamanager, "train_dataparser_outputs") and 'points3D_xyz' in self.datamanager.train_dataparser_outputs.metadata: + if ( + hasattr(self.datamanager, "train_dataparser_outputs") + and "points3D_xyz" in self.datamanager.train_dataparser_outputs.metadata + ): pts = self.datamanager.train_dataparser_outputs.metadata["points3D_xyz"] pts_rgb = self.datamanager.train_dataparser_outputs.metadata["points3D_rgb"] - seed_pts = (pts,pts_rgb) + seed_pts = (pts, pts_rgb) self.datamanager.to(device) # TODO(ethan): get rid of scene_bounds from the model assert self.datamanager.train_dataset is not None, "Missing input dataset" diff --git a/nerfstudio/viewer_beta/render_state_machine.py b/nerfstudio/viewer_beta/render_state_machine.py index a6b06570b..ee4f14c27 100644 --- a/nerfstudio/viewer_beta/render_state_machine.py +++ b/nerfstudio/viewer_beta/render_state_machine.py @@ -208,7 +208,7 @@ class RenderStateMachine(threading.Thread): except viewer_utils.IOChangeException: # if we got interrupted, don't send the output to the viewer continue - self._send_output_to_viewer(outputs,static_render = (action.action in ["static",'step'])) + self._send_output_to_viewer(outputs, static_render=(action.action in ["static", "step"])) def check_interrupt(self, frame, event, arg): """Raises interrupt when flag has been set and not already on lowest resolution.