mirror of
https://github.com/nerfstudio-project/nerfstudio.git
synced 2026-12-03 22:38:48 +08:00
quality improvements, param changes, camera optimization support, misc updates
This commit is contained in:
1 parent
40c05be7a6
commit
bb7c7f9a94
9 files changed
+228
-122
No files matched your search
@@ -45,10 +45,10 @@ class CameraOptimizerConfig(InstantiateConfig):
|
|||||||
mode: Literal["off", "SO3xR3", "SE3"] = "off"
|
mode: Literal["off", "SO3xR3", "SE3"] = "off"
|
||||||
"""Pose optimization strategy to use. If enabled, we recommend SO3xR3."""
|
"""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."""
|
"""L2 penalty on translation parameters."""
|
||||||
|
|
||||||
rot_l2_penalty: float = 1e-3
|
rot_l2_penalty: float = 1e-4
|
||||||
"""L2 penalty on rotation parameters."""
|
"""L2 penalty on rotation parameters."""
|
||||||
|
|
||||||
optimizer: Optional[OptimizerConfig] = field(default=None)
|
optimizer: Optional[OptimizerConfig] = field(default=None)
|
||||||
@@ -150,9 +150,12 @@ class CameraOptimizer(nn.Module):
|
|||||||
def apply_to_camera(self, camera: Cameras) -> None:
|
def apply_to_camera(self, camera: Cameras) -> None:
|
||||||
"""Apply the pose correction to the raybundle"""
|
"""Apply the pose correction to the raybundle"""
|
||||||
if self.config.mode != "off":
|
if self.config.mode != "off":
|
||||||
correction_matrices = self(raybundle.camera_indices.squeeze()) # type: ignore
|
assert camera.metadata is not None, "Must provide id of camera in its metadata"
|
||||||
raybundle.origins = raybundle.origins + correction_matrices[:, :3, 3]
|
assert "cam_idx" in camera.metadata, "Must provide id of camera in its metadata"
|
||||||
raybundle.directions = torch.bmm(correction_matrices[:, :3, :3], raybundle.directions[..., None]).squeeze()
|
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:
|
def get_loss_dict(self, loss_dict: dict) -> None:
|
||||||
"""Add regularization"""
|
"""Add regularization"""
|
||||||
|
|||||||
@@ -597,7 +597,8 @@ method_configs["neus-facto"] = TrainerConfig(
|
|||||||
viewer=ViewerConfig(num_rays_per_chunk=1 << 15),
|
viewer=ViewerConfig(num_rays_per_chunk=1 << 15),
|
||||||
vis="viewer",
|
vis="viewer",
|
||||||
)
|
)
|
||||||
|
from dataclasses import field
|
||||||
|
from collections import defaultdict
|
||||||
method_configs["gaussian-splatting"] = TrainerConfig(
|
method_configs["gaussian-splatting"] = TrainerConfig(
|
||||||
method_name="gaussian-splatting",
|
method_name="gaussian-splatting",
|
||||||
steps_per_eval_image=10,
|
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
|
steps_per_eval_all_images=1000000, # set to a very large model so we don't eval with all images
|
||||||
max_num_iterations=30000,
|
max_num_iterations=30000,
|
||||||
mixed_precision=False,
|
mixed_precision=False,
|
||||||
gradient_accumulation_steps=1,
|
gradient_accumulation_steps = {'camera_opt': 100},
|
||||||
pipeline=VanillaPipelineConfig(
|
pipeline=VanillaPipelineConfig(
|
||||||
datamanager=FullImageDatamanagerConfig(
|
datamanager=FullImageDatamanagerConfig(
|
||||||
dataparser=ColmapDataParserConfig(load_3D_points=True),
|
dataparser=ColmapDataParserConfig(load_3D_points=True),
|
||||||
@@ -618,7 +619,7 @@ method_configs["gaussian-splatting"] = TrainerConfig(
|
|||||||
"optimizer": AdamOptimizerConfig(lr=1.6e-4, eps=1e-15),
|
"optimizer": AdamOptimizerConfig(lr=1.6e-4, eps=1e-15),
|
||||||
"scheduler": ExponentialDecaySchedulerConfig(
|
"scheduler": ExponentialDecaySchedulerConfig(
|
||||||
lr_final=1.6e-6,
|
lr_final=1.6e-6,
|
||||||
max_steps=15000,
|
max_steps=30000,
|
||||||
),
|
),
|
||||||
},
|
},
|
||||||
"color": {
|
"color": {
|
||||||
@@ -641,17 +642,15 @@ method_configs["gaussian-splatting"] = TrainerConfig(
|
|||||||
},
|
},
|
||||||
"scaling": {
|
"scaling": {
|
||||||
"optimizer": AdamOptimizerConfig(lr=0.005, eps=1e-15),
|
"optimizer": AdamOptimizerConfig(lr=0.005, eps=1e-15),
|
||||||
"scheduler": ExponentialDecaySchedulerConfig(
|
"scheduler": None
|
||||||
lr_final=1e-3,
|
|
||||||
max_steps=15000,
|
|
||||||
),
|
|
||||||
},
|
},
|
||||||
"rotation": {
|
"rotation": {
|
||||||
"optimizer": AdamOptimizerConfig(lr=0.001, eps=1e-15),
|
"optimizer": AdamOptimizerConfig(lr=0.001, eps=1e-15),
|
||||||
"scheduler": ExponentialDecaySchedulerConfig(
|
"scheduler": None
|
||||||
lr_final=1e-4,
|
},
|
||||||
max_steps=15000,
|
"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),
|
viewer=ViewerConfig(num_rays_per_chunk=1 << 15),
|
||||||
|
|||||||
@@ -141,22 +141,26 @@ class FullImageDatamanager(DataManager, Generic[TDataset]):
|
|||||||
0,
|
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)
|
image = cv2.undistort(image, K, distortion_params, None, newK)
|
||||||
#crop the image and update the intrinsics accordingly
|
# crop the image and update the intrinsics accordingly
|
||||||
x,y,w,h = roi
|
x, y, w, h = roi
|
||||||
image = image[y:y+h,x:x+w]
|
image = image[y : y + h, x : x + w]
|
||||||
K = newK
|
K = newK
|
||||||
#update the width, height
|
# update the width, height
|
||||||
self.train_dataset.cameras.width[i] = w
|
self.train_dataset.cameras.width[i] = w
|
||||||
self.train_dataset.cameras.height[i] = h
|
self.train_dataset.cameras.height[i] = h
|
||||||
|
|
||||||
elif camera.camera_type.item() == CameraType.FISHEYE.value:
|
elif camera.camera_type.item() == CameraType.FISHEYE.value:
|
||||||
distortion_params = np.array(
|
distortion_params = np.array(
|
||||||
[distortion_params[0], distortion_params[1], distortion_params[2], distortion_params[3]]
|
[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)
|
newK = cv2.fisheye.estimateNewCameraMatrixForUndistortRectify(
|
||||||
map1, map2 = cv2.fisheye.initUndistortRectifyMap(K, distortion_params, np.eye(3), newK, (image.shape[1],image.shape[0]), cv2.CV_32FC1)
|
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:
|
# and then remap:
|
||||||
image = cv2.remap(image, map1, map2, interpolation=cv2.INTER_LINEAR, borderMode=cv2.BORDER_CONSTANT)
|
image = cv2.remap(image, map1, map2, interpolation=cv2.INTER_LINEAR, borderMode=cv2.BORDER_CONSTANT)
|
||||||
K = newK
|
K = newK
|
||||||
@@ -204,21 +208,25 @@ class FullImageDatamanager(DataManager, Generic[TDataset]):
|
|||||||
0,
|
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)
|
image = cv2.undistort(image, K, distortion_params, None, newK)
|
||||||
#crop the image and update the intrinsics accordingly
|
# crop the image and update the intrinsics accordingly
|
||||||
x,y,w,h = roi
|
x, y, w, h = roi
|
||||||
image = image[y:y+h,x:x+w]
|
image = image[y : y + h, x : x + w]
|
||||||
K = newK
|
K = newK
|
||||||
#update the width, height
|
# update the width, height
|
||||||
self.train_dataset.cameras.width[i] = w
|
self.train_dataset.cameras.width[i] = w
|
||||||
self.train_dataset.cameras.height[i] = h
|
self.train_dataset.cameras.height[i] = h
|
||||||
elif camera.camera_type.item() == CameraType.FISHEYE.value:
|
elif camera.camera_type.item() == CameraType.FISHEYE.value:
|
||||||
distortion_params = np.array(
|
distortion_params = np.array(
|
||||||
[distortion_params[0], distortion_params[1], distortion_params[2], distortion_params[3]]
|
[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)
|
newK = cv2.fisheye.estimateNewCameraMatrixForUndistortRectify(
|
||||||
map1, map2 = cv2.fisheye.initUndistortRectifyMap(K, distortion_params, np.eye(3), newK, (image.shape[1],image.shape[0]), cv2.CV_32FC1)
|
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:
|
# and then remap:
|
||||||
image = cv2.remap(image, map1, map2, interpolation=cv2.INTER_LINEAR, borderMode=cv2.BORDER_CONSTANT)
|
image = cv2.remap(image, map1, map2, interpolation=cv2.INTER_LINEAR, borderMode=cv2.BORDER_CONSTANT)
|
||||||
K = newK
|
K = newK
|
||||||
@@ -325,10 +333,12 @@ class FullImageDatamanager(DataManager, Generic[TDataset]):
|
|||||||
|
|
||||||
data = deepcopy(self.cached_train[image_idx])
|
data = deepcopy(self.cached_train[image_idx])
|
||||||
data["image"] = data["image"].to(self.device)
|
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"
|
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)
|
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
|
return camera, data
|
||||||
|
|
||||||
def next_eval(self, step: int) -> Tuple[Cameras, Dict]:
|
def next_eval(self, step: int) -> Tuple[Cameras, Dict]:
|
||||||
|
|||||||
@@ -135,6 +135,12 @@ class Optimizers:
|
|||||||
for _, optimizer in self.optimizers.items():
|
for _, optimizer in self.optimizers.items():
|
||||||
optimizer.zero_grad()
|
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:
|
def optimizer_scaler_step_all(self, grad_scaler: GradScaler) -> None:
|
||||||
"""Take an optimizer step using a grad scaler.
|
"""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):
|
if any(any(p.grad is not None for p in g["params"]) for g in optimizer.param_groups):
|
||||||
grad_scaler.step(optimizer)
|
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:
|
def optimizer_step_all(self) -> None:
|
||||||
"""Run step for all optimizers."""
|
"""Run step for all optimizers."""
|
||||||
for param_group, optimizer in self.optimizers.items():
|
for param_group, optimizer in self.optimizers.items():
|
||||||
|
|||||||
@@ -24,8 +24,8 @@ import time
|
|||||||
from dataclasses import dataclass, field
|
from dataclasses import dataclass, field
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
from threading import Lock
|
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
|
import torch
|
||||||
from nerfstudio.configs.experiment_config import ExperimentConfig
|
from nerfstudio.configs.experiment_config import ExperimentConfig
|
||||||
from nerfstudio.data.datamanagers.base_datamanager import VanillaDataManager
|
from nerfstudio.data.datamanagers.base_datamanager import VanillaDataManager
|
||||||
@@ -81,8 +81,8 @@ class TrainerConfig(ExperimentConfig):
|
|||||||
"""Path to checkpoint file."""
|
"""Path to checkpoint file."""
|
||||||
log_gradients: bool = False
|
log_gradients: bool = False
|
||||||
"""Optionally log gradients during training"""
|
"""Optionally log gradients during training"""
|
||||||
gradient_accumulation_steps: int = 1
|
gradient_accumulation_steps: Dict = field(default_factory=lambda: {})
|
||||||
"""Number of steps to accumulate gradients over."""
|
"""Number of steps to accumulate gradients over. Contains a mapping of {param_group:num}"""
|
||||||
|
|
||||||
|
|
||||||
class Trainer:
|
class Trainer:
|
||||||
@@ -119,7 +119,8 @@ class Trainer:
|
|||||||
self.mixed_precision: bool = self.config.mixed_precision
|
self.mixed_precision: bool = self.config.mixed_precision
|
||||||
self.use_grad_scaler: bool = self.mixed_precision or self.config.use_grad_scaler
|
self.use_grad_scaler: bool = self.mixed_precision or self.config.use_grad_scaler
|
||||||
self.training_state: Literal["training", "paused", "completed"] = "training"
|
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":
|
if self.device == "cpu":
|
||||||
self.mixed_precision = False
|
self.mixed_precision = False
|
||||||
@@ -462,18 +463,26 @@ class Trainer:
|
|||||||
step: Current training step.
|
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]
|
cpu_or_cuda_str: str = self.device.split(":")[0]
|
||||||
assert (
|
# assert (
|
||||||
self.gradient_accumulation_steps > 0
|
# self.gradient_accumulation_steps > 0
|
||||||
), f"gradient_accumulation_steps must be > 0, not {self.gradient_accumulation_steps}"
|
# ), f"gradient_accumulation_steps must be > 0, not {self.gradient_accumulation_steps}"
|
||||||
for _ in range(self.gradient_accumulation_steps):
|
# for _ in range(self.gradient_accumulation_steps):
|
||||||
with torch.autocast(device_type=cpu_or_cuda_str, enabled=self.mixed_precision):
|
# 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_dict, metrics_dict = self.pipeline.get_train_loss_dict(step=step)
|
||||||
loss = functools.reduce(torch.add, loss_dict.values())
|
# loss = functools.reduce(torch.add, loss_dict.values())
|
||||||
loss /= self.gradient_accumulation_steps
|
# loss /= self.gradient_accumulation_steps
|
||||||
self.grad_scaler.scale(loss).backward() # type: ignore
|
# self.grad_scaler.scale(loss).backward() # type: ignore
|
||||||
self.optimizers.optimizer_scaler_step_all(self.grad_scaler)
|
# 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:
|
if self.config.log_gradients:
|
||||||
total_grad = 0
|
total_grad = 0
|
||||||
|
|||||||
@@ -567,6 +567,22 @@ def scale_gradients_by_distance_squared(
|
|||||||
out[key], _ = cast(Tuple[Tensor, Tensor], _GradientScaler.apply(value, scaling))
|
out[key], _ = cast(Tuple[Tensor, Tensor], _GradientScaler.apply(value, scaling))
|
||||||
return out
|
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):
|
def depth_ranking_loss(rendered_depth, gt_depth):
|
||||||
"""
|
"""
|
||||||
|
|||||||
@@ -36,8 +36,10 @@ import math
|
|||||||
import numpy as np
|
import numpy as np
|
||||||
from sklearn.neighbors import NearestNeighbors
|
from sklearn.neighbors import NearestNeighbors
|
||||||
import viser.transforms as vtf
|
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.rasterize import RasterizeGaussians
|
||||||
from gsplat.project_gaussians import ProjectGaussians
|
from gsplat.project_gaussians import ProjectGaussians
|
||||||
from gsplat.sh import SphericalHarmonics, num_sh_bases
|
from gsplat.sh import SphericalHarmonics, num_sh_bases
|
||||||
@@ -63,7 +65,7 @@ def RGB2SH(rgb):
|
|||||||
return (rgb - 0.5) / C0
|
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)
|
t = znear * math.tan(0.5 * fovy)
|
||||||
b = -t
|
b = -t
|
||||||
r = znear * math.tan(0.5 * fovx)
|
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, (f + n) / (f - n), -1.0 * f * n / (f - n)],
|
||||||
[0.0, 0.0, 1.0, 0.0],
|
[0.0, 0.0, 1.0, 0.0],
|
||||||
],
|
],
|
||||||
**kwargs,
|
device=device,
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
@@ -86,17 +88,17 @@ class GaussianSplattingModelConfig(ModelConfig):
|
|||||||
"""Gaussian Splatting Model Config"""
|
"""Gaussian Splatting Model Config"""
|
||||||
|
|
||||||
_target: Type = field(default_factory=lambda: GaussianSplattingModel)
|
_target: Type = field(default_factory=lambda: GaussianSplattingModel)
|
||||||
warmup_length: int = 1000
|
warmup_length: int = 500
|
||||||
"""period of steps where refinement is turned off"""
|
"""period of steps where refinement is turned off"""
|
||||||
refine_every: int = 100
|
refine_every: int = 100
|
||||||
"""period of steps where gaussians are culled and densified"""
|
"""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"""
|
"""training starts at 1/d resolution, every n steps this is doubled"""
|
||||||
num_downscales: int = 2
|
num_downscales: int = 2
|
||||||
"""at the beginning, resolution is 1/2^d, where d is this number"""
|
"""at the beginning, resolution is 1/2^d, where d is this number"""
|
||||||
cull_alpha_thresh: float = 0.01
|
cull_alpha_thresh: float = 0.01
|
||||||
"""threshold of opacity for culling gaussians"""
|
"""threshold of opacity for culling gaussians"""
|
||||||
cull_scale_thresh: float = 0.5
|
cull_scale_thresh: float = 0.1
|
||||||
"""threshold of scale for culling gaussians"""
|
"""threshold of scale for culling gaussians"""
|
||||||
reset_alpha_every: int = 30
|
reset_alpha_every: int = 30
|
||||||
"""Every this many refinement steps, reset the alpha"""
|
"""Every this many refinement steps, reset the alpha"""
|
||||||
@@ -104,18 +106,26 @@ class GaussianSplattingModelConfig(ModelConfig):
|
|||||||
"""threshold of positional gradient norm for densifying gaussians"""
|
"""threshold of positional gradient norm for densifying gaussians"""
|
||||||
densify_size_thresh: float = 0.01
|
densify_size_thresh: float = 0.01
|
||||||
"""below this size, gaussians are *duplicated*, otherwise split"""
|
"""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"""
|
"""every n intervals turn on another sh degree"""
|
||||||
max_screen_size: int = 150
|
cull_screen_size: int = 150
|
||||||
"""maximum screen size of a gaussian, in pixels"""
|
"""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
|
random_init: bool = False
|
||||||
"""whether to initialize the positions uniformly randomly (not SFM points)"""
|
"""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
|
ssim_lambda: float = 0.2
|
||||||
"""weight of ssim loss"""
|
"""weight of ssim loss"""
|
||||||
stop_split_at: int = 25000
|
stop_split_at: int = 25000
|
||||||
"""stop splitting at this step"""
|
"""stop splitting at this step"""
|
||||||
sh_degree: int = 4
|
sh_degree: int = 4
|
||||||
"""maximum degree of spherical harmonics to use"""
|
"""maximum degree of spherical harmonics to use"""
|
||||||
|
camera_optimizer: CameraOptimizerConfig = CameraOptimizerConfig(mode="off")
|
||||||
|
"""camera optimizer config"""
|
||||||
|
|
||||||
|
|
||||||
class GaussianSplattingModel(Model):
|
class GaussianSplattingModel(Model):
|
||||||
@@ -136,9 +146,10 @@ class GaussianSplattingModel(Model):
|
|||||||
|
|
||||||
def populate_modules(self):
|
def populate_modules(self):
|
||||||
if self.seed_pts is not None and not self.config.random_init:
|
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:
|
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.xys_grad_norm = None
|
||||||
self.max_2Dsize = None
|
self.max_2Dsize = None
|
||||||
distances, _ = self.k_nearest_sklearn(self.means.data, 3)
|
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
|
# 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)
|
avg_dist = distances.mean(dim=-1, keepdim=True)
|
||||||
self.scales = torch.nn.Parameter(torch.log(avg_dist.repeat(1, 3)))
|
self.scales = torch.nn.Parameter(torch.log(avg_dist.repeat(1, 3)))
|
||||||
|
|
||||||
self.quats = torch.nn.Parameter(random_quat_tensor(self.num_points))
|
self.quats = torch.nn.Parameter(random_quat_tensor(self.num_points))
|
||||||
dim_sh = num_sh_bases(self.config.sh_degree)
|
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 = torch.zeros((fused_color.shape[0], 3, dim_sh)).float().cuda()
|
||||||
shs[:, :3, 0] = fused_color
|
shs[:, :3, 0] = fused_color
|
||||||
shs[:, 3:, 1:] = 0.0
|
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.colors = torch.nn.Parameter(shs[:, :, 0:1])
|
||||||
self.shs_rest = torch.nn.Parameter(shs[:, :, 1:])
|
self.shs_rest = torch.nn.Parameter(shs[:, :, 1:])
|
||||||
else:
|
else:
|
||||||
@@ -164,7 +178,6 @@ class GaussianSplattingModel(Model):
|
|||||||
self.opacities = torch.nn.Parameter(torch.logit(0.1 * torch.ones(self.num_points, 1)))
|
self.opacities = torch.nn.Parameter(torch.logit(0.1 * torch.ones(self.num_points, 1)))
|
||||||
# metrics
|
# metrics
|
||||||
self.psnr = PeakSignalNoiseRatio(data_range=1.0)
|
self.psnr = PeakSignalNoiseRatio(data_range=1.0)
|
||||||
from torchmetrics.image import StructuralSimilarityIndexMeasure
|
|
||||||
|
|
||||||
self.ssim = StructuralSimilarityIndexMeasure()
|
self.ssim = StructuralSimilarityIndexMeasure()
|
||||||
self.lpips = LearnedPerceptualImagePatchSimilarity(normalize=True)
|
self.lpips = LearnedPerceptualImagePatchSimilarity(normalize=True)
|
||||||
@@ -172,6 +185,10 @@ class GaussianSplattingModel(Model):
|
|||||||
self.crop_box: Optional[OrientedBox] = None
|
self.crop_box: Optional[OrientedBox] = None
|
||||||
self.back_color = torch.zeros(3)
|
self.back_color = torch.zeros(3)
|
||||||
|
|
||||||
|
self.camera_optimizer: CameraOptimizer = self.config.camera_optimizer.setup(
|
||||||
|
num_cameras=self.num_train_data, device="cpu"
|
||||||
|
)
|
||||||
|
|
||||||
@property
|
@property
|
||||||
def get_colors(self):
|
def get_colors(self):
|
||||||
color = self.colors
|
color = self.colors
|
||||||
@@ -213,7 +230,7 @@ class GaussianSplattingModel(Model):
|
|||||||
def remove_from_optim(self, optimizer, deleted_mask, new_params):
|
def remove_from_optim(self, optimizer, deleted_mask, new_params):
|
||||||
"""removes the deleted_mask from the optimizer provided"""
|
"""removes the deleted_mask from the optimizer provided"""
|
||||||
assert len(new_params) == 1
|
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 = optimizer.param_groups[0]["params"][0]
|
||||||
param_state = optimizer.state[param]
|
param_state = optimizer.state[param]
|
||||||
@@ -266,7 +283,7 @@ class GaussianSplattingModel(Model):
|
|||||||
# update the max screen size
|
# update the max screen size
|
||||||
if self.max_2Dsize is None:
|
if self.max_2Dsize is None:
|
||||||
self.max_2Dsize = torch.zeros_like(self.radii)
|
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)
|
self.max_2Dsize[visible_mask] = torch.maximum(self.max_2Dsize[visible_mask], newradii)
|
||||||
|
|
||||||
def set_crop(self, crop_box: OrientedBox):
|
def set_crop(self, crop_box: OrientedBox):
|
||||||
@@ -277,7 +294,7 @@ class GaussianSplattingModel(Model):
|
|||||||
self.back_color = back_color
|
self.back_color = back_color
|
||||||
|
|
||||||
def refinement_after(self, optimizers: Optimizers, step):
|
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():
|
with torch.no_grad():
|
||||||
if self.step < self.config.stop_split_at:
|
if self.step < self.config.stop_split_at:
|
||||||
# then we densify
|
# then we densify
|
||||||
@@ -286,8 +303,9 @@ class GaussianSplattingModel(Model):
|
|||||||
)
|
)
|
||||||
high_grads = (avg_grad_norm > self.config.densify_grad_thresh).squeeze()
|
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.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
|
splits &= high_grads
|
||||||
nsamps = 2
|
nsamps = self.config.n_split_samples
|
||||||
(
|
(
|
||||||
split_means,
|
split_means,
|
||||||
split_colors,
|
split_colors,
|
||||||
@@ -314,12 +332,12 @@ class GaussianSplattingModel(Model):
|
|||||||
dim=0,
|
dim=0,
|
||||||
)
|
)
|
||||||
split_idcs = torch.where(splits)[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():
|
for group, param in param_groups.items():
|
||||||
self.dup_in_optim(optimizers.optimizers[group], split_idcs, param, n=nsamps)
|
self.dup_in_optim(optimizers.optimizers[group], split_idcs, param, n=nsamps)
|
||||||
dup_idcs = torch.where(dups)[0]
|
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():
|
for group, param in param_groups.items():
|
||||||
self.dup_in_optim(optimizers.optimizers[group], dup_idcs, param, 1)
|
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:
|
if self.step % reset_interval > self.num_train_data:
|
||||||
# then cull
|
# then cull
|
||||||
deleted_mask = self.cull_gaussians()
|
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():
|
for group, param in param_groups.items():
|
||||||
self.remove_from_optim(optimizers.optimizers[group], deleted_mask, param)
|
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
|
reset_value = 0.01
|
||||||
self.opacities.data = torch.full_like(
|
self.opacities.data = torch.full_like(
|
||||||
self.opacities.data, torch.logit(torch.tensor(reset_value)).item()
|
self.opacities.data, torch.logit(torch.tensor(reset_value)).item()
|
||||||
@@ -358,8 +376,9 @@ class GaussianSplattingModel(Model):
|
|||||||
# cull huge ones
|
# cull huge ones
|
||||||
toobigs = (torch.exp(self.scales).max(dim=-1).values > self.config.cull_scale_thresh).squeeze()
|
toobigs = (torch.exp(self.scales).max(dim=-1).values > self.config.cull_scale_thresh).squeeze()
|
||||||
culls = culls | toobigs
|
culls = culls | toobigs
|
||||||
# cull big screen space
|
if self.step < self.config.stop_split_at:
|
||||||
culls = culls | (self.max_2Dsize > self.config.max_screen_size).squeeze()
|
# cull big screen space
|
||||||
|
culls = culls | (self.max_2Dsize > self.config.cull_screen_size).squeeze()
|
||||||
self.means = Parameter(self.means[~culls].detach())
|
self.means = Parameter(self.means[~culls].detach())
|
||||||
self.scales = Parameter(self.scales[~culls].detach())
|
self.scales = Parameter(self.scales[~culls].detach())
|
||||||
self.quats = Parameter(self.quats[~culls].detach())
|
self.quats = Parameter(self.quats[~culls].detach())
|
||||||
@@ -392,8 +411,9 @@ class GaussianSplattingModel(Model):
|
|||||||
# step 3, sample new opacities
|
# step 3, sample new opacities
|
||||||
new_opacities = self.opacities[split_mask].repeat(samps, 1)
|
new_opacities = self.opacities[split_mask].repeat(samps, 1)
|
||||||
# step 4, sample new scales
|
# step 4, sample new scales
|
||||||
new_scales = torch.log(torch.exp(self.scales[split_mask]) / 1.6).repeat(samps, 1)
|
size_fac = 1.6
|
||||||
self.scales[split_mask] = torch.log(torch.exp(self.scales[split_mask]) / 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
|
# step 5, sample new quats
|
||||||
new_quats = self.quats[split_mask].repeat(samps, 1)
|
new_quats = self.quats[split_mask].repeat(samps, 1)
|
||||||
return new_means, new_colors, new_shs, new_opacities, new_scales, new_quats
|
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):
|
def step_cb(self, step):
|
||||||
self.step = step
|
self.step = step
|
||||||
|
|
||||||
def get_param_groups(self) -> Dict[str, List[Parameter]]:
|
def get_gaussian_param_groups(self) -> Dict[str, List[Parameter]]:
|
||||||
"""Obtain the parameter groups for the optimizers
|
|
||||||
|
|
||||||
Returns:
|
|
||||||
Mapping of different parameter groups
|
|
||||||
"""
|
|
||||||
return {
|
return {
|
||||||
"xyz": [self.means],
|
"xyz": [self.means],
|
||||||
"color": [self.colors],
|
"color": [self.colors],
|
||||||
@@ -456,6 +471,17 @@ class GaussianSplattingModel(Model):
|
|||||||
"rotation": [self.quats],
|
"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):
|
def _get_downscale_factor(self):
|
||||||
return 2 ** max((self.config.num_downscales - self.step // self.config.resolution_schedule), 0)
|
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"
|
assert camera.shape[0] == 1, "Only one camera at a time"
|
||||||
# dont mutate the input
|
# dont mutate the input
|
||||||
camera = deepcopy(camera)
|
camera = deepcopy(camera)
|
||||||
|
if self.training:
|
||||||
|
#currently relies on the branch vickie/camera-grads
|
||||||
|
self.camera_optimizer.apply_to_camera(camera)
|
||||||
if self.training:
|
if self.training:
|
||||||
d = self._get_downscale_factor()
|
d = self._get_downscale_factor()
|
||||||
camera.rescale_output_resolution(1 / d)
|
camera.rescale_output_resolution(1 / d)
|
||||||
@@ -483,18 +512,19 @@ class GaussianSplattingModel(Model):
|
|||||||
if crop_ids.sum() == 0:
|
if crop_ids.sum() == 0:
|
||||||
return {"rgb": torch.full((camera.height.item(), camera.width.item(), 3), 0.5, device=self.device)}
|
return {"rgb": torch.full((camera.height.item(), camera.width.item(), 3), 0.5, device=self.device)}
|
||||||
else:
|
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
|
# shift the camera to center of scene looking at center
|
||||||
R = camera.camera_to_worlds[..., :3, :3] # 1 x 3 x 3
|
R = camera.camera_to_worlds[0, :3, :3] # 3 x 3
|
||||||
T = camera.camera_to_worlds[..., :3, 3:4] # 1 x 3 x 1
|
T = camera.camera_to_worlds[0, :3, 3:4] # 3 x 1
|
||||||
R = vtf.SO3.from_matrix(R.cpu().squeeze().numpy())
|
# flip the z axis to align with gsplat conventions
|
||||||
R = R @ vtf.SO3.from_x_radians(np.pi)
|
R_edit = torch.tensor(vtf.SO3.from_x_radians(np.pi).as_matrix(), device=R.device, dtype=R.dtype)
|
||||||
R = torch.from_numpy(R.as_matrix()[None, ...]).to(self.device, torch.float32)
|
R = R @ R_edit
|
||||||
viewmat = torch.cat([R, T], dim=2)
|
# analytic matrix inverse to get world2camera matrix
|
||||||
# add a row of zeros and a 1 to the bottom of the viewmat
|
R_inv = R.T
|
||||||
viewmat = torch.cat([viewmat, torch.tensor([[[0, 0, 0, 1]]], device=self.device)], dim=1)
|
T_inv = -R_inv @ T
|
||||||
# invert it
|
viewmat = torch.eye(4, device=R.device, dtype=R.dtype)
|
||||||
viewmat = torch.inverse(viewmat)
|
viewmat[:3, :3] = R_inv
|
||||||
|
viewmat[:3, 3:4] = T_inv
|
||||||
# calculate the FOV of the camera given fx and fy, width and height
|
# calculate the FOV of the camera given fx and fy, width and height
|
||||||
cx = camera.cx.item()
|
cx = camera.cx.item()
|
||||||
cy = camera.cy.item()
|
cy = camera.cy.item()
|
||||||
@@ -502,7 +532,7 @@ class GaussianSplattingModel(Model):
|
|||||||
fovy = 2 * math.atan(camera.height / (2 * camera.fy))
|
fovy = 2 * math.atan(camera.height / (2 * camera.fy))
|
||||||
W, H = camera.width.item(), camera.height.item()
|
W, H = camera.width.item(), camera.height.item()
|
||||||
self.last_size = (H, W)
|
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
|
BLOCK_X, BLOCK_Y = 16, 16
|
||||||
tile_bounds = (
|
tile_bounds = (
|
||||||
(W + BLOCK_X - 1) // BLOCK_X,
|
(W + BLOCK_X - 1) // BLOCK_X,
|
||||||
@@ -514,14 +544,24 @@ class GaussianSplattingModel(Model):
|
|||||||
else:
|
else:
|
||||||
background = self.back_color
|
background = self.back_color
|
||||||
|
|
||||||
opacities_crop = self.opacities[crop_ids]
|
|
||||||
means_crop = self.means[crop_ids]
|
if crop_ids is not None:
|
||||||
colors_crop = self.get_colors[crop_ids]
|
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.xys, depths, self.radii, conics, num_tiles_hit, cov3d = ProjectGaussians.apply(
|
||||||
self.means[crop_ids],
|
means_crop,
|
||||||
torch.exp(self.scales[crop_ids]),
|
torch.exp(scales_crop),
|
||||||
1,
|
1,
|
||||||
self.quats[crop_ids],
|
quats_crop / quats_crop.norm(dim=-1, keepdim=True),
|
||||||
viewmat.squeeze()[:3, :],
|
viewmat.squeeze()[:3, :],
|
||||||
projmat.squeeze() @ viewmat.squeeze(),
|
projmat.squeeze() @ viewmat.squeeze(),
|
||||||
camera.fx.item(),
|
camera.fx.item(),
|
||||||
@@ -532,45 +572,50 @@ class GaussianSplattingModel(Model):
|
|||||||
W,
|
W,
|
||||||
tile_bounds,
|
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
|
# Important to allow xys grads to populate properly
|
||||||
if self.training:
|
if self.training:
|
||||||
self.xys.retain_grad()
|
self.xys.retain_grad()
|
||||||
rend_mask = self.radii > 0
|
|
||||||
if self.config.sh_degree > 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)
|
viewdirs = viewdirs / viewdirs.norm(dim=-1, keepdim=True)
|
||||||
n = min(self.step // self.config.sh_degree_interval, self.config.sh_degree)
|
n = min(self.step // self.config.sh_degree_interval, self.config.sh_degree)
|
||||||
n_coeffs = num_sh_bases(n)
|
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 = SphericalHarmonics.apply(n, viewdirs, coeffs)
|
||||||
rgbs = torch.clamp(rgbs + 0.5, 0.0, 1.0)
|
rgbs = torch.clamp(rgbs + 0.5, 0.0, 1.0)
|
||||||
else:
|
else:
|
||||||
rgbs = self.get_colors.squeeze()[rend_mask] # (N, 3)
|
rgbs = self.get_colors.squeeze() # (N, 3)
|
||||||
rgbs = torch.sigmoid(rgbs)
|
rgbs = torch.sigmoid(rgbs)
|
||||||
rgb = RasterizeGaussians.apply(
|
rgb = RasterizeGaussians.apply(
|
||||||
self.xys[rend_mask],
|
self.xys,
|
||||||
depths[rend_mask],
|
depths,
|
||||||
self.radii[rend_mask],
|
self.radii,
|
||||||
conics[rend_mask],
|
conics,
|
||||||
num_tiles_hit[rend_mask],
|
num_tiles_hit,
|
||||||
rgbs,
|
rgbs,
|
||||||
torch.sigmoid(opacities_crop[rend_mask]),
|
torch.sigmoid(opacities_crop),
|
||||||
H,
|
H,
|
||||||
W,
|
W,
|
||||||
background,
|
background,
|
||||||
)
|
)
|
||||||
depth_im = RasterizeGaussians.apply(
|
depth_im = None
|
||||||
self.xys[rend_mask],
|
if not self.training:
|
||||||
depths[rend_mask],
|
depth_im = RasterizeGaussians.apply(
|
||||||
self.radii[rend_mask],
|
self.xys,
|
||||||
conics[rend_mask],
|
depths,
|
||||||
num_tiles_hit[rend_mask],
|
self.radii,
|
||||||
depths[rend_mask, None].repeat(1, 3),
|
conics,
|
||||||
torch.sigmoid(opacities_crop[rend_mask]),
|
num_tiles_hit,
|
||||||
H,
|
depths[:, None].repeat(1, 3),
|
||||||
W,
|
torch.sigmoid(opacities_crop),
|
||||||
torch.ones(3, device=self.device) * 10,
|
H,
|
||||||
)[..., 0:1]
|
W,
|
||||||
|
torch.ones(3, device=self.device) * 10,
|
||||||
|
)[..., 0:1]
|
||||||
return {"rgb": rgb, "depth": depth_im}
|
return {"rgb": rgb, "depth": depth_im}
|
||||||
|
|
||||||
def get_metrics_dict(self, outputs, batch) -> Dict[str, torch.Tensor]:
|
def get_metrics_dict(self, outputs, batch) -> Dict[str, torch.Tensor]:
|
||||||
|
|||||||
@@ -261,10 +261,13 @@ class VanillaPipeline(Pipeline):
|
|||||||
)
|
)
|
||||||
# TODO make cleaner
|
# TODO make cleaner
|
||||||
seed_pts = None
|
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 = self.datamanager.train_dataparser_outputs.metadata["points3D_xyz"]
|
||||||
pts_rgb = self.datamanager.train_dataparser_outputs.metadata["points3D_rgb"]
|
pts_rgb = self.datamanager.train_dataparser_outputs.metadata["points3D_rgb"]
|
||||||
seed_pts = (pts,pts_rgb)
|
seed_pts = (pts, pts_rgb)
|
||||||
self.datamanager.to(device)
|
self.datamanager.to(device)
|
||||||
# TODO(ethan): get rid of scene_bounds from the model
|
# TODO(ethan): get rid of scene_bounds from the model
|
||||||
assert self.datamanager.train_dataset is not None, "Missing input dataset"
|
assert self.datamanager.train_dataset is not None, "Missing input dataset"
|
||||||
|
|||||||
@@ -208,7 +208,7 @@ class RenderStateMachine(threading.Thread):
|
|||||||
except viewer_utils.IOChangeException:
|
except viewer_utils.IOChangeException:
|
||||||
# if we got interrupted, don't send the output to the viewer
|
# if we got interrupted, don't send the output to the viewer
|
||||||
continue
|
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):
|
def check_interrupt(self, frame, event, arg):
|
||||||
"""Raises interrupt when flag has been set and not already on lowest resolution.
|
"""Raises interrupt when flag has been set and not already on lowest resolution.
|
||||||
|
|||||||
Reference in new issue
Block a user