Args:
config: Splatfacto configuration to instantiate model
"""
config: SplatfactoModelConfig
def __init__(
self,
*args,
seed_points: Optional[Tuple[torch.Tensor, torch.Tensor]] = None,
**kwargs,
):
self.seed_points = seed_points
super().__init__(*args, **kwargs)
def populate_modules(self):
if self.seed_points is not None and not self.config.random_init:
means = torch.nn.Parameter(self.seed_points[0]) # (Location, Color)
else:
means = torch.nn.Parameter((torch.rand((self.config.num_random, 3)) - 0.5) * self.config.random_scale)
distances, _ = k_nearest_sklearn(means.data, 3)
# 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)
scales = torch.nn.Parameter(torch.log(avg_dist.repeat(1, 3)))
num_points = means.shape[0]
quats = torch.nn.Parameter(random_quat_tensor(num_points))
dim_sh = num_sh_bases(self.config.sh_degree)
if (
self.seed_points is not None
and not self.config.random_init
# We can have colors without points.
and self.seed_points[1].shape[0] > 0
):
shs = torch.zeros((self.seed_points[1].shape[0], dim_sh, 3)).float().cuda()
if self.config.sh_degree > 0:
shs[:, 0, :3] = RGB2SH(self.seed_points[1] / 255)
shs[:, 1:, 3:] = 0.0
else:
CONSOLE.log("use color only optimization with sigmoid activation")
shs[:, 0, :3] = torch.logit(self.seed_points[1] / 255, eps=1e-10)
features_dc = torch.nn.Parameter(shs[:, 0, :])
features_rest = torch.nn.Parameter(shs[:, 1:, :])
else:
features_dc = torch.nn.Parameter(torch.rand(num_points, 3))
features_rest = torch.nn.Parameter(torch.zeros((num_points, dim_sh - 1, 3)))
opacities = torch.nn.Parameter(torch.logit(0.1 * torch.ones(num_points, 1)))
self.gauss_params = torch.nn.ParameterDict(
{
"means": means,
"scales": scales,
"quats": quats,
"features_dc": features_dc,
"features_rest": features_rest,
"opacities": opacities,
}
)
self.camera_optimizer: CameraOptimizer = self.config.camera_optimizer.setup(
num_cameras=self.num_train_data, device="cpu"
)
# metrics
from torchmetrics.image import PeakSignalNoiseRatio
from torchmetrics.image.lpip import LearnedPerceptualImagePatchSimilarity
self.psnr = PeakSignalNoiseRatio(data_range=1.0)
self.ssim = SSIM(data_range=1.0, size_average=True, channel=3)
self.lpips = LearnedPerceptualImagePatchSimilarity(normalize=True)
self.step = 0
self.crop_box: Optional[OrientedBox] = None
if self.config.background_color == "random":
self.background_color = torch.tensor(
[0.1490, 0.1647, 0.2157]
) # This color is the same as the default background color in Viser. This would only affect the background color when rendering.
else:
self.background_color = get_color(self.config.background_color)
if self.config.use_bilateral_grid:
self.bil_grids = BilateralGrid(
num=self.num_train_data,
grid_X=self.config.grid_shape[0],
grid_Y=self.config.grid_shape[1],
grid_W=self.config.grid_shape[2],
)
# Strategy for GS densification
if self.config.strategy == "default":
# Strategy for GS densification
self.strategy = DefaultStrategy(
prune_opa=self.config.cull_alpha_thresh,
grow_grad2d=self.config.densify_grad_thresh,
grow_scale3d=self.config.densify_size_thresh,
grow_scale2d=self.config.split_screen_size,
prune_scale3d=self.config.cull_scale_thresh,
prune_scale2d=self.config.cull_screen_size,
refine_scale2d_stop_iter=self.config.stop_screen_size_at,
refine_start_iter=self.config.warmup_length,
refine_stop_iter=self.config.stop_split_at,
reset_every=self.config.reset_alpha_every * self.config.refine_every,
refine_every=self.config.refine_every,
pause_refine_after_reset=self.num_train_data + self.config.refine_every,
absgrad=self.config.use_absgrad,
revised_opacity=False,
verbose=True,
)
self.strategy_state = self.strategy.initialize_state(scene_scale=1.0)
elif self.config.strategy == "mcmc":
self.strategy = MCMCStrategy(
cap_max=self.config.max_gs_num,
noise_lr=self.config.noise_lr,
refine_start_iter=self.config.warmup_length,
refine_stop_iter=self.config.stop_split_at,
refine_every=self.config.refine_every,
min_opacity=self.config.cull_alpha_thresh,
verbose=False,
)
self.strategy_state = self.strategy.initialize_state()
else:
raise ValueError(f"""Splatfacto does not support strategy {self.config.strategy}
Currently, the supported strategies include default and mcmc.""")
@property
def colors(self):
if self.config.sh_degree > 0:
return SH2RGB(self.features_dc)
else:
return torch.sigmoid(self.features_dc)
@property
def shs_0(self):
if self.config.sh_degree > 0:
return self.features_dc
else:
return RGB2SH(torch.sigmoid(self.features_dc))
@property
def shs_rest(self):
return self.features_rest
@property
def num_points(self):
return self.means.shape[0]
@property
def means(self):
return self.gauss_params["means"]
@property
def scales(self):
return self.gauss_params["scales"]
@property
def quats(self):
return self.gauss_params["quats"]
@property
def features_dc(self):
return self.gauss_params["features_dc"]
@property
def features_rest(self):
return self.gauss_params["features_rest"]
@property
def opacities(self):
return self.gauss_params["opacities"]
def load_state_dict(self, dict, **kwargs): # type: ignore
# resize the parameters to match the new number of points
self.step = 30000
if "means" in dict:
# For backwards compatibility, we remap the names of parameters from
# means->gauss_params.means since old checkpoints have that format
for p in ["means", "scales", "quats", "features_dc", "features_rest", "opacities"]:
dict[f"gauss_params.{p}"] = dict[p]
newp = dict["gauss_params.means"].shape[0]
for name, param in self.gauss_params.items():
old_shape = param.shape
new_shape = (newp,) + old_shape[1:]
self.gauss_params[name] = torch.nn.Parameter(torch.zeros(new_shape, device=self.device))
super().load_state_dict(dict, **kwargs)
def set_crop(self, crop_box: Optional[OrientedBox]):
self.crop_box = crop_box
def set_background(self, background_color: torch.Tensor):
assert background_color.shape == (3,)
self.background_color = background_color
def step_post_backward(self, step):
assert step == self.step
if isinstance(self.strategy, DefaultStrategy):
self.strategy.step_post_backward(
params=self.gauss_params,
optimizers=self.optimizers,
state=self.strategy_state,
step=self.step,
info=self.info,
packed=False,
)
elif isinstance(self.strategy, MCMCStrategy):
self.strategy.step_post_backward(
params=self.gauss_params,
optimizers=self.optimizers,
state=self.strategy_state,
step=step,
info=self.info,
lr=self.schedulers["means"].get_last_lr()[0], # the learning rate for the "means" attribute of the GS
)
else:
raise ValueError(f"Unknown strategy {self.strategy}")
def get_training_callbacks(
self, training_callback_attributes: TrainingCallbackAttributes
) -> List[TrainingCallback]:
cbs = []
cbs.append(
TrainingCallback(
[TrainingCallbackLocation.BEFORE_TRAIN_ITERATION],
self.step_cb,
args=[training_callback_attributes.optimizers],
)
)
cbs.append(
TrainingCallback(
[TrainingCallbackLocation.AFTER_TRAIN_ITERATION],
self.step_post_backward,
)
)
return cbs
def step_cb(self, optimizers: Optimizers, step):
self.step = step
self.optimizers = optimizers.optimizers
self.schedulers = optimizers.schedulers
def get_gaussian_param_groups(self) -> Dict[str, List[Parameter]]:
# Here we explicitly use the means, scales as parameters so that the user can override this function and
# specify more if they want to add more optimizable params to gaussians.
return {
name: [self.gauss_params[name]]
for name in ["means", "scales", "quats", "features_dc", "features_rest", "opacities"]
}
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()
if self.config.use_bilateral_grid:
gps["bilateral_grid"] = list(self.bil_grids.parameters())
self.camera_optimizer.get_param_groups(param_groups=gps)
return gps
def _get_downscale_factor(self):
if self.training:
return 2 ** max(
(self.config.num_downscales - self.step // self.config.resolution_schedule),
0,
)
else:
return 1
def _downscale_if_required(self, image):
d = self._get_downscale_factor()
if d > 1:
return resize_image(image, d)
return image
@staticmethod
def get_empty_outputs(width: int, height: int, background: torch.Tensor) -> Dict[str, Union[torch.Tensor, List]]:
rgb = background.repeat(height, width, 1)
depth = background.new_ones(*rgb.shape[:2], 1) * 10
accumulation = background.new_zeros(*rgb.shape[:2], 1)
return {"rgb": rgb, "depth": depth, "accumulation": accumulation, "background": background}
def _get_background_color(self):
if self.config.background_color == "random":
if self.training:
background = torch.rand(3, device=self.device)
else:
background = self.background_color.to(self.device)
elif self.config.background_color == "white":
background = torch.ones(3, device=self.device)
elif self.config.background_color == "black":
background = torch.zeros(3, device=self.device)
else:
raise ValueError(f"Unknown background color {self.config.background_color}")
return background
def _apply_bilateral_grid(self, rgb: torch.Tensor, cam_idx: int, H: int, W: int) -> torch.Tensor:
# make xy grid
grid_y, grid_x = torch.meshgrid(
torch.linspace(0, 1.0, H, device=self.device),
torch.linspace(0, 1.0, W, device=self.device),
indexing="ij",
)
grid_xy = torch.stack([grid_x, grid_y], dim=-1).unsqueeze(0)
out = slice(
bil_grids=self.bil_grids,
rgb=rgb,
xy=grid_xy,
grid_idx=torch.tensor(cam_idx, device=self.device, dtype=torch.long),
)
return out["rgb"]
def get_outputs(self, camera: Cameras) -> Dict[str, Union[torch.Tensor, List]]:
"""Takes in a camera and returns a dictionary of outputs.
Args:
camera: The camera(s) for which output images are rendered. It should have
all the needed information to compute the outputs.
Returns:
Outputs of model. (ie. rendered colors)
"""
if not isinstance(camera, Cameras):
print("Called get_outputs with not a camera")
return {}
if self.training:
assert camera.shape[0] == 1, "Only one camera at a time"
optimized_camera_to_world = self.camera_optimizer.apply_to_camera(camera)
else:
optimized_camera_to_world = camera.camera_to_worlds
# cropping
if self.crop_box is not None and not self.training:
crop_ids = self.crop_box.within(self.means).squeeze()
if crop_ids.sum() == 0:
return self.get_empty_outputs(
int(camera.width.item()), int(camera.height.item()), self.background_color
)
else:
crop_ids = None
if crop_ids is not None:
opacities_crop = self.opacities[crop_ids]
means_crop = self.means[crop_ids]
features_dc_crop = self.features_dc[crop_ids]
features_rest_crop = self.features_rest[crop_ids]
scales_crop = self.scales[crop_ids]
quats_crop = self.quats[crop_ids]
else:
opacities_crop = self.opacities
means_crop = self.means
features_dc_crop = self.features_dc
features_rest_crop = self.features_rest
scales_crop = self.scales
quats_crop = self.quats
colors_crop = torch.cat((features_dc_crop[:, None, :], features_rest_crop), dim=1)
camera_scale_fac = self._get_downscale_factor()
camera.rescale_output_resolution(1 / camera_scale_fac)
viewmat = get_viewmat(optimized_camera_to_world)
K = camera.get_intrinsics_matrices().cuda()
W, H = int(camera.width.item()), int(camera.height.item())
self.last_size = (H, W)
camera.rescale_output_resolution(camera_scale_fac) # type: ignore
# apply the compensation of screen space blurring to gaussians
if self.config.rasterize_mode not in ["antialiased", "classic"]:
raise ValueError("Unknown rasterize_mode: %s", self.config.rasterize_mode)
if self.config.output_depth_during_training or not self.training:
render_mode = "RGB+ED"
else:
render_mode = "RGB"
if self.config.sh_degree > 0:
sh_degree_to_use = min(self.step // self.config.sh_degree_interval, self.config.sh_degree)
else:
colors_crop = torch.sigmoid(colors_crop).squeeze(1) # [N, 1, 3] -> [N, 3]
sh_degree_to_use = None
render, alpha, self.info = rasterization(
means=means_crop,
quats=quats_crop, # rasterization does normalization internally
scales=torch.exp(scales_crop),
opacities=torch.sigmoid(opacities_crop).squeeze(-1),
colors=colors_crop,
viewmats=viewmat, # [1, 4, 4]
Ks=K, # [1, 3, 3]
width=W,
height=H,
packed=False,
near_plane=0.01,
far_plane=1e10,
render_mode=render_mode,
sh_degree=sh_degree_to_use,
sparse_grad=False,
absgrad=self.strategy.absgrad if isinstance(self.strategy, DefaultStrategy) else False,
rasterize_mode=self.config.rasterize_mode,
# set some threshold to disregrad small gaussians for faster rendering.
# radius_clip=3.0,
)
if self.training:
self.strategy.step_pre_backward(
self.gauss_params, self.optimizers, self.strategy_state, self.step, self.info
)
alpha = alpha[:, ...]
background = self._get_background_color()
rgb = render[:, ..., :3] + (1 - alpha) * background
rgb = torch.clamp(rgb, 0.0, 1.0)
# apply bilateral grid
if self.config.use_bilateral_grid and self.training:
if camera.metadata is not None and "cam_idx" in camera.metadata:
rgb = self._apply_bilateral_grid(rgb, camera.metadata["cam_idx"], H, W)
if render_mode == "RGB+ED":
depth_im = render[:, ..., 3:4]
depth_im = torch.where(alpha > 0, depth_im, depth_im.detach().max()).squeeze(0)
else:
depth_im = None
if background.shape[0] == 3 and not self.training:
background = background.expand(H, W, 3)
return {
"rgb": rgb.squeeze(0), # type: ignore
"depth": depth_im, # type: ignore
"accumulation": alpha.squeeze(0), # type: ignore
"background": background, # type: ignore
} # type: ignore
def get_gt_img(self, image: torch.Tensor):
"""Compute groundtruth image with iteration dependent downscale factor for evaluation purpose
Args:
image: tensor.Tensor in type uint8 or float32
"""
if image.dtype == torch.uint8:
image = image.float() / 255.0
gt_img = self._downscale_if_required(image)
return gt_img.to(self.device)
def composite_with_background(self, image, background) -> torch.Tensor:
"""Composite the ground truth image with a background color when it has an alpha channel.
Args:
image: the image to composite
background: the background color
"""
if image.shape[2] == 4:
alpha = image[..., -1].unsqueeze(-1).repeat((1, 1, 3))
return alpha * image[..., :3] + (1 - alpha) * background
else:
return image
def get_metrics_dict(self, outputs, batch) -> Dict[str, torch.Tensor]:
"""Compute and returns metrics.
Args:
outputs: the output to compute loss dict to
batch: ground truth batch corresponding to outputs
"""
gt_rgb = self.composite_with_background(self.get_gt_img(batch["image"]), outputs["background"])
metrics_dict = {}
predicted_rgb = outputs["rgb"]
metrics_dict["psnr"] = self.psnr(predicted_rgb, gt_rgb)
if self.config.color_corrected_metrics:
cc_rgb = color_correct(predicted_rgb, gt_rgb)
metrics_dict["cc_psnr"] = self.psnr(cc_rgb, gt_rgb)
metrics_dict["gaussian_count"] = self.num_points
self.camera_optimizer.get_metrics_dict(metrics_dict)
return metrics_dict
def pearson_loss(self, pred, target):
pred_flat = pred.reshape(-1)
target_flat = target.reshape(-1)
pred_mean = pred_flat.mean()
target_mean = target_flat.mean()
pred_centered = pred_flat - pred_mean
target_centered = target_flat - target_mean
numerator = (pred_centered * target_centered).sum()
denominator = torch.sqrt((pred_centered**2).sum() * (target_centered**2).sum())
correlation = numerator / (denominator + 1e-8)
return 1.0 - correlation
def log_mean_std_normalize(self, x, mask=None, eps=1e-6):
x = torch.log(torch.relu(x) + eps)
if mask is not None:
m = mask.float()
m_sum = m.sum()
mean = (x * m).sum() / m_sum
std = torch.sqrt(((x - mean)**2 * m).sum() / m_sum)
else:
mean = x.mean()
std = x.std()
normed = (x - mean) / (std + eps)
return normed
def get_loss_dict(self, outputs, batch, metrics_dict=None) -> Dict[str, torch.Tensor]:
"""Computes and returns the losses dict."""
gt_img = self.composite_with_background(self.get_gt_img(batch["image"]), outputs["background"])
pred_img = outputs["rgb"]
if "mask" in batch:
mask = self._downscale_if_required(batch["mask"])
mask = mask.to(self.device)
assert mask.shape[:2] == gt_img.shape[:2] == pred_img.shape[:2]
gt_img = gt_img * mask
pred_img = pred_img * mask
Ll1 = torch.abs(gt_img - pred_img).mean()
simloss = 1 - self.ssim(gt_img.permute(0, 3, 1, 2), pred_img.permute(0, 3, 1, 2))
if self.config.use_scale_regularization and self.step % 10 == 0:
scale_exp =