diff --git a/nerfactory/configs/base.py b/nerfactory/configs/base.py index cc0dd84b6..57b4b0036 100644 --- a/nerfactory/configs/base.py +++ b/nerfactory/configs/base.py @@ -38,6 +38,7 @@ from nerfactory.datamanagers.dataparsers.record3d_parser import Record3D # model instances from nerfactory.models.base import Model +from nerfactory.models.compound import CompoundModel from nerfactory.models.instant_ngp import NGPModel from nerfactory.models.nerfw import NerfWModel from nerfactory.models.tensorf import TensoRFModel @@ -402,6 +403,18 @@ class InstantNGPModelConfig(ModelConfig): """Number of samples in field evaluation. Defaults to 1024,""" +@dataclass +class CompoundModelConfig(ModelConfig): + """Compound Model Config""" + + _target: Type = CompoundModel + enable_density_field: bool = True + enable_collider: bool = False + field_implementation: Literal["torch", "tcnn"] = "tcnn" # torch, tcnn, ... + loss_coefficients: Dict[str, float] = to_immutable_dict({"rgb_loss": 1.0}) + num_samples: int = 1024 # instead of course/fine samples + + @dataclass class NerfWModelConfig(ModelConfig): """NerfW model config""" diff --git a/nerfactory/configs/base_configs.py b/nerfactory/configs/base_configs.py index a708c1d5c..1ac3ff09d 100644 --- a/nerfactory/configs/base_configs.py +++ b/nerfactory/configs/base_configs.py @@ -20,6 +20,7 @@ from typing import Dict from nerfactory.configs.base import ( BlenderDataParserConfig, + CompoundModelConfig, Config, FriendsDataManagerConfig, InstantNGPModelConfig, @@ -149,3 +150,22 @@ base_configs["tensorf"] = Config( }, }, ) + +base_configs["compound"] = Config( + method_name="compound", + trainer=TrainerConfig(mixed_precision=True), + pipeline=PipelineConfig( + datamanager=VanillaDataManagerConfig( + train_dataparser=BlenderDataParserConfig(), + train_num_rays_per_batch=8192, + eval_num_rays_per_chunk=8192, + ), + model=CompoundModelConfig(), + ), + optimizers={ + "fields": { + "optimizer": OptimizerConfig(lr=3e-3, eps=1e-15), + "scheduler": None, + } + }, +) diff --git a/nerfactory/fields/compound_field.py b/nerfactory/fields/compound_field.py new file mode 100644 index 000000000..85dd6a771 --- /dev/null +++ b/nerfactory/fields/compound_field.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. + +""" +Field for compound nerf model, adds scene contraction and image embeddings to instant ngp +""" + + +from typing import Optional, Tuple + +import torch +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.instant_ngp_field import TCNNInstantNGPField +from nerfactory.fields.modules.embedding import Embedding +from nerfactory.fields.modules.encoding import Encoding, HashEncoding, SHEncoding +from nerfactory.fields.modules.field_heads import FieldHeadNames +from nerfactory.fields.modules.spatial_distortions import ( + SceneContraction, + SpatialDistortion, +) +from nerfactory.fields.nerf_field import NeRFField +from nerfactory.utils.activations import trunc_exp + +try: + import tinycudann as tcnn +except ImportError: + # tinycudann module doesn't exist + pass + + +def get_normalized_directions(directions): + """SH encoding must be in the range [0, 1]""" + return (directions + 1.0) / 2.0 + + +class TCNNCompoundField(TCNNInstantNGPField): + """Compound Field that uses TCNN""" + + def __init__( + self, + aabb, + num_images: int, + num_layers=2, + hidden_dim=64, + geo_feat_dim=15, + num_layers_color=3, + hidden_dim_color=64, + appearance_embedding_dim: int = 40, + spatial_distortion: SpatialDistortion = SceneContraction(), + ) -> None: + super().__init__(self, aabb) + self.geo_feat_dim = geo_feat_dim + + self.spatial_distortion = spatial_distortion + self.num_images = num_images + self.appearance_embedding_dim = appearance_embedding_dim + self.embedding_appearance = Embedding(self.num_images, self.appearance_embedding_dim) + + self.aabb = Parameter(aabb, requires_grad=False) + + self.geo_feat_dim = geo_feat_dim + + # TODO: set this properly based on the aabb + per_level_scale = 1.4472692012786865 + + 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 + self.geo_feat_dim, + encoding_config={ + "otype": "HashGrid", + "n_levels": 16, + "n_features_per_level": 2, + "log2_hashmap_size": 19, + "base_resolution": 16, + "per_level_scale": per_level_scale, + }, + network_config={ + "otype": "FullyFusedMLP", + "activation": "ReLU", + "output_activation": "None", + "n_neurons": hidden_dim, + "n_hidden_layers": num_layers - 1, + }, + ) + + self.mlp_head = tcnn.Network( + n_input_dims=self.direction_encoding.n_output_dims + self.geo_feat_dim + self.appearance_embedding_dim, + n_output_dims=3, + network_config={ + "otype": "FullyFusedMLP", + "activation": "ReLU", + "output_activation": "Sigmoid", + "n_neurons": hidden_dim_color, + "n_hidden_layers": num_layers_color - 1, + }, + ) + + def get_density(self, ray_samples: RaySamples): + """Computes and returns the densities.""" + # positions = self.spatial_distortion(ray_samples.frustums.get_positions()) + positions = SceneBounds.get_normalized_positions(ray_samples.frustums.get_positions(), self.aabb) + positions_flat = positions.view(-1, 3) + h = self.mlp_base(positions_flat).view(*ray_samples.frustums.shape, -1) + density_before_activation, base_mlp_out = torch.split(h, [1, self.geo_feat_dim], dim=-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, base_mlp_out + + def get_outputs(self, ray_samples: RaySamples, density_embedding: Optional[TensorType] = None): + # TODO: add valid_mask masking! + # tcnn requires directions in the range [0,1] + if ray_samples.camera_indices is None: + raise AttributeError("Camera indices are not provided.") + + camera_indices = ray_samples.camera_indices.squeeze().to(ray_samples.frustums.origins.device) + embedded_appearance = self.embedding_appearance(camera_indices) + + directions = get_normalized_directions(ray_samples.frustums.directions) + directions_flat = directions.view(-1, 3) + d = self.direction_encoding(directions_flat) + + if density_embedding is None: + positions = SceneBounds.get_normalized_positions(ray_samples.frustums.get_positions(), self.aabb) + h = torch.cat([d, positions.view(-1, 3), embedded_appearance], dim=-1) + else: + h = torch.cat([d, density_embedding.view(-1, self.geo_feat_dim), embedded_appearance], dim=-1) + rgb = self.mlp_head(h).view(*ray_samples.frustums.directions.shape[:-1], -1).to(directions) + + return {FieldHeadNames.RGB: rgb} + + +class TorchCompoundField(NeRFField): + """ + PyTorch implementation of the compound field. + """ + + def __init__( + self, + aabb, + position_encoding: Encoding = HashEncoding(), + direction_encoding: Encoding = SHEncoding(), + base_mlp_num_layers: int = 3, + base_mlp_layer_width: int = 64, + head_mlp_num_layers: int = 2, + head_mlp_layer_width: int = 32, + skip_connections: Tuple = (4,), + spatial_distortion: SpatialDistortion = SceneContraction(), + ) -> None: + super().__init__( + position_encoding, + direction_encoding, + base_mlp_num_layers, + base_mlp_layer_width, + head_mlp_num_layers, + head_mlp_layer_width, + skip_connections, + spatial_distortion=spatial_distortion, + ) + self.aabb = Parameter(aabb, requires_grad=False) + + +field_implementation_to_class = {"tcnn": TCNNCompoundField, "torch": TorchCompoundField} diff --git a/nerfactory/models/compound.py b/nerfactory/models/compound.py new file mode 100644 index 000000000..43e79d37b --- /dev/null +++ b/nerfactory/models/compound.py @@ -0,0 +1,195 @@ +# 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. + +""" Compound model that integrates multiple NeRF Advancements + +Features: + + NGP Hash encoding for fast training + NGP ray sampler for fast training + Spatial contraction for training on large scenes + Appearance conditioning + +TODO: + Pose optimization + +""" + +from __future__ import annotations + +from typing import Dict, List + +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 + +import nerfactory.cuda as nerfactory_cuda +from nerfactory.cameras.rays import RayBundle +from nerfactory.configs import base as cfg +from nerfactory.fields.instant_ngp_field import field_implementation_to_class +from nerfactory.fields.modules.field_heads import FieldHeadNames +from nerfactory.models.base import Model +from nerfactory.models.modules.ray_sampler import NGPSpacedSampler +from nerfactory.optimizers.loss import MSELoss +from nerfactory.utils import colors, misc, visualization, writer +from nerfactory.utils.callbacks import ( + TrainingCallback, + TrainingCallbackAttributes, + TrainingCallbackLocation, +) + + +class CompoundModel(Model): + """Compound model + + Args: + field_implementation (str): one of "torch" or "tcnn", or other fields in 'field_implementation_to_class' + kwargs: additional params to pass up to the parent class model + """ + + config: cfg.CompoundModelConfig + + def __init__(self, config: cfg.CompoundModelConfig, **kwargs) -> None: + assert config.field_implementation in field_implementation_to_class + self.field = None + super().__init__(config=config, **kwargs) + + def get_training_callbacks( + self, training_callback_attributes: TrainingCallbackAttributes + ) -> List[TrainingCallback]: + assert self.density_field is not None + return [ + TrainingCallback( + where_to_run=[TrainingCallbackLocation.AFTER_TRAIN_ITERATION], + update_every_num_iters=self.density_field.update_every_num_iters, + func=self.density_field.update_density_grid, + kwargs={"density_eval_func": self.field.density_fn}, # type: ignore + ) + ] + + def populate_modules(self): + """Set the fields and modules.""" + super().populate_modules() + # torch or tiny-cuda-nn version + self.field = field_implementation_to_class[self.config.field_implementation](self.scene_bounds.aabb) + + # samplers + self.sampler = NGPSpacedSampler(num_samples=self.config.num_samples, density_field=self.density_field) + + # losses + self.rgb_loss = MSELoss() + + # metrics + self.psnr = PeakSignalNoiseRatio(data_range=1.0) + self.ssim = structural_similarity_index_measure + self.lpips = LearnedPerceptualImagePatchSimilarity() + + # no colliders default + + def get_param_groups(self) -> Dict[str, List[Parameter]]: + param_groups = {} + if self.field is None: + raise ValueError("populate_fields() must be called before get_param_groups") + param_groups["fields"] = list(self.field.parameters()) + return param_groups + + @torch.cuda.amp.autocast() + def get_outputs(self, ray_bundle: RayBundle): + # TODO(ruilongli) + # - train test difference + # - visualize "depth_density_grid" + num_rays = len(ray_bundle) + device = ray_bundle.origins.device + + if self.field is None: + raise ValueError("populate_fields() must be called before get_outputs") + ray_samples, packed_info, t_min, t_max = self.sampler(ray_bundle, self.field.aabb) + + field_outputs = self.field.forward(ray_samples) + + rgbs = field_outputs[FieldHeadNames.RGB] + sigmas = field_outputs[FieldHeadNames.DENSITY] + + # accumulate all the rays start from zero opacity + opacities = torch.zeros((num_rays, 1), device=device) + ( + accumulated_weight, + accumulated_depth, + accumulated_color, + alive_ray_mask, + ) = nerfactory_cuda.VolumeRenderer.apply( + packed_info, + ray_samples.frustums.starts, + ray_samples.frustums.ends, + sigmas.contiguous(), + rgbs.contiguous(), + opacities, + ) + accumulated_depth = torch.clip(accumulated_depth, t_min[:, None], t_max[:, None]) + accumulated_color = accumulated_color + colors.WHITE.to(accumulated_color) * (1.0 - accumulated_weight) + + outputs = { + "rgb": accumulated_color, + "accumulation": accumulated_weight, + "depth": accumulated_depth, + "alive_ray_mask": alive_ray_mask, # the rays we kept from sampler + } + return outputs + + def get_loss_dict(self, outputs, batch, metrics_dict, loss_coefficients): + device = self.device + image = batch["image"].to(device) + if "alive_ray_mask" in outputs: + mask = outputs["alive_ray_mask"] + rgb_loss = self.rgb_loss(image[mask], outputs["rgb"][mask]) + else: + rgb_loss = self.rgb_loss(image, outputs["rgb"]) + loss_dict = {"rgb_loss": rgb_loss} + loss_dict = misc.scale_dict(loss_dict, loss_coefficients) + return loss_dict + + def log_test_image_outputs(self, image_idx, step, batch, outputs): + image = batch["image"] + 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) + + writer.put_image(name=f"img/image_idx_{image_idx}", image=combined_rgb, step=step) + writer.put_image(name=f"accumulation/image_idx_{image_idx}", image=combined_acc, step=step) + writer.put_image(name=f"depth/image_idx_{image_idx}", image=combined_depth, step=step) + + # 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) + + writer.put_scalar(name=f"psnr/val_{image_idx}-fine", scalar=float(psnr), step=step) + writer.put_scalar(name=f"ssim/val_{image_idx}", scalar=float(ssim), step=step) # type: ignore + writer.put_scalar(name=f"lpips/val_{image_idx}", scalar=float(lpips), step=step) + + writer.put_scalar(name=writer.EventName.CURR_TEST_PSNR, scalar=float(psnr), step=step) + + return psnr.item()