From 383a6075ccc0f7466857af999798d51ac6499ccb Mon Sep 17 00:00:00 2001 From: Ethan Weber Date: Sun, 25 Sep 2022 16:56:29 -0700 Subject: [PATCH] [wip] proposal network sampler (#534) * initial running code * dozer and poster 6K experiments * code reorganization * removed print * black --- nerfactory/configs/base_configs.py | 20 ++ nerfactory/fields/density_field.py | 112 +++++++++++ nerfactory/fields/instant_ngp_field.py | 11 +- nerfactory/models/base.py | 26 +-- nerfactory/models/modules/ray_sampler.py | 67 ++++++- nerfactory/models/modules/scene_colliders.py | 14 +- nerfactory/models/proposal.py | 188 +++++++++++++++++++ nerfactory/optimizers/loss.py | 100 +++++++++- nerfactory/pipelines/base.py | 11 +- tests/test_run_train.py | 2 +- 10 files changed, 515 insertions(+), 36 deletions(-) create mode 100644 nerfactory/fields/density_field.py create mode 100644 nerfactory/models/proposal.py diff --git a/nerfactory/configs/base_configs.py b/nerfactory/configs/base_configs.py index b240af494..00b49eddc 100644 --- a/nerfactory/configs/base_configs.py +++ b/nerfactory/configs/base_configs.py @@ -45,6 +45,7 @@ from nerfactory.models.instant_ngp import InstantNGPModelConfig from nerfactory.models.mipnerf import MipNerfModel from nerfactory.models.mipnerf_360 import MipNerf360Model from nerfactory.models.nerfw import NerfWModelConfig +from nerfactory.models.proposal import ProposalModelConfig from nerfactory.models.semantic_nerf import SemanticNerfModel from nerfactory.models.tensorf import TensoRFModelConfig from nerfactory.models.vanilla_nerf import NeRFModel @@ -86,6 +87,25 @@ base_configs["instant-ngp"] = Config( logging=LoggingConfig(event_writer="none"), ) +base_configs["proposal"] = Config( + method_name="proposal", + trainer=TrainerConfig(steps_per_eval_batch=500, steps_per_save=2000, mixed_precision=True), + pipeline=VanillaPipelineConfig( + datamanager=VanillaDataManagerConfig( + dataparser=BlenderDataParserConfig(), train_num_rays_per_batch=8192, eval_num_rays_per_batch=8192 + ), + model=ProposalModelConfig(eval_num_rays_per_chunk=8192), + ), + optimizers={ + "fields": { + "optimizer": AdamOptimizerConfig(lr=1e-2, eps=1e-15), + "scheduler": None, + } + }, + viewer=ViewerConfig(enable=True), + logging=LoggingConfig(event_writer="none"), +) + base_configs["mipnerf-360"] = Config( method_name="mipnerf-360", trainer=TrainerConfig(steps_per_eval_batch=200), diff --git a/nerfactory/fields/density_field.py b/nerfactory/fields/density_field.py new file mode 100644 index 000000000..410fd0323 --- /dev/null +++ b/nerfactory/fields/density_field.py @@ -0,0 +1,112 @@ +# Copyright 2022 The Plenoptix Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +""" +Proposal network field. +""" + + +from typing import Optional + +import numpy as np +from torch.nn.parameter import Parameter +from torchtyping import TensorType + +from nerfactory.cameras.rays import RaySamples +from nerfactory.datamanagers.structs import SceneBounds +from nerfactory.fields.base import Field +from nerfactory.fields.modules.spatial_distortions import SpatialDistortion +from nerfactory.utils.activations import trunc_exp + +try: + import tinycudann as tcnn +except ImportError: + # tinycudann module doesn't exist + pass + + +class DensityField(Field): + """A lightweight density field module. + + Args: + aabb: parameters of scene aabb bounds + num_layers: number of hidden layers + hidden_dim: dimension of hidden layers + spatial_distortion: spatial distortion module + """ + + def __init__( + self, aabb, num_layers: int = 2, hidden_dim: int = 64, spatial_distortion: Optional[SpatialDistortion] = None + ) -> None: + super().__init__() + + self.aabb = Parameter(aabb, requires_grad=False) + self.spatial_distortion = spatial_distortion + + num_levels = 16 + # max_res = 2048 + max_res = 4096 + base_res = 16 + growth_factor = np.exp((np.log(max_res) - np.log(base_res)) / (num_levels - 1)) + + self.direction_encoding = tcnn.Encoding( + n_input_dims=3, + encoding_config={ + "otype": "SphericalHarmonics", + "degree": 4, + }, + ) + + self.mlp_base = tcnn.NetworkWithInputEncoding( + n_input_dims=3, + n_output_dims=1, + encoding_config={ + "otype": "HashGrid", + "n_levels": num_levels, + "n_features_per_level": 2, + "log2_hashmap_size": 19, + "base_resolution": base_res, + "per_level_scale": growth_factor, + }, + network_config={ + "otype": "FullyFusedMLP", + "activation": "ReLU", + "output_activation": "None", + "n_neurons": hidden_dim, + "n_hidden_layers": num_layers - 1, + }, + ) + + def get_density(self, ray_samples: RaySamples): + if self.spatial_distortion is not None: + positions = self.spatial_distortion(ray_samples.frustums.get_positions()) + positions = (positions + 2.0) / 4.0 + else: + positions = SceneBounds.get_normalized_positions(ray_samples.frustums.get_positions(), self.aabb) + positions_flat = positions.view(-1, 3) + # assert all positions are in the range [0, 1] + # otherwise print min and max values + # assert torch.all(positions >= 0.0) and torch.all( + # positions <= 1.0 + # ), f"positions: {positions.min()} {positions.max()}" + density_before_activation = self.mlp_base(positions_flat).view(*ray_samples.frustums.shape, -1) + + # Rectifying the density with an exponential is much more stable than a ReLU or + # softplus, because it enables high post-activation (float32) density outputs + # from smaller internal (float16) parameters. + density = trunc_exp(density_before_activation.to(positions)) + return density, None + + def get_outputs(self, ray_samples: RaySamples, density_embedding: Optional[TensorType] = None): + return {} diff --git a/nerfactory/fields/instant_ngp_field.py b/nerfactory/fields/instant_ngp_field.py index 779563249..e0782f256 100644 --- a/nerfactory/fields/instant_ngp_field.py +++ b/nerfactory/fields/instant_ngp_field.py @@ -28,6 +28,7 @@ from nerfactory.datamanagers.structs import SceneBounds from nerfactory.fields.base import Field from nerfactory.fields.modules.encoding import Encoding, HashEncoding, SHEncoding from nerfactory.fields.modules.field_heads import FieldHeadNames +from nerfactory.fields.modules.spatial_distortions import SpatialDistortion from nerfactory.fields.nerf_field import NeRFField from nerfactory.utils.activations import trunc_exp @@ -67,12 +68,13 @@ class TCNNInstantNGPField(Field): geo_feat_dim: int = 15, num_layers_color: int = 3, hidden_dim_color: int = 64, + spatial_distortion: Optional[SpatialDistortion] = None, ) -> None: super().__init__() self.aabb = Parameter(aabb, requires_grad=False) - self.geo_feat_dim = geo_feat_dim + self.spatial_distortion = spatial_distortion # TODO: set this properly based on the aabb per_level_scale = 1.4472692012786865 @@ -118,7 +120,12 @@ class TCNNInstantNGPField(Field): ) def get_density(self, ray_samples: RaySamples): - positions = SceneBounds.get_normalized_positions(ray_samples.frustums.get_positions(), self.aabb) + if self.spatial_distortion is not None: + positions = ray_samples.frustums.get_positions() + positions = self.spatial_distortion(positions) + positions = (positions + 2.0) / 4.0 + else: + positions = SceneBounds.get_normalized_positions(ray_samples.frustums.get_positions(), self.aabb) positions_flat = positions.view(-1, 3) # assert all positions are in the range [0, 1] # otherwise print min and max values diff --git a/nerfactory/models/base.py b/nerfactory/models/base.py index 82ea54359..97a80dd79 100644 --- a/nerfactory/models/base.py +++ b/nerfactory/models/base.py @@ -34,7 +34,6 @@ from nerfactory.datamanagers.structs import SceneBounds from nerfactory.fields.density_fields.density_grid import DensityGrid from nerfactory.models.modules.scene_colliders import NearFarCollider from nerfactory.utils.callbacks import TrainingCallback, TrainingCallbackAttributes -from nerfactory.utils.misc import get_masked_dict # Model related configs @@ -146,36 +145,28 @@ class Model(nn.Module): Outputs of model. (ie. rendered colors) """ - def forward( - self, ray_bundle: RayBundle, batch: Optional[Dict[str, torch.Tensor]] = None - ) -> Dict[str, torch.Tensor]: + def forward(self, ray_bundle: RayBundle) -> Dict[str, torch.Tensor]: """Run forward starting with a ray bundle. This outputs different things depending on the configuration of the model and whether or not the batch is provided (whether or not we are training basically) Args: ray_bundle: containing all the information needed to render that ray latents included - batch: containing all the auxilury things needed to train like masks and ground truth pixels. """ if self.collider is not None: intersected_ray_bundle = self.collider(ray_bundle) # pylint: disable=not-callable valid_mask = intersected_ray_bundle.valid_mask[..., 0] + intersected_ray_bundle = intersected_ray_bundle[valid_mask] else: # NOTE(ruilongli): we don't need collider for ngp intersected_ray_bundle = ray_bundle valid_mask = None - if batch is None: - # during inference, keep all rays - outputs = self.get_outputs(intersected_ray_bundle) - return outputs - - if valid_mask is not None: - intersected_ray_bundle = intersected_ray_bundle[valid_mask] - # during training, keep only the rays that intersect the scene. discard the rest - batch = get_masked_dict(batch, valid_mask) # NOTE(ethan): this is really slow if on CPU! - outputs = self.get_outputs(intersected_ray_bundle) + # TODO: update this once outputs is no longer a dictionary and is instead typed + if valid_mask is not None: + assert "valid_mask" not in outputs, "valid_mask should not be in outputs" + outputs["valid_mask"] = valid_mask return outputs def get_metrics_dict(self, outputs, batch) -> Dict[str, torch.Tensor]: @@ -209,7 +200,6 @@ class Model(nn.Module): num_rays_per_chunk = self.config.eval_num_rays_per_chunk image_height, image_width = camera_ray_bundle.origins.shape[:2] num_rays = len(camera_ray_bundle) - outputs = {} outputs_lists = defaultdict(list) for i in range(0, num_rays, num_rays_per_chunk): start_idx = i @@ -218,7 +208,11 @@ class Model(nn.Module): outputs = self.forward(ray_bundle=ray_bundle) for output_name, output in outputs.items(): # type: ignore outputs_lists[output_name].append(output) + outputs = {} for output_name, outputs_list in outputs_lists.items(): + if not torch.is_tensor(outputs_list[0]): + # TODO: handle lists of tensors as well + continue outputs[output_name] = torch.cat(outputs_list).view(image_height, image_width, -1) # type: ignore return outputs diff --git a/nerfactory/models/modules/ray_sampler.py b/nerfactory/models/modules/ray_sampler.py index 378558c9b..8edc2dd63 100644 --- a/nerfactory/models/modules/ray_sampler.py +++ b/nerfactory/models/modules/ray_sampler.py @@ -18,7 +18,7 @@ Collection of sampling strategies import math from abc import abstractmethod -from typing import Callable, Optional, Tuple +from typing import Callable, List, Optional, Tuple import nerfacc import torch @@ -38,7 +38,10 @@ class Sampler(nn.Module): """ def __init__( - self, num_samples: int, density_field: Optional[DensityGrid] = None, weight_threshold: float = 0.01 + self, + num_samples: Optional[int] = None, + density_field: Optional[DensityGrid] = None, + weight_threshold: float = 0.01, ) -> None: super().__init__() self.num_samples = num_samples @@ -75,9 +78,9 @@ class SpacedSampler(Sampler): def __init__( self, - num_samples: int, spacing_fn: Callable, spacing_fn_inv: Callable, + num_samples: Optional[int] = None, train_stratified=True, density_field: Optional[DensityGrid] = None, weight_threshold: float = 1e-2, @@ -138,7 +141,7 @@ class UniformSampler(SpacedSampler): def __init__( self, - num_samples: int, + num_samples: Optional[int] = None, train_stratified=True, density_field: Optional[DensityGrid] = None, weight_threshold: float = 1e-2, @@ -165,7 +168,7 @@ class LinearDisparitySampler(SpacedSampler): def __init__( self, - num_samples: int, + num_samples: Optional[int] = None, train_stratified=True, density_field: Optional[DensityGrid] = None, weight_threshold: float = 1e-2, @@ -192,7 +195,7 @@ class SqrtSampler(SpacedSampler): def __init__( self, - num_samples: int, + num_samples: Optional[int] = None, train_stratified=True, density_field: Optional[DensityGrid] = None, weight_threshold: float = 1e-2, @@ -219,7 +222,7 @@ class LogSampler(SpacedSampler): def __init__( self, - num_samples: int, + num_samples: Optional[int] = None, train_stratified=True, density_field: Optional[DensityGrid] = None, weight_threshold: float = 1e-2, @@ -248,7 +251,7 @@ class PDFSampler(Sampler): def __init__( self, - num_samples: int, + num_samples: Optional[int] = None, train_stratified: bool = True, include_original: bool = True, density_field: Optional[DensityGrid] = None, @@ -481,3 +484,51 @@ class VolumetricSampler(Sampler): camera_indices=camera_indices, ) return ray_samples, packed_info, ray_indices + + +class ProposalNetworkSampler(Sampler): + """Sampler that uses a proposal network to generate samples.""" + + def __init__( + self, + num_proposal_samples_per_ray: int = 64, + num_nerf_samples_per_ray: int = 32, + num_proposal_network_iterations: int = 2, + density_field: Optional[DensityGrid] = None, + weight_threshold: float = 1e-2, + ) -> None: + super().__init__(density_field=density_field, weight_threshold=weight_threshold) + self.num_proposal_samples_per_ray = num_proposal_samples_per_ray + self.num_nerf_samples_per_ray = num_nerf_samples_per_ray + self.num_proposal_network_iterations = num_proposal_network_iterations + + # NOTE: a linear disparity sampler won't work until we sample in s space instead of t space + self.uniform_sampler = UniformSampler() + self.pdf_sampler = PDFSampler(include_original=False) + + def generate_ray_samples( + self, + ray_bundle: Optional[RayBundle] = None, + density_fn: Optional[Callable] = None, + ) -> Tuple[RaySamples, List, List]: + + weights_list = [] + ray_samples_list = [] + + n = self.num_proposal_network_iterations + for i_level in range(n + 1): + is_prop = i_level < n + num_samples = self.num_proposal_samples_per_ray if is_prop else self.num_nerf_samples_per_ray + if i_level == 0: + # Uniform sampling because we need to start with some samples + ray_samples = self.uniform_sampler(ray_bundle, num_samples=num_samples) + else: + # PDF sampling based on the last samples and their weights + ray_samples = self.pdf_sampler(ray_bundle, ray_samples, weights, num_samples=num_samples) + if is_prop: + density = density_fn(ray_samples.frustums.get_positions()) + weights = ray_samples.get_weights(density) + weights_list.append(weights) # (num_rays, num_samples) + ray_samples_list.append(ray_samples) + + return ray_samples, weights_list, ray_samples_list diff --git a/nerfactory/models/modules/scene_colliders.py b/nerfactory/models/modules/scene_colliders.py index 5a18a6db6..9b9b25574 100644 --- a/nerfactory/models/modules/scene_colliders.py +++ b/nerfactory/models/modules/scene_colliders.py @@ -45,13 +45,13 @@ class AABBBoxCollider(SceneBoundsCollider): scene_bounds: scene bounds to apply to dataset """ - def __init__(self, scene_bounds: SceneBounds, **kwargs) -> None: + def __init__(self, scene_bounds: SceneBounds, near_plane: float = 0.0, **kwargs) -> None: super().__init__(**kwargs) self.scene_bounds = scene_bounds + self.near_plane = near_plane - @classmethod - def intersect_with_aabb( - cls, rays_o: TensorType["num_rays", 3], rays_d: TensorType["num_rays", 3], aabb: TensorType[2, 3] + def _intersect_with_aabb( + self, rays_o: TensorType["num_rays", 3], rays_d: TensorType["num_rays", 3], aabb: TensorType[2, 3] ): """Returns collection of valid rays within a specified near/far bounding box along with a mask specifying which rays are valid @@ -81,10 +81,12 @@ class AABBBoxCollider(SceneBoundsCollider): torch.cat([torch.maximum(t1, t2), torch.maximum(t3, t4), torch.maximum(t5, t6)], dim=1), dim=1 ).values + # clamp to near plane + nears = torch.clamp(nears, min=self.near_plane) + # fars < 0: means the ray is behind the camera # nears > fars: means no intersection valid_mask = ((fars > nears).float() * (fars > 0).float()).bool() - nears[nears < 0.0] = 0.0 nears[~valid_mask] = 0.0 fars[~valid_mask] = 0.0 return nears, fars, valid_mask @@ -97,7 +99,7 @@ class AABBBoxCollider(SceneBoundsCollider): ray_bundle: specified ray bundle to operate on """ aabb = self.scene_bounds.aabb - nears, fars, valid_mask = self.intersect_with_aabb(ray_bundle.origins, ray_bundle.directions, aabb) + nears, fars, valid_mask = self._intersect_with_aabb(ray_bundle.origins, ray_bundle.directions, aabb) ray_bundle.nears = nears[..., None] ray_bundle.fars = fars[..., None] ray_bundle.valid_mask = valid_mask[..., None] diff --git a/nerfactory/models/proposal.py b/nerfactory/models/proposal.py new file mode 100644 index 000000000..1aa632e1f --- /dev/null +++ b/nerfactory/models/proposal.py @@ -0,0 +1,188 @@ +# Copyright 2022 The Plenoptix Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +""" +Implementation of Instant NGP. +""" + +from __future__ import annotations + +from dataclasses import dataclass, field +from typing import Dict, List, Tuple, Type + +import torch +from torch.nn import Parameter +from torchmetrics import PeakSignalNoiseRatio +from torchmetrics.functional import structural_similarity_index_measure +from torchmetrics.image.lpip import LearnedPerceptualImagePatchSimilarity + +from nerfactory.cameras.rays import RayBundle +from nerfactory.fields.density_field import DensityField +from nerfactory.fields.instant_ngp_field import TCNNInstantNGPField +from nerfactory.fields.modules.field_heads import FieldHeadNames +from nerfactory.fields.modules.spatial_distortions import SceneContraction +from nerfactory.models.base import Model, ModelConfig +from nerfactory.models.modules.ray_sampler import ProposalNetworkSampler +from nerfactory.models.modules.scene_colliders import NearFarCollider +from nerfactory.optimizers.loss import MSELoss, distortion_loss, interlevel_loss +from nerfactory.renderers.renderers import ( + AccumulationRenderer, + DepthRenderer, + RGBRenderer, +) +from nerfactory.utils import colors, visualization + + +@dataclass +class ProposalModelConfig(ModelConfig): + """Proposal Model Config""" + + _target: Type = field(default_factory=lambda: ProposalModel) + near_plane: float = 0.05 + """How far along the ray to start sampling.""" + far_plane: float = 20.0 + """How far along the ray to stop sampling.""" + randomize_background: bool = True + """Whether to randomize the background color.""" + num_proposal_samples_per_ray: int = 64 + """Number of samples per ray for the proposal network.""" + num_nerf_samples_per_ray: int = 32 + """Number of samples per ray for the nerf network.""" + num_proposal_network_iterations: int = 2 + """Number of proposal network iterations.""" + interlevel_loss_mult: float = 1.0 + """Proposal loss multiplier.""" + distortion_loss_mult: float = 0.01 + """Distortion loss multiplier.""" + + +class ProposalModel(Model): + """Instant NGP model + + Args: + config: instant NGP configuration to instantiate model + """ + + config: ProposalModelConfig + + def populate_modules(self): + """Set the fields and modules.""" + super().populate_modules() + + # Fields + self.field = TCNNInstantNGPField(self.scene_bounds.aabb, spatial_distortion=SceneContraction()) + self.proposal_network = DensityField(self.scene_bounds.aabb, spatial_distortion=SceneContraction()) + + # Collider + self.collider = NearFarCollider(near_plane=self.config.near_plane, far_plane=self.config.far_plane) + + # Samplers + self.proposal_sampler = ProposalNetworkSampler( + num_nerf_samples_per_ray=self.config.num_nerf_samples_per_ray, + num_proposal_samples_per_ray=self.config.num_proposal_samples_per_ray, + num_proposal_network_iterations=self.config.num_proposal_network_iterations, + ) + + # renderers + background_color = None if self.config.randomize_background else colors.WHITE + self.renderer_rgb = RGBRenderer(background_color=background_color) + self.renderer_accumulation = AccumulationRenderer() + self.renderer_depth = DepthRenderer() + + # losses + self.rgb_loss = MSELoss() + + # metrics + self.psnr = PeakSignalNoiseRatio(data_range=1.0) + self.ssim = structural_similarity_index_measure + self.lpips = LearnedPerceptualImagePatchSimilarity() + + def get_param_groups(self) -> Dict[str, List[Parameter]]: + param_groups = {} + param_groups["fields"] = list(self.proposal_network.parameters()) + list(self.field.parameters()) + return param_groups + + def get_outputs(self, ray_bundle: RayBundle): + ray_samples, weights_list, ray_samples_list = self.proposal_sampler( + ray_bundle, density_fn=self.proposal_network.density_fn + ) + field_outputs = self.field(ray_samples) + weights = ray_samples.get_weights(field_outputs[FieldHeadNames.DENSITY]) + weights_list.append(weights) + ray_samples_list.append(ray_samples) + + rgb = self.renderer_rgb(rgb=field_outputs[FieldHeadNames.RGB], weights=weights) + depth = self.renderer_depth(weights=weights, ray_samples=ray_samples) + accumulation = self.renderer_accumulation(weights=weights) + + outputs = {"rgb": rgb, "accumulation": accumulation, "depth": depth} + outputs["weights_list"] = weights_list + outputs["ray_samples_list"] = ray_samples_list + return outputs + + def get_metrics_dict(self, outputs, batch): + metrics_dict = {} + image = batch["image"].to(self.device) + metrics_dict["psnr"] = self.psnr(outputs["rgb"], image) + return metrics_dict + + def get_loss_dict(self, outputs, batch, metrics_dict=None): + loss_dict = {} + image = batch["image"].to(self.device) + loss_dict["rgb_loss"] = self.rgb_loss(image, outputs["rgb"]) + loss_dict["interlevel_loss"] = self.config.interlevel_loss_mult * interlevel_loss( + outputs["weights_list"], + outputs["ray_samples_list"], + self.config.near_plane, + self.config.far_plane, + ) + loss_dict["distortion_loss"] = self.config.distortion_loss_mult * distortion_loss( + outputs["weights_list"], + outputs["ray_samples_list"], + self.config.near_plane, + self.config.far_plane, + ) + return loss_dict + + def get_image_metrics_and_images( + self, outputs: Dict[str, torch.Tensor], batch: Dict[str, torch.Tensor] + ) -> Tuple[Dict[str, float], Dict[str, torch.Tensor]]: + + image = batch["image"].to(self.device) + rgb = outputs["rgb"] + acc = visualization.apply_colormap(outputs["accumulation"]) + depth = visualization.apply_depth_colormap( + outputs["depth"], + accumulation=outputs["accumulation"], + ) + + combined_rgb = torch.cat([image, rgb], dim=1) + combined_acc = torch.cat([acc], dim=1) + combined_depth = torch.cat([depth], dim=1) + + # Switch images from [H, W, C] to [1, C, H, W] for metrics computations + image = torch.moveaxis(image, -1, 0)[None, ...] + rgb = torch.moveaxis(rgb, -1, 0)[None, ...] + + psnr = self.psnr(image, rgb) + ssim = self.ssim(image, rgb) + lpips = self.lpips(image, rgb) + + # all of these metrics will be logged as scalars + metrics_dict = {"psnr": float(psnr.item()), "ssim": float(ssim), "lpips": float(lpips)} # type: ignore + # TODO(ethan): return an image dictionary + + images_dict = {"img": combined_rgb, "accumulation": combined_acc, "depth": combined_depth} + + return metrics_dict, images_dict diff --git a/nerfactory/optimizers/loss.py b/nerfactory/optimizers/loss.py index 12f0c3dce..6f79be8f8 100644 --- a/nerfactory/optimizers/loss.py +++ b/nerfactory/optimizers/loss.py @@ -13,11 +13,109 @@ # limitations under the License. """ -Collection of Losses +Collection of Losses. """ + +import torch from torch import nn L1Loss = nn.L1Loss MSELoss = nn.MSELoss LOSSES = {"L1": L1Loss, "MSE": MSELoss} + +EPS = 1.0e-7 + + +def searchsorted(a, v): + """ + https://github.com/kakaobrain/NeRF-Factory/blob/f61bb8744a5cb4820a4d968fb3bfbed777550f4a/src/model/mipnerf360/helper.py#L109 + https://github.com/google-research/multinerf/blob/b02228160d3179300c7d499dca28cb9ca3677f32/internal/stepfun.py#L30 + """ + i = torch.arange(a.shape[-1], device=a.device) + v_ge_a = v[..., None, :] >= a[..., :, None] + idx_lo = torch.where(v_ge_a, i[..., :, None], i[..., :1, None]).max(dim=-2).values + idx_hi = torch.where(~v_ge_a, i[..., :, None], i[..., -1:, None]).min(dim=-2).values + return idx_lo, idx_hi + + +def inner_outer(t0, t1, y1): + """ + https://github.com/kakaobrain/NeRF-Factory/blob/f61bb8744a5cb4820a4d968fb3bfbed777550f4a/src/model/mipnerf360/helper.py#L117 + https://github.com/google-research/multinerf/blob/b02228160d3179300c7d499dca28cb9ca3677f32/internal/stepfun.py#L64 + """ + + cy1 = torch.cat([torch.zeros_like(y1[..., :1]), torch.cumsum(y1, dim=-1)], dim=-1) + idx_lo, idx_hi = searchsorted(t1, t0) + + cy1_lo = torch.take_along_dim(cy1, idx_lo, dim=-1) + cy1_hi = torch.take_along_dim(cy1, idx_hi, dim=-1) + + y0_outer = cy1_hi[..., 1:] - cy1_lo[..., :-1] + y0_inner = torch.where( + idx_hi[..., :-1] <= idx_lo[..., 1:], + cy1_lo[..., 1:] - cy1_hi[..., :-1], + torch.zeros_like(cy1_lo[..., 1:]), + ) + + return y0_inner, y0_outer + + +def lossfun_outer(t, w, t_env, w_env): + """ + https://github.com/kakaobrain/NeRF-Factory/blob/f61bb8744a5cb4820a4d968fb3bfbed777550f4a/src/model/mipnerf360/helper.py#L136 + https://github.com/google-research/multinerf/blob/b02228160d3179300c7d499dca28cb9ca3677f32/internal/stepfun.py#L80 + """ + _, w_outer = inner_outer(t, t_env, w_env) + return torch.clip(w - w_outer, min=0) ** 2 / (w + EPS) + + +def lossfun_distortion(t, w): + """ + https://github.com/kakaobrain/NeRF-Factory/blob/f61bb8744a5cb4820a4d968fb3bfbed777550f4a/src/model/mipnerf360/helper.py#L142 + https://github.com/google-research/multinerf/blob/b02228160d3179300c7d499dca28cb9ca3677f32/internal/stepfun.py#L266 + """ + ut = (t[..., 1:] + t[..., :-1]) / 2 + dut = torch.abs(ut[..., :, None] - ut[..., None, :]) + loss_inter = torch.sum(w * torch.sum(w[..., None, :] * dut, dim=-1), dim=-1) + + loss_intra = torch.sum(w**2 * (t[..., 1:] - t[..., :-1]), dim=-1) / 3 + + return loss_inter + loss_intra + + +def ray_samples_to_sdist(ray_samples, near_plane, far_plane): + """Convert ray samples to s space""" + starts = (ray_samples.frustums.starts - near_plane) / (far_plane - near_plane) + ends = (ray_samples.frustums.ends - near_plane) / (far_plane - near_plane) + sdist = torch.cat([starts[..., 0], ends[..., -1:, 0]], dim=-1) # (num_rays, num_samples + 1) + return sdist + + +def interlevel_loss(weights_list, ray_samples_list, near_plane, far_plane): + """Calculates the proposal loss in the MipNeRF-360 paper. + + https://github.com/kakaobrain/NeRF-Factory/blob/f61bb8744a5cb4820a4d968fb3bfbed777550f4a/src/model/mipnerf360/model.py#L515 + https://github.com/google-research/multinerf/blob/b02228160d3179300c7d499dca28cb9ca3677f32/internal/train_utils.py#L133 + """ + c = ray_samples_to_sdist(ray_samples_list[-1], near_plane, far_plane).detach() + w = weights_list[-1][..., 0].detach() + loss_interlevel = 0.0 + for ray_samples, weights in zip(ray_samples_list[:-1], weights_list[:-1]): + sdist = ray_samples_to_sdist(ray_samples, near_plane, far_plane) + cp = sdist # (num_rays, num_samples + 1) + wp = weights[..., 0] # (num_rays, num_samples) + loss_interlevel += torch.mean(lossfun_outer(c, w, cp, wp)) + return loss_interlevel + + +def distortion_loss(weights_list, ray_samples_list, near_plane, far_plane): + """Calculates the distortion loss in the MipNeRF-360 paper. + + https://github.com/kakaobrain/NeRF-Factory/blob/f61bb8744a5cb4820a4d968fb3bfbed777550f4a/src/model/mipnerf360/model.py#L526 + https://github.com/google-research/multinerf/blob/b02228160d3179300c7d499dca28cb9ca3677f32/internal/train_utils.py#L147 + """ + c = ray_samples_to_sdist(ray_samples_list[-1], near_plane, far_plane).detach() + w = weights_list[-1][..., 0] + loss = torch.mean(lossfun_distortion(c, w)) + return loss diff --git a/nerfactory/pipelines/base.py b/nerfactory/pipelines/base.py index f2bf86c55..e29ae3587 100644 --- a/nerfactory/pipelines/base.py +++ b/nerfactory/pipelines/base.py @@ -46,6 +46,7 @@ from nerfactory.datamanagers.base import ( from nerfactory.models.base import Model, ModelConfig from nerfactory.utils import profiler from nerfactory.utils.callbacks import TrainingCallback, TrainingCallbackAttributes +from nerfactory.utils.misc import get_masked_dict def module_wrapper(ddp_or_model: Union[DDP, Model]) -> Model: @@ -240,7 +241,10 @@ class VanillaPipeline(Pipeline): step: current iteration step to update sampler if using DDP (distributed) """ ray_bundle, batch = self.datamanager.next_train(step) - model_outputs = self.model(ray_bundle, batch) + model_outputs = self.model(ray_bundle) + if "valid_mask" in model_outputs: + valid_mask = model_outputs["valid_mask"] + batch = get_masked_dict(batch, valid_mask) metrics_dict = self.model.get_metrics_dict(model_outputs, batch) loss_dict = self.model.get_loss_dict(model_outputs, batch, metrics_dict) @@ -263,7 +267,10 @@ class VanillaPipeline(Pipeline): """ self.eval() ray_bundle, batch = self.datamanager.next_eval(step) - model_outputs = self.model(ray_bundle, batch) + model_outputs = self.model(ray_bundle) + if "valid_mask" in model_outputs: + valid_mask = model_outputs["valid_mask"] + batch = get_masked_dict(batch, valid_mask) loss_dict = self.model.get_loss_dict(model_outputs, batch) metrics_dict = self.model.get_metrics_dict(model_outputs, batch) self.train() diff --git a/tests/test_run_train.py b/tests/test_run_train.py index 58038aed5..ff3ce7135 100644 --- a/tests/test_run_train.py +++ b/tests/test_run_train.py @@ -14,7 +14,7 @@ from nerfactory.configs.base_configs import base_configs from nerfactory.datamanagers.dataparsers.blender_parser import BlenderDataParserConfig from nerfactory.engine.trainer import train_loop -BLACKLIST = ["base", "semantic-nerf", "mipnerf-360", "instant-ngp", "compound"] +BLACKLIST = ["base", "semantic-nerf", "mipnerf-360", "instant-ngp", "compound", "proposal"] def set_reduced_config(config: Config):