| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
|
|
| import torch |
| import numpy as np |
| from utils.general_utils import inverse_sigmoid, get_expon_lr_func, build_rotation |
| from torch import nn |
| import os |
| from utils.system_utils import mkdir_p |
| from plyfile import PlyData, PlyElement |
| from utils.sh_utils import RGB2SH |
| from simple_knn._C import distCUDA2 |
| from utils.graphics_utils import BasicPointCloud |
| from utils.general_utils import strip_symmetric, build_scaling_rotation |
|
|
| class GaussianModel: |
|
|
| def setup_functions(self): |
| def build_covariance_from_scaling_rotation(scaling, scaling_modifier, rotation): |
| L = build_scaling_rotation(scaling_modifier * scaling, rotation) |
| actual_covariance = L @ L.transpose(1, 2) |
| symm = strip_symmetric(actual_covariance) |
| return symm |
| |
| self.scaling_activation = torch.exp |
| self.scaling_inverse_activation = torch.log |
|
|
| self.covariance_activation = build_covariance_from_scaling_rotation |
|
|
| self.opacity_activation = torch.sigmoid |
| self.inverse_opacity_activation = inverse_sigmoid |
|
|
| self.rotation_activation = torch.nn.functional.normalize |
|
|
|
|
| def __init__(self, sh_degree : int): |
| self.active_sh_degree = 0 |
| self.max_sh_degree = sh_degree |
| self._xyz = torch.empty(0) |
| self._features_dc = torch.empty(0) |
| self._features_rest = torch.empty(0) |
| self._scaling = torch.empty(0) |
| self._rotation = torch.empty(0) |
| self._opacity = torch.empty(0) |
| self.max_radii2D = torch.empty(0) |
| self.xyz_gradient_accum = torch.empty(0) |
| self.denom = torch.empty(0) |
| self.optimizer = None |
| self.percent_dense = 0 |
| self.spatial_lr_scale = 0 |
| self.setup_functions() |
|
|
| def capture(self): |
| return ( |
| self.active_sh_degree, |
| self._xyz, |
| self._features_dc, |
| self._features_rest, |
| self._scaling, |
| self._rotation, |
| self._opacity, |
| self.max_radii2D, |
| self.xyz_gradient_accum, |
| self.denom, |
| self.optimizer.state_dict(), |
| self.spatial_lr_scale, |
| ) |
| |
| def restore(self, model_args, training_args): |
| (self.active_sh_degree, |
| self._xyz, |
| self._features_dc, |
| self._features_rest, |
| self._scaling, |
| self._rotation, |
| self._opacity, |
| self.max_radii2D, |
| xyz_gradient_accum, |
| denom, |
| opt_dict, |
| self.spatial_lr_scale) = model_args |
| self.training_setup(training_args) |
| self.xyz_gradient_accum = xyz_gradient_accum |
| self.denom = denom |
| self.optimizer.load_state_dict(opt_dict) |
|
|
| @property |
| def get_scaling(self): |
| return self.scaling_activation(self._scaling) |
| |
| @property |
| def get_scaling_with_3D_filter(self): |
| scales = self.get_scaling |
| |
| scales = torch.square(scales) + torch.square(self.filter_3D) |
| scales = torch.sqrt(scales) |
| return scales |
| |
| @property |
| def get_rotation(self): |
| return self.rotation_activation(self._rotation) |
| |
| @property |
| def get_xyz(self): |
| return self._xyz |
| |
| @property |
| def get_features(self): |
| features_dc = self._features_dc |
| features_rest = self._features_rest |
| return torch.cat((features_dc, features_rest), dim=1) |
| |
| @property |
| def get_opacity(self): |
| return self.opacity_activation(self._opacity) |
| |
| @property |
| def get_opacity_with_3D_filter(self): |
| opacity = self.opacity_activation(self._opacity) |
| |
| scales = self.get_scaling |
| |
| scales_square = torch.square(scales) |
| det1 = scales_square.prod(dim=1) |
| |
| scales_after_square = scales_square + torch.square(self.filter_3D) |
| det2 = scales_after_square.prod(dim=1) |
| coef = torch.sqrt(det1 / det2) |
| return opacity * coef[..., None] |
|
|
| def get_covariance(self, scaling_modifier = 1): |
| return self.covariance_activation(self.get_scaling, scaling_modifier, self._rotation) |
|
|
| @torch.no_grad() |
| def compute_3D_filter(self, cameras): |
| |
| |
| xyz = self.get_xyz |
| distance = torch.ones((xyz.shape[0]), device=xyz.device) * 100000.0 |
| valid_points = torch.zeros((xyz.shape[0]), device=xyz.device, dtype=torch.bool) |
| |
| |
| focal_length = 0. |
| for camera in cameras: |
|
|
| |
| R = torch.tensor(camera.R, device=xyz.device, dtype=torch.float32) |
| T = torch.tensor(camera.T, device=xyz.device, dtype=torch.float32) |
| |
| xyz_cam = xyz @ R + T[None, :] |
| |
| xyz_to_cam = torch.norm(xyz_cam, dim=1) |
| |
| |
| valid_depth = xyz_cam[:, 2] > 0.2 |
| |
| |
| x, y, z = xyz_cam[:, 0], xyz_cam[:, 1], xyz_cam[:, 2] |
| z = torch.clamp(z, min=0.001) |
| |
| x = x / z * camera.focal_x + camera.image_width / 2.0 |
| y = y / z * camera.focal_y + camera.image_height / 2.0 |
| |
| |
| |
| |
| in_screen = torch.logical_and(torch.logical_and(x >= -0.15 * camera.image_width, x <= camera.image_width * 1.15), torch.logical_and(y >= -0.15 * camera.image_height, y <= 1.15 * camera.image_height)) |
| |
| |
| valid = torch.logical_and(valid_depth, in_screen) |
| |
| |
| distance[valid] = torch.min(distance[valid], z[valid]) |
| valid_points = torch.logical_or(valid_points, valid) |
| if focal_length < camera.focal_x: |
| focal_length = camera.focal_x |
| |
| distance[~valid_points] = distance[valid_points].max() |
| |
| |
| |
| filter_3D = distance / focal_length * (0.2 ** 0.5) |
| self.filter_3D = filter_3D[..., None] |
| |
| def oneupSHdegree(self): |
| if self.active_sh_degree < self.max_sh_degree: |
| self.active_sh_degree += 1 |
|
|
| def create_from_pcd(self, pcd : BasicPointCloud, spatial_lr_scale : float): |
| self.spatial_lr_scale = spatial_lr_scale |
| fused_point_cloud = torch.tensor(np.asarray(pcd.points)).float().cuda() |
| fused_color = RGB2SH(torch.tensor(np.asarray(pcd.colors)).float().cuda()) |
| features = torch.zeros((fused_color.shape[0], 3, (self.max_sh_degree + 1) ** 2)).float().cuda() |
| features[:, :3, 0 ] = fused_color |
| features[:, 3:, 1:] = 0.0 |
|
|
| print("Number of points at initialisation : ", fused_point_cloud.shape[0]) |
|
|
| dist2 = torch.clamp_min(distCUDA2(torch.from_numpy(np.asarray(pcd.points)).float().cuda()), 0.0000001) |
| scales = torch.log(torch.sqrt(dist2))[...,None].repeat(1, 3) |
| rots = torch.zeros((fused_point_cloud.shape[0], 4), device="cuda") |
| rots[:, 0] = 1 |
|
|
| opacities = inverse_sigmoid(0.1 * torch.ones((fused_point_cloud.shape[0], 1), dtype=torch.float, device="cuda")) |
|
|
| self._xyz = nn.Parameter(fused_point_cloud.requires_grad_(True)) |
| self._features_dc = nn.Parameter(features[:,:,0:1].transpose(1, 2).contiguous().requires_grad_(True)) |
| self._features_rest = nn.Parameter(features[:,:,1:].transpose(1, 2).contiguous().requires_grad_(True)) |
| self._scaling = nn.Parameter(scales.requires_grad_(True)) |
| self._rotation = nn.Parameter(rots.requires_grad_(True)) |
| self._opacity = nn.Parameter(opacities.requires_grad_(True)) |
| self.max_radii2D = torch.zeros((self.get_xyz.shape[0]), device="cuda") |
|
|
| def training_setup(self, training_args): |
| self.percent_dense = training_args.percent_dense |
| self.xyz_gradient_accum = torch.zeros((self.get_xyz.shape[0], 1), device="cuda") |
| self.xyz_gradient_accum_abs = torch.zeros((self.get_xyz.shape[0], 1), device="cuda") |
| self.xyz_gradient_accum_abs_max = torch.zeros((self.get_xyz.shape[0], 1), device="cuda") |
| self.denom = torch.zeros((self.get_xyz.shape[0], 1), device="cuda") |
|
|
| l = [ |
| {'params': [self._xyz], 'lr': training_args.position_lr_init * self.spatial_lr_scale, "name": "xyz"}, |
| {'params': [self._features_dc], 'lr': training_args.feature_lr, "name": "f_dc"}, |
| {'params': [self._features_rest], 'lr': training_args.feature_lr / 20.0, "name": "f_rest"}, |
| {'params': [self._opacity], 'lr': training_args.opacity_lr, "name": "opacity"}, |
| {'params': [self._scaling], 'lr': training_args.scaling_lr, "name": "scaling"}, |
| {'params': [self._rotation], 'lr': training_args.rotation_lr, "name": "rotation"} |
| ] |
|
|
| self.optimizer = torch.optim.Adam(l, lr=0.0, eps=1e-15) |
| self.xyz_scheduler_args = get_expon_lr_func(lr_init=training_args.position_lr_init*self.spatial_lr_scale, |
| lr_final=training_args.position_lr_final*self.spatial_lr_scale, |
| lr_delay_mult=training_args.position_lr_delay_mult, |
| max_steps=training_args.position_lr_max_steps) |
|
|
| def update_learning_rate(self, iteration): |
| ''' Learning rate scheduling per step ''' |
| for param_group in self.optimizer.param_groups: |
| if param_group["name"] == "xyz": |
| lr = self.xyz_scheduler_args(iteration) |
| param_group['lr'] = lr |
| return lr |
|
|
| def construct_list_of_attributes(self, exclude_filter=False): |
| l = ['x', 'y', 'z', 'nx', 'ny', 'nz'] |
| |
| for i in range(self._features_dc.shape[1]*self._features_dc.shape[2]): |
| l.append('f_dc_{}'.format(i)) |
| for i in range(self._features_rest.shape[1]*self._features_rest.shape[2]): |
| l.append('f_rest_{}'.format(i)) |
| l.append('opacity') |
| for i in range(self._scaling.shape[1]): |
| l.append('scale_{}'.format(i)) |
| for i in range(self._rotation.shape[1]): |
| l.append('rot_{}'.format(i)) |
| if not exclude_filter: |
| l.append('filter_3D') |
| return l |
|
|
| def save_ply(self, path): |
| mkdir_p(os.path.dirname(path)) |
|
|
| xyz = self._xyz.detach().cpu().numpy() |
| normals = np.zeros_like(xyz) |
| f_dc = self._features_dc.detach().transpose(1, 2).flatten(start_dim=1).contiguous().cpu().numpy() |
| f_rest = self._features_rest.detach().transpose(1, 2).flatten(start_dim=1).contiguous().cpu().numpy() |
| opacities = self._opacity.detach().cpu().numpy() |
| scale = self._scaling.detach().cpu().numpy() |
| rotation = self._rotation.detach().cpu().numpy() |
|
|
| filter_3D = self.filter_3D.detach().cpu().numpy() |
| dtype_full = [(attribute, 'f4') for attribute in self.construct_list_of_attributes()] |
|
|
| elements = np.empty(xyz.shape[0], dtype=dtype_full) |
| attributes = np.concatenate((xyz, normals, f_dc, f_rest, opacities, scale, rotation, filter_3D), axis=1) |
| elements[:] = list(map(tuple, attributes)) |
| el = PlyElement.describe(elements, 'vertex') |
| PlyData([el]).write(path) |
|
|
| def save_fused_ply(self, path): |
| mkdir_p(os.path.dirname(path)) |
|
|
| xyz = self._xyz.detach().cpu().numpy() |
| normals = np.zeros_like(xyz) |
| f_dc = self._features_dc.detach().transpose(1, 2).flatten(start_dim=1).contiguous().cpu().numpy() |
| f_rest = self._features_rest.detach().transpose(1, 2).flatten(start_dim=1).contiguous().cpu().numpy() |
| |
| current_opacity_with_filter = self.get_opacity_with_3D_filter |
| opacities = inverse_sigmoid(current_opacity_with_filter).detach().cpu().numpy() |
| scale = self.scaling_inverse_activation(self.get_scaling_with_3D_filter).detach().cpu().numpy() |
| |
| rotation = self._rotation.detach().cpu().numpy() |
|
|
| dtype_full = [(attribute, 'f4') for attribute in self.construct_list_of_attributes(exclude_filter=True)] |
|
|
| elements = np.empty(xyz.shape[0], dtype=dtype_full) |
| attributes = np.concatenate((xyz, normals, f_dc, f_rest, opacities, scale, rotation), axis=1) |
| elements[:] = list(map(tuple, attributes)) |
| el = PlyElement.describe(elements, 'vertex') |
| PlyData([el]).write(path) |
|
|
| def reset_opacity(self): |
| |
| current_opacity_with_filter = self.get_opacity_with_3D_filter |
| opacities_new = torch.min(current_opacity_with_filter, torch.ones_like(current_opacity_with_filter)*0.01) |
| |
| |
| scales = self.get_scaling |
| |
| scales_square = torch.square(scales) |
| det1 = scales_square.prod(dim=1) |
| |
| scales_after_square = scales_square + torch.square(self.filter_3D) |
| det2 = scales_after_square.prod(dim=1) |
| coef = torch.sqrt(det1 / det2) |
| opacities_new = opacities_new / coef[..., None] |
| opacities_new = inverse_sigmoid(opacities_new) |
|
|
| optimizable_tensors = self.replace_tensor_to_optimizer(opacities_new, "opacity") |
| self._opacity = optimizable_tensors["opacity"] |
|
|
| def load_ply(self, path): |
| plydata = PlyData.read(path) |
|
|
| xyz = np.stack((np.asarray(plydata.elements[0]["x"]), |
| np.asarray(plydata.elements[0]["y"]), |
| np.asarray(plydata.elements[0]["z"])), axis=1) |
| opacities = np.asarray(plydata.elements[0]["opacity"])[..., np.newaxis] |
|
|
| filter_3D = np.asarray(plydata.elements[0]["filter_3D"])[..., np.newaxis] |
|
|
| features_dc = np.zeros((xyz.shape[0], 3, 1)) |
| features_dc[:, 0, 0] = np.asarray(plydata.elements[0]["f_dc_0"]) |
| features_dc[:, 1, 0] = np.asarray(plydata.elements[0]["f_dc_1"]) |
| features_dc[:, 2, 0] = np.asarray(plydata.elements[0]["f_dc_2"]) |
|
|
| extra_f_names = [p.name for p in plydata.elements[0].properties if p.name.startswith("f_rest_")] |
| extra_f_names = sorted(extra_f_names, key = lambda x: int(x.split('_')[-1])) |
| assert len(extra_f_names)==3*(self.max_sh_degree + 1) ** 2 - 3 |
| features_extra = np.zeros((xyz.shape[0], len(extra_f_names))) |
| for idx, attr_name in enumerate(extra_f_names): |
| features_extra[:, idx] = np.asarray(plydata.elements[0][attr_name]) |
| |
| features_extra = features_extra.reshape((features_extra.shape[0], 3, (self.max_sh_degree + 1) ** 2 - 1)) |
|
|
| scale_names = [p.name for p in plydata.elements[0].properties if p.name.startswith("scale_")] |
| scale_names = sorted(scale_names, key = lambda x: int(x.split('_')[-1])) |
| scales = np.zeros((xyz.shape[0], len(scale_names))) |
| for idx, attr_name in enumerate(scale_names): |
| scales[:, idx] = np.asarray(plydata.elements[0][attr_name]) |
|
|
| rot_names = [p.name for p in plydata.elements[0].properties if p.name.startswith("rot")] |
| rot_names = sorted(rot_names, key = lambda x: int(x.split('_')[-1])) |
| rots = np.zeros((xyz.shape[0], len(rot_names))) |
| for idx, attr_name in enumerate(rot_names): |
| rots[:, idx] = np.asarray(plydata.elements[0][attr_name]) |
|
|
| self._xyz = nn.Parameter(torch.tensor(xyz, dtype=torch.float, device="cuda").requires_grad_(True)) |
| self._features_dc = nn.Parameter(torch.tensor(features_dc, dtype=torch.float, device="cuda").transpose(1, 2).contiguous().requires_grad_(True)) |
| self._features_rest = nn.Parameter(torch.tensor(features_extra, dtype=torch.float, device="cuda").transpose(1, 2).contiguous().requires_grad_(True)) |
| self._opacity = nn.Parameter(torch.tensor(opacities, dtype=torch.float, device="cuda").requires_grad_(True)) |
| self._scaling = nn.Parameter(torch.tensor(scales, dtype=torch.float, device="cuda").requires_grad_(True)) |
| self._rotation = nn.Parameter(torch.tensor(rots, dtype=torch.float, device="cuda").requires_grad_(True)) |
| self.filter_3D = torch.tensor(filter_3D, dtype=torch.float, device="cuda") |
|
|
| self.active_sh_degree = self.max_sh_degree |
|
|
| def replace_tensor_to_optimizer(self, tensor, name): |
| optimizable_tensors = {} |
| for group in self.optimizer.param_groups: |
| if group["name"] == name: |
| stored_state = self.optimizer.state.get(group['params'][0], None) |
| stored_state["exp_avg"] = torch.zeros_like(tensor) |
| stored_state["exp_avg_sq"] = torch.zeros_like(tensor) |
|
|
| del self.optimizer.state[group['params'][0]] |
| group["params"][0] = nn.Parameter(tensor.requires_grad_(True)) |
| self.optimizer.state[group['params'][0]] = stored_state |
|
|
| optimizable_tensors[group["name"]] = group["params"][0] |
| return optimizable_tensors |
|
|
| def _prune_optimizer(self, mask): |
| optimizable_tensors = {} |
| for group in self.optimizer.param_groups: |
| old_param = group['params'][0] |
| stored_state = self.optimizer.state.pop(old_param, None) |
| if stored_state is not None: |
| old_exp_avg = stored_state.pop("exp_avg") |
| exp_avg = old_exp_avg[mask].contiguous() |
| del old_exp_avg |
| torch.cuda.empty_cache() |
|
|
| old_exp_avg_sq = stored_state.pop("exp_avg_sq") |
| exp_avg_sq = old_exp_avg_sq[mask].contiguous() |
| del old_exp_avg_sq |
| torch.cuda.empty_cache() |
|
|
| new_param = nn.Parameter(old_param[mask].contiguous().requires_grad_(True)) |
| group["params"][0] = new_param |
| stored_state["exp_avg"] = exp_avg |
| stored_state["exp_avg_sq"] = exp_avg_sq |
| self.optimizer.state[new_param] = stored_state |
|
|
| optimizable_tensors[group["name"]] = new_param |
| else: |
| new_param = nn.Parameter(old_param[mask].contiguous().requires_grad_(True)) |
| group["params"][0] = new_param |
| optimizable_tensors[group["name"]] = new_param |
| del old_param |
| torch.cuda.empty_cache() |
| return optimizable_tensors |
|
|
| def prune_points(self, mask): |
| valid_points_mask = ~mask |
| optimizable_tensors = self._prune_optimizer(valid_points_mask) |
|
|
| self._xyz = optimizable_tensors["xyz"] |
| self._features_dc = optimizable_tensors["f_dc"] |
| self._features_rest = optimizable_tensors["f_rest"] |
| self._opacity = optimizable_tensors["opacity"] |
| self._scaling = optimizable_tensors["scaling"] |
| self._rotation = optimizable_tensors["rotation"] |
|
|
| self.xyz_gradient_accum = self.xyz_gradient_accum[valid_points_mask] |
| self.xyz_gradient_accum_abs = self.xyz_gradient_accum_abs[valid_points_mask] |
| self.xyz_gradient_accum_abs_max = self.xyz_gradient_accum_abs_max[valid_points_mask] |
| self.denom = self.denom[valid_points_mask] |
| self.max_radii2D = self.max_radii2D[valid_points_mask] |
|
|
| def cat_tensors_to_optimizer(self, tensors_dict, copy_original_en=True): |
| optimizable_tensors = {} |
| for group in self.optimizer.param_groups: |
| assert len(group["params"]) == 1 |
| extension_tensor = tensors_dict[group["name"]] |
| old_param = group['params'][0] |
| stored_state = self.optimizer.state.pop(old_param, None) |
| if stored_state is not None: |
| old_exp_avg = stored_state.pop("exp_avg") |
| new_exp_avg = torch.cat((old_exp_avg, torch.zeros_like(extension_tensor)), dim=0) |
| del old_exp_avg |
| torch.cuda.empty_cache() |
|
|
| old_exp_avg_sq = stored_state.pop("exp_avg_sq") |
| new_exp_avg_sq = torch.cat((old_exp_avg_sq, torch.zeros_like(extension_tensor)), dim=0) |
| del old_exp_avg_sq |
| torch.cuda.empty_cache() |
|
|
| new_param = nn.Parameter(torch.cat((old_param, extension_tensor), dim=0).requires_grad_(True)) |
|
|
| group["params"][0] = new_param |
| stored_state["exp_avg"] = new_exp_avg |
| stored_state["exp_avg_sq"] = new_exp_avg_sq |
| self.optimizer.state[new_param] = stored_state |
|
|
| optimizable_tensors[group["name"]] = new_param |
| elif not copy_original_en: |
| new_param = nn.Parameter(extension_tensor.requires_grad_(True)) |
| group["params"][0] = new_param |
| optimizable_tensors[group["name"]] = new_param |
| else: |
| new_param = nn.Parameter(torch.cat((old_param, extension_tensor), dim=0).requires_grad_(True)) |
| group["params"][0] = new_param |
| optimizable_tensors[group["name"]] = new_param |
| del old_param |
| torch.cuda.empty_cache() |
|
|
| return optimizable_tensors |
|
|
| def densification_postfix(self, new_xyz, new_features_dc, new_features_rest, new_opacities, new_scaling, new_rotation, SR_GS_en=False): |
| d = {"xyz": new_xyz, |
| "f_dc": new_features_dc, |
| "f_rest": new_features_rest, |
| "opacity": new_opacities, |
| "scaling" : new_scaling, |
| "rotation" : new_rotation} |
|
|
| if SR_GS_en: |
| optimizable_tensors = self.cat_tensors_to_optimizer(d, copy_original_en=False) |
| else: |
| optimizable_tensors = self.cat_tensors_to_optimizer(d) |
|
|
| self._xyz = optimizable_tensors["xyz"] |
| self._features_dc = optimizable_tensors["f_dc"] |
| self._features_rest = optimizable_tensors["f_rest"] |
| self._opacity = optimizable_tensors["opacity"] |
| self._scaling = optimizable_tensors["scaling"] |
| self._rotation = optimizable_tensors["rotation"] |
|
|
| |
| self.xyz_gradient_accum = torch.zeros((self.get_xyz.shape[0], 1), device="cuda") |
| self.xyz_gradient_accum_abs = torch.zeros((self.get_xyz.shape[0], 1), device="cuda") |
| self.xyz_gradient_accum_abs_max = torch.zeros((self.get_xyz.shape[0], 1), device="cuda") |
| self.denom = torch.zeros((self.get_xyz.shape[0], 1), device="cuda") |
| self.max_radii2D = torch.zeros((self.get_xyz.shape[0]), device="cuda") |
|
|
| def densify_and_split(self, grads, grad_threshold, grads_abs, grad_abs_threshold, scene_extent, N=2): |
| n_init_points = self.get_xyz.shape[0] |
| |
| padded_grad = torch.zeros((n_init_points), device="cuda") |
| padded_grad[:grads.shape[0]] = grads.squeeze() |
| selected_pts_mask = torch.where(padded_grad >= grad_threshold, True, False) |
| padded_grad_abs = torch.zeros((n_init_points), device="cuda") |
| padded_grad_abs[:grads_abs.shape[0]] = grads_abs.squeeze() |
| selected_pts_mask_abs = torch.where(padded_grad_abs >= grad_abs_threshold, True, False) |
| selected_pts_mask = torch.logical_or(selected_pts_mask, selected_pts_mask_abs) |
| selected_pts_mask = torch.logical_and(selected_pts_mask, |
| torch.max(self.get_scaling, dim=1).values > self.percent_dense*scene_extent) |
|
|
| stds = self.get_scaling[selected_pts_mask].repeat(N,1) |
| means =torch.zeros((stds.size(0), 3),device="cuda") |
| samples = torch.normal(mean=means, std=stds) |
| rots = build_rotation(self._rotation[selected_pts_mask]).repeat(N,1,1) |
| new_xyz = torch.bmm(rots, samples.unsqueeze(-1)).squeeze(-1) + self.get_xyz[selected_pts_mask].repeat(N, 1) |
| new_scaling = self.scaling_inverse_activation(self.get_scaling[selected_pts_mask].repeat(N,1) / (0.8*N)) |
| new_rotation = self._rotation[selected_pts_mask].repeat(N,1) |
| new_features_dc = self._features_dc[selected_pts_mask].repeat(N,1,1) |
| new_features_rest = self._features_rest[selected_pts_mask].repeat(N,1,1) |
| new_opacity = self._opacity[selected_pts_mask].repeat(N,1) |
|
|
| self.densification_postfix(new_xyz, new_features_dc, new_features_rest, new_opacity, new_scaling, new_rotation) |
| del stds, means, samples, rots |
| del new_xyz, new_scaling, new_rotation, new_features_dc, new_features_rest, new_opacity |
| torch.cuda.empty_cache() |
|
|
| prune_filter = torch.cat((selected_pts_mask, torch.zeros(N * selected_pts_mask.sum(), device="cuda", dtype=bool))) |
| del selected_pts_mask, selected_pts_mask_abs, padded_grad, padded_grad_abs |
| self.prune_points(prune_filter) |
| del prune_filter |
| torch.cuda.empty_cache() |
|
|
| def densify_and_clone(self, grads, grad_threshold, grads_abs, grad_abs_threshold, scene_extent): |
| |
| selected_pts_mask = torch.where(torch.norm(grads, dim=-1) >= grad_threshold, True, False) |
| selected_pts_mask_abs = torch.where(torch.norm(grads_abs, dim=-1) >= grad_abs_threshold, True, False) |
| selected_pts_mask = torch.logical_or(selected_pts_mask, selected_pts_mask_abs) |
| selected_pts_mask = torch.logical_and(selected_pts_mask, |
| torch.max(self.get_scaling, dim=1).values <= self.percent_dense*scene_extent) |
| |
| new_xyz = self._xyz[selected_pts_mask] |
| new_features_dc = self._features_dc[selected_pts_mask] |
| new_features_rest = self._features_rest[selected_pts_mask] |
| new_opacities = self._opacity[selected_pts_mask] |
| new_scaling = self._scaling[selected_pts_mask] |
| new_rotation = self._rotation[selected_pts_mask] |
|
|
| self.densification_postfix(new_xyz, new_features_dc, new_features_rest, new_opacities, new_scaling, new_rotation) |
| del selected_pts_mask, selected_pts_mask_abs |
| del new_xyz, new_features_dc, new_features_rest, new_opacities, new_scaling, new_rotation |
| torch.cuda.empty_cache() |
|
|
| def densify_and_prune(self, max_grad, min_opacity, extent, max_screen_size): |
| grads = self.xyz_gradient_accum / self.denom |
| grads[grads.isnan()] = 0.0 |
|
|
| grads_abs = self.xyz_gradient_accum_abs / self.denom |
| grads_abs[grads_abs.isnan()] = 0.0 |
| ratio = (torch.norm(grads, dim=-1) >= max_grad).float().mean() |
| |
| qqq = np.quantile(grads_abs.reshape(-1).cpu().numpy(), 1 - ratio.cpu().numpy()) |
| |
| before = self._xyz.shape[0] |
| |
| self.densify_and_clone(grads, max_grad, grads_abs, qqq, extent) |
| clone = self._xyz.shape[0] |
| |
| self.densify_and_split(grads, max_grad, grads_abs, qqq, extent) |
| split = self._xyz.shape[0] |
|
|
| prune_mask = (self.get_opacity < min_opacity).squeeze() |
| if max_screen_size: |
| big_points_vs = self.max_radii2D > max_screen_size |
| big_points_ws = self.get_scaling.max(dim=1).values > 0.1 * extent |
| prune_mask = torch.logical_or(torch.logical_or(prune_mask, big_points_vs), big_points_ws) |
| self.prune_points(prune_mask) |
| prune = self._xyz.shape[0] |
| del grads, grads_abs, prune_mask |
| torch.cuda.empty_cache() |
| return clone - before, split - clone, split - prune |
|
|
| def add_densification_stats(self, viewspace_point_tensor, update_filter): |
| self.xyz_gradient_accum[update_filter] += torch.norm(viewspace_point_tensor.grad[update_filter,:2], dim=-1, keepdim=True) |
| |
| self.xyz_gradient_accum_abs[update_filter] += torch.norm(viewspace_point_tensor.grad[update_filter,2:], dim=-1, keepdim=True) |
| self.xyz_gradient_accum_abs_max[update_filter] = torch.max(self.xyz_gradient_accum_abs_max[update_filter], torch.norm(viewspace_point_tensor.grad[update_filter,2:], dim=-1, keepdim=True)) |
| self.denom[update_filter] += 1 |
| |
| def super_resolving_gaussians(self, factor, rendering=False): |
| device = self._xyz.device |
| num_points = self._xyz.shape[0] |
| xyz_orig = self._xyz.clone().detach() |
| scalings_orig = self.get_scaling.clone().detach() |
| rotations_orig = self.get_rotation.clone().detach() |
| features_dc_orig = self._features_dc.clone().detach() |
| features_rest_orig = self._features_rest.clone().detach() |
| opacity_orig = self._opacity.clone().detach() |
| filter_3D_orig = self.filter_3D.clone().detach() |
|
|
| |
| |
| |
| new_xyz = xyz_orig.repeat(factor**3, 1) |
| |
| shift_value = 1.0 |
|
|
| |
| shift_range = np.linspace(-1 + shift_value, 1 - shift_value, factor) |
|
|
| |
| shift_combinations = torch.from_numpy(np.array([[x, y, z] for x in shift_range for y in shift_range for z in shift_range])).to(device) |
|
|
| |
|
|
| |
| |
| extended_points_offset = [] |
|
|
| |
| for shift_scale in shift_combinations: |
| try: |
| new_shift = scaling_orig * shift_scale |
| except: |
| new_shift = scalings_orig.detach().cpu().numpy() * shift_scale |
| extended_points_offset.append(new_shift) |
|
|
| |
| extended_points_offset = torch.vstack(extended_points_offset) |
| new_xyz += extended_points_offset |
| new_rotation = rotations_orig.repeat(factor**3, 1) |
| new_features_dc = features_dc_orig.repeat(factor**3, 1, 1) |
| new_features_rest = features_rest_orig.repeat(factor**3, 1, 1) |
| new_opacities = opacity_orig.repeat(factor**3, 1) |
| scale_new = torch.log(scalings_orig / 2) |
| new_scaling = scale_new.repeat(factor**3, 1) |
| print(" === Number of points before densification postfix ", self._xyz.shape[0]) |
|
|
| if not rendering: |
| self.densification_postfix(new_xyz, new_features_dc, new_features_rest, new_opacities, new_scaling, new_rotation, SR_GS_en=True) |
| else: |
| self._xyz = new_xyz |
| self._rotation = new_rotation |
| self._features_dc = new_features_dc |
| self._features_rest = new_features_rest |
| self._opacity = new_opacities |
| self._scaling = new_scaling |
| print(" === Number of points after densification postfix ", self._xyz.shape[0]) |
|
|