diff --git a/docs/index.md b/docs/index.md index 9ebd68308..b189e03c3 100644 --- a/docs/index.md +++ b/docs/index.md @@ -114,6 +114,7 @@ This documentation is organized into 3 parts: - [Instruct-NeRF2NeRF](nerfology/methods/in2n.md): Editing 3D Scenes with Instructions - [K-Planes](nerfology/methods/kplanes.md): Unified 3D and 4D Radiance Fields - [LERF](nerfology/methods/lerf.md): Language Embedded Radiance Fields +- [NeRFPlayer](nerfology/methods/nerfplayer.md): 4D Radiance Fields by Streaming Feature Channels - [Tetra-NeRF](nerfology/methods/tetranerf.md): Representing Neural Radiance Fields Using Tetrahedra **Eager to contribute a method?** We'd love to see you use nerfstudio in implementing new (or even existing) methods! Please view our {ref}`guide` for more details about how to add to this list! diff --git a/docs/nerfology/methods/generfacto.md b/docs/nerfology/methods/generfacto.md new file mode 100644 index 000000000..2c037f08b --- /dev/null +++ b/docs/nerfology/methods/generfacto.md @@ -0,0 +1,62 @@ +# Generfacto + +

Generate 3D models from text

+ +**Our model that combines generative 3D with our latest NeRF methods** + +## Installation + +First install nerfstudio dependencies. Then run: + +```bash +pip install -e .[gen] +``` + +Two options for text to image diffusion models are provided: Stable Diffusion and DeepFloyd IF. +We use Deepfloyd IF by default because it trains faster and produces better results. Using this model requires users to sign a license agreement for the model card of DeepFloyd IF, which can be found [here](https://huggingface.co/DeepFloyd/IF-I-XL-v1.0). Once the licensed is signed, log into Huggingface locally by running the following command: + +```bash +huggingface-cli login +``` + +If you do not want to sign the license agreement, you can use the Stable Diffusion model (instructions below). + +## Running Generfacto + +Once installed, run: + +```bash +ns-train generfacto --prompt "a high quality photo of a pineapple" +``` + +The first time you run this method, the diffusion model weights will be downloaded and cached +from Hugging Face, which may take a couple minutes. + +Specify which diffusion model to use with the diffusion_model flag: + +```bash +ns-train generfacto --pipeline.model.diffusion_model ["stablediffusion", "deepfloyd"] +``` + +# Example Results + +The following videos are renders of NeRFs generated from Generfacto. Each model was trained 30k steps, which took around 1 hour with DeepFloyd +and around 4 hours with Stable Diffusion. + +"a high quality photo of a ripe pineapple" (Stable Diffusion) + + + +"a high quality zoomed out photo of a palm tree" (DeepFloyd) + + + +"a high quality zoomed out photo of a light grey baby shark" (DeepFloyd) + + diff --git a/docs/nerfology/methods/index.md b/docs/nerfology/methods/index.md index 07eccb4b0..8eac41800 100644 --- a/docs/nerfology/methods/index.md +++ b/docs/nerfology/methods/index.md @@ -33,8 +33,10 @@ The following methods are supported in nerfstudio: Mip-NeRF NeRF Nerfacto + NeRFPlayer Tetra-NeRF TensoRF + Generfacto ``` (own_method_docs)= diff --git a/docs/nerfology/methods/nerfacto.md b/docs/nerfology/methods/nerfacto.md index c1137884a..63684848f 100644 --- a/docs/nerfology/methods/nerfacto.md +++ b/docs/nerfology/methods/nerfacto.md @@ -55,7 +55,7 @@ It is not uncommon to have errors in the predicted camera poses. This is even mo ### Piecewise Sampler -We use a Piecewise sampler to produce the initial set of samples of the scene. This sampler allocates half of the samples uniformly up to a distance of 1 from the camera. The remaining samples are distributed such that the step size increases with each sample. The step size is chosen such that the [frustums](../model_components/visualize_samples.ipynb) are scaled versions of themselves. By increasing the step sizes, we are able to sample distant objects will still having a dense set of samples for nearby objects. +We use a Piecewise sampler to produce the initial set of samples of the scene. This sampler allocates half of the samples uniformly up to a distance of 1 from the camera. The remaining samples are distributed such that the step size increases with each sample. The step size is chosen such that the [frustums](../model_components/visualize_samples.ipynb) are scaled versions of themselves. By increasing the step sizes, we are able to sample distant objects while still having a dense set of samples for nearby objects. ### Proposal Sampler diff --git a/docs/nerfology/methods/nerfplayer.md b/docs/nerfology/methods/nerfplayer.md new file mode 100644 index 000000000..dafe11c5d --- /dev/null +++ b/docs/nerfology/methods/nerfplayer.md @@ -0,0 +1,50 @@ +# NeRFPlayer + +

A Streamable Dynamic Scene Representation with Decomposed Neural Radiance Fields

+ + +```{button-link} https://lsongx.github.io/projects/nerfplayer.html +:color: primary +:outline: +Paper Website +``` + +```{button-link} https://github.com/lsongx/nerfplayer-nerfstudio +:color: primary +:outline: +Nerfstudio add-on code +``` + +[![NeRFPlayer Video](https://img.youtube.com/vi/flVqSLZWBMI/0.jpg)](https://www.youtube.com/watch?v=flVqSLZWBMI) + + +## Installation + +First install nerfstudio dependencies. Then run: + +```bash +pip install git+https://github.com/lsongx/nerfplayer-nerfstudio.git +``` + +## Running NeRFPlayer + +Details for running NeRFPlayer can be found [here](https://github.com/lsongx/nerfplayer-nerfstudio). Once installed, run: + +```bash +ns-train nerfplayer-ngp --help +``` + +Two variants of NeRFPlayer are provided: + +| Method | Description | +| --------------------- | ----------------------------------------------- | +| `nerfplayer-nerfacto` | NeRFPlayer with nerfacto backbone | +| `nerfplayer-ngp` | NeRFPlayer with instant-ngp-bounded backbone | + + +## Method Overview + +![method overview](https://lsongx.github.io/projects/images/nerfplayer-framework.png)
+First, we propose to decompose the 4D spatiotemporal space according to temporal characteristics. Points in the 4D space are associated with probabilities of belonging to three categories: static, deforming, and new areas. Each area is represented and regularized by a separate neural field. Second, we propose a hybrid representations based feature streaming scheme for efficiently modeling the neural fields. + +Please see [TODO lists](https://github.com/lsongx/nerfplayer-nerfstudio#known-todos) to see the unimplemented components in the nerfstudio based version. \ No newline at end of file diff --git a/docs/quickstart/viewer_quickstart.rst b/docs/quickstart/viewer_quickstart.rst index 6d110e7c0..0ff258277 100644 --- a/docs/quickstart/viewer_quickstart.rst +++ b/docs/quickstart/viewer_quickstart.rst @@ -57,25 +57,19 @@ You should be able to click the link obtained while running a script to open the Training on a remote machine ---------------------------- -If you are training on a remote maching, the viewer will still let you view your trainings. -You will need to forward the port that the viewer is running on. - -For example, if you are running the viewer on port 7007, you will need to forward that port to your local machine. -You can (without needing to modify router port settings) simply do this by opening a new terminal window and sshing into the remote machine with the following command: +If you are training on a remote machine, the viewer will still let you view your trainings. You will need to forward traffic from your viewing host to the listening port on the host running ns-train (7007 by default). You can achieve this by securely tunneling traffic on the specified port through an ssh session. In a terminal window on the viewing host, issue the following command: .. code-block:: bash - ssh -L 7007:localhost:7007 @ + ssh -L 7007::7007 @ .. admonition:: Note - So long as you don't close this terminal window with this specific active ssh connection, the port will remain open for all your other ssh sessions. + You can now simply open the link (same one shown in image above) in your browser on your local machine and it should connect!. So long as you don't close this terminal window with this specific active ssh connection, the port will remain open for all your other ssh sessions. For example, if you do this in a new terminal window, any existing ssh sessions (terminal windows, VSCode remote connection, etc) will still be able to access the port, but if you close this terminal window, the port will be closed. -You can now simply open the link (same ones shown in image above) in your browser on your local machine and it should connect! - .. warning:: - If the port is being used, you will need to switch the port using the `--viewer.websocket-port` flag tied to the model subcommand. \ No newline at end of file + If the port is being used, you will need to switch the port using the `--viewer.websocket-port` flag tied to the model subcommand. diff --git a/nerfstudio/cameras/camera_optimizers.py b/nerfstudio/cameras/camera_optimizers.py index 899833f83..77b7e2b47 100644 --- a/nerfstudio/cameras/camera_optimizers.py +++ b/nerfstudio/cameras/camera_optimizers.py @@ -20,7 +20,7 @@ from __future__ import annotations import functools from dataclasses import dataclass, field -from typing import Literal, Type, Union +from typing import Literal, Optional, Type, Union import torch import tyro @@ -53,10 +53,10 @@ class CameraOptimizerConfig(InstantiateConfig): orientation_noise_std: float = 0.0 """Noise to add to initial orientations. Useful for debugging.""" - optimizer: OptimizerConfig = AdamOptimizerConfig(lr=6e-4, eps=1e-15) + optimizer: OptimizerConfig = field(default_factory=lambda: AdamOptimizerConfig(lr=6e-4, eps=1e-15)) """ADAM parameters for camera optimization.""" - scheduler: SchedulerConfig = ExponentialDecaySchedulerConfig(max_steps=10000) + scheduler: SchedulerConfig = field(default_factory=lambda: ExponentialDecaySchedulerConfig(max_steps=10000)) """Learning rate scheduler for camera optimizer..""" param_group: tyro.conf.Suppress[str] = "camera_opt" @@ -74,12 +74,14 @@ class CameraOptimizer(nn.Module): config: CameraOptimizerConfig, num_cameras: int, device: Union[torch.device, str], + non_trainable_camera_indices: Optional[Int[Tensor, "num_non_trainable_cameras"]] = None, **kwargs, ) -> None: super().__init__() self.config = config self.num_cameras = num_cameras self.device = device + self.non_trainable_camera_indices = non_trainable_camera_indices # Initialize learnable parameters. if self.config.mode == "off": @@ -121,11 +123,13 @@ class CameraOptimizer(nn.Module): outputs.append(exp_map_SE3(self.pose_adjustment[indices, :])) else: assert_never(self.config.mode) + # Detach non-trainable indices by setting to identity transform + if self.non_trainable_camera_indices is not None: + outputs[0][self.non_trainable_camera_indices] = torch.eye(4, device=self.device)[:3, :4] # Apply initial pose noise. if self.pose_noise is not None: outputs.append(self.pose_noise[indices, :, :]) - # Return: identity if no transforms are needed, otherwise multiply transforms together. if len(outputs) == 0: # Note that using repeat() instead of tile() here would result in unnecessary copies. diff --git a/nerfstudio/configs/experiment_config.py b/nerfstudio/configs/experiment_config.py index 2f57d50e4..c3a400dd1 100644 --- a/nerfstudio/configs/experiment_config.py +++ b/nerfstudio/configs/experiment_config.py @@ -72,6 +72,8 @@ class ExperimentConfig(InstantiateConfig): """Which visualizer to use.""" data: Optional[Path] = None """Alias for --pipeline.datamanager.data""" + prompt: Optional[str] = None + """Alias for --pipeline.model.prompt""" relative_model_dir: Path = Path("nerfstudio_models/") """Relative path to save all checkpoints.""" diff --git a/nerfstudio/configs/external_methods.py b/nerfstudio/configs/external_methods.py index 0510d6ec2..4b7433969 100644 --- a/nerfstudio/configs/external_methods.py +++ b/nerfstudio/configs/external_methods.py @@ -106,6 +106,21 @@ To enable Tetra-NeRF, you must install it first. Please follow the instructions ) ) +# NeRFPlayer +external_methods.append( + ExternalMethod( + """[bold yellow]NeRFPlayer[/bold yellow] +For more information visit: https://docs.nerf.studio/en/latest/nerfology/methods/nerfplayer.html + +To enable NeRFPlayer, you must install it first by running: + [grey]pip install git+https://github.com/lsongx/nerfplayer-nerfstudio[/grey]""", + configurations=[ + ("nerfplayer-nerfacto", "NeRFPlayer with nerfacto backbone"), + ("nerfplayer-ngp", "NeRFPlayer with instang-ngp-bounded backbone"), + ], + ) +) + @dataclass class ExternalMethodTrainerConfig(TrainerConfig): diff --git a/nerfstudio/configs/method_configs.py b/nerfstudio/configs/method_configs.py index 9700fc6d1..2aadc351a 100644 --- a/nerfstudio/configs/method_configs.py +++ b/nerfstudio/configs/method_configs.py @@ -27,20 +27,15 @@ from nerfstudio.data.pixel_samplers import PairPixelSamplerConfig from nerfstudio.cameras.camera_optimizers import CameraOptimizerConfig from nerfstudio.configs.base_config import ViewerConfig from nerfstudio.configs.external_methods import get_external_methods -from nerfstudio.data.datamanagers.base_datamanager import ( - VanillaDataManager, - VanillaDataManagerConfig, -) + +from nerfstudio.data.datamanagers.random_cameras_datamanager import RandomCamerasDataManagerConfig +from nerfstudio.data.datamanagers.base_datamanager import VanillaDataManager, VanillaDataManagerConfig + from nerfstudio.data.dataparsers.blender_dataparser import BlenderDataParserConfig from nerfstudio.data.dataparsers.dnerf_dataparser import DNeRFDataParserConfig -from nerfstudio.data.dataparsers.dycheck_dataparser import DycheckDataParserConfig -from nerfstudio.data.dataparsers.instant_ngp_dataparser import ( - InstantNGPDataParserConfig, -) +from nerfstudio.data.dataparsers.instant_ngp_dataparser import InstantNGPDataParserConfig from nerfstudio.data.dataparsers.nerfstudio_dataparser import NerfstudioDataParserConfig -from nerfstudio.data.dataparsers.phototourism_dataparser import ( - PhototourismDataParserConfig, -) +from nerfstudio.data.dataparsers.phototourism_dataparser import PhototourismDataParserConfig from nerfstudio.data.dataparsers.sdfstudio_dataparser import SDFStudioDataParserConfig from nerfstudio.data.dataparsers.sitcoms3d_dataparser import Sitcoms3DDataParserConfig from nerfstudio.data.datasets.depth_dataset import DepthDataset @@ -56,11 +51,10 @@ from nerfstudio.engine.trainer import TrainerConfig from nerfstudio.field_components.temporal_distortions import TemporalDistortionKind from nerfstudio.fields.sdf_field import SDFFieldConfig from nerfstudio.models.depth_nerfacto import DepthNerfactoModelConfig +from nerfstudio.models.generfacto import GenerfactoModelConfig from nerfstudio.models.instant_ngp import InstantNGPModelConfig from nerfstudio.models.mipnerf import MipNerfModel from nerfstudio.models.nerfacto import NerfactoModelConfig -from nerfstudio.models.nerfplayer_nerfacto import NerfplayerNerfactoModelConfig -from nerfstudio.models.nerfplayer_ngp import NerfplayerNGPModelConfig from nerfstudio.models.neus import NeuSModelConfig from nerfstudio.models.neus_facto import NeuSFactoModelConfig from nerfstudio.models.semantic_nerfw import SemanticNerfWModelConfig @@ -83,8 +77,7 @@ descriptions = { "tensorf": "tensorf", "dnerf": "Dynamic-NeRF model. (slow)", "phototourism": "Uses the Phototourism data.", - "nerfplayer-nerfacto": "NeRFPlayer with nerfacto backbone.", - "nerfplayer-ngp": "NeRFPlayer with InstantNGP backbone.", + "generfacto": "Generative Text to NeRF model", "neus": "Implementation of NeuS. (slow)", "neus-facto": "Implementation of NeuS-Facto. (slow)", } @@ -130,7 +123,7 @@ method_configs["nerfacto-big"] = TrainerConfig( pipeline=VanillaPipelineConfig( datamanager=VanillaDataManagerConfig( dataparser=NerfstudioDataParserConfig(), - train_num_rays_per_batch=4096, + train_num_rays_per_batch=8192, eval_num_rays_per_batch=4096, camera_optimizer=CameraOptimizerConfig( mode="SO3xR3", @@ -143,8 +136,9 @@ method_configs["nerfacto-big"] = TrainerConfig( num_proposal_samples_per_ray=(512, 256), hidden_dim=128, hidden_dim_color=128, - hidden_dim_transient=128, - max_res=3000, + appearance_embed_dim=128, + base_res=32, + max_res=4096, proposal_weights_anneal_max_num_iters=5000, log2_hashmap_size=21, ), @@ -156,7 +150,55 @@ method_configs["nerfacto-big"] = TrainerConfig( }, "fields": { "optimizer": RAdamOptimizerConfig(lr=1e-2, eps=1e-15), - "scheduler": ExponentialDecaySchedulerConfig(lr_final=1e-4, max_steps=100000), + "scheduler": ExponentialDecaySchedulerConfig(lr_final=1e-4, max_steps=50000), + }, + }, + viewer=ViewerConfig(num_rays_per_chunk=1 << 15), + vis="viewer", +) +method_configs["nerfacto-huge"] = TrainerConfig( + method_name="nerfacto", + steps_per_eval_batch=500, + steps_per_save=2000, + max_num_iterations=100000, + mixed_precision=True, + pipeline=VanillaPipelineConfig( + datamanager=VanillaDataManagerConfig( + dataparser=NerfstudioDataParserConfig(), + train_num_rays_per_batch=16384, + eval_num_rays_per_batch=4096, + camera_optimizer=CameraOptimizerConfig( + mode="SO3xR3", + optimizer=RAdamOptimizerConfig(lr=6e-4, eps=1e-8, weight_decay=1e-3), + scheduler=ExponentialDecaySchedulerConfig(lr_final=6e-5, max_steps=50000), + ), + ), + model=NerfactoModelConfig( + eval_num_rays_per_chunk=1 << 15, + num_nerf_samples_per_ray=64, + num_proposal_samples_per_ray=(512, 512), + proposal_net_args_list=[ + {"hidden_dim": 16, "log2_hashmap_size": 17, "num_levels": 5, "max_res": 512, "use_linear": False}, + {"hidden_dim": 16, "log2_hashmap_size": 17, "num_levels": 7, "max_res": 2048, "use_linear": False}, + ], + hidden_dim=256, + hidden_dim_color=256, + appearance_embed_dim=32, + features_per_level=4, + base_res=32, + max_res=8192, + proposal_weights_anneal_max_num_iters=5000, + log2_hashmap_size=21, + ), + ), + optimizers={ + "proposal_networks": { + "optimizer": RAdamOptimizerConfig(lr=1e-2, eps=1e-15), + "scheduler": None, + }, + "fields": { + "optimizer": RAdamOptimizerConfig(lr=1e-2, eps=1e-15), + "scheduler": ExponentialDecaySchedulerConfig(lr_final=1e-4, max_steps=50000), }, }, viewer=ViewerConfig(num_rays_per_chunk=1 << 15), @@ -448,66 +490,48 @@ method_configs["phototourism"] = TrainerConfig( vis="viewer", ) -method_configs["nerfplayer-nerfacto"] = TrainerConfig( - method_name="nerfplayer-nerfacto", - steps_per_eval_batch=500, - steps_per_save=2000, +method_configs["generfacto"] = TrainerConfig( + method_name="generfacto", + experiment_name="", + steps_per_eval_batch=50, + steps_per_eval_image=50, + steps_per_save=200, max_num_iterations=30000, mixed_precision=True, pipeline=VanillaPipelineConfig( - datamanager=VanillaDataManagerConfig( - _target=VanillaDataManager[DepthDataset], - dataparser=DycheckDataParserConfig(), - train_num_rays_per_batch=4096, - eval_num_rays_per_batch=4096, - camera_optimizer=CameraOptimizerConfig( - mode="SO3xR3", optimizer=AdamOptimizerConfig(lr=6e-4, eps=1e-8, weight_decay=1e-2) - ), + datamanager=RandomCamerasDataManagerConfig( + horizontal_rotation_warmup=3000, + ), + model=GenerfactoModelConfig( + eval_num_rays_per_chunk=1 << 15, + distortion_loss_mult=1.0, + interlevel_loss_mult=100.0, + max_res=256, + sphere_collider=True, + initialize_density=True, + taper_range=(0, 2000), + random_background=True, + proposal_warmup=2000, + proposal_update_every=0, + proposal_weights_anneal_max_num_iters=2000, + start_lambertian_training=500, + start_normals_training=2000, + opacity_loss_mult=0.001, + positional_prompting="discrete", + guidance_scale=25, ), - model=NerfplayerNerfactoModelConfig(eval_num_rays_per_chunk=1 << 15), ), optimizers={ "proposal_networks": { - "optimizer": AdamOptimizerConfig(lr=1e-2, eps=1e-15), + "optimizer": AdamOptimizerConfig(lr=1e-3, eps=1e-15), "scheduler": None, }, "fields": { - "optimizer": AdamOptimizerConfig(lr=1e-2, eps=1e-15), + "optimizer": AdamOptimizerConfig(lr=5e-4, eps=1e-15), "scheduler": None, }, }, - viewer=ViewerConfig(num_rays_per_chunk=1 << 15), - vis="viewer", -) - -method_configs["nerfplayer-ngp"] = TrainerConfig( - method_name="nerfplayer-ngp", - steps_per_eval_batch=500, - steps_per_save=2000, - max_num_iterations=30000, - mixed_precision=True, - pipeline=DynamicBatchPipelineConfig( - datamanager=VanillaDataManagerConfig( - _target=VanillaDataManager[DepthDataset], - dataparser=DycheckDataParserConfig(), - train_num_rays_per_batch=8192, - ), - model=NerfplayerNGPModelConfig( - eval_num_rays_per_chunk=8192, - grid_levels=1, - alpha_thre=0.0, - render_step_size=0.001, - disable_scene_contraction=True, - near_plane=0.01, - ), - ), - optimizers={ - "fields": { - "optimizer": AdamOptimizerConfig(lr=1e-2, eps=1e-15), - "scheduler": None, - } - }, - viewer=ViewerConfig(num_rays_per_chunk=64000), + viewer=ViewerConfig(), vis="viewer", ) diff --git a/nerfstudio/data/datamanagers/base_datamanager.py b/nerfstudio/data/datamanagers/base_datamanager.py index fcf7c1fcb..59ef7e84a 100644 --- a/nerfstudio/data/datamanagers/base_datamanager.py +++ b/nerfstudio/data/datamanagers/base_datamanager.py @@ -110,6 +110,8 @@ class DataManagerConfig(InstantiateConfig): """Source of data, may not be used by all models.""" camera_optimizer: Optional[CameraOptimizerConfig] = None """Specifies the camera pose optimizer used during training. Helpful if poses are noisy.""" + masks_on_gpu: Optional[bool] = None + """Process masks on GPU for speed at the expense of memory, if True.""" class DataManager(nn.Module): @@ -395,6 +397,8 @@ class VanillaDataManager(DataManager, Generic[TDataset]): self.train_dataset = self.create_train_dataset() self.eval_dataset = self.create_eval_dataset() self.exclude_batch_keys_from_device = self.train_dataset.exclude_batch_keys_from_device + if self.config.masks_on_gpu is True: + self.exclude_batch_keys_from_device.remove("mask") if self.train_dataparser_outputs is not None: cameras = self.train_dataparser_outputs.cameras diff --git a/nerfstudio/data/datamanagers/random_cameras_datamanager.py b/nerfstudio/data/datamanagers/random_cameras_datamanager.py new file mode 100644 index 000000000..4269b428a --- /dev/null +++ b/nerfstudio/data/datamanagers/random_cameras_datamanager.py @@ -0,0 +1,315 @@ +# Copyright 2022 The Nerfstudio 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. + +""" +Data manager without input images, only random camera poses +""" + +from __future__ import annotations + +import sys +from dataclasses import dataclass, field +from typing import Dict, List, Tuple, Type, Union + +import torch +from rich.progress import Console +from torch.nn import Parameter +from torch import Tensor +from typing_extensions import Literal + +from nerfstudio.cameras.cameras import Cameras +from nerfstudio.cameras.rays import RayBundle +from nerfstudio.configs.config_utils import to_immutable_dict +from nerfstudio.data.datamanagers.base_datamanager import DataManager, DataManagerConfig +from nerfstudio.data.datasets.base_dataset import InputDataset +from nerfstudio.data.scene_box import SceneBox +from nerfstudio.data.utils.dataloaders import RandIndicesEvalDataloader + +CONSOLE = Console(width=120) + + +class TrivialDataset(InputDataset): + """A trivial dataset with blank images for the viewer""" + + # pylint: disable=super-init-not-called + def __init__(self, cameras: Cameras): + self.size = cameras.size + self.cameras = cameras + self.alpha_color = None + self.scene_box = SceneBox(torch.Tensor([[-1, -1, -1], [1, 1, 1]])) + self.mask_filenames = None + self.metadata = to_immutable_dict({}) + + def __len__(self): + return self.size + + def __getitem__(self, index: int) -> Dict: + return { + "image": torch.cat([torch.ones(128, 256, 3), torch.zeros(128, 256, 3)], dim=0), + "image_idx": index, + } + + +def random_train_pose( + size: int, + resolution: int, + device: Union[torch.device, str], + radius_mean: float = 1.0, + radius_std: float = 0.1, + central_rotation_range: Tuple[float, float] = (0, 360), + vertical_rotation_range: Tuple[float, float] = (-90, 0), + focal_range: Tuple[float, float] = (0.75, 1.35), + jitter_std: float = 0.01, + center: Tuple[float, float, float] = (0, 0, 0), +) -> Tuple[Cameras, Tensor, Tensor]: + """generate random poses from an orbit camera + Args: + size: batch size of generated poses. + device: where to allocate the output. + radius_mean: mean radius of the orbit camera. + radius_std: standard deviation of the radius of the orbit camera. + central_rotation_range: amount that we rotate around the center of the object + vertical_rotation_range: amount that we allow the cameras to pan up and down from horizontal + focal_range: focal length range + jitter_std: standard deviation of the jitter added to the camera position + center: center of the object + Return: + poses: [size, 4, 4] + """ + + vertical_rotation_range = ( + vertical_rotation_range[0] + 90, + vertical_rotation_range[1] + 90, + ) + # This is the uniform sample on the part of the sphere we care about where 0 = 0 degrees and 1 = 360 degrees + sampled_uniform = ( + torch.rand(size) * (vertical_rotation_range[1] - vertical_rotation_range[0]) + vertical_rotation_range[0] + ) / 180 + vertical_rotation = torch.arccos(1 - 2 * sampled_uniform) + central_rotation = torch.deg2rad( + torch.rand(size) * (central_rotation_range[1] - central_rotation_range[0]) + central_rotation_range[0] + ) + + c_cos = torch.cos(central_rotation) + c_sin = torch.sin(central_rotation) + v_cos = torch.cos(vertical_rotation) + v_sin = torch.sin(vertical_rotation) + zeros = torch.zeros_like(central_rotation) + ones = torch.ones_like(central_rotation) + + rot_z = torch.stack( + [ + torch.stack([c_cos, -c_sin, zeros], dim=-1), + torch.stack([c_sin, c_cos, zeros], dim=-1), + torch.stack([zeros, zeros, ones], dim=-1), + ], + dim=-2, + ) + + rot_x = torch.stack( + [ + torch.stack([ones, zeros, zeros], dim=-1), + torch.stack([zeros, v_cos, -v_sin], dim=-1), + torch.stack([zeros, v_sin, v_cos], dim=-1), + ], + dim=-2, + ) + + # Default directions are facing in the -z direction, so origins should face opposite way + origins = torch.stack([torch.tensor([0, 0, 1])] * size, dim=0) + origins = (origins * radius_mean) + (origins * (torch.randn((origins.shape)) * radius_std)) + R = torch.bmm(rot_z, rot_x) # Want to have Rx @ Ry @ origin + t = ( + torch.bmm(R, origins.unsqueeze(-1)) + + torch.randn((size, 3, 1)) * jitter_std + + torch.tensor(center)[None, :, None] + ) + camera_to_worlds = torch.cat([R, t], dim=-1) + + focals = torch.rand(size) * (focal_range[1] - focal_range[0]) + focal_range[0] + + cameras = Cameras( + camera_to_worlds=camera_to_worlds, + fx=focals * resolution, + fy=focals * resolution, + cx=resolution / 2, + cy=resolution / 2, + ).to(device) + + return cameras, torch.rad2deg(vertical_rotation), torch.rad2deg(central_rotation) + + +@dataclass +class RandomCamerasDataManagerConfig(DataManagerConfig): + """Configuration for data manager that does not load from a dataset. Instead, it generates random poses.""" + + _target: Type = field(default_factory=lambda: RandomCamerasDataManager) + train_resolution: int = 64 + """Training resolution""" + eval_resolution: int = 64 + """Evaluation resolution""" + num_eval_angles: int = 256 + """Number of evaluation angles""" + train_images_per_batch: int = 1 + """Number of images per batch for training""" + eval_images_per_batch: int = 1 + """Number of images per batch for evaluation""" + radius_mean: float = 2.5 + """Mean radius of camera orbit""" + radius_std: float = 0.1 + """Std of radius of camera orbit""" + focal_range: Tuple[float, float] = (0.7, 1.35) + """Range of focal length""" + vertical_rotation_range: Tuple[float, float] = (-90, 0) + """Range of vertical rotation""" + jitter_std: float = 0.05 + """Std of camera direction jitter, so we don't just point the cameras towards the center every time""" + center: Tuple[float, float, float] = (0, 0, 0) + """Center coordinate of the camera sphere""" + horizontal_rotation_warmup: int = 0 + """How many steps until the full horizontal rotation range is used""" + + +class RandomCamerasDataManager(DataManager): # pylint: disable=abstract-method + """Basic stored data manager implementation. + + This is pretty much a port over from our old dataloading utilities, and is a little jank + under the hood. We may clean this up a little bit under the hood with more standard dataloading + components that can be strung together, but it can be just used as a black box for now since + only the constructor is likely to change in the future, or maybe passing in step number to the + next_train and next_eval functions. + + Args: + config: the DataManagerConfig used to instantiate class + """ + + config: RandomCamerasDataManagerConfig + + # pylint: disable=super-init-not-called + def __init__( + self, + config: RandomCamerasDataManagerConfig, + device: Union[torch.device, str] = "cpu", + test_mode: Literal["test", "val", "inference"] = "val", + world_size: int = 1, + local_rank: int = 0, + **kwargs, # pylint: disable=unused-argument + ): + self.config = config + self.device = device + self.world_size = world_size + self.local_rank = local_rank + self.sampler = None + self.test_mode = test_mode + self.test_split = "test" if test_mode in ["test", "inference"] else "val" + + if self.config.data is not None: + CONSOLE.print("[red] --data should not be used with the RandomCamerasDataManager[/red]") + sys.exit(1) + + cameras, _, _ = random_train_pose( + self.config.num_eval_angles, + self.config.eval_resolution, + device=self.device, + radius_mean=self.config.radius_mean, + radius_std=self.config.radius_std, + focal_range=self.config.focal_range, + central_rotation_range=(-180, 180), + vertical_rotation_range=self.config.vertical_rotation_range, + jitter_std=self.config.jitter_std, + center=self.config.center, + ) + + self.train_dataset = TrivialDataset(cameras) + self.eval_dataset = TrivialDataset(cameras) + + self.eval_dataloader = RandIndicesEvalDataloader( + input_dataset=self.eval_dataset, + device=self.device, + num_workers=self.world_size * 4, + ) + + # pylint: disable=non-parent-init-called + DataManager.__init__(self) + + def next_train(self, step: int) -> Tuple[RayBundle, Dict]: + """Returns the next batch of data from the train dataloader.""" + + self.train_count += 1 + horizontal_range = min((step / max(1, self.config.horizontal_rotation_warmup)), 1) * 180 + + cameras, vertical_rotation, central_rotation = random_train_pose( + self.config.train_images_per_batch, + self.config.train_resolution, + device=self.device, + radius_mean=self.config.radius_mean, + radius_std=self.config.radius_std, + focal_range=self.config.focal_range, + vertical_rotation_range=self.config.vertical_rotation_range, + jitter_std=self.config.jitter_std, + center=self.config.center, + central_rotation_range=(-horizontal_range, horizontal_range), + ) + ray_bundle = cameras.generate_rays(torch.tensor(list(range(self.config.train_images_per_batch)))).flatten() + + return ray_bundle, { + "vertical": vertical_rotation, + "central": central_rotation, + "initialization": True, + } + + def next_eval(self, step: int) -> Tuple[RayBundle, Dict]: + """Returns the next batch of data from the eval dataloader.""" + self.eval_count += 1 + + cameras, vertical_rotation, central_rotation = random_train_pose( + self.config.eval_images_per_batch, + self.config.eval_resolution, + device=self.device, + radius_mean=self.config.radius_mean, + radius_std=self.config.radius_std, + focal_range=self.config.focal_range, + vertical_rotation_range=self.config.vertical_rotation_range, + jitter_std=self.config.jitter_std, + center=self.config.center, + ) + ray_bundle = cameras.generate_rays( + torch.tensor([[i] for i in range(self.config.train_images_per_batch)]) + ).flatten() + + return ray_bundle, {"vertical": vertical_rotation, "central": central_rotation} + + def next_eval_image(self, step: int) -> Tuple[int, RayBundle, Dict]: + for camera_ray_bundle, batch in self.eval_dataloader: + assert camera_ray_bundle.camera_indices is not None + image_idx = int(camera_ray_bundle.camera_indices[0, 0, 0]) + return image_idx, camera_ray_bundle, batch + raise ValueError("No more eval images") + + def get_train_rays_per_batch(self) -> int: + return self.config.train_resolution**2 + + def get_eval_rays_per_batch(self) -> int: + return self.config.eval_resolution**2 + + def get_param_groups( + self, + ) -> Dict[str, List[Parameter]]: # pylint: disable=no-self-use + """Get the param groups for the data manager. + Returns: + A list of dictionaries containing the data manager's param groups. + """ + param_groups = {} + + return param_groups diff --git a/nerfstudio/data/utils/data_utils.py b/nerfstudio/data/utils/data_utils.py index 92a85ef8b..e3a37a75a 100644 --- a/nerfstudio/data/utils/data_utils.py +++ b/nerfstudio/data/utils/data_utils.py @@ -74,7 +74,7 @@ def get_depth_image_from_path( interpolation: Depth value interpolation for resizing. Returns: - Depth image torch tensor with shape [width, height, 1]. + Depth image torch tensor with shape [height, width, 1]. """ if filepath.suffix == ".npy": image = np.load(filepath) * scale_factor diff --git a/nerfstudio/engine/trainer.py b/nerfstudio/engine/trainer.py index 713263234..0ce05db0b 100644 --- a/nerfstudio/engine/trainer.py +++ b/nerfstudio/engine/trainer.py @@ -33,6 +33,7 @@ from rich.table import Table from torch.cuda.amp.grad_scaler import GradScaler from nerfstudio.configs.experiment_config import ExperimentConfig +from nerfstudio.data.datamanagers.base_datamanager import VanillaDataManager from nerfstudio.engine.callbacks import TrainingCallback, TrainingCallbackAttributes, TrainingCallbackLocation from nerfstudio.engine.optimizers import Optimizers from nerfstudio.pipelines.base_pipeline import VanillaPipeline @@ -81,6 +82,8 @@ class TrainerConfig(ExperimentConfig): """Path to checkpoint file.""" log_gradients: bool = False """Optionally log gradients during training""" + gradient_accumulation_steps: int = 1 + """Number of steps to accumulate gradients over.""" class Trainer: @@ -117,6 +120,7 @@ class Trainer: self.mixed_precision: bool = self.config.mixed_precision self.use_grad_scaler: bool = self.mixed_precision or self.config.use_grad_scaler self.training_state: Literal["training", "paused", "completed"] = "training" + self.gradient_accumulation_steps: int = self.config.gradient_accumulation_steps if self.device == "cpu": self.mixed_precision = False @@ -224,9 +228,11 @@ class Trainer: """Train the model.""" assert self.pipeline.datamanager.train_dataset is not None, "Missing DatsetInputs" - self.pipeline.datamanager.train_dataparser_outputs.save_dataparser_transform( - self.base_dir / "dataparser_transforms.json" - ) + # don't want to call save_dataparser_transform if pipeline's datamanager does not have a dataparser + if isinstance(self.pipeline.datamanager, VanillaDataManager): + self.pipeline.datamanager.train_dataparser_outputs.save_dataparser_transform( + self.base_dir / "dataparser_transforms.json" + ) self._init_viewer_state() with TimeWriter(writer, EventName.TOTAL_TRAIN_TIME): @@ -453,13 +459,16 @@ class Trainer: """ self.optimizers.zero_grad_all() - - device_type: str = self.device.split(":")[0] if "cuda" in self.device else "cpu" - - with torch.autocast(device_type=device_type, 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 + cpu_or_cuda_str: str = self.device.split(":")[0] + assert ( + self.gradient_accumulation_steps > 0 + ), f"gradient_accumulation_steps must be > 0, not {self.gradient_accumulation_steps}" + for _ in range(self.gradient_accumulation_steps): + 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()) + loss /= self.gradient_accumulation_steps + self.grad_scaler.scale(loss).backward() # type: ignore self.optimizers.optimizer_scaler_step_all(self.grad_scaler) if self.config.log_gradients: @@ -468,10 +477,10 @@ class Trainer: assert tag != "Total" if value.grad is not None: grad = value.grad.norm() - metrics_dict[f"Gradients/{tag}"] = grad + metrics_dict[f"Gradients/{tag}"] = grad # type: ignore total_grad += grad - metrics_dict["Gradients/Total"] = cast(torch.Tensor, total_grad) + metrics_dict["Gradients/Total"] = cast(torch.Tensor, total_grad) # type: ignore scale = self.grad_scaler.get_scale() self.grad_scaler.update() @@ -480,7 +489,7 @@ class Trainer: self.optimizers.scheduler_step_all(step) # Merging loss and metrics dict into a single output. - return loss, loss_dict, metrics_dict + return loss, loss_dict, metrics_dict # type: ignore @check_eval_enabled @profiler.time_function diff --git a/nerfstudio/field_components/cuda/__init__.py b/nerfstudio/field_components/cuda/__init__.py deleted file mode 100644 index 8b160d066..000000000 --- a/nerfstudio/field_components/cuda/__init__.py +++ /dev/null @@ -1,31 +0,0 @@ -# Copyright 2022 the Regents of the University of California, Nerfstudio Team and contributors. 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. - -"""init cuda functions""" -from typing import Callable - - -def _make_lazy_cuda_func(name: str) -> Callable: - """_make_lazy_cuda_func from nerfacc.cuda""" - - def call_cuda(*args, **kwargs): - from ._backend import _C - - return getattr(_C, name)(*args, **kwargs) - - return call_cuda - - -temporal_grid_encode_forward = _make_lazy_cuda_func("temporal_grid_encode_forward") -temporal_grid_encode_backward = _make_lazy_cuda_func("temporal_grid_encode_backward") diff --git a/nerfstudio/field_components/cuda/_backend.py b/nerfstudio/field_components/cuda/_backend.py deleted file mode 100644 index efaf67e13..000000000 --- a/nerfstudio/field_components/cuda/_backend.py +++ /dev/null @@ -1,58 +0,0 @@ -# Copyright 2022 the Regents of the University of California, Nerfstudio Team and contributors. 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. - -"""compiling the cuda kernels""" -import glob -import os -import shutil - -from nerfacc.cuda._backend import cuda_toolkit_available -from torch.utils.cpp_extension import _get_build_directory, load - -PATH = os.path.dirname(os.path.abspath(__file__)) -NAME = "nerfstudio_field_components_cuda" -BUILD_DIR = _get_build_directory(NAME, verbose=False) - - -_C = None -if cuda_toolkit_available(): - if os.listdir(BUILD_DIR) != []: - # If the build exists, we assume the extension has been built - # and we can load it. - print("nerfstudio field components: CUDA set up, loading (should be quick)") - _C = load( - name=NAME, - sources=glob.glob(os.path.join(PATH, "csrc/*.cu")), - extra_cflags=["-O3", "-std=c++14"], - extra_cuda_cflags=["-O3", "-std=c++14"], - extra_include_paths=[], - ) - else: - # Build from scratch. Remove the build directory just to be safe: pytorch jit might stuck - # if the build directory exists. - shutil.rmtree(BUILD_DIR) - print("nerfstudio field components: Setting up CUDA (This may take a few minutes the first time)") - _C = load( - name=NAME, - sources=glob.glob(os.path.join(PATH, "csrc/*.cu")), - extra_cflags=["-O3", "-std=c++14"], - extra_cuda_cflags=["-O3", "-std=c++14"], - extra_include_paths=[], - ) - print("nerfstudio field components: Setting up CUDA finished") -else: - print("nerfstudio field components: No CUDA toolkit found. Some models may fail.") - - -__all__ = ["_C"] diff --git a/nerfstudio/field_components/cuda/csrc/include/temporal_gridencoder.h b/nerfstudio/field_components/cuda/csrc/include/temporal_gridencoder.h deleted file mode 100644 index 7b5ad3d28..000000000 --- a/nerfstudio/field_components/cuda/csrc/include/temporal_gridencoder.h +++ /dev/null @@ -1,62 +0,0 @@ -/* - * Code adapted from (@ashawkey) https://github.com/ashawkey/torch-ngp/ - * Author: @lsongx - */ - -#ifndef _TEMPORAL_HASH_ENCODE_H -#define _TEMPORAL_HASH_ENCODE_H - -#include -#include - -// inputs: input coordinates, [B, D], float, in [0, 1] -// temporal_row_index: row index for sampling from channels, [B, 4*num_of_channels], uint32_t -// embeddings: the grid embedding, [sO, grid_C], float -// offsets: offsets for different levels used in NGP, [L + 1], uint32_t -// outputs: interpolated outputs, [B, L * C], float -// grid_C: number of channels for the grid embedding -// B: batch size -// D: coord dim -// L: number of levels -// S: resolution multiplier at each level -// H: base resolution - -void temporal_grid_encode_forward( - const at::Tensor inputs, - const at::Tensor temporal_row_index, - const at::Tensor embeddings, - const at::Tensor offsets, - at::Tensor outputs, - const uint32_t B, - const uint32_t D, - const uint32_t grid_C, - const uint32_t C, - const uint32_t L, - const float S, - const uint32_t H, - at::optional dy_dx, - const uint32_t gridtype, - const bool align_corners -); - -void temporal_grid_encode_backward( - const at::Tensor grad, - const at::Tensor inputs, - const at::Tensor temporal_row_index, - const at::Tensor embeddings, - const at::Tensor offsets, - at::Tensor grad_embeddings, - const uint32_t B, - const uint32_t D, - const uint32_t grid_C, - const uint32_t C, - const uint32_t L, - const float S, - const uint32_t H, - const at::optional dy_dx, - at::optional grad_inputs, - const uint32_t gridtype, - const bool align_corners -); - -#endif \ No newline at end of file diff --git a/nerfstudio/field_components/cuda/csrc/pybind.cu b/nerfstudio/field_components/cuda/csrc/pybind.cu deleted file mode 100644 index 877b386ca..000000000 --- a/nerfstudio/field_components/cuda/csrc/pybind.cu +++ /dev/null @@ -1,14 +0,0 @@ -/* - * Code adapted from (@ashawkey) https://github.com/ashawkey/torch-ngp/ - * Author: @lsongx - */ - - -#include - -#include "include/temporal_gridencoder.h" - -PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) { - m.def("temporal_grid_encode_forward", &temporal_grid_encode_forward, "temporal_grid_encode_forward (CUDA)"); - m.def("temporal_grid_encode_backward", &temporal_grid_encode_backward, "temporal_grid_encode_backward (CUDA)"); -} \ No newline at end of file diff --git a/nerfstudio/field_components/cuda/csrc/temporal_gridencoder.cu b/nerfstudio/field_components/cuda/csrc/temporal_gridencoder.cu deleted file mode 100644 index b0ca666eb..000000000 --- a/nerfstudio/field_components/cuda/csrc/temporal_gridencoder.cu +++ /dev/null @@ -1,667 +0,0 @@ -/* - * Code adapted from (@ashawkey) https://github.com/ashawkey/torch-ngp/blob/main/gridencoder/src/gridencoder.cu - * Author: @lsongx - */ - -#include -#include -#include - -#include -#include - -#include -#include - -#include -#include - - -#define CHECK_CUDA(x) TORCH_CHECK(x.device().is_cuda(), #x " must be a CUDA tensor") -#define CHECK_CONTIGUOUS(x) TORCH_CHECK(x.is_contiguous(), #x " must be a contiguous tensor") -#define CHECK_INPUT(x) CHECK_CUDA(x); CHECK_CONTIGUOUS(x) -#define CHECK_IS_INT(x) TORCH_CHECK(x.scalar_type() == at::ScalarType::Int, #x " must be an int tensor") -#define CHECK_IS_FLOATING(x) TORCH_CHECK( \ - x.scalar_type() == at::ScalarType::Float || \ - x.scalar_type() == at::ScalarType::Half || \ - x.scalar_type() == at::ScalarType::Double, #x " must be a floating tensor" \ -) - - -// just for compatability of half precision in AT_DISPATCH_FLOATING_TYPES_AND_HALF... -static inline __device__ at::Half atomicAdd(at::Half *address, at::Half val) { - // requires CUDA >= 10 and ARCH >= 70 - // this is very slow compared to float or __half2, and never used. - // The following line was commented in torch-ngp; uncomment it in case someone want to try fp16... - return atomicAdd(reinterpret_cast<__half*>(address), val); -} - - -template -static inline __host__ __device__ T div_round_up(T val, T divisor) { - return (val + divisor - 1) / divisor; -} - - -template -__device__ uint32_t fast_hash(const uint32_t pos_grid[D]) { - - // coherent type of hashing - constexpr uint32_t primes[7] = { 1u, 2654435761u, 805459861u, 3674653429u, 2097192037u, 1434869437u, 2165219737u }; - - uint32_t result = 0; - #pragma unroll - for (uint32_t i = 0; i < D; ++i) { - result ^= pos_grid[i] * primes[i]; - } - - return result; -} - -// locate the index of grid with channel (ch) -template -__device__ uint32_t get_grid_index( - const uint32_t gridtype, // gridtype: 0 == hash, 1 == tiled - const uint32_t grid_C, // number of total channels for the embedding - const bool align_corners, - const uint32_t ch, // number of output channels - const uint32_t hashmap_size, - const uint32_t resolution, - const uint32_t pos_grid[D] // location of the grid -) { - uint32_t stride = 1; - uint32_t index = 0; - - #pragma unroll - for (uint32_t d = 0; d < D && stride <= hashmap_size; d++) { - index += pos_grid[d] * stride; - stride *= align_corners ? resolution: (resolution + 1); - } - - // NOTE: for NeRF, the hash is in fact not necessary. Check https://github.com/NVlabs/instant-ngp/issues/97. - // gridtype: 0 == hash, 1 == tiled - if (gridtype == 0 && stride > hashmap_size) { - index = fast_hash(pos_grid); - } - - return (index % hashmap_size) * grid_C + ch; -} - -// grid sampling kernel -template -__global__ void kernel_grid( - const float * __restrict__ inputs, // input coordinates - const float * __restrict__ temporal_row_index, // row index for sampling from channels - const scalar_t * __restrict__ grid, // the grid embedding - const int * __restrict__ offsets, // offsets for different levels used in NGP - scalar_t * __restrict__ outputs, - const uint32_t B, // batch size - const uint32_t grid_C, // number of channels for the grid embedding - const uint32_t L, // number of levels - const float S, // resolution multiplier at each level - const uint32_t H, // base resolution - scalar_t * __restrict__ dy_dx, // gradient to the input coords - const uint32_t gridtype, // gridtype: 0 == hash, 1 == tiled - const bool align_corners -) { - const uint32_t b = blockIdx.x * blockDim.x + threadIdx.x; - - if (b >= B) return; - - const uint32_t level = blockIdx.y; - - // locate - grid += (uint32_t)offsets[level] * grid_C; - inputs += b * D; - outputs += level * B * C + b * C; - temporal_row_index += b*C*4; - - // check input range (should be in [0, 1]) - bool flag_oob = false; - #pragma unroll - for (uint32_t d = 0; d < D; d++) { - if (inputs[d] < 0 || inputs[d] > 1) { - flag_oob = true; - } - } - // if input out of bound, just set output to 0 - if (flag_oob) { - #pragma unroll - for (uint32_t ch = 0; ch < C; ch++) { - outputs[ch] = 0; - } - if (dy_dx) { - dy_dx += b * D * L * C + level * D * C; // B L D C - #pragma unroll - for (uint32_t d = 0; d < D; d++) { - #pragma unroll - for (uint32_t ch = 0; ch < C; ch++) { - dy_dx[d * C + ch] = 0; - } - } - } - return; - } - - const uint32_t hashmap_size = offsets[level + 1] - offsets[level]; - const float scale = exp2f(level * S) * H - 1.0f; - const uint32_t resolution = (uint32_t)ceil(scale) + 1; - - // calculate coordinate - float pos[D]; - uint32_t pos_grid[D]; - - #pragma unroll - for (uint32_t d = 0; d < D; d++) { - pos[d] = inputs[d] * scale + (align_corners ? 0.0f : 0.5f); - pos_grid[d] = floorf(pos[d]); - pos[d] -= (float)pos_grid[d]; - } - - // interpolate - scalar_t results[C] = {0}; // temp results in register - - #pragma unroll - for (uint32_t idx = 0; idx < (1 << D); idx++) { - float w = 1; - uint32_t pos_grid_local[D]; - - #pragma unroll - for (uint32_t d = 0; d < D; d++) { - if ((idx & (1 << d)) == 0) { - w *= 1 - pos[d]; - pos_grid_local[d] = pos_grid[d]; - } else { - w *= pos[d]; - pos_grid_local[d] = pos_grid[d] + 1; - } - } - - // writing to register (fast) - #pragma unroll - for (uint32_t ch = 0; ch < C; ch++) { - if (temporal_row_index[ch*4] == 1) { - // if a temporal_row_index == 1, then no interpolation between channels are used - uint32_t index = get_grid_index(gridtype, grid_C, align_corners, - __float2uint_rn(temporal_row_index[ch*4+1]), hashmap_size, resolution, pos_grid_local); - results[ch] += w * grid[index]; - } else { - // else, we need to interpolate between channels - uint32_t index_a = get_grid_index(gridtype, grid_C, align_corners, - __float2uint_rn(temporal_row_index[ch*4+1]), hashmap_size, resolution, pos_grid_local); - uint32_t index_b = get_grid_index(gridtype, grid_C, align_corners, - __float2uint_rn(temporal_row_index[ch*4+3]), hashmap_size, resolution, pos_grid_local); - results[ch] += w * (grid[index_a]*temporal_row_index[ch*4]+grid[index_b]*temporal_row_index[ch*4+2]); - } - } - } - - // writing to global memory (slow) - #pragma unroll - for (uint32_t ch = 0; ch < C; ch++) { - outputs[ch] = results[ch]; - } - - // prepare dy_dx - // differentiable (soft) indexing: https://discuss.pytorch.org/t/differentiable-indexing/17647/9 - if (dy_dx) { - - dy_dx += b * D * L * C + level * D * C; // B L D C - - #pragma unroll - for (uint32_t gd = 0; gd < D; gd++) { - - scalar_t results_grad[C] = {0}; - - #pragma unroll - for (uint32_t idx = 0; idx < (1 << (D - 1)); idx++) { - float w = scale; - uint32_t pos_grid_local[D]; - - #pragma unroll - for (uint32_t nd = 0; nd < D - 1; nd++) { - const uint32_t d = (nd >= gd) ? (nd + 1) : nd; - - if ((idx & (1 << nd)) == 0) { - w *= 1 - pos[d]; - pos_grid_local[d] = pos_grid[d]; - } else { - w *= pos[d]; - pos_grid_local[d] = pos_grid[d] + 1; - } - } - - scalar_t left[C] = {0}; - scalar_t right[C] = {0}; - pos_grid_local[gd] = pos_grid[gd]; - #pragma unroll - for (uint32_t ch = 0; ch < C; ch++) { - if (temporal_row_index[ch*4] == 1) { - uint32_t index = get_grid_index(gridtype, grid_C, align_corners, - __float2uint_rn(temporal_row_index[ch*4+1]), hashmap_size, resolution, pos_grid_local); - left[ch] += grid[index]; - } else { - uint32_t index_a = get_grid_index(gridtype, grid_C, align_corners, - __float2uint_rn(temporal_row_index[ch*4+1]), hashmap_size, resolution, pos_grid_local); - uint32_t index_b = get_grid_index(gridtype, grid_C, align_corners, - __float2uint_rn(temporal_row_index[ch*4+3]), hashmap_size, resolution, pos_grid_local); - left[ch] += grid[index_a]*temporal_row_index[ch*4]+grid[index_b]*temporal_row_index[ch*4+2]; - } - } - - pos_grid_local[gd] = pos_grid[gd] + 1; - #pragma unroll - for (uint32_t ch = 0; ch < C; ch++) { - if (temporal_row_index[ch*4] == 1) { - uint32_t index = get_grid_index(gridtype, grid_C, align_corners, - __float2uint_rn(temporal_row_index[ch*4+1]), hashmap_size, resolution, pos_grid_local); - right[ch] += grid[index]; - } else { - uint32_t index_a = get_grid_index(gridtype, grid_C, align_corners, - __float2uint_rn(temporal_row_index[ch*4+1]), hashmap_size, resolution, pos_grid_local); - uint32_t index_b = get_grid_index(gridtype, grid_C, align_corners, - __float2uint_rn(temporal_row_index[ch*4+3]), hashmap_size, resolution, pos_grid_local); - right[ch] += grid[index_a]*temporal_row_index[ch*4]+grid[index_b]*temporal_row_index[ch*4+2]; - } - } - - #pragma unroll - for (uint32_t ch = 0; ch < C; ch++) { - results_grad[ch] += w * (right[ch] - left[ch]); - } - } - - #pragma unroll - for (uint32_t ch = 0; ch < C; ch++) { - dy_dx[gd * C + ch] = results_grad[ch]; - } - } - } -} - -// grid backward kernel; N_C is kept here though always set to 1 (maybe useful for future updates) -template -__global__ void kernel_grid_backward( - const scalar_t * __restrict__ grad, - const float * __restrict__ inputs, - const float * __restrict__ temporal_row_index, - const scalar_t * __restrict__ grid, - const int * __restrict__ offsets, - scalar_t * __restrict__ grad_grid, - const uint32_t B, - const uint32_t grid_C, - const uint32_t L, - const float S, - const uint32_t H, - const uint32_t gridtype, - const bool align_corners -) { - const uint32_t b = (blockIdx.x * blockDim.x + threadIdx.x) * N_C / C; - if (b >= B) return; - - const uint32_t level = blockIdx.y; - // embed channel (from the outputs) - const uint32_t ch = (blockIdx.x * blockDim.x + threadIdx.x) * N_C - b * C; - - // locate - grad_grid += offsets[level] * grid_C; - inputs += b * D; - grad += level * B * C + b * C + ch; // L, B, C - temporal_row_index += b*C*4 + ch*4; - - const uint32_t hashmap_size = offsets[level + 1] - offsets[level]; - const float scale = exp2f(level * S) * H - 1.0f; - const uint32_t resolution = (uint32_t)ceil(scale) + 1; - - // check input range (should be in [0, 1]) - #pragma unroll - for (uint32_t d = 0; d < D; d++) { - if (inputs[d] < 0 || inputs[d] > 1) { - return; // grad is init as 0, so we simply return. - } - } - - // calculate coordinate - float pos[D]; - uint32_t pos_grid[D]; - - #pragma unroll - for (uint32_t d = 0; d < D; d++) { - pos[d] = inputs[d] * scale + (align_corners ? 0.0f : 0.5f); - pos_grid[d] = floorf(pos[d]); - pos[d] -= (float)pos_grid[d]; - } - - scalar_t grad_cur = grad[0]; - - // interpolate - #pragma unroll - for (uint32_t idx = 0; idx < (1 << D); idx++) { - float w = 1; - uint32_t pos_grid_local[D]; - - #pragma unroll - for (uint32_t d = 0; d < D; d++) { - if ((idx & (1 << d)) == 0) { - w *= 1 - pos[d]; - pos_grid_local[d] = pos_grid[d]; - } else { - w *= pos[d]; - pos_grid_local[d] = pos_grid[d] + 1; - } - } - - // get the weights used for calculating the interpolation - if (temporal_row_index[0] == 1) { - // if no interpolation, directly return grad - uint32_t index = get_grid_index(gridtype, grid_C, align_corners, - __float2uint_rn(temporal_row_index[1]), hashmap_size, resolution, pos_grid_local); - atomicAdd(&grad_grid[index], w*grad_cur); - } else { - // if interpolation used, return with weights multiplied - uint32_t index_a = get_grid_index(gridtype, grid_C, align_corners, - __float2uint_rn(temporal_row_index[1]), hashmap_size, resolution, pos_grid_local); - uint32_t index_b = get_grid_index(gridtype, grid_C, align_corners, - __float2uint_rn(temporal_row_index[3]), hashmap_size, resolution, pos_grid_local); - atomicAdd(&grad_grid[index_a], temporal_row_index[0]*w*grad_cur); - atomicAdd(&grad_grid[index_b], temporal_row_index[2]*w*grad_cur); - } - } -} - -// coord backward kernel -template -__global__ void kernel_input_backward( - const scalar_t * __restrict__ grad, - const scalar_t * __restrict__ dy_dx, - scalar_t * __restrict__ grad_inputs, - uint32_t B, - uint32_t L -) { - const uint32_t t = threadIdx.x + blockIdx.x * blockDim.x; - if (t >= B * D) return; - - const uint32_t b = t / D; - const uint32_t d = t - b * D; - - dy_dx += b * L * D * C; - - scalar_t result = 0; - - # pragma unroll - for (int l = 0; l < L; l++) { - # pragma unroll - for (int ch = 0; ch < C; ch++) { - result += grad[l * B * C + b * C + ch] * dy_dx[l * D * C + d * C + ch]; - } - } - - grad_inputs[t] = result; -} - - -template -void kernel_grid_wrapper( - const float *inputs, - const float *temporal_row_index, - const scalar_t *embeddings, - const int *offsets, - scalar_t *outputs, - const uint32_t B, - const uint32_t grid_C, - const uint32_t C, - const uint32_t L, - const float S, - const uint32_t H, - scalar_t *dy_dx, - const uint32_t gridtype, - const bool align_corners -) { - static constexpr uint32_t N_THREAD = 512; - const dim3 blocks_hashgrid = { div_round_up(B, N_THREAD), L, 1 }; - switch (C) { - case 1: kernel_grid<<>>( - inputs, temporal_row_index, embeddings, offsets, outputs, - B, grid_C, L, S, H, dy_dx, gridtype, align_corners); break; - case 2: kernel_grid<<>>( - inputs, temporal_row_index, embeddings, offsets, outputs, - B, grid_C, L, S, H, dy_dx, gridtype, align_corners); break; - case 4: kernel_grid<<>>( - inputs, temporal_row_index, embeddings, offsets, outputs, - B, grid_C, L, S, H, dy_dx, gridtype, align_corners); break; - case 8: kernel_grid<<>>( - inputs, temporal_row_index, embeddings, offsets, outputs, - B, grid_C, L, S, H, dy_dx, gridtype, align_corners); break; - default: throw std::runtime_error{"GridEncoding: C must be 1, 2, 4, or 8."}; - } -} - -template -void temporal_grid_encode_forward_cuda( - const float *inputs, - const float *temporal_row_index, - const scalar_t *embeddings, - const int *offsets, - scalar_t *outputs, - const uint32_t B, - const uint32_t D, - const uint32_t grid_C, - const uint32_t C, - const uint32_t L, - const float S, - const uint32_t H, - scalar_t *dy_dx, - const uint32_t gridtype, - const bool align_corners -) { - switch (D) { - case 1: kernel_grid_wrapper( - inputs, temporal_row_index, embeddings, offsets, outputs, - B, grid_C, C, L, S, H, dy_dx, gridtype, align_corners); break; - case 2: kernel_grid_wrapper( - inputs, temporal_row_index, embeddings, offsets, outputs, - B, grid_C, C, L, S, H, dy_dx, gridtype, align_corners); break; - case 3: kernel_grid_wrapper( - inputs, temporal_row_index, embeddings, offsets, outputs, - B, grid_C, C, L, S, H, dy_dx, gridtype, align_corners); break; - case 4: kernel_grid_wrapper( - inputs, temporal_row_index, embeddings, offsets, outputs, - B, grid_C, C, L, S, H, dy_dx, gridtype, align_corners); break; - case 5: kernel_grid_wrapper( - inputs, temporal_row_index, embeddings, offsets, outputs, - B, grid_C, C, L, S, H, dy_dx, gridtype, align_corners); break; - default: throw std::runtime_error{"GridEncoding: D must be 1, 2, 3, 4, or 5."}; - } -} - -template -void kernel_grid_backward_wrapper( - const scalar_t *grad, - const float *inputs, - const float *temporal_row_index, - const scalar_t *embeddings, - const int *offsets, - scalar_t *grad_embeddings, - const uint32_t B, - const uint32_t grid_C, - const uint32_t C, - const uint32_t L, - const float S, - const uint32_t H, - scalar_t *dy_dx, - scalar_t *grad_inputs, - const uint32_t gridtype, - const bool align_corners -) { - static constexpr uint32_t N_THREAD = 256; - const dim3 blocks_hashgrid = { div_round_up(B * C, N_THREAD), L, 1 }; - switch (C) { - case 1: - kernel_grid_backward<<>>( - grad, inputs, temporal_row_index, - embeddings, offsets, grad_embeddings, B, grid_C, L, S, H, gridtype, align_corners); - if (dy_dx) { - kernel_input_backward<<>>( - grad, dy_dx, grad_inputs, B, L); - } - break; - case 2: - kernel_grid_backward<<>>( - grad, inputs, temporal_row_index, - embeddings, offsets, grad_embeddings, B, grid_C, L, S, H, gridtype, align_corners); - if (dy_dx) { - kernel_input_backward<<>>( - grad, dy_dx, grad_inputs, B, L); - } - break; - case 4: - kernel_grid_backward<<>>( - grad, inputs, temporal_row_index, - embeddings, offsets, grad_embeddings, B, grid_C, L, S, H, gridtype, align_corners); - if (dy_dx) { - kernel_input_backward<<>>( - grad, dy_dx, grad_inputs, B, L); - } - break; - case 8: - kernel_grid_backward<<>>( - grad, inputs, temporal_row_index, - embeddings, offsets, grad_embeddings, B, grid_C, L, S, H, gridtype, align_corners); - if (dy_dx) { - kernel_input_backward<<>>( - grad, dy_dx, grad_inputs, B, L); - } - break; - default: throw std::runtime_error{"GridEncoding: C must be 1, 2, 4, or 8."}; - } -} - -template -void temporal_grid_encode_backward_cuda( - const scalar_t *grad, - const float *inputs, - const float *temporal_row_index, - const scalar_t *embeddings, - const int *offsets, - scalar_t *grad_embeddings, - const uint32_t B, - const uint32_t D, - const uint32_t grid_C, - const uint32_t C, - const uint32_t L, - const float S, - const uint32_t H, - scalar_t *dy_dx, - scalar_t *grad_inputs, - const uint32_t gridtype, - const bool align_corners -) { - switch (D) { - case 1: kernel_grid_backward_wrapper( - grad, inputs, temporal_row_index, embeddings, offsets, - grad_embeddings, B, grid_C, C, L, S, H, dy_dx, grad_inputs, gridtype, align_corners); break; - case 2: kernel_grid_backward_wrapper( - grad, inputs, temporal_row_index, embeddings, offsets, - grad_embeddings, B, grid_C, C, L, S, H, dy_dx, grad_inputs, gridtype, align_corners); break; - case 3: kernel_grid_backward_wrapper( - grad, inputs, temporal_row_index, embeddings, offsets, - grad_embeddings, B, grid_C, C, L, S, H, dy_dx, grad_inputs, gridtype, align_corners); break; - case 4: kernel_grid_backward_wrapper( - grad, inputs, temporal_row_index, embeddings, offsets, - grad_embeddings, B, grid_C, C, L, S, H, dy_dx, grad_inputs, gridtype, align_corners); break; - case 5: kernel_grid_backward_wrapper( - grad, inputs, temporal_row_index, embeddings, offsets, - grad_embeddings, B, grid_C, C, L, S, H, dy_dx, grad_inputs, gridtype, align_corners); break; - default: throw std::runtime_error{"GridEncoding: D must be 1, 2, 3, 4, or 5."}; - } -} - -void temporal_grid_encode_forward( - const at::Tensor inputs, - const at::Tensor temporal_row_index, - const at::Tensor embeddings, - const at::Tensor offsets, - at::Tensor outputs, - const uint32_t B, - const uint32_t D, - const uint32_t grid_C, - const uint32_t C, - const uint32_t L, - const float S, - const uint32_t H, - at::optional dy_dx, - const uint32_t gridtype, - const bool align_corners -) { - CHECK_INPUT(inputs); - CHECK_INPUT(temporal_row_index); - CHECK_INPUT(embeddings); - CHECK_INPUT(offsets); - CHECK_INPUT(outputs); - // CHECK_INPUT(dy_dx); - - CHECK_IS_FLOATING(inputs); - CHECK_IS_FLOATING(temporal_row_index); - CHECK_IS_FLOATING(embeddings); - CHECK_IS_INT(offsets); - CHECK_IS_FLOATING(outputs); - // CHECK_IS_FLOATING(dy_dx); - - AT_DISPATCH_FLOATING_TYPES_AND_HALF( - embeddings.scalar_type(), "temporal_grid_encode_forward", ([&] { - temporal_grid_encode_forward_cuda( - inputs.data_ptr(), temporal_row_index.data_ptr(), embeddings.data_ptr(), - offsets.data_ptr(), outputs.data_ptr(), B, D, grid_C, C, L, S, H, - dy_dx.has_value() ? dy_dx.value().data_ptr() : nullptr, - gridtype, align_corners); - })); -} - -void temporal_grid_encode_backward( - const at::Tensor grad, - const at::Tensor inputs, - const at::Tensor temporal_row_index, - const at::Tensor embeddings, - const at::Tensor offsets, - at::Tensor grad_embeddings, - const uint32_t B, - const uint32_t D, - const uint32_t grid_C, - const uint32_t C, - const uint32_t L, - const float S, - const uint32_t H, - const at::optional dy_dx, - at::optional grad_inputs, - const uint32_t gridtype, - const bool align_corners -) { - CHECK_INPUT(grad); - CHECK_INPUT(inputs); - CHECK_INPUT(temporal_row_index); - CHECK_INPUT(embeddings); - CHECK_INPUT(offsets); - CHECK_INPUT(grad_embeddings); - // CHECK_INPUT(dy_dx); - // CHECK_INPUT(grad_inputs); - - CHECK_IS_FLOATING(grad); - CHECK_IS_FLOATING(inputs); - CHECK_IS_FLOATING(temporal_row_index); - CHECK_IS_FLOATING(embeddings); - CHECK_IS_INT(offsets); - CHECK_IS_FLOATING(grad_embeddings); - // CHECK_IS_FLOATING(dy_dx); - // CHECK_IS_FLOATING(grad_inputs); - - AT_DISPATCH_FLOATING_TYPES_AND_HALF( - grad.scalar_type(), "temporal_grid_encode_backward", ([&] { - temporal_grid_encode_backward_cuda( - grad.data_ptr(), inputs.data_ptr(), temporal_row_index.data_ptr(), - embeddings.data_ptr(), offsets.data_ptr(), grad_embeddings.data_ptr(), - B, D, grid_C, C, L, S, H, - dy_dx.has_value() ? dy_dx.value().data_ptr() : nullptr, - grad_inputs.has_value() ? grad_inputs.value().data_ptr() : nullptr, - gridtype, align_corners); - })); -} diff --git a/nerfstudio/field_components/field_heads.py b/nerfstudio/field_components/field_heads.py index ed199b4b9..44df9f602 100644 --- a/nerfstudio/field_components/field_heads.py +++ b/nerfstudio/field_components/field_heads.py @@ -34,6 +34,7 @@ class FieldHeadNames(Enum): NORMALS = "normals" PRED_NORMALS = "pred_normals" UNCERTAINTY = "uncertainty" + BACKGROUND_RGB = "background_rgb" TRANSIENT_RGB = "transient_rgb" TRANSIENT_DENSITY = "transient_density" SEMANTICS = "semantics" diff --git a/nerfstudio/field_components/temporal_grid.py b/nerfstudio/field_components/temporal_grid.py deleted file mode 100644 index 5c80c57a3..000000000 --- a/nerfstudio/field_components/temporal_grid.py +++ /dev/null @@ -1,363 +0,0 @@ -# Copyright 2022 the Regents of the University of California, Nerfstudio Team and contributors. 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. - -"""Implements the temporal grid used by NeRFPlayer (https://arxiv.org/abs/2210.15947). -A time conditioned sliding window is applied on the feature channels, so -that the feature vectors become time-aware. -(A large) Part of the code are adapted from (@ashawkey) https://github.com/ashawkey/torch-ngp/ -""" -from typing import Optional - -import numpy as np -import torch -from jaxtyping import Float, Int -from torch import Tensor, nn -from torch.autograd import Function -from torch.cuda.amp import custom_bwd, custom_fwd - -import nerfstudio.field_components.cuda as _C - - -class TemporalGridEncodeFunc(Function): - """Class for autograd in pytorch.""" - - @staticmethod - @custom_fwd - def forward( - ctx, - inputs: Float[Tensor, "bs input_dim"], - temporal_row_index: Float[Tensor, "bs temporal_index_dim"], - embeddings: Float[Tensor, "table_size embed_dim"], - offsets: Int[Tensor, "num_levels_plus_1"], - per_level_scale: float, - base_resolution: int, - calc_grad_inputs: bool = False, - gridtype: int = 0, - align_corners: bool = False, - ) -> Float[Tensor, "bs output_dim"]: - """Call forward and interpolate the feature from embeddings - - Args: - inputs: the input coords - temporal_row_index: the input index of channels for doing the interpolation - embeddings: the saved (hashing) table for the feature grid (of the full sequence) - offsets: offsets for each level in the multilevel table, used for locating in cuda kernels - per_level_scale: scale parameter for the table; same as InstantNGP - base_resolution: base resolution for the table; same as InstantNGP - calc_grad_inputs: bool indicator for calculating gradients on the inputs - gridtype: 0 == hash, 1 == tiled; tiled is a baseline in InstantNGP (not random collision) - align_corners: same as other interpolation operators - """ - - inputs = inputs.contiguous() - temporal_row_index = temporal_row_index.contiguous() - - B, D = inputs.shape # batch size, coord dim - L = offsets.shape[0] - 1 # level - grid_channel = embeddings.shape[1] # embedding dim for each level - C = temporal_row_index.shape[1] // 4 # output embedding dim for each level - S = np.log2(per_level_scale) # resolution multiplier at each level, apply log2 for later CUDA exp2f - H = base_resolution # base resolution - - # torch.half used by torch-ngp, but we disable it - # (could be of negative impact on the performance? not sure, but feel free to inform me and help improve it!) - # # manually handle autocast (only use half precision embeddings, inputs must be float for enough precision) - # # if C % 2 != 0, force float, since half for atomicAdd is very slow. - # if torch.is_autocast_enabled() and C % 2 == 0: - # embeddings = embeddings.to(torch.half) - - # L first, optimize cache for cuda kernel, but needs an extra permute later - outputs = torch.empty(L, B, C, device=inputs.device, dtype=embeddings.dtype) - - if calc_grad_inputs: - dy_dx = torch.empty(B, L * D * C, device=inputs.device, dtype=embeddings.dtype) - else: - dy_dx = None - - _C.temporal_grid_encode_forward( - inputs, - temporal_row_index, - embeddings, - offsets, - outputs, - B, - D, - grid_channel, - C, - L, - S, - H, - dy_dx, - gridtype, - align_corners, - ) - - # permute back to [B, L * C] - outputs = outputs.permute(1, 0, 2).reshape(B, L * C) - - ctx.save_for_backward(inputs, temporal_row_index, embeddings, offsets, dy_dx) - ctx.dims = [B, D, grid_channel, C, L, S, H, gridtype] - ctx.align_corners = align_corners - - return outputs - - @staticmethod - @custom_bwd - def backward(ctx, grad): - inputs, temporal_row_index, embeddings, offsets, dy_dx = ctx.saved_tensors - B, D, grid_channel, C, L, S, H, gridtype = ctx.dims - align_corners = ctx.align_corners - - # grad: [B, L * C] --> [L, B, C] - grad = grad.view(B, L, C).permute(1, 0, 2).contiguous() - - grad_embeddings = torch.zeros_like(embeddings).contiguous() - - if dy_dx is not None: - grad_inputs = torch.zeros_like(inputs, dtype=embeddings.dtype) - else: - grad_inputs = None - - _C.temporal_grid_encode_backward( - grad, - inputs, - temporal_row_index, - embeddings, - offsets, - grad_embeddings, - B, - D, - grid_channel, - C, - L, - S, - H, - dy_dx, - grad_inputs, - gridtype, - align_corners, - ) - - if grad_inputs is not None: - grad_inputs = grad_inputs.to(inputs.dtype) - - return grad_inputs, None, grad_embeddings, None, None, None, None, None, None - - -class TemporalGridEncoder(nn.Module): - """Class for temporal grid encoding. - This class extends the grid encoding (from InstantNGP) by allowing the output time-dependent feature channels. - For example, for time 0 the interpolation uses channels [0,1], then for time 1 channels [2,1] are used. - This operation can be viewed as applying a time-dependent sliding window on the feature channels. - - Args: - temporal_dim: the dimension of temporal modeling; a higher dim indicates a higher freq on the time axis - input_dim: the dimension of input coords - num_levels: number of levels for multi-scale hashing; same as InstantNGP - level_dim: the dim of output feature vector for each level; same as InstantNGP - per_level_scale: scale factor; same as InstantNGP - base_resolution: base resolution for the table; same as InstantNGP - log2_hashmap_size: the size of the table; same as InstantNGP - desired_resolution: desired resolution at the last level; same as InstantNGP - gridtype: "tiled" or "hash" - align_corners: same as other interpolation operators - """ - - sampling_index: Tensor - index_a_mask: Tensor - index_b_mask: Tensor - index_list: Tensor - - def __init__( - self, - temporal_dim: int = 64, - input_dim: int = 3, - num_levels: int = 16, - level_dim: int = 2, - per_level_scale: float = 2.0, - base_resolution: int = 16, - log2_hashmap_size: int = 19, - desired_resolution: Optional[int] = None, - gridtype: str = "hash", - align_corners: bool = False, - ) -> None: - super().__init__() - - # the finest resolution desired at the last level, if provided, overridee per_level_scale - if desired_resolution is not None: - per_level_scale = np.exp2(np.log2(desired_resolution / base_resolution) / (num_levels - 1)) - - self.temporal_dim = temporal_dim - self.input_dim = input_dim # coord dims, 2 or 3 - self.num_levels = num_levels # num levels, each level multiply resolution by 2 - self.level_dim = level_dim # encode channels per level - self.per_level_scale = per_level_scale # multiply resolution by this scale at each level. - self.log2_hashmap_size = log2_hashmap_size - self.base_resolution = base_resolution - self.output_dim = num_levels * level_dim - self.gridtype = gridtype - _gridtype_to_id = {"hash": 0, "tiled": 1} - self.gridtype_id = _gridtype_to_id[gridtype] # "tiled" or "hash" - self.align_corners = align_corners - - # allocate parameters - offsets = [] - offset = 0 - self.max_params = 2**log2_hashmap_size - for i in range(num_levels): - resolution = int(np.ceil(base_resolution * per_level_scale**i)) - params_in_level = min( - self.max_params, (resolution if align_corners else resolution + 1) ** input_dim - ) # limit max number - params_in_level = int(np.ceil(params_in_level / 8) * 8) # make divisible - offsets.append(offset) - offset += params_in_level - offsets.append(offset) - offsets = torch.from_numpy(np.array(offsets, dtype=np.int32)) - self.register_buffer("offsets", offsets) - self.n_params = offsets[-1] * level_dim - self.embeddings = nn.Parameter(torch.empty(offset, level_dim + temporal_dim)) - self.init_parameters() - - def init_parameters(self) -> None: - """Initialize the parameters: - 1. Uniform initialization of the embeddings - 2. Temporal interpolation index initialization: - For each temporal dim, we initialize a interpolation candidate. - For example, if temporal dim 0, we use channels [0,1,2,3], then for temporal dim 1, - we use channels [4,1,2,3]. After that, temporal dim 2, we use channels [4,5,2,3]. - This is for the alignment of the channels. I.e., each temporal dim should differ - on only one channel, otherwise moving from one temporal dim to the next one is not - that consistent. - To associate time w.r.t. temporal dim, we evenly distribute time into the temporal dims. - That is, if we have 16 temporal dims, then the 16th channel combinations is the time 1. - (Time should be within 0 and 1.) Given a time, we first look up which temporal dim should - be used. And then compute the linear combination weights. - For implementing it, a table for all possible channel combination are used. Each row in - the table is the candidate feature channels, and means we move from one temporal dim to - the next one. For example, the first row will use feature channels [0,1,2,3,4]. Each row - is of length `num_of_output_channel*4`. The expanding param 4 is for saving the combination - weights and channels. The first row will be [?,0,?,1, 1,2,0,0, 1,3,0,0, 1,4,0,0]. Each - 4 tuple means - `[weight_for_channel_A, index_for_channel_A, weight_for_channel_B, index_for_channel_B]` - If `weight_for_channel_A` is 1, then there is no interpolation on this channel. - """ - std = 1e-4 - self.embeddings.data.uniform_(-std, std) - # generate sampling index - temporal_grid_rows = self.temporal_dim - index_init = [0, self.level_dim] + list(range(1, self.level_dim)) - permute_base = list(range(2, self.level_dim + 1)) - last_entry = 0 # insert into ith place - permute_init = permute_base[:last_entry] + [0] + permute_base[last_entry:] - index_list = [torch.as_tensor(index_init, dtype=torch.long)] - permute_list = [torch.as_tensor(permute_init, dtype=torch.long)] - - # converts a list of channel candidates into sampling row - def to_sampling_index(index, permute, last_entry): - row = index[permute] - row = torch.stack([torch.ones_like(row), row, torch.zeros_like(row), torch.zeros_like(row)], 1) - row = row.reshape([-1]) - mask_a = torch.zeros_like(row).bool() - mask_b = torch.zeros_like(row).bool() - row[last_entry * 4 + 3] = index[1] - mask_a[last_entry * 4] = 1 - mask_b[last_entry * 4 + 2] = 1 - return row, mask_a, mask_b - - row, mask_a, mask_b = to_sampling_index(index_list[0], permute_list[0], last_entry) - sampling_index = [row] - index_a_mask, index_b_mask = [mask_a], [mask_b] - # iterate on all temporal grid to get all rows - for _ in range(1, temporal_grid_rows - 1): - # the following lines are a little confusing... - # the basic idea is to keep a buffer and then move to the next channel - last_entry += 1 - if last_entry >= self.level_dim: - last_entry = 0 - last_index_max = index_list[-1].max().item() - last_index_min = index_list[-1].min().item() - tem_permute_list = permute_list[-1].clone() # for rearrange - tem_permute_list[tem_permute_list == 0] += 1 - prev = index_list[-1][1:][tem_permute_list - 1].tolist() - prev.pop(last_entry) - new_index = [last_index_min + 1, last_index_max + 1] + prev - new_index = torch.as_tensor(new_index, dtype=torch.long) - new_permute = permute_base[:last_entry] + [0] + permute_base[last_entry:] - new_permute = torch.as_tensor(new_permute, dtype=torch.long) - index_list.append(torch.as_tensor(new_index, dtype=torch.long)) - permute_list.append(torch.as_tensor(new_permute, dtype=torch.long)) - row, mask_a, mask_b = to_sampling_index(index_list[-1], permute_list[-1], last_entry) - sampling_index.append(row) - index_a_mask.append(mask_a) - index_b_mask.append(mask_b) - self.register_buffer("index_list", torch.stack(index_list)) - self.register_buffer("sampling_index", torch.stack(sampling_index)) - # index_a_mask and index_b_mask are for inserting the combination weights - self.register_buffer("index_a_mask", torch.stack(index_a_mask)) - self.register_buffer("index_b_mask", torch.stack(index_b_mask)) - - def __repr__(self) -> str: - """For debug and logging purpose.""" - return ( - f"GridEncoder: input_dim={self.input_dim} num_levels={self.num_levels} " - f"level_dim={self.level_dim} resolution={self.base_resolution} -> " - f"{int(round(self.base_resolution * self.per_level_scale ** (self.num_levels - 1)))} " - f"per_level_scale={self.per_level_scale:.4f} params={tuple(self.embeddings.shape)} " - f"gridtype={self.gridtype} align_corners={self.align_corners}" - ) - - def get_temporal_index(self, time: Float[Tensor, "bs"]) -> Float[Tensor, "bs temporal_index_dim"]: - """Convert the time into sampling index lists.""" - row_idx_value = time * (len(self.sampling_index) - 1) - row_idx = row_idx_value.long() - row_idx[time == 1] = len(self.sampling_index) - 1 - temporal_row_index = self.sampling_index[row_idx].float() - mask_a = self.index_a_mask[row_idx] - mask_b = self.index_b_mask[row_idx] - temporal_row_index[mask_a] = row_idx + 1 - row_idx_value - temporal_row_index[mask_b] = row_idx_value - row_idx - return temporal_row_index - - def forward( - self, xyz: Float[Tensor, "bs input_dim"], time: Float[Tensor, "bs 1"] - ) -> Float[Tensor, "bs output_dim"]: - """Forward and sampling feature vectors from the embedding. - - Args: - xyz: input coords, should be in [0,1] - time: input time, should be in [0,1] with shape [bs, 1] - """ - outputs = TemporalGridEncodeFunc.apply( - xyz, - self.get_temporal_index(time[:, 0].float()), - self.embeddings, - self.offsets, - self.per_level_scale, - self.base_resolution, - xyz.requires_grad, - self.gridtype_id, - self.align_corners, - ) - assert isinstance(outputs, Tensor) - return outputs - - def get_temporal_tv_loss(self) -> Float[Tensor, ""]: - """Apply TV loss on the temporal channels. - Sample a random channel combination (i.e., row for the combination table), - and then compute loss on it. - """ - row_idx = torch.randint(0, len(self.index_list), [1]) - feat_idx = self.index_list[row_idx] - return (self.embeddings[:, feat_idx[0]] - self.embeddings[:, feat_idx[1]]).abs().mean() diff --git a/nerfstudio/fields/generfacto_field.py b/nerfstudio/fields/generfacto_field.py new file mode 100644 index 000000000..d72f5c263 --- /dev/null +++ b/nerfstudio/fields/generfacto_field.py @@ -0,0 +1,169 @@ +# Copyright 2022 The Nerfstudio 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 Generfacto model +""" + + +from typing import Optional, Tuple, Dict, Literal + +import numpy as np +import torch +from torch.nn.parameter import Parameter +from jaxtyping import Float +from torch import Tensor, nn + +from nerfstudio.field_components.mlp import MLP +from nerfstudio.cameras.rays import RayBundle, RaySamples +from nerfstudio.data.scene_box import SceneBox +from nerfstudio.field_components.activations import trunc_exp +from nerfstudio.field_components.field_heads import FieldHeadNames +from nerfstudio.field_components.encodings import HashEncoding, SHEncoding +from nerfstudio.fields.base_field import Field + + +def get_normalized_directions(directions: Float[Tensor, "bs 3"]): + """SH encoding must be in the range [0, 1] + + Args: + directions: batch of directions + """ + return (directions + 1.0) / 2.0 + + +class GenerfactoField(Field): + """Generfacto Field that uses TCNN + + Args: + aabb: parameters of scene aabb bounds + num_layers: number of hidden layers + hidden_dim: dimension of hidden layers + geo_feat_dim: output geo feat dimensions + num_levels: number of levels of the hashmap for the base mlp + max_res: maximum resolution of the hashmap for the base mlp + log2_hashmap_size: size of the hashmap for the base mlp + num_layers_color: number of hidden layers for color network + hidden_dim_color: dimension of hidden layers for color network + """ + + def __init__( + self, + aabb: Tensor, + num_layers: int = 2, + hidden_dim: int = 64, + geo_feat_dim: int = 15, + num_levels: int = 16, + max_res: int = 256, + log2_hashmap_size: int = 19, + num_layers_color: int = 3, + hidden_dim_color: int = 64, + implementation: Literal["tcnn", "torch"] = "tcnn", + ) -> None: + super().__init__() + + self.aabb = Parameter(aabb, requires_grad=False) + self.geo_feat_dim = geo_feat_dim + + base_res = 16 + features_per_level = 2 + np.exp((np.log(max_res) - np.log(base_res)) / (num_levels - 1)) + + self.direction_encoding = SHEncoding( + levels=4, + implementation=implementation, + ) + + encoder = HashEncoding( + num_levels=num_levels, + min_res=base_res, + max_res=max_res, + log2_hashmap_size=log2_hashmap_size, + features_per_level=features_per_level, + implementation=implementation, + ) + network = MLP( + in_dim=encoder.get_out_dim(), + num_layers=num_layers, + layer_width=hidden_dim, + out_dim=1 + self.geo_feat_dim, + activation=nn.ReLU(), + out_activation=None, + implementation=implementation, + ) + self.mlp_base = torch.nn.Sequential(encoder, network) + + self.mlp_background_color = MLP( + in_dim=self.direction_encoding.get_out_dim(), + num_layers=2, + layer_width=32, + out_dim=3, + activation=nn.ReLU(), + out_activation=nn.Sigmoid(), + implementation=implementation, + ) + + self.mlp_head = MLP( + in_dim=self.geo_feat_dim, + num_layers=num_layers_color, + layer_width=hidden_dim_color, + out_dim=3, + activation=nn.ReLU(), + out_activation=nn.Sigmoid(), + implementation=implementation, + ) + + def get_density(self, ray_samples: RaySamples) -> Tuple[Tensor, Tensor]: + """Computes and returns the densities.""" + positions = SceneBox.get_normalized_positions(ray_samples.frustums.get_positions(), self.aabb) + self._sample_locations = positions + if not self._sample_locations.requires_grad: + self._sample_locations.requires_grad = True + 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) + self._density_before_activation = density_before_activation + + # 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_background_rgb(self, ray_bundle: RayBundle) -> Tensor: + """Predicts background colors at infinity.""" + directions = get_normalized_directions(ray_bundle.directions) + + outputs_shape = ray_bundle.directions.shape[:-1] + directions_flat = self.direction_encoding(directions.view(-1, 3)) + background_rgb = self.mlp_background_color(directions_flat).view(*outputs_shape, -1).to(directions) + + return background_rgb + + def get_outputs( + self, ray_samples: RaySamples, density_embedding: Optional[Tensor] = None + ) -> Dict[FieldHeadNames, Tensor]: + assert density_embedding is not None + outputs = {} + + directions = get_normalized_directions(ray_samples.frustums.directions) + + outputs_shape = ray_samples.frustums.directions.shape[:-1] + + h = density_embedding.view(-1, self.geo_feat_dim) + + rgb = self.mlp_head(h).view(*outputs_shape, -1).to(directions) + outputs.update({FieldHeadNames.RGB: rgb}) + + return outputs diff --git a/nerfstudio/fields/nerfacto_field.py b/nerfstudio/fields/nerfacto_field.py index 898d344d3..1c35b7121 100644 --- a/nerfstudio/fields/nerfacto_field.py +++ b/nerfstudio/fields/nerfacto_field.py @@ -76,10 +76,12 @@ class NerfactoField(Field): hidden_dim: int = 64, geo_feat_dim: int = 15, num_levels: int = 16, + base_res: int = 16, max_res: int = 2048, log2_hashmap_size: int = 19, num_layers_color: int = 3, num_layers_transient: int = 2, + features_per_level: int = 2, hidden_dim_color: int = 64, hidden_dim_transient: int = 64, appearance_embedding_dim: int = 32, @@ -111,9 +113,7 @@ class NerfactoField(Field): self.use_semantics = use_semantics self.use_pred_normals = use_pred_normals self.pass_semantic_gradients = pass_semantic_gradients - - base_res: int = 16 - features_per_level: int = 2 + self.base_res = base_res self.direction_encoding = SHEncoding( levels=4, @@ -124,7 +124,7 @@ class NerfactoField(Field): in_dim=3, num_frequencies=2, min_freq_exp=0, max_freq_exp=2 - 1, implementation=implementation ) - encoder = HashEncoding( + self.mlp_base_grid = HashEncoding( num_levels=num_levels, min_res=base_res, max_res=max_res, @@ -132,8 +132,8 @@ class NerfactoField(Field): features_per_level=features_per_level, implementation=implementation, ) - network = MLP( - in_dim=encoder.get_out_dim(), + self.mlp_base_mlp = MLP( + in_dim=self.mlp_base_grid.get_out_dim(), num_layers=num_layers, layer_width=hidden_dim, out_dim=1 + self.geo_feat_dim, @@ -141,7 +141,7 @@ class NerfactoField(Field): out_activation=None, implementation=implementation, ) - self.mlp_base = torch.nn.Sequential(encoder, network) + self.mlp_base = torch.nn.Sequential(self.mlp_base_grid, self.mlp_base_mlp) # transients if self.use_transient_embedding: diff --git a/nerfstudio/fields/nerfplayer_nerfacto_field.py b/nerfstudio/fields/nerfplayer_nerfacto_field.py deleted file mode 100644 index 759806f84..000000000 --- a/nerfstudio/fields/nerfplayer_nerfacto_field.py +++ /dev/null @@ -1,412 +0,0 @@ -# Copyright 2022 the Regents of the University of California, Nerfstudio Team and contributors. 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 implementations for NeRFPlayer (https://arxiv.org/abs/2210.15947) implementation with nerfacto backbone -""" - - -from typing import Dict, Optional, Tuple - -import numpy as np -import torch -from jaxtyping import Float -from torch import Tensor -from torch.nn.parameter import Parameter - -from nerfstudio.cameras.rays import Frustums, RaySamples -from nerfstudio.data.scene_box import SceneBox -from nerfstudio.field_components.activations import trunc_exp -from nerfstudio.field_components.embedding import Embedding -from nerfstudio.field_components.field_heads import ( - FieldHeadNames, - PredNormalsFieldHead, - SemanticFieldHead, - TransientDensityFieldHead, - TransientRGBFieldHead, - UncertaintyFieldHead, -) -from nerfstudio.field_components.spatial_distortions import SpatialDistortion -from nerfstudio.field_components.temporal_grid import TemporalGridEncoder -from nerfstudio.fields.base_field import Field, shift_directions_for_tcnn - -try: - import tinycudann as tcnn -except ModuleNotFoundError: - # tinycudann module doesn't exist - pass - - -class TemporalHashMLPDensityField(Field): - """A lightweight temporal density field module. - - Args: - aabb: Parameters of scene aabb bounds - temporal_dim: Hashing grid parameter. A higher temporal dim means a higher temporal frequency. - num_layers: Number of hidden layers - hidden_dim: Dimension of hidden layers - spatial_distortion: Spatial distortion module - num_levels: Hashing grid parameter. Used for initialize TemporalGridEncoder class. - max_res: Hashing grid parameter. Used for initialize TemporalGridEncoder class. - base_res: Hashing grid parameter. Used for initialize TemporalGridEncoder class. - log2_hashmap_size: Hashing grid parameter. Used for initialize TemporalGridEncoder class. - features_per_level: Hashing grid parameter. Used for initialize TemporalGridEncoder class. - """ - - def __init__( - self, - aabb: Tensor, - temporal_dim: int = 64, - num_layers: int = 2, - hidden_dim: int = 64, - spatial_distortion: Optional[SpatialDistortion] = None, - num_levels: int = 8, - max_res: int = 1024, - base_res: int = 16, - log2_hashmap_size: int = 18, - features_per_level: int = 2, - ) -> None: - super().__init__() - # from .temporal_grid import test; test() # DEBUG - self.aabb = Parameter(aabb, requires_grad=False) - self.spatial_distortion = spatial_distortion - growth_factor = np.exp((np.log(max_res) - np.log(base_res)) / (num_levels - 1)) - - self.encoding = TemporalGridEncoder( - input_dim=3, - temporal_dim=temporal_dim, - num_levels=num_levels, - level_dim=features_per_level, - per_level_scale=growth_factor, - base_resolution=base_res, - log2_hashmap_size=log2_hashmap_size, - ) - self.linear = tcnn.Network( - n_input_dims=num_levels * features_per_level, - n_output_dims=1, - network_config={ - "otype": "FullyFusedMLP", - "activation": "ReLU", - "output_activation": "None", - "n_neurons": hidden_dim, - "n_hidden_layers": num_layers - 1, - }, - ) - - def density_fn( - self, positions: Float[Tensor, "*bs 3"], times: Optional[Float[Tensor, "bs 1"]] = None - ) -> Float[Tensor, "*bs 1"]: - """Returns only the density. Used primarily with the density grid. - - Args: - positions: the origin of the samples/frustums - times: the time of rays - """ - assert times is not None, "TemporalHashMLPDensityField requires times to be specified" - if len(positions.shape) == 3 and len(times.shape) == 2: - # position is [ray, sample, 3]; times is [ray, 1] - times = times[:, None] # RaySamples can handle the shape - # Need to figure out a better way to descibe positions with a ray. - ray_samples = RaySamples( - frustums=Frustums( - origins=positions, - directions=torch.ones_like(positions), - starts=torch.zeros_like(positions[..., :1]), - ends=torch.zeros_like(positions[..., :1]), - pixel_area=torch.ones_like(positions[..., :1]), - ), - times=times, - ) - density, _ = self.get_density(ray_samples) - return density - - def get_density(self, ray_samples: RaySamples) -> Tuple[Tensor, None]: - if self.spatial_distortion is not None: - positions = self.spatial_distortion(ray_samples.frustums.get_positions()) - positions = (positions + 2.0) / 4.0 - else: - positions = SceneBox.get_normalized_positions(ray_samples.frustums.get_positions(), self.aabb) - positions_flat = positions.view(-1, 3) - assert ray_samples.times is not None - time_flat = ray_samples.times.reshape(-1, 1) - x = self.encoding(positions_flat, time_flat).to(positions) - density_before_activation = self.linear(x).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) - return density, None - - def get_outputs(self, ray_samples: RaySamples, density_embedding: Optional[Tensor] = None) -> dict: - return {} - - -class NerfplayerNerfactoField(Field): - """NeRFPlayer (https://arxiv.org/abs/2210.15947) field with nerfacto backbone. - - Args: - aabb: parameters of scene aabb bounds - num_images: number of images in the dataset - num_layers: number of hidden layers - hidden_dim: dimension of hidden layers - geo_feat_dim: output geo feat dimensions - num_levels: number of levels of the hashmap for the base mlp - max_res: maximum resolution of the hashmap for the base mlp - log2_hashmap_size: size of the hashmap for the base mlp - num_layers_color: number of hidden layers for color network - num_layers_transient: number of hidden layers for transient network - hidden_dim_color: dimension of hidden layers for color network - hidden_dim_transient: dimension of hidden layers for transient network - appearance_embedding_dim: dimension of appearance embedding - transient_embedding_dim: dimension of transient embedding - use_transient_embedding: whether to use transient embedding - use_semantics: whether to use semantic segmentation - num_semantic_classes: number of semantic classes - use_pred_normals: whether to use predicted normals - use_average_appearance_embedding: whether to use average appearance embedding or zeros for inference - spatial_distortion: spatial distortion to apply to the scene - """ - - def __init__( - self, - aabb: Tensor, - num_images: int, - num_layers: int = 2, - hidden_dim: int = 64, - geo_feat_dim: int = 15, - temporal_dim: int = 64, - num_levels: int = 16, - features_per_level: int = 2, - log2_hashmap_size: int = 19, - num_layers_color: int = 3, - num_layers_transient: int = 2, - hidden_dim_color: int = 64, - hidden_dim_transient: int = 64, - appearance_embedding_dim: int = 32, - transient_embedding_dim: int = 16, - use_transient_embedding: bool = False, - use_semantics: bool = False, - num_semantic_classes: int = 100, - use_pred_normals: bool = False, - use_average_appearance_embedding: bool = False, - 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 - self.num_images = num_images - self.appearance_embedding_dim = appearance_embedding_dim - self.embedding_appearance = Embedding(self.num_images, self.appearance_embedding_dim) - self.use_average_appearance_embedding = use_average_appearance_embedding - self.use_transient_embedding = use_transient_embedding - self.use_semantics = use_semantics - self.use_pred_normals = use_pred_normals - - self.direction_encoding = tcnn.Encoding( - n_input_dims=3, - encoding_config={ - "otype": "SphericalHarmonics", - "degree": 4, - }, - ) - - self.position_encoding = tcnn.Encoding( - n_input_dims=3, - encoding_config={"otype": "Frequency", "n_frequencies": 2}, - ) - - self.mlp_base = TemporalGridEncoder( - input_dim=3, - temporal_dim=temporal_dim, - num_levels=num_levels, - level_dim=features_per_level, - log2_hashmap_size=log2_hashmap_size, - desired_resolution=int(1024 * (self.aabb.max().item() - self.aabb.min().item())), - ) - self.mlp_base_decode = tcnn.Network( - n_input_dims=num_levels * features_per_level, - n_output_dims=1 + self.geo_feat_dim, - network_config={ - "otype": "FullyFusedMLP", - "activation": "ReLU", - "output_activation": "None", - "n_neurons": hidden_dim, - "n_hidden_layers": num_layers - 1, - }, - ) - - # transients - if self.use_transient_embedding: - self.transient_embedding_dim = transient_embedding_dim - self.embedding_transient = Embedding(self.num_images, self.transient_embedding_dim) - self.mlp_transient = tcnn.Network( - n_input_dims=self.geo_feat_dim + self.transient_embedding_dim, - n_output_dims=hidden_dim_transient, - network_config={ - "otype": "FullyFusedMLP", - "activation": "ReLU", - "output_activation": "None", - "n_neurons": hidden_dim_transient, - "n_hidden_layers": num_layers_transient - 1, - }, - ) - self.field_head_transient_uncertainty = UncertaintyFieldHead(in_dim=self.mlp_transient.n_output_dims) - self.field_head_transient_rgb = TransientRGBFieldHead(in_dim=self.mlp_transient.n_output_dims) - self.field_head_transient_density = TransientDensityFieldHead(in_dim=self.mlp_transient.n_output_dims) - - # semantics - if self.use_semantics: - self.mlp_semantics = tcnn.Network( - n_input_dims=self.geo_feat_dim, - n_output_dims=hidden_dim_transient, - network_config={ - "otype": "FullyFusedMLP", - "activation": "ReLU", - "output_activation": "None", - "n_neurons": 64, - "n_hidden_layers": 1, - }, - ) - self.field_head_semantics = SemanticFieldHead( - in_dim=self.mlp_semantics.n_output_dims, num_classes=num_semantic_classes - ) - - # predicted normals - if self.use_pred_normals: - self.mlp_pred_normals = tcnn.Network( - n_input_dims=self.geo_feat_dim + self.position_encoding.n_output_dims, - n_output_dims=hidden_dim_transient, - network_config={ - "otype": "FullyFusedMLP", - "activation": "ReLU", - "output_activation": "None", - "n_neurons": 64, - "n_hidden_layers": 2, - }, - ) - self.field_head_pred_normals = PredNormalsFieldHead(in_dim=self.mlp_pred_normals.n_output_dims) - - 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) -> Tuple[Tensor, Tensor]: - """Computes and returns the densities.""" - 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 = SceneBox.get_normalized_positions(ray_samples.frustums.get_positions(), self.aabb) - positions_flat = positions.view(-1, 3) - assert ray_samples.times is not None, "Time should be included in the input for NeRFPlayer" - time_flat = ray_samples.times.reshape(-1, 1) - h = self.mlp_base(positions_flat, time_flat) - h = self.mlp_base_decode(h).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[Tensor] = None - ) -> Dict[FieldHeadNames, Tensor]: - assert density_embedding is not None - outputs = {} - if ray_samples.camera_indices is None: - raise AttributeError("Camera indices are not provided.") - camera_indices = ray_samples.camera_indices.squeeze() - directions = shift_directions_for_tcnn(ray_samples.frustums.directions) - directions_flat = directions.view(-1, 3) - d = self.direction_encoding(directions_flat) - - outputs_shape = ray_samples.frustums.directions.shape[:-1] - - # appearance - if self.training: - embedded_appearance = self.embedding_appearance(camera_indices) - else: - if self.use_average_appearance_embedding: - embedded_appearance = torch.ones( - (*directions.shape[:-1], self.appearance_embedding_dim), device=directions.device - ) * self.embedding_appearance.mean(dim=0) - else: - embedded_appearance = torch.zeros( - (*directions.shape[:-1], self.appearance_embedding_dim), device=directions.device - ) - - # transients - if self.use_transient_embedding and self.training: - embedded_transient = self.embedding_transient(camera_indices) - transient_input = torch.cat( - [ - density_embedding.view(-1, self.geo_feat_dim), - embedded_transient.view(-1, self.transient_embedding_dim), - ], - dim=-1, - ) - x = self.mlp_transient(transient_input).view(*outputs_shape, -1).to(directions) - outputs[FieldHeadNames.UNCERTAINTY] = self.field_head_transient_uncertainty(x) - outputs[FieldHeadNames.TRANSIENT_RGB] = self.field_head_transient_rgb(x) - outputs[FieldHeadNames.TRANSIENT_DENSITY] = self.field_head_transient_density(x) - - # semantics - if self.use_semantics: - density_embedding_copy = density_embedding.clone().detach() - semantics_input = torch.cat( - [ - density_embedding_copy.view(-1, self.geo_feat_dim), - ], - dim=-1, - ) - x = self.mlp_semantics(semantics_input).view(*outputs_shape, -1).to(directions) - outputs[FieldHeadNames.SEMANTICS] = self.field_head_semantics(x) - - # predicted normals - if self.use_pred_normals: - positions = ray_samples.frustums.get_positions() - - positions_flat = self.position_encoding(positions.view(-1, 3)) - pred_normals_inp = torch.cat([positions_flat, density_embedding.view(-1, self.geo_feat_dim)], dim=-1) - - x = self.mlp_pred_normals(pred_normals_inp).view(*outputs_shape, -1).to(directions) - outputs[FieldHeadNames.PRED_NORMALS] = self.field_head_pred_normals(x) - - h = torch.cat( - [ - d, - density_embedding.view(-1, self.geo_feat_dim), - embedded_appearance.view(-1, self.appearance_embedding_dim), - ], - dim=-1, - ) - rgb = self.mlp_head(h).view(*outputs_shape, -1).to(directions) - outputs.update({FieldHeadNames.RGB: rgb}) - - return outputs diff --git a/nerfstudio/fields/nerfplayer_ngp_field.py b/nerfstudio/fields/nerfplayer_ngp_field.py deleted file mode 100644 index cdd122e13..000000000 --- a/nerfstudio/fields/nerfplayer_ngp_field.py +++ /dev/null @@ -1,243 +0,0 @@ -# Copyright 2022 the Regents of the University of California, Nerfstudio Team and contributors. 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. - -""" -NeRFPlayer (https://arxiv.org/abs/2210.15947) field implementations with InstantNGP backbone -""" - - -from typing import Dict, Optional, Tuple - -import torch -from jaxtyping import Float -from torch import Tensor -from torch.nn.parameter import Parameter - -from nerfstudio.cameras.rays import Frustums, RaySamples -from nerfstudio.data.scene_box import SceneBox -from nerfstudio.field_components.activations import trunc_exp -from nerfstudio.field_components.embedding import Embedding -from nerfstudio.field_components.field_heads import FieldHeadNames -from nerfstudio.field_components.spatial_distortions import ( - SceneContraction, - SpatialDistortion, -) -from nerfstudio.field_components.temporal_grid import TemporalGridEncoder -from nerfstudio.fields.base_field import Field, shift_directions_for_tcnn - -try: - import tinycudann as tcnn -except ModuleNotFoundError: - # tinycudann module doesn't exist - pass - - -class NerfplayerNGPField(Field): - """NeRFPlayer (https://arxiv.org/abs/2210.15947) field with InstantNGP backbone. - - Args: - aabb: parameters of scene aabb bounds - temporal_dim: the dimension of temporal axis, a higher dimension indicates a higher temporal frequency - please refer to the implementation of TemporalGridEncoder for more details - num_levels: the number of multi-resolution levels; same as InstantNGP - features_per_level: the dim of output feature vector for each level; same as InstantNGP - log2_hashmap_size: the size of the table; same as InstantNGP - base_resolution: base resolution for the table; same as InstantNGP - num_layers: number of hidden layers (occupancy decoder network after sampling) - hidden_dim: dimension of hidden layers (occupancy decoder network after sampling) - geo_feat_dim: output geo feat dimensions - num_layers_color: number of hidden layers for color network - hidden_dim_color: dimension of hidden layers for color network - use_appearance_embedding: whether to use appearance embedding - disable_viewing_dependent: if true, disable the viewing dependent effect (no viewing direction as inputs) - Sometimes we need to disable viewing dependent effects in a dynamic scene, because there is - ambiguity between being dynamic and viewing dependent effects. For example, the shadow of the camera - should be a dynamic effect, but may be reconstructed as viewing dependent effects. - num_images: number of images, required if use_appearance_embedding is True - appearance_embedding_dim: dimension of appearance embedding - contraction_type: type of contraction - """ - - def __init__( - self, - aabb: Tensor, - temporal_dim: int = 16, - num_levels: int = 16, - features_per_level: int = 2, - log2_hashmap_size: int = 19, - base_resolution: int = 16, - num_layers: int = 2, - hidden_dim: int = 64, - geo_feat_dim: int = 15, - num_layers_color: int = 3, - hidden_dim_color: int = 64, - use_appearance_embedding: bool = False, - disable_viewing_dependent: bool = False, - num_images: Optional[int] = None, - appearance_embedding_dim: int = 32, - spatial_distortion: Optional[SpatialDistortion] = SceneContraction(), - ) -> None: - super().__init__() - - self.aabb = Parameter(aabb, requires_grad=False) - self.geo_feat_dim = geo_feat_dim - self.spatial_distortion = spatial_distortion - - self.use_appearance_embedding = use_appearance_embedding - if use_appearance_embedding: - assert num_images is not None - self.appearance_embedding_dim = appearance_embedding_dim - self.appearance_embedding = Embedding(num_images, appearance_embedding_dim) - - self.direction_encoding = tcnn.Encoding( - n_input_dims=3, - encoding_config={ - "otype": "SphericalHarmonics", - "degree": 4, - }, - ) - - self.mlp_base = TemporalGridEncoder( - input_dim=3, - temporal_dim=temporal_dim, - num_levels=num_levels, - level_dim=features_per_level, - base_resolution=base_resolution, - log2_hashmap_size=log2_hashmap_size, - desired_resolution=int(1024 * (self.aabb.max() - self.aabb.min())), - ) - self.mlp_base_decode = tcnn.Network( - n_input_dims=num_levels * features_per_level, - n_output_dims=1 + self.geo_feat_dim, - network_config={ - "otype": "FullyFusedMLP", - "activation": "ReLU", - "output_activation": "None", - "n_neurons": hidden_dim, - "n_hidden_layers": num_layers - 1, - }, - ) - - in_dim = self.direction_encoding.n_output_dims + self.geo_feat_dim - if disable_viewing_dependent: - in_dim = self.geo_feat_dim - self.direction_encoding = None - if self.use_appearance_embedding: - in_dim += self.appearance_embedding_dim - self.mlp_head = tcnn.Network( - n_input_dims=in_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) -> Tuple[Tensor, Tensor]: - 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 = SceneBox.get_normalized_positions(ray_samples.frustums.get_positions(), self.aabb) - # Make sure the tcnn gets inputs between 0 and 1. - selector = ((positions > 0.0) & (positions < 1.0)).all(dim=-1) - positions = positions * selector[..., None] - positions_flat = positions.view(-1, 3) - assert ray_samples.times is not None, "Time should be included in the input for NeRFPlayer" - times_flat = ray_samples.times.view(-1, 1) - - h = self.mlp_base(positions_flat, times_flat) - h = self.mlp_base_decode(h).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)) - density = density * selector[..., None] - return density, base_mlp_out - - def get_outputs( - self, ray_samples: RaySamples, density_embedding: Optional[Tensor] = None - ) -> Dict[FieldHeadNames, Tensor]: - assert density_embedding is not None - directions = shift_directions_for_tcnn(ray_samples.frustums.directions) - directions_flat = directions.view(-1, 3) - - if self.direction_encoding is not None: - d = self.direction_encoding(directions_flat) - h = torch.cat([d, density_embedding.view(-1, self.geo_feat_dim)], dim=-1) - else: - # viewing direction is disabled - h = density_embedding.view(-1, self.geo_feat_dim) - - if self.use_appearance_embedding: - if ray_samples.camera_indices is None: - raise AttributeError("Camera indices are not provided.") - camera_indices = ray_samples.camera_indices.squeeze() - if self.training: - embedded_appearance = self.appearance_embedding(camera_indices) - else: - embedded_appearance = torch.zeros( - (*directions.shape[:-1], self.appearance_embedding_dim), device=directions.device - ) - h = torch.cat([h, embedded_appearance.view(-1, self.appearance_embedding_dim)], dim=-1) - - rgb = self.mlp_head(h).view(*ray_samples.frustums.directions.shape[:-1], -1).to(directions) - return {FieldHeadNames.RGB: rgb} - - def density_fn( - self, positions: Float[Tensor, "*bs 3"], times: Optional[Float[Tensor, "*bs 1"]] = None - ) -> Float[Tensor, "*bs 1"]: - """Returns only the density. Used primarily with the density grid. - Overwrite this function since density is time dependent now. - - Args: - positions: the origin of the samples/frustums - times: the time of each position - """ - ray_samples = RaySamples( - frustums=Frustums( - origins=positions, - directions=torch.ones_like(positions), - starts=torch.zeros_like(positions[..., :1]), - ends=torch.zeros_like(positions[..., :1]), - pixel_area=torch.ones_like(positions[..., :1]), - ), - times=times, - ) - density, _ = self.get_density(ray_samples) - return density - - def get_opacity(self, positions: Float[Tensor, "*bs 3"], step_size, time_intervals=10) -> Float[Tensor, "*bs 1"]: - """Returns the opacity for a position and time. Used primarily by the occupancy grid. - This will return the maximum opacity of the points in the space in a dynamic sequence. - - Args: - positions: the positions to evaluate the opacity at. - step_size: the step size to use for the opacity evaluation. - time_intervals: sample density on N time stamps - """ - # TODO: Converting opacity by time intervals is slow, and may lead to temporal artifacts. - # (Maybe random sample time and EMA?) - opacity = [] - for t in range(0, time_intervals): - density = self.density_fn(positions, t / (time_intervals - 1) * torch.ones_like(positions)[..., [0]]) - opacity.append(density * step_size) - opacity = torch.stack(opacity, dim=0).max(dim=0).values - return opacity diff --git a/nerfstudio/generative/deepfloyd.py b/nerfstudio/generative/deepfloyd.py index 982be0879..72c6cc373 100644 --- a/nerfstudio/generative/deepfloyd.py +++ b/nerfstudio/generative/deepfloyd.py @@ -14,21 +14,30 @@ import gc from pathlib import Path -from typing import List, Optional, Union, cast +from typing import List, Optional, Union import torch import torch.nn.functional as F import tyro -from diffusers import IFPipeline -from diffusers.pipelines.deepfloyd_if import IFPipelineOutput + from jaxtyping import Float from PIL import Image -from torch import FloatTensor, Generator, Tensor, nn +from torch import Generator, Tensor, nn from torch.cuda.amp.grad_scaler import GradScaler -from transformers import T5EncoderModel -from nerfstudio.generative.utils import _SDSGradient +from nerfstudio.generative.utils import CatchMissingPackages + +try: + from diffusers import IFPipeline as IFOrig + from diffusers.pipelines.deepfloyd_if import IFPipelineOutput as IFOutputOrig + + from diffusers import IFPipeline, DiffusionPipeline + from diffusers.pipelines.deepfloyd_if import IFPipelineOutput + from transformers import T5EncoderModel + +except ImportError: + IFPipeline = IFPipelineOutput = T5EncoderModel = CatchMissingPackages() IMG_DIM = 64 @@ -61,7 +70,7 @@ class DeepFloyd(nn.Module): variant="fp16", torch_dtype=torch.float16, ) - assert isinstance(self.pipe, IFPipeline) + assert isinstance(self.pipe, DiffusionPipeline) self.pipe = self.pipe.to(self.device) self.pipe.enable_attention_slicing(1) @@ -96,7 +105,7 @@ class DeepFloyd(nn.Module): variant="fp16", torch_dtype=torch.float16, ) - assert isinstance(self.pipe, IFPipeline) + assert isinstance(self.pipe, DiffusionPipeline) self.pipe = self.pipe.to(self.device) self.pipe.enable_attention_slicing(1) @@ -122,12 +131,12 @@ class DeepFloyd(nn.Module): prompt = [prompt] if isinstance(prompt, str) else prompt negative_prompt = [negative_prompt] if isinstance(negative_prompt, str) else negative_prompt - assert isinstance(self.pipe, IFPipeline) + assert isinstance(self.pipe, DiffusionPipeline) with torch.no_grad(): prompt_embeds, negative_embeds = self.pipe.encode_prompt(prompt, negative_prompt=negative_prompt) - assert isinstance(negative_embeds, FloatTensor) - assert isinstance(prompt_embeds, FloatTensor) + assert isinstance(negative_embeds, Tensor) + assert isinstance(prompt_embeds, Tensor) return torch.cat([negative_embeds, prompt_embeds]) def sds_loss( @@ -146,40 +155,37 @@ class DeepFloyd(nn.Module): Returns: The loss """ - with torch.autocast(device_type="cuda", enabled=False): - image = F.interpolate(image.half(), (IMG_DIM, IMG_DIM), mode="bilinear", align_corners=False) - t = torch.randint(self.min_step, self.max_step + 1, [1], dtype=torch.long, device=self.device) + image = F.interpolate(image.half(), (IMG_DIM, IMG_DIM), mode="bilinear", align_corners=False) + t = torch.randint(self.min_step, self.max_step + 1, [1], dtype=torch.long, device=self.device) - # predict the noise residual with unet, NO grad! - with torch.no_grad(): - # add noise - noise = torch.randn_like(image) - image_noisy = self.scheduler.add_noise(image, noise, t) # type: ignore - # pred noise - image_model_input = torch.cat((image_noisy,) * 2) - noise_pred = self.unet(image_model_input, t, encoder_hidden_states=text_embeddings).sample + # predict the noise residual with unet, NO grad! + with torch.no_grad(): + # add noise + noise = torch.randn_like(image) + image_noisy = self.scheduler.add_noise(image, noise, t) # type: ignore + # pred noise + image_model_input = torch.cat((image_noisy,) * 2) + noise_pred = self.unet(image_model_input, t, encoder_hidden_states=text_embeddings).sample - # perform guidance - noise_pred_uncond, noise_pred_text = noise_pred.chunk(2) - noise_pred_text, predicted_variance = noise_pred_text.split(3, dim=1) - noise_pred_uncond, _ = noise_pred_uncond.split(3, dim=1) + # perform guidance + noise_pred_uncond, noise_pred_text = noise_pred.chunk(2) + noise_pred_text, predicted_variance = noise_pred_text.split(3, dim=1) + noise_pred_uncond, _ = noise_pred_uncond.split(3, dim=1) - noise_pred = noise_pred_text + guidance_scale * (noise_pred_text - noise_pred_uncond) + noise_pred = noise_pred_text + guidance_scale * (noise_pred_text - noise_pred_uncond) - # w(t), sigma_t^2 - w = 1 - self.alphas[t] + # w(t), sigma_t^2 + w = 1 - self.alphas[t] - grad = w * (noise_pred - noise) - grad = torch.nan_to_num(grad) + grad = w * (noise_pred - noise) + grad = torch.nan_to_num(grad) - if grad_scaler is not None: - loss = cast(Tensor, _SDSGradient.apply(grad_scaler.scale(image), grad)) - else: - loss = cast(Tensor, _SDSGradient.apply(image, grad)) + target = (image - grad).detach() + loss = 0.5 * F.mse_loss(image, target, reduction="sum") / image.shape[0] return loss - def prompt_to_img( + def prompt_to_image( self, prompts: Union[str, List[str]], negative_prompts: Union[str, List[str]] = "", @@ -201,16 +207,17 @@ class DeepFloyd(nn.Module): prompts = [prompts] if isinstance(prompts, str) else prompts negative_prompts = [negative_prompts] if isinstance(negative_prompts, str) else negative_prompts - - assert isinstance(self.pipe, IFPipeline) + assert isinstance(self.pipe, DiffusionPipeline) prompt_embeds, negative_embeds = self.pipe.encode_prompt(prompts, negative_prompt=negative_prompts) + + assert isinstance(self.pipe, IFOrig) model_output = self.pipe( prompt_embeds=prompt_embeds, negative_prompt_embeds=negative_embeds, generator=generator ) - assert isinstance(model_output, IFPipelineOutput) - image = model_output.images[0] + assert isinstance(model_output, IFOutputOrig) + output_image = model_output.images[0] - return image + return output_image def generate_image( @@ -228,7 +235,7 @@ def generate_image( cuda_device = torch.device("cuda") with torch.no_grad(): df = DeepFloyd(cuda_device) - img = df.prompt_to_img(prompt, negative, generator, steps) + img = df.prompt_to_image(prompt, negative, generator, steps) img.save(save_path) diff --git a/nerfstudio/generative/positional_text_embeddings.py b/nerfstudio/generative/positional_text_embeddings.py new file mode 100644 index 000000000..4ba62b024 --- /dev/null +++ b/nerfstudio/generative/positional_text_embeddings.py @@ -0,0 +1,120 @@ +# Copyright 2022 the Regents of the University of California, Nerfstudio Team and contributors. 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. + +"""Utility helper functions for generative 3D models""" + +import torch +from torch import Tensor +from jaxtyping import Float +from typing_extensions import Literal +from typing import Union + +from nerfstudio.generative.stable_diffusion import StableDiffusion +from nerfstudio.generative.deepfloyd import DeepFloyd + + +class PositionalTextEmbeddings: + """Postional Prompts. Currently the following location based text embeddings are supported: + - discrete: Choose the embedding closest to the camera position + - interpolated: Interpolate between the embeddings based on the camera position + - off: Don't modify the text embedding based on the camera position + + Args: + base_prompt: Prompt for base view + top_prompt: Prompt for top view + side_prompt: Prompt for side view + back_prompt: Prompt for back view + front_prompt: Prompt for front view + diffusion_model: Instance of StableDiffusion + positional_prompting: how to incorporate position into prompt. + """ + + def __init__( + self, + base_prompt: str, + top_prompt: str, + side_prompt: str, + back_prompt: str, + front_prompt: str, + diffusion_model: Union[StableDiffusion, DeepFloyd], + positional_prompting: Literal["discrete", "interpolated", "off"] = "discrete", + ): + self.positional_prompting = positional_prompting + self.diffusion_device = diffusion_model.device + self.diffusion = diffusion_model + self.update_prompt(base_prompt, top_prompt, side_prompt, back_prompt, front_prompt) + + def update_prompt(self, base_prompt: str, top_prompt: str, side_prompt: str, back_prompt: str, front_prompt: str): + """Update the text embeddings based on the new prompts. + + Args: + base_prompt: Prompt for base view + top_prompt: Prompt for top view + side_prompt: Prompt for side view + back_prompt: Prompt for back view + front_prompt: Prompt for front view + """ + self.base_embed = self.diffusion.get_text_embeds(base_prompt, "") + self.top_embed = self.diffusion.get_text_embeds(top_prompt, "") + self.side_embed = self.diffusion.get_text_embeds(side_prompt, "") + self.back_embed = self.diffusion.get_text_embeds(back_prompt, "") + self.front_embed = self.diffusion.get_text_embeds(front_prompt, "") + + if isinstance(self.diffusion, DeepFloyd): + self.diffusion.delete_text_encoder() + + def get_text_embedding( + self, vertical_angle: Float[Tensor, "1"], horizontal_angle: Float[Tensor, "1"] + ) -> Float[Tensor, "2 max_length embed_dim"]: + """Get text embedding based on the position of the camera relative to the scene. + This trick is used in Dreamfusion (https://dreamfusion3d.github.io/). + + Args: + vertical_angle: vertical angle of the camera + horizonal_angle: horizonal angle of the camera + """ + # set horizontal_angle between 0, 360 + horizontal_angle = torch.fmod(horizontal_angle, 360) + horizontal_angle = torch.where(horizontal_angle < 0, horizontal_angle + 360, horizontal_angle) + + if self.positional_prompting == "discrete": + if vertical_angle < 40: + text_embedding = self.top_embed + elif 315 < horizontal_angle or horizontal_angle <= 45: + text_embedding = self.front_embed + elif 45 < horizontal_angle <= 135: + text_embedding = self.side_embed + elif 135 < horizontal_angle <= 225: + text_embedding = self.back_embed + else: # horizontal_angle > 225 and horizontal_angle <= 315: + text_embedding = self.side_embed + elif self.positional_prompting == "interpolated": + horiz = horizontal_angle.detach().numpy()[0] + vert = max(vertical_angle.detach().numpy()[0], 0) + + if 0 < horizontal_angle <= 90: + text_embedding = (horiz) * self.side_embed + (90 - horiz) * self.front_embed + elif 90 < horizontal_angle <= 180: + text_embedding = (horiz - 90) * self.back_embed + (180 - horiz) * self.side_embed + elif 180 < horizontal_angle <= 270: + text_embedding = (horiz - 180) * self.side_embed + (270 - horiz) * self.back_embed + else: # 270 < horizontal_angle <= 360: + text_embedding = (horiz - 270) * self.front_embed + (360 - horiz) * self.side_embed + + text_embedding = text_embedding / 90.0 + text_embedding = (vert * text_embedding + (90 - vert) * self.top_embed) / 90.0 + else: + text_embedding = self.base_embed + + return text_embedding diff --git a/nerfstudio/generative/stable_diffusion.py b/nerfstudio/generative/stable_diffusion.py index 6202a9046..7e7f3dac4 100644 --- a/nerfstudio/generative/stable_diffusion.py +++ b/nerfstudio/generative/stable_diffusion.py @@ -16,10 +16,9 @@ # Modified from https://github.com/ashawkey/stable-dreamfusion/blob/main/nerf/sd.py -import sys -from dataclasses import dataclass from pathlib import Path -from typing import List, Optional, Union, cast +from typing import List, Optional, Union +from nerfstudio.utils.rich_utils import CONSOLE import mediapy import numpy as np @@ -30,22 +29,16 @@ from jaxtyping import Float from torch import Tensor, nn from torch.cuda.amp.grad_scaler import GradScaler -from nerfstudio.utils.rich_utils import CONSOLE - -from nerfstudio.generative.utils import _SDSGradient +from nerfstudio.generative.utils import CatchMissingPackages try: - from diffusers import PNDMScheduler, StableDiffusionPipeline - from transformers import logging + from diffusers import PNDMScheduler, StableDiffusionPipeline, DiffusionPipeline except ImportError: - CONSOLE.print("[bold red]Missing Stable Diffusion packages.") - CONSOLE.print(r"Install using [yellow]pip install nerfstudio\[gen][/yellow]") - CONSOLE.print(r"or [yellow]pip install -e .\[gen][/yellow] if installing from source.") - sys.exit(1) + PNDMScheduler = StableDiffusionPipeline = CatchMissingPackages() + -logging.set_verbosity_error() IMG_DIM = 512 CONST_SCALE = 0.18215 SD_IDENTIFIERS = { @@ -55,13 +48,6 @@ SD_IDENTIFIERS = { } -@dataclass -class UNet2DConditionOutput: - """Class to hold traced model""" - - sample: torch.FloatTensor - - class StableDiffusion(nn.Module): """Stable Diffusion implementation Args: @@ -88,7 +74,8 @@ class StableDiffusion(nn.Module): sd_id = SD_IDENTIFIERS[version] pipe = StableDiffusionPipeline.from_pretrained(sd_id, torch_dtype=torch.float16) - assert isinstance(pipe, StableDiffusionPipeline) + + assert isinstance(pipe, DiffusionPipeline) # and hasattr(pipe, "to") pipe = pipe.to(self.device) pipe.enable_attention_slicing() @@ -154,7 +141,7 @@ class StableDiffusion(nn.Module): Returns: The loss """ - image = F.interpolate(image, (IMG_DIM, IMG_DIM), mode="bilinear") + image = F.interpolate(image, (IMG_DIM, IMG_DIM), mode="bilinear").to(torch.float16) t = torch.randint(self.min_step, self.max_step + 1, [1], dtype=torch.long, device=self.device) latents = self.imgs_to_latent(image) @@ -177,9 +164,8 @@ class StableDiffusion(nn.Module): grad = w * (noise_pred - noise) grad = torch.nan_to_num(grad) - if grad_scaler is not None: - latents = grad_scaler.scale(latents) - loss = cast(Tensor, _SDSGradient.apply(latents, grad)) + target = (latents - grad).detach() + loss = 0.5 * F.mse_loss(latents, target, reduction="sum") / latents.shape[0] return loss @@ -230,6 +216,7 @@ class StableDiffusion(nn.Module): # compute the previous noisy sample x_t -> x_t-1 latents = self.scheduler.step(noise_pred, t, latents)["prev_sample"] # type: ignore + assert isinstance(latents, Tensor) return latents def latents_to_img(self, latents: Float[Tensor, "BS 4 H W"]) -> Float[Tensor, "BS 3 H W"]: diff --git a/nerfstudio/generative/utils.py b/nerfstudio/generative/utils.py index e5996da6d..ec5a72844 100644 --- a/nerfstudio/generative/utils.py +++ b/nerfstudio/generative/utils.py @@ -12,28 +12,23 @@ # See the License for the specific language governing permissions and # limitations under the License. +"""Utility helper functions for diffusion models""" -import torch -from torch.cuda.amp import custom_bwd, custom_fwd - -"""Gradient helper functions for SDS loss""" +import sys +from nerfstudio.utils.rich_utils import CONSOLE -class _SDSGradient(torch.autograd.Function): - """Custom gradient function for SDS loss. Since it is already computed, we can just return it.""" +class CatchMissingPackages: + """Class to catch missing environment packages related to diffusion models.""" - @staticmethod - @custom_fwd - def forward(ctx, input_tensor, gt_grad): - del input_tensor - ctx.save_for_backward(gt_grad) - # Return magniture of gradient, not the actual loss. - return torch.mean(gt_grad**2) ** 0.5 + def __init__(self): + pass - @staticmethod - @custom_bwd - def backward(ctx, grad): - del grad - (gt_grad,) = ctx.saved_tensors - batch_size = len(gt_grad) - return gt_grad / batch_size, None + def __call__(self, *args, **kwargs): + CONSOLE.print("[bold red]Missing Stable Diffusion packages.") + CONSOLE.print(r"Install using [yellow]pip install nerfstudio\[gen][/yellow]") + CONSOLE.print(r"or [yellow]pip install -e .\[gen][/yellow] if installing from source.") + sys.exit(1) + + def __getattr__(self, attr): + return self.__call__ diff --git a/nerfstudio/model_components/losses.py b/nerfstudio/model_components/losses.py index 9823e76e3..8c53c24f1 100644 --- a/nerfstudio/model_components/losses.py +++ b/nerfstudio/model_components/losses.py @@ -543,7 +543,8 @@ class _GradientScaler(torch.autograd.Function): # typing: ignore def scale_gradients_by_distance_squared( - field_outputs: Dict[FieldHeadNames, torch.Tensor], ray_samples: RaySamples + field_outputs: Dict[FieldHeadNames, torch.Tensor], + ray_samples: RaySamples, ) -> Dict[FieldHeadNames, torch.Tensor]: """ Scale gradients by the ray distance to the pixel diff --git a/nerfstudio/model_components/scene_colliders.py b/nerfstudio/model_components/scene_colliders.py index 3e2e793ae..69c073b3b 100644 --- a/nerfstudio/model_components/scene_colliders.py +++ b/nerfstudio/model_components/scene_colliders.py @@ -24,7 +24,6 @@ from torch import Tensor, nn from nerfstudio.cameras.rays import RayBundle from nerfstudio.data.scene_box import SceneBox -from nerfstudio.utils.misc import torch_compile class SceneCollider(nn.Module): @@ -109,7 +108,6 @@ class AABBBoxCollider(SceneCollider): return ray_bundle -@torch_compile(dynamic=True, mode="reduce-overhead") def _intersect_with_sphere( rays_o: torch.Tensor, rays_d: torch.Tensor, center: torch.Tensor, radius: float = 1.0, near_plane: float = 0.0 ): diff --git a/nerfstudio/models/base_model.py b/nerfstudio/models/base_model.py index 1feb22adb..6f31c3b30 100644 --- a/nerfstudio/models/base_model.py +++ b/nerfstudio/models/base_model.py @@ -50,6 +50,8 @@ class ModelConfig(InstantiateConfig): """parameters to instantiate density field with""" eval_num_rays_per_chunk: int = 4096 """specifies number of rays per chunk during eval""" + prompt: Optional[str] = None + """A prompt to be used in text to NeRF models""" class Model(nn.Module): diff --git a/nerfstudio/models/generfacto.py b/nerfstudio/models/generfacto.py new file mode 100644 index 000000000..bf34eb335 --- /dev/null +++ b/nerfstudio/models/generfacto.py @@ -0,0 +1,528 @@ +# Copyright 2022 The Nerfstudio 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. + +""" +Nerfstudio's Text to 3D model. +""" + +from __future__ import annotations + +from dataclasses import dataclass, field +from typing import Dict, List, Optional, Tuple, Type + +import numpy as np +import torch +from torch.nn import Parameter +from typing_extensions import Literal + +from nerfstudio.cameras.rays import RayBundle +from nerfstudio.engine.callbacks import ( + TrainingCallback, + TrainingCallbackAttributes, + TrainingCallbackLocation, +) +from nerfstudio.field_components.field_heads import FieldHeadNames +from nerfstudio.fields.density_fields import HashMLPDensityField +from nerfstudio.fields.generfacto_field import GenerfactoField +from nerfstudio.generative.stable_diffusion import StableDiffusion +from nerfstudio.generative.deepfloyd import DeepFloyd +from nerfstudio.generative.positional_text_embeddings import PositionalTextEmbeddings +from nerfstudio.model_components.losses import ( + MSELoss, + distortion_loss, + interlevel_loss, + orientation_loss, +) +from nerfstudio.model_components.ray_samplers import ( + ProposalNetworkSampler, + UniformSampler, +) +from nerfstudio.model_components.renderers import ( + AccumulationRenderer, + DepthRenderer, + NormalsRenderer, + RGBRenderer, +) +from nerfstudio.model_components.scene_colliders import AABBBoxCollider, SphereCollider +from nerfstudio.model_components.shaders import LambertianShader, NormalsShader +from nerfstudio.models.base_model import Model, ModelConfig +from nerfstudio.utils import colormaps, colors, math, misc + + +@dataclass +class GenerfactoModelConfig(ModelConfig): + """Generfacto model config""" + + _target: Type = field(default_factory=lambda: GenerfactoModel) + """target class to instantiate""" + prompt: str = "a high quality photo of a ripe pineapple" + """prompt for stable dreamfusion""" + + orientation_loss_mult: Tuple[float, float] = (0.001, 10.0) + """Orientation loss multipier on computed normals.""" + orientation_loss_mult_range: Tuple[int, int] = (0, 15000) + """number of iterations to reach last orientation_loss_mult value""" + random_light_source: bool = True + """Randomizes light source per output.""" + initialize_density: bool = True + """Initialize density in center of scene.""" + taper_range: Tuple[int, int] = (0, 1000) + """Range of step values for the density tapering""" + taper_strength: Tuple[float, float] = (1.0, 0.0) + """Strength schedule of center density""" + sphere_collider: bool = True + """Use spherical collider instead of box""" + random_background: bool = True + """Randomly choose between using background mlp and random color for background""" + + target_transmittance_start: float = 0.4 + """target transmittance for opacity penalty. This is the percent of the scene that is + background when rendered at the start of training""" + target_transmittance_end: float = 0.7 + """target transmittance for opacity penalty. This is the percent of the scene that is + background when rendered at the end of training""" + transmittance_end_schedule: int = 1500 + """number of iterations to reach target_transmittance_end""" + + num_proposal_samples_per_ray: Tuple[int, ...] = (256, 96) + """Number of samples per ray for each proposal network.""" + num_nerf_samples_per_ray: int = 48 + """Number of samples per ray for the nerf network.""" + proposal_update_every: int = 5 + """Sample every n steps after the warmup""" + proposal_warmup: int = 5000 + """Scales n from 1 to proposal_update_every over this many steps""" + num_proposal_iterations: int = 2 + """Number of proposal network iterations.""" + use_same_proposal_network: bool = False + """Use the same proposal network. Otherwise use different ones.""" + proposal_net_args_list: List[Dict] = field( + default_factory=lambda: [ + {"hidden_dim": 16, "log2_hashmap_size": 17, "num_levels": 5, "max_res": 128}, + {"hidden_dim": 16, "log2_hashmap_size": 17, "num_levels": 5, "max_res": 256}, + ] + ) + """Arguments for the proposal density fields.""" + proposal_weights_anneal_slope: float = 10.0 + """Slope of the annealing function for the proposal weights.""" + proposal_weights_anneal_max_num_iters: int = 500 + """Max num iterations for the annealing function.""" + use_single_jitter: bool = True + """Whether use single jitter or not for the proposal networks.""" + interlevel_loss_mult: float = 1.0 + """Proposal loss multiplier.""" + distortion_loss_mult: float = 1.0 + """Distortion loss multiplier.""" + start_normals_training: int = 1000 + """Start training normals after this many iterations""" + start_lambertian_training: int = 1000 + """start training with lambertian shading after this many iterations""" + opacity_penalty: bool = True + """enables penalty to encourage sparse weights (penalizing for uniform density along ray)""" + opacity_loss_mult: float = 1 + """scale for opacity penalty""" + max_res: int = 256 + """Maximum resolution of the density field.""" + + location_based_prompting: bool = True + """enables location based prompting""" + interpolated_prompting: bool = False + """enables interpolated location prompting""" + positional_prompting: Literal["discrete", "interpolated", "off"] = "discrete" + """ how to incorporate position into prompt""" + top_prompt: str = ", overhead view" + """appended to prompt for overhead view""" + side_prompt: str = ", side view" + """appended to prompt for side view""" + front_prompt: str = ", front view" + """appended to prompt for front view""" + back_prompt: str = ", back view" + """appended to prompt for back view""" + guidance_scale: float = 20 + """guidance scale for sds loss""" + diffusion_device: Optional[str] = None + """device for diffusion model""" + diffusion_model: Literal["stablediffusion", "deepfloyd"] = "deepfloyd" + """diffusion model for SDS loss""" + sd_version: str = "1-5" + """model version when using stable diffusion""" + implementation: Literal["tcnn", "torch"] = "tcnn" + """Which implementation to use for the model.""" + + +class GenerfactoModel(Model): + """Generfacto Model + + Args: + config: Generfacto configuration to instantiate model + """ + + config: GenerfactoModelConfig + + def __init__( + self, + config: GenerfactoModelConfig, + **kwargs, + ) -> None: + self.prompt = config.prompt + self.cur_prompt = config.prompt + self.sd_version = config.sd_version + self.initialize_density = config.initialize_density + self.train_normals = False + self.train_shaded = False + self.random_background = config.random_background + self.density_strength = 1.0 + self.target_transmittance = config.target_transmittance_start + self.grad_scaler = kwargs["grad_scaler"] + + self.guidance_scale = config.guidance_scale + self.top_prompt = config.top_prompt + self.side_prompt = config.side_prompt + self.back_prompt = config.back_prompt + self.front_prompt = config.front_prompt + + self.diffusion_device = ( + torch.device(kwargs["device"]) if config.diffusion_device is None else torch.device(config.diffusion_device) + ) + + super().__init__(config=config, **kwargs) + + def populate_modules(self): + """Set the fields and modules""" + super().populate_modules() + + if self.config.diffusion_model == "stablediffusion": + self._diffusion_model = StableDiffusion(self.diffusion_device, version=self.sd_version) + elif self.config.diffusion_model == "deepfloyd": + self._diffusion_model = DeepFloyd(self.diffusion_device) + + self.text_embeddings = PositionalTextEmbeddings( + base_prompt=self.cur_prompt, + top_prompt=self.cur_prompt + self.top_prompt, + side_prompt=self.cur_prompt + self.side_prompt, + back_prompt=self.cur_prompt + self.back_prompt, + front_prompt=self.cur_prompt + self.front_prompt, + diffusion_model=self._diffusion_model, + positional_prompting=self.config.positional_prompting, + ) + + # setting up fields + self.field = GenerfactoField(self.scene_box.aabb, max_res=self.config.max_res) + + # samplers + self.density_fns = [] + num_prop_nets = self.config.num_proposal_iterations + # Build the proposal network(s) + self.proposal_networks = torch.nn.ModuleList() + + for i in range(num_prop_nets): + prop_net_args = self.config.proposal_net_args_list[min(i, len(self.config.proposal_net_args_list) - 1)] + network = HashMLPDensityField( + self.scene_box.aabb, **prop_net_args, implementation=self.config.implementation + ) + self.proposal_networks.append(network) + self.density_fns.extend([network.density_fn for network in self.proposal_networks]) + + def update_schedule(step): + return np.clip( + np.interp(step, [0, self.config.proposal_warmup], [0, self.config.proposal_update_every]), + 1, + self.config.proposal_update_every, + ) + + 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_iterations, + single_jitter=self.config.use_single_jitter, + update_sched=update_schedule, + initial_sampler=UniformSampler(single_jitter=self.config.use_single_jitter), + ) + + # renderers + self.renderer_rgb = RGBRenderer(background_color=colors.WHITE) + self.renderer_accumulation = AccumulationRenderer() + self.renderer_depth = DepthRenderer() + self.renderer_normals = NormalsRenderer() + + # shaders + self.shader_lambertian = LambertianShader() + self.shader_normals = NormalsShader() + + # losses + self.rgb_loss = MSELoss() + + # colliders + if self.config.sphere_collider: + self.collider = SphereCollider(torch.Tensor([0, 0, 0]), 1.0) + else: + self.collider = AABBBoxCollider(scene_box=self.scene_box) + + def get_training_callbacks( + self, training_callback_attributes: TrainingCallbackAttributes + ) -> List[TrainingCallback]: + # the callback that we want to run every X iterations after the training iteration + def taper_density( + self, training_callback_attributes: TrainingCallbackAttributes, step: int # pylint: disable=unused-argument + ): + self.density_strength = np.interp(step, self.config.taper_range, self.config.taper_strength) + + def start_training_normals( + self, training_callback_attributes: TrainingCallbackAttributes, step: int # pylint: disable=unused-argument + ): + self.train_normals = True + + def start_shaded_training( + self, training_callback_attributes: TrainingCallbackAttributes, step: int # pylint: disable=unused-argument + ): + self.train_shaded = True + + def update_orientation_loss_mult( + self, training_callback_attributes: TrainingCallbackAttributes, step: int # pylint: disable=unused-argument + ): + if step <= self.config.start_normals_training: + self.orientation_loss_mult = 0 + else: + self.orientation_loss_mult = np.interp( + step, + self.config.orientation_loss_mult_range, + self.config.orientation_loss_mult, + ) + + # anneal the weights of the proposal network before doing PDF sampling + def set_anneal(step): + # https://arxiv.org/pdf/2111.12077.pdf eq. 18 + train_frac = np.clip(step / self.config.proposal_weights_anneal_max_num_iters, 0, 1) + + def bias(x, b): + return b * x / ((b - 1) * x + 1) + + anneal = bias(train_frac, self.config.proposal_weights_anneal_slope) + self.proposal_sampler.set_anneal(anneal) + + callbacks = [ + TrainingCallback( + where_to_run=[TrainingCallbackLocation.AFTER_TRAIN_ITERATION], + func=taper_density, + update_every_num_iters=1, + args=[self, training_callback_attributes], + ), + TrainingCallback( + where_to_run=[TrainingCallbackLocation.AFTER_TRAIN_ITERATION], + iters=(self.config.start_normals_training,), + func=start_training_normals, + args=[self, training_callback_attributes], + ), + TrainingCallback( + where_to_run=[TrainingCallbackLocation.AFTER_TRAIN_ITERATION], + iters=(self.config.start_lambertian_training,), + func=start_shaded_training, + args=[self, training_callback_attributes], + ), + TrainingCallback( + where_to_run=[TrainingCallbackLocation.AFTER_TRAIN_ITERATION], + update_every_num_iters=1, + func=update_orientation_loss_mult, + args=[self, training_callback_attributes], + ), + TrainingCallback( + where_to_run=[TrainingCallbackLocation.AFTER_TRAIN_ITERATION], + update_every_num_iters=1, + func=self.proposal_sampler.step_cb, + ), + TrainingCallback( + where_to_run=[TrainingCallbackLocation.BEFORE_TRAIN_ITERATION], + update_every_num_iters=1, + func=set_anneal, + ), + ] + return callbacks + + def get_param_groups(self) -> Dict[str, List[Parameter]]: + param_groups = {} + param_groups["proposal_networks"] = list(self.proposal_networks.parameters()) + param_groups["fields"] = list(self.field.parameters()) + return param_groups + + def get_outputs(self, ray_bundle: RayBundle): # pylint: disable=too-many-statements + # uniform sampling + background_rgb = self.field.get_background_rgb(ray_bundle) + ray_samples, weights_list, ray_samples_list = self.proposal_sampler(ray_bundle, density_fns=self.density_fns) + field_outputs = self.field(ray_samples, compute_normals=True) + density = field_outputs[FieldHeadNames.DENSITY] + + if self.initialize_density: + pos = ray_samples.frustums.get_positions() + density_blob = self.density_strength * (-torch.exp(torch.norm(pos, dim=-1) / 0.4) + 2)[..., None] + density = torch.max(density + density_blob, torch.tensor([0.0], device=self.device)) + + weights = ray_samples.get_weights(density) + weights_list.append(weights) + ray_samples_list.append(ray_samples) + + accumulation = self.renderer_accumulation(weights) + depth = self.renderer_depth(weights, ray_samples) + rgb = self.renderer_rgb(rgb=field_outputs[FieldHeadNames.RGB], weights=weights) + + accum_mask = torch.clamp((torch.nan_to_num(accumulation, nan=0.0)), min=0.0, max=1.0) + accum_mask_inv = 1.0 - accum_mask + + background = accum_mask_inv * background_rgb + + outputs = { + "rgb_only": rgb, + "background_rgb": background_rgb, + "background": background, + "accumulation": accum_mask, + "depth": depth, + } + + # These use a lot of GPU memory, so we avoid storing them for eval. + if self.training: + outputs["weights_list"] = weights_list + outputs["ray_samples_list"] = ray_samples_list + + for i in range(self.config.num_proposal_iterations): + outputs[f"prop_depth_{i}"] = self.renderer_depth(weights=weights_list[i], ray_samples=ray_samples_list[i]) + + normals = self.renderer_normals(normals=field_outputs[FieldHeadNames.NORMALS], weights=weights) + + # lambertian shading + if self.config.random_light_source: # and self.training: + light_d = ray_bundle.origins[0] + torch.randn(3, dtype=torch.float).to(normals) + else: + light_d = ray_bundle.origins[0] + light_d = math.safe_normalize(light_d) + + if (self.train_shaded and np.random.random_sample() > 0.75) or not self.training: + shading_weight = 0.9 + else: + shading_weight = 0.0 + + shaded, shaded_albedo = self.shader_lambertian( + rgb=rgb, normals=normals, light_direction=light_d, shading_weight=shading_weight, detach_normals=False + ) + + shaded, shaded_albedo = accum_mask * shaded, accum_mask * shaded_albedo + + outputs["normals"] = self.shader_normals(normals, weights=accum_mask) + outputs["shaded"] = shaded + outputs["other_train_output"] = shaded_albedo + background + outputs["shaded_albedo"] = shaded_albedo + outputs["rgb"] = accum_mask * rgb + background + + # while training 50% of the time use a random background + if np.random.random_sample() < 0.5 and self.random_background and self.training: + background = torch.ones_like(background) * torch.rand(3, device=self.device) * accum_mask_inv + + if shading_weight > 0: + samp = np.random.random_sample() + if samp > 0.5: + outputs["train_output"] = outputs["shaded"] + else: + outputs["train_output"] = shaded_albedo + background + else: + outputs["train_output"] = accum_mask * rgb + background + + outputs["rendered_orientation_loss"] = orientation_loss( + weights.detach(), field_outputs[FieldHeadNames.NORMALS], ray_bundle.directions + ) + + assert weights.shape[-1] == 1 + if self.config.opacity_penalty: + outputs["opacity_loss"] = torch.sqrt(torch.sum(weights, dim=-2) ** 2 + 0.01) * self.config.opacity_loss_mult + + return outputs + + def get_loss_dict(self, outputs, batch, metrics_dict=None) -> Dict[str, torch.Tensor]: + # Scaling metrics by coefficients to create the losses. + + loss_dict = {} + loss_dict = misc.scale_dict(loss_dict, self.config.loss_coefficients) + if self.train_normals: + # orientation loss for computed normals + loss_dict["orientation_loss"] = self.orientation_loss_mult * torch.mean( + outputs["rendered_orientation_loss"] + ) + else: + loss_dict["orientation_loss"] = 0 + + if self.config.opacity_penalty: + loss_dict["opacity_loss"] = self.config.opacity_loss_mult * outputs["opacity_loss"].mean() + + if self.prompt != self.cur_prompt: + self.cur_prompt = self.prompt + self.text_embeddings.update_prompt( + base_prompt=self.cur_prompt, + top_prompt=self.cur_prompt + self.top_prompt, + side_prompt=self.cur_prompt + self.side_prompt, + back_prompt=self.cur_prompt + self.back_prompt, + front_prompt=self.cur_prompt + self.front_prompt, + ) + + text_embedding = self.text_embeddings.get_text_embedding( + vertical_angle=batch["vertical"], horizontal_angle=batch["central"] + ) + + train_output = ( + outputs["train_output"] + .view(1, int(outputs["train_output"].shape[0] ** 0.5), int(outputs["train_output"].shape[0] ** 0.5), 3) + .permute(0, 3, 1, 2) + ) + + sds_loss = self._diffusion_model.sds_loss( + text_embedding.to(self.diffusion_device), + train_output.to(self.diffusion_device), + guidance_scale=int(self.guidance_scale), + grad_scaler=self.grad_scaler, + ) + + loss_dict["sds_loss"] = sds_loss.to(self.device) + + if self.training: + loss_dict["distortion_loss"] = self.config.distortion_loss_mult * distortion_loss( + outputs["weights_list"], outputs["ray_samples_list"] + ) + loss_dict["interlevel_loss"] = self.config.interlevel_loss_mult * interlevel_loss( + outputs["weights_list"], outputs["ray_samples_list"] + ) + 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]]: + acc = colormaps.apply_colormap(outputs["accumulation"]) + depth = colormaps.apply_depth_colormap( + outputs["depth"], + accumulation=outputs["accumulation"], + ) + prop_depth_0 = colormaps.apply_depth_colormap( + outputs["prop_depth_0"], + accumulation=outputs["accumulation"], + ) + prop_depth_1 = colormaps.apply_depth_colormap( + outputs["prop_depth_1"], + accumulation=outputs["accumulation"], + ) + + metrics_dict = {} + images_dict = { + "img": outputs["rgb"], + "accumulation": acc, + "depth": depth, + "prop_depth_0": prop_depth_0, + "prop_depth_1": prop_depth_1, + "normals": outputs["normals"], + } + return metrics_dict, images_dict diff --git a/nerfstudio/models/nerfacto.py b/nerfstudio/models/nerfacto.py index 6fcc984c7..369e3e67c 100644 --- a/nerfstudio/models/nerfacto.py +++ b/nerfstudio/models/nerfacto.py @@ -29,11 +29,7 @@ from torchmetrics.functional import structural_similarity_index_measure from torchmetrics.image.lpip import LearnedPerceptualImagePatchSimilarity from nerfstudio.cameras.rays import RayBundle, RaySamples -from nerfstudio.engine.callbacks import ( - TrainingCallback, - TrainingCallbackAttributes, - TrainingCallbackLocation, -) +from nerfstudio.engine.callbacks import TrainingCallback, TrainingCallbackAttributes, TrainingCallbackLocation from nerfstudio.field_components.field_heads import FieldHeadNames from nerfstudio.field_components.spatial_distortions import SceneContraction from nerfstudio.fields.density_fields import HashMLPDensityField @@ -46,16 +42,8 @@ from nerfstudio.model_components.losses import ( pred_normal_loss, scale_gradients_by_distance_squared, ) -from nerfstudio.model_components.ray_samplers import ( - ProposalNetworkSampler, - UniformSampler, -) -from nerfstudio.model_components.renderers import ( - AccumulationRenderer, - DepthRenderer, - NormalsRenderer, - RGBRenderer, -) +from nerfstudio.model_components.ray_samplers import ProposalNetworkSampler, UniformSampler +from nerfstudio.model_components.renderers import AccumulationRenderer, DepthRenderer, NormalsRenderer, RGBRenderer from nerfstudio.model_components.scene_colliders import NearFarCollider from nerfstudio.model_components.shaders import NormalsShader from nerfstudio.models.base_model import Model, ModelConfig @@ -81,10 +69,14 @@ class NerfactoModelConfig(ModelConfig): """Dimension of hidden layers for transient network""" num_levels: int = 16 """Number of levels of the hashmap for the base mlp.""" + base_res: int = 16 + """Resolution of the base grid for the hasgrid.""" max_res: int = 2048 """Maximum resolution of the hashmap for the base mlp.""" log2_hashmap_size: int = 19 """Size of the hashmap for the base mlp""" + features_per_level: int = 2 + """How many hashgrid features per level""" num_proposal_samples_per_ray: Tuple[int, ...] = (256, 96) """Number of samples per ray for each proposal network.""" num_nerf_samples_per_ray: int = 48 @@ -132,6 +124,8 @@ class NerfactoModelConfig(ModelConfig): """Use gradient scaler where the gradients are lower for points closer to the camera.""" implementation: Literal["tcnn", "torch"] = "tcnn" """Which implementation to use for the model.""" + appearance_embed_dim: int = 32 + """Dimension of the appearance embedding.""" class NerfactoModel(Model): @@ -165,6 +159,7 @@ class NerfactoModel(Model): num_images=self.num_train_data, use_pred_normals=self.config.predict_normals, use_average_appearance_embedding=self.config.use_average_appearance_embedding, + appearance_embedding_dim=self.config.appearance_embed_dim, implementation=self.config.implementation, ) diff --git a/nerfstudio/models/nerfplayer_nerfacto.py b/nerfstudio/models/nerfplayer_nerfacto.py deleted file mode 100644 index 7a5a56c25..000000000 --- a/nerfstudio/models/nerfplayer_nerfacto.py +++ /dev/null @@ -1,266 +0,0 @@ -# Copyright 2022 the Regents of the University of California, Nerfstudio Team and contributors. 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. - -""" -NeRFPlayer (https://arxiv.org/abs/2210.15947) implementation with nerfacto backbone. -""" - -from __future__ import annotations - -import functools -from dataclasses import dataclass, field -from typing import Dict, List, Literal, Sequence, Type, cast - -import numpy as np -import torch -from torchmetrics import PeakSignalNoiseRatio -from torchmetrics.functional import structural_similarity_index_measure -from torchmetrics.image.lpip import LearnedPerceptualImagePatchSimilarity - -from nerfstudio.cameras.rays import RayBundle -from nerfstudio.field_components.field_heads import FieldHeadNames -from nerfstudio.field_components.spatial_distortions import SceneContraction -from nerfstudio.fields.nerfplayer_nerfacto_field import ( - NerfplayerNerfactoField, - TemporalHashMLPDensityField, -) -from nerfstudio.model_components.losses import ( - MSELoss, - interlevel_loss, - orientation_loss, - pred_normal_loss, -) -from nerfstudio.model_components.ray_samplers import ProposalNetworkSampler -from nerfstudio.model_components.renderers import ( - AccumulationRenderer, - DepthRenderer, - NormalsRenderer, - RGBRenderer, -) -from nerfstudio.model_components.scene_colliders import NearFarCollider -from nerfstudio.model_components.shaders import NormalsShader -from nerfstudio.models.base_model import Model -from nerfstudio.models.nerfacto import NerfactoModel, NerfactoModelConfig - - -@dataclass -class NerfplayerNerfactoModelConfig(NerfactoModelConfig): - """Nerfplayer Model Config with Nerfacto backbone""" - - _target: Type = field(default_factory=lambda: NerfplayerNerfactoModel) - near_plane: float = 0.05 - """How far along the ray to start sampling.""" - far_plane: float = 1000.0 - """How far along the ray to stop sampling.""" - background_color: Literal["random", "last_sample", "black", "white"] = "random" - """Whether to randomize the background color. (Random is reported to be better on DyCheck.)""" - num_levels: int = 16 - """Hashing grid parameter.""" - features_per_level: int = 2 - """Hashing grid parameter.""" - log2_hashmap_size: int = 18 - """Hashing grid parameter.""" - temporal_dim: int = 32 - """Hashing grid parameter. A higher temporal dim means a higher temporal frequency.""" - proposal_net_args_list: List[Dict] = field( - default_factory=lambda: [ - {"hidden_dim": 16, "temporal_dim": 32, "log2_hashmap_size": 17, "num_levels": 5, "max_res": 64}, - {"hidden_dim": 16, "temporal_dim": 32, "log2_hashmap_size": 17, "num_levels": 5, "max_res": 256}, - ] - ) - """Arguments for the proposal density fields.""" - distortion_loss_mult: float = 1e-2 - """Distortion loss multiplier.""" - temporal_tv_weight: float = 1 - """Temporal TV balancing weight for feature channels.""" - depth_weight: float = 1e-1 - """depth loss balancing weight for feature channels.""" - - -class NerfplayerNerfactoModel(NerfactoModel): - """Nerfplayer model with Nerfacto backbone. - - Args: - config: Nerfplayer configuration to instantiate model - """ - - config: NerfplayerNerfactoModelConfig - - def populate_modules(self): - """Set the fields and modules.""" - Model.populate_modules(self) - - scene_contraction = SceneContraction(order=float("inf")) - - # Fields - self.field = NerfplayerNerfactoField( - self.scene_box.aabb, - temporal_dim=self.config.temporal_dim, - num_levels=self.config.num_levels, - features_per_level=self.config.features_per_level, - log2_hashmap_size=self.config.log2_hashmap_size, - spatial_distortion=scene_contraction, - num_images=self.num_train_data, - use_pred_normals=self.config.predict_normals, - use_average_appearance_embedding=self.config.use_average_appearance_embedding, - ) - - self.density_fns = [] - num_prop_nets = self.config.num_proposal_iterations - - # Build the proposal network(s) - proposal_networks: List[TemporalHashMLPDensityField] = [] - if self.config.use_same_proposal_network: - assert len(self.config.proposal_net_args_list) == 1, "Only one proposal network is allowed." - prop_net_args = self.config.proposal_net_args_list[0] - network = TemporalHashMLPDensityField( - self.scene_box.aabb, spatial_distortion=scene_contraction, **prop_net_args - ) - proposal_networks.append(network) - self.density_fns.extend([network.density_fn for _ in range(num_prop_nets)]) - else: - for i in range(num_prop_nets): - prop_net_args = self.config.proposal_net_args_list[min(i, len(self.config.proposal_net_args_list) - 1)] - network = TemporalHashMLPDensityField( - self.scene_box.aabb, - spatial_distortion=scene_contraction, - **prop_net_args, - ) - proposal_networks.append(network) - self.density_fns.extend([network.density_fn for network in proposal_networks]) - self.proposal_networks = cast(Sequence[TemporalHashMLPDensityField], torch.nn.ModuleList(proposal_networks)) - - # Samplers - def update_schedule(step): - return np.clip( - np.interp(step, [0, self.config.proposal_warmup], [0, self.config.proposal_update_every]), - 1, - self.config.proposal_update_every, - ) - - 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_iterations, - single_jitter=self.config.use_single_jitter, - update_sched=update_schedule, - ) - - # Collider - self.collider = NearFarCollider(near_plane=self.config.near_plane, far_plane=self.config.far_plane) - - # renderers - self.renderer_rgb = RGBRenderer(background_color=self.config.background_color) - self.renderer_accumulation = AccumulationRenderer() - self.renderer_depth = DepthRenderer(method="expected") # for depth loss - self.renderer_normals = NormalsRenderer() - - # shaders - self.normals_shader = NormalsShader() - - # losses - self.rgb_loss = MSELoss() - - # metrics - self.psnr = PeakSignalNoiseRatio(data_range=1.0) - self.ssim = structural_similarity_index_measure - self.lpips = LearnedPerceptualImagePatchSimilarity(normalize=True) - self.temporal_distortion = True # for viewer - - def get_outputs(self, ray_bundle: RayBundle): - assert ray_bundle.times is not None, "Time not provided." - ray_samples, weights_list, ray_samples_list = self.proposal_sampler( - ray_bundle, density_fns=[functools.partial(f, times=ray_bundle.times) for f in self.density_fns] - ) - field_outputs = self.field(ray_samples, compute_normals=self.config.predict_normals) - 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, - } - - if self.config.predict_normals: - outputs["normals"] = self.normals_shader( - self.renderer_normals(normals=field_outputs[FieldHeadNames.NORMALS], weights=weights) - ) - outputs["pred_normals"] = self.normals_shader( - self.renderer_normals(field_outputs[FieldHeadNames.PRED_NORMALS], weights=weights) - ) - - # These use a lot of GPU memory, so we avoid storing them for eval. - if self.training: - outputs["weights_list"] = weights_list - outputs["ray_samples_list"] = ray_samples_list - - if self.training and self.config.predict_normals: - outputs["rendered_orientation_loss"] = orientation_loss( - weights.detach(), field_outputs[FieldHeadNames.NORMALS], ray_bundle.directions - ) - - outputs["rendered_pred_normal_loss"] = pred_normal_loss( - weights.detach(), - field_outputs[FieldHeadNames.NORMALS].detach(), - field_outputs[FieldHeadNames.PRED_NORMALS], - ) - - for i in range(self.config.num_proposal_iterations): - outputs[f"prop_depth_{i}"] = self.renderer_depth(weights=weights_list[i], ray_samples=ray_samples_list[i]) - - return outputs - - 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"]) - if self.training: - loss_dict["interlevel_loss"] = self.config.interlevel_loss_mult * interlevel_loss( - outputs["weights_list"], outputs["ray_samples_list"] - ) - assert metrics_dict is not None and "distortion" in metrics_dict - loss_dict["distortion_loss"] = self.config.distortion_loss_mult * metrics_dict["distortion"] - if self.config.predict_normals: - # orientation loss for computed normals - loss_dict["orientation_loss"] = self.config.orientation_loss_mult * torch.mean( - outputs["rendered_orientation_loss"] - ) - - # ground truth supervision for normals - loss_dict["pred_normal_loss"] = self.config.pred_normal_loss_mult * torch.mean( - outputs["rendered_pred_normal_loss"] - ) - if "depth_image" in batch.keys() and self.config.depth_weight > 0: - depth_image = batch["depth_image"].to(self.device) - mask = (depth_image != 0).view([-1]) - loss_dict["depth_loss"] = 0 - - def compute_depth_loss(x): - return self.config.depth_weight * (x - depth_image[mask]).pow(2).mean() - - loss_dict["depth_loss"] = compute_depth_loss(outputs["depth"][mask]) - for i in range(self.config.num_proposal_iterations): - loss_dict["depth_loss"] += compute_depth_loss(outputs[f"prop_depth_{i}"][mask]) - if self.config.temporal_tv_weight > 0: - loss_dict["temporal_tv_loss"] = self.field.mlp_base.get_temporal_tv_loss() - for net in self.proposal_networks: - loss_dict["temporal_tv_loss"] += net.encoding.get_temporal_tv_loss() - loss_dict["temporal_tv_loss"] *= self.config.temporal_tv_weight - return loss_dict diff --git a/nerfstudio/models/nerfplayer_ngp.py b/nerfstudio/models/nerfplayer_ngp.py deleted file mode 100644 index c19cb4da2..000000000 --- a/nerfstudio/models/nerfplayer_ngp.py +++ /dev/null @@ -1,257 +0,0 @@ -# Copyright 2022 the Regents of the University of California, Nerfstudio Team and contributors. 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 NeRFPlayer (https://arxiv.org/abs/2210.15947) with InstantNGP backbone. -""" - -from __future__ import annotations - -from dataclasses import dataclass, field -from typing import List, Literal, Type - -import nerfacc -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 nerfstudio.cameras.rays import RayBundle -from nerfstudio.engine.callbacks import ( - TrainingCallback, - TrainingCallbackAttributes, - TrainingCallbackLocation, -) -from nerfstudio.field_components.field_heads import FieldHeadNames -from nerfstudio.field_components.spatial_distortions import SceneContraction -from nerfstudio.fields.nerfplayer_ngp_field import NerfplayerNGPField -from nerfstudio.model_components.losses import MSELoss -from nerfstudio.model_components.ray_samplers import VolumetricSampler -from nerfstudio.model_components.renderers import ( - AccumulationRenderer, - DepthRenderer, - RGBRenderer, -) -from nerfstudio.models.base_model import Model -from nerfstudio.models.instant_ngp import InstantNGPModelConfig, NGPModel - - -@dataclass -class NerfplayerNGPModelConfig(InstantNGPModelConfig): - """NeRFPlayer Model Config with InstantNGP backbone. - Tips for tuning the performance: - 1. If the scene is flickering, this is caused by unwanted high-freq on the temporal dimension. - Try reducing `temporal_dim` first, but don't be too small, otherwise the dynamic object is blurred. - Then try increasing the `temporal_tv_weight`. This is the loss for promoting smoothness among the - temporal channels. - 2. If a faster rendering is preferred, then try reducing `log2_hashmap_size`. If more details are - wanted, try increasing `log2_hashmap_size`. - 3. If the input cameras are of limited numbers, try reducing `num_levels`. `num_levels` is for - multi-resolution volume sampling, and has a similar behavior to the freq in NeRF. With a small - `num_levels`, a blurred rendering will be generated, but it is unlikely to overfit the training views. - """ - - _target: Type = field(default_factory=lambda: NerfplayerNGPModel) - temporal_dim: int = 64 - """Hashing grid parameter. A higher temporal dim means a higher temporal frequency.""" - num_levels: int = 16 - """Hashing grid parameter.""" - features_per_level: int = 2 - """Hashing grid parameter.""" - log2_hashmap_size: int = 17 - """Hashing grid parameter.""" - base_resolution: int = 16 - """Hashing grid parameter.""" - temporal_tv_weight: float = 1 - """Temporal TV loss balancing weight for feature channels.""" - depth_weight: float = 1e-1 - """depth loss balancing weight for feature channels.""" - train_background_color: Literal["random", "black", "white"] = "random" - """The training background color that is given to untrained areas.""" - eval_background_color: Literal["random", "black", "white"] = "white" - """The training background color that is given to untrained areas.""" - disable_viewing_dependent: bool = True - """Disable viewing dependent effects.""" - disable_scene_contraction: bool = False - """Whether to disable scene contraction or not.""" - - -class NerfplayerNGPModel(NGPModel): - """NeRFPlayer Model with InstantNGP backbone. - - Args: - config: NeRFPlayer NGP configuration to instantiate model - """ - - config: NerfplayerNGPModelConfig - field: NerfplayerNGPField - - def populate_modules(self): - """Set the fields and modules.""" - Model.populate_modules(self) - - if self.config.disable_scene_contraction: - scene_contraction = None - else: - scene_contraction = SceneContraction(order=float("inf")) - - self.field = NerfplayerNGPField( - aabb=self.scene_box.aabb, - use_appearance_embedding=self.config.use_appearance_embedding, - num_images=self.num_train_data, - temporal_dim=self.config.temporal_dim, - num_levels=self.config.num_levels, - features_per_level=self.config.features_per_level, - log2_hashmap_size=self.config.log2_hashmap_size, - base_resolution=self.config.base_resolution, - disable_viewing_dependent=self.config.disable_viewing_dependent, - spatial_distortion=scene_contraction, - ) - - self.scene_aabb = Parameter(self.scene_box.aabb.flatten(), requires_grad=False) - - # Occupancy Grid - self.occupancy_grid = nerfacc.OccGridEstimator( - roi_aabb=self.scene_aabb, - resolution=self.config.grid_resolution, - levels=self.config.grid_levels, - ) - - # Sampler - self.sampler = VolumetricSampler( - occupancy_grid=self.occupancy_grid, - density_fn=self.field.density_fn, - ) # need to update the density_fn later during forward (for input time) - - # renderers - self.renderer_rgb = RGBRenderer() # will update bgcolor later during forward - self.renderer_accumulation = AccumulationRenderer() - self.renderer_depth = DepthRenderer(method="expected") - - # losses - self.rgb_loss = MSELoss() - - # metrics - self.psnr = PeakSignalNoiseRatio(data_range=1.0) - self.ssim = structural_similarity_index_measure - self.lpips = LearnedPerceptualImagePatchSimilarity(normalize=True) - self.temporal_distortion = True # for viewer - - def get_training_callbacks( - self, training_callback_attributes: TrainingCallbackAttributes - ) -> List[TrainingCallback]: - def update_occupancy_grid(step: int): - self.occupancy_grid.update_every_n_steps( - step=step, - occ_eval_fn=lambda x: self.field.get_opacity(x, self.config.render_step_size), - ) - - return [ - TrainingCallback( - where_to_run=[TrainingCallbackLocation.BEFORE_TRAIN_ITERATION], - update_every_num_iters=1, - func=update_occupancy_grid, - ), - ] - - def get_outputs(self, ray_bundle: RayBundle): - num_rays = len(ray_bundle) - - with torch.no_grad(): - ray_samples, ray_indices = self.sampler( - ray_bundle=ray_bundle, - near_plane=self.config.near_plane, - far_plane=self.config.far_plane, - render_step_size=self.config.render_step_size, - cone_angle=self.config.cone_angle, - alpha_thre=self.config.alpha_thre, - ) - - field_outputs = self.field(ray_samples) - - # accumulation - packed_info = nerfacc.pack_info(ray_indices, num_rays) - weights = nerfacc.render_weight_from_density( - packed_info=packed_info, - sigmas=field_outputs[FieldHeadNames.DENSITY][..., 0], - t_starts=ray_samples.frustums.starts[..., 0], - t_ends=ray_samples.frustums.ends[..., 0], - )[0] - weights = weights[..., None] - - # update bgcolor in the renderer; usually random color for training and fixed color for inference - if self.training: - self.renderer_rgb.background_color = self.config.train_background_color - else: - self.renderer_rgb.background_color = self.config.eval_background_color - rgb = self.renderer_rgb( - rgb=field_outputs[FieldHeadNames.RGB], - weights=weights, - ray_indices=ray_indices, - num_rays=num_rays, - ) - depth = self.renderer_depth( - weights=weights, ray_samples=ray_samples, ray_indices=ray_indices, num_rays=num_rays - ) - accumulation = self.renderer_accumulation(weights=weights, ray_indices=ray_indices, num_rays=num_rays) - - outputs = { - "rgb": rgb, - "accumulation": accumulation, - "depth": depth, - "num_samples_per_ray": packed_info[:, 1], - } - # adding them to outputs for calculating losses - if self.training and self.config.depth_weight > 0: - outputs["ray_indices"] = ray_indices - outputs["ray_samples"] = ray_samples - outputs["weights"] = weights - outputs["sigmas"] = field_outputs[FieldHeadNames.DENSITY] - return outputs - - def get_loss_dict(self, outputs, batch, metrics_dict=None): - image = batch["image"].to(self.device) - rgb_loss = self.rgb_loss(image, outputs["rgb"]) - loss_dict = {"rgb_loss": rgb_loss} - if "depth_image" in batch.keys() and self.config.depth_weight > 0 and self.training: - depth_image = batch["depth_image"].to(self.device) - mask = depth_image != 0 - # First we calculate the depth value, just like most of the papers. - loss_dict["depth_loss"] = (outputs["depth"][mask] - depth_image[mask]).abs().mean() - # But this is not enough -- it will lead to fog like reconstructions, even with depth supervision. - # Because this loss only cares about the mean value. - # (Feel free to try it and see the fog-like effects on DyCheck by commenting out the following loss.) - # > The fog can be effectively penalized by multiview inputs (i.e., from another viewing point). - # > However, it is hard to get multiple views under the setting of dynamic scenes. - # > A new view always indicates another camera, which is expensive and brings sync problems. - # In DyCheck (https://arxiv.org/abs/2210.13445), surface sparsity regularizer - # (i.e., `distortion_loss` in nerfstudio) is used to make surface tight. - # The `distortion_loss` can be used here as well, but personally find it hard to implement... - # (Due to volume sampling, seems that cuda kernels are needed for efficiently computing the loss.) - # (Try nerfplayer with nerfacto backbone for distortion loss.) - # Instead, directly penalizing the empty space is found effective here. Perhaps due to a more - # "clear" loss (as it is directly applied to the network outputs, rather than post-processed values). - # But such a loss also has drawbacks: it tends to overfit wrong (or noise) presented in the depth map. - # Some structures are floating in the air with this loss... - gt_depth_packed = depth_image[outputs["ray_indices"]] - steps = (outputs["ray_samples"].frustums.starts + outputs["ray_samples"].frustums.ends) / 2 - # empty area should not be too close to the given depth, so lets add a margin to the gt depth - margin = (self.scene_box.aabb.max() - self.scene_box.aabb.min()) / 128 - density_min_mask = (gt_depth_packed - steps > margin) & (gt_depth_packed != 0) - loss_dict["depth_loss"] += (outputs["sigmas"][density_min_mask[..., 0]].pow(2)).mean() * 1e-2 - loss_dict["depth_loss"] *= self.config.depth_weight - if self.config.temporal_tv_weight > 0 and self.training: - loss_dict["temporal_tv_loss"] = self.config.temporal_tv_weight * self.field.mlp_base.get_temporal_tv_loss() - return loss_dict diff --git a/nerfstudio/pipelines/base_pipeline.py b/nerfstudio/pipelines/base_pipeline.py index 1e1e0fab5..e9d30a9ab 100644 --- a/nerfstudio/pipelines/base_pipeline.py +++ b/nerfstudio/pipelines/base_pipeline.py @@ -40,8 +40,8 @@ from torch.cuda.amp.grad_scaler import GradScaler from nerfstudio.configs import base_config as cfg from nerfstudio.data.datamanagers.base_datamanager import ( DataManager, + DataManagerConfig, VanillaDataManager, - VanillaDataManagerConfig, ) from nerfstudio.engine.callbacks import TrainingCallback, TrainingCallbackAttributes from nerfstudio.models.base_model import Model, ModelConfig @@ -205,7 +205,7 @@ class VanillaPipelineConfig(cfg.InstantiateConfig): _target: Type = field(default_factory=lambda: VanillaPipeline) """target class to instantiate""" - datamanager: VanillaDataManagerConfig = VanillaDataManagerConfig() + datamanager: DataManagerConfig = DataManagerConfig() """specifies the datamanager config""" model: ModelConfig = ModelConfig() """specifies the model config""" @@ -242,7 +242,7 @@ class VanillaPipeline(Pipeline): super().__init__() self.config = config self.test_mode = test_mode - self.datamanager: VanillaDataManager = config.datamanager.setup( + self.datamanager: DataManager = config.datamanager.setup( device=device, test_mode=test_mode, world_size=world_size, local_rank=local_rank ) self.datamanager.to(device) @@ -347,6 +347,7 @@ class VanillaPipeline(Pipeline): """ self.eval() metrics_dict_list = [] + assert isinstance(self.datamanager, VanillaDataManager) num_images = len(self.datamanager.fixed_indices_eval_dataloader) with Progress( TextColumn("[progress.description]{task.description}"), diff --git a/nerfstudio/process_data/colmap_converter_to_nerfstudio_dataset.py b/nerfstudio/process_data/colmap_converter_to_nerfstudio_dataset.py index b80923d3e..fb2fb88b6 100644 --- a/nerfstudio/process_data/colmap_converter_to_nerfstudio_dataset.py +++ b/nerfstudio/process_data/colmap_converter_to_nerfstudio_dataset.py @@ -189,9 +189,15 @@ class ColmapConverterToNerfstudioDataset(BaseConverterToNerfstudioDataset): if self.refine_pixsfm: assert sfm_tool == "hloc", "refine_pixsfm only works with sfm_tool hloc" + # set the image_dir if didn't copy + if self.skip_image_processing: + image_dir = self.data + else: + image_dir = self.image_dir + if sfm_tool == "colmap": colmap_utils.run_colmap( - image_dir=self.image_dir, + image_dir=image_dir, colmap_dir=self.absolute_colmap_path, camera_model=CAMERA_MODELS[self.camera_type], camera_mask_path=mask_path, @@ -208,7 +214,7 @@ class ColmapConverterToNerfstudioDataset(BaseConverterToNerfstudioDataset): assert matcher_type is not None assert matcher_type != "NN" # Only used for colmap. hloc_utils.run_hloc( - image_dir=self.image_dir, + image_dir=image_dir, colmap_dir=self.absolute_colmap_path, camera_model=CAMERA_MODELS[self.camera_type], verbose=self.verbose, diff --git a/nerfstudio/process_data/process_data_utils.py b/nerfstudio/process_data/process_data_utils.py index f8441b319..5b7ae9686 100644 --- a/nerfstudio/process_data/process_data_utils.py +++ b/nerfstudio/process_data/process_data_utils.py @@ -15,9 +15,9 @@ """Helper utils for processing data into the nerfstudio format.""" import math -import os import shutil import sys +import re from enum import Enum from pathlib import Path from typing import List, Literal, Optional, OrderedDict, Tuple, Union @@ -94,8 +94,9 @@ def get_num_frames_in_video(video: Path) -> int: -show_entries stream=nb_read_packets -of csv=p=0 "{video}"' output = run_command(cmd) assert output is not None - output = output.strip(" ,\t\n\r") - return int(output) + number_match = re.search(r"\d+", output) + assert number_match is not None + return int(number_match[0]) def convert_video_to_images( @@ -348,11 +349,8 @@ def downscale_images( assert isinstance(downscale_factor, int) downscale_dir = image_dir.parent / f"{folder_name}_{downscale_factor}" downscale_dir.mkdir(parents=True, exist_ok=True) - # Using %05d ffmpeg commands appears to be unreliable (skips images), so use scandir. - files = os.scandir(image_dir) - for f in files: - if f.is_dir(): - continue + # Using %05d ffmpeg commands appears to be unreliable (skips images). + for f in list_images(image_dir): filename = f.name nn_flag = "" if not nearest_neighbor else ":flags=neighbor" ffmpeg_cmd = [ diff --git a/nerfstudio/scripts/train.py b/nerfstudio/scripts/train.py index cd5e73324..9ca18c71a 100644 --- a/nerfstudio/scripts/train.py +++ b/nerfstudio/scripts/train.py @@ -231,6 +231,10 @@ def main(config: TrainerConfig) -> None: CONSOLE.log("Using --data alias for --data.pipeline.datamanager.data") config.pipeline.datamanager.data = config.data + if config.prompt: + CONSOLE.log("Using --prompt alias for --data.pipeline.model.prompt") + config.pipeline.model.prompt = config.prompt + if config.load_config: CONSOLE.log(f"Loading pre-set config from: {config.load_config}") config = yaml.load(config.load_config.read_text(), Loader=yaml.Loader) diff --git a/nerfstudio/utils/colormaps.py b/nerfstudio/utils/colormaps.py index 0e09c0bfd..d772d40b4 100644 --- a/nerfstudio/utils/colormaps.py +++ b/nerfstudio/utils/colormaps.py @@ -24,7 +24,7 @@ from torch import Tensor from nerfstudio.utils import colors -Colormaps = Literal["default", "turbo", "viridis", "magma", "inferno", "cividis", "pca"] +Colormaps = Literal["default", "turbo", "viridis", "magma", "inferno", "cividis", "gray", "pca"] @dataclass(frozen=True) @@ -104,6 +104,8 @@ def apply_float_colormap(image: Float[Tensor, "*bs 1"], colormap: Colormaps = "v colormap = "turbo" image = torch.nan_to_num(image, 0) + if colormap == "gray": + return image.repeat(1, 1, 3) image_long = (image * 255).long() image_long_min = torch.min(image_long) image_long_max = torch.max(image_long) diff --git a/nerfstudio/utils/eval_utils.py b/nerfstudio/utils/eval_utils.py index acd8bee18..13948678b 100644 --- a/nerfstudio/utils/eval_utils.py +++ b/nerfstudio/utils/eval_utils.py @@ -89,7 +89,6 @@ def eval_setup( assert isinstance(config, TrainerConfig) config.pipeline.datamanager._target = all_methods[config.method_name].pipeline.datamanager._target - if eval_num_rays_per_chunk: config.pipeline.model.eval_num_rays_per_chunk = eval_num_rays_per_chunk diff --git a/nerfstudio/utils/math.py b/nerfstudio/utils/math.py index 866d280f8..788a0520d 100644 --- a/nerfstudio/utils/math.py +++ b/nerfstudio/utils/math.py @@ -80,12 +80,12 @@ def components_from_spherical_harmonics( components[..., 16] = 2.5033429417967046 * x * y * (xx - yy) components[..., 17] = 1.7701307697799304 * y * z * (3 * xx - yy) components[..., 18] = 0.9461746957575601 * x * y * (7 * zz - 1) - components[..., 19] = 0.6690465435572892 * y * (7 * zz - 3) + components[..., 19] = 0.6690465435572892 * y * z * (7 * zz - 3) components[..., 20] = 0.10578554691520431 * (35 * zz * zz - 30 * zz + 3) components[..., 21] = 0.6690465435572892 * x * z * (7 * zz - 3) components[..., 22] = 0.47308734787878004 * (xx - yy) * (7 * zz - 1) components[..., 23] = 1.7701307697799304 * x * z * (xx - 3 * yy) - components[..., 24] = 0.4425326924449826 * (xx * (xx - 3 * yy) - yy * (3 * xx - yy)) + components[..., 24] = 0.6258357354491761 * (xx * (xx - 3 * yy) - yy * (3 * xx - yy)) return components diff --git a/nerfstudio/viewer/server/control_panel.py b/nerfstudio/viewer/server/control_panel.py index 456e3598c..7039b61c3 100644 --- a/nerfstudio/viewer/server/control_panel.py +++ b/nerfstudio/viewer/server/control_panel.py @@ -361,7 +361,7 @@ def _get_colormap_options(dimensions: int, dtype: type) -> List[Colormaps]: if dimensions == 3: colormap_options = ["default"] if dimensions == 1 and dtype == torch.float: - colormap_options = [c for c in list(get_args(Colormaps)) if c != "default"] + colormap_options = [c for c in list(get_args(Colormaps)) if c not in ("default", "pca")] if dimensions > 3: colormap_options = ["pca"] return colormap_options diff --git a/nerfstudio/viewer_beta/render_state_machine.py b/nerfstudio/viewer_beta/render_state_machine.py index d18200761..6be9b3403 100644 --- a/nerfstudio/viewer_beta/render_state_machine.py +++ b/nerfstudio/viewer_beta/render_state_machine.py @@ -17,6 +17,7 @@ from __future__ import annotations import contextlib import threading +import time from dataclasses import dataclass from typing import TYPE_CHECKING, Any, Dict, Literal, Optional, Tuple, get_args @@ -97,12 +98,16 @@ class RenderStateMachine(threading.Thread): elif self.next_action == "rerender": # never overwrite rerenders pass + elif action.action == "static" and self.next_action.action == "move": + # don't overwrite a move action with a static: static is always self-fired + return else: # monimal use case, just set the next action self.next_action = action # handle interrupt logic if self.state == "high" and self.next_action.action in ("move", "rerender"): + print("interrupting render", self.next_action.action) self.interrupt_render_flag = True self.render_trigger.set() @@ -176,7 +181,10 @@ class RenderStateMachine(threading.Thread): continue self._send_output_to_viewer(outputs) # if we rendered a static low res, we need to self-trigger a static high-res - if self.state == "low_static": + if self.next_action is None: + # if there hasn't been an action, wait for 1/target_fps seconds in case we get another move command + time.sleep(1 / self.target_fps) + if self.state in ["low_static", "low_move"]: self.action(RenderAction("static", action.camera_state)) def check_interrupt(self, frame, event, arg): diff --git a/nerfstudio/viewer_beta/viewer.py b/nerfstudio/viewer_beta/viewer.py index f4e8d3429..51ca6ab14 100644 --- a/nerfstudio/viewer_beta/viewer.py +++ b/nerfstudio/viewer_beta/viewer.py @@ -126,8 +126,8 @@ class Viewer: def _interrupt_render(self, _) -> None: """Interrupt current render.""" - if self.camera_message is not None: - self.render_statemachine.action(RenderAction("rerender", self.camera_message)) + if self.camera_state is not None: + self.render_statemachine.action(RenderAction("rerender", self.camera_state)) def _crop_params_update(self, _) -> None: """Update crop parameters""" diff --git a/pyproject.toml b/pyproject.toml index 7420c9217..94ba37b95 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta" [project] name = "nerfstudio" -version = "0.3.1" +version = "0.3.2" description = "All-in-one repository for state-of-the-art NeRFs" readme = "README.md" license = { text="Apache 2.0"} @@ -69,6 +69,9 @@ dependencies = [ gen = [ "diffusers==0.16.1", "transformers==4.29.2", + "accelerate==0.19.0", + "bitsandbytes==0.39.0", + "sentencepiece==0.1.99", ] @@ -81,7 +84,7 @@ dev = [ "typeguard==2.13.3", "ruff==0.0.267", "sshconf==0.2.5", - "pycolmap==0.3.0", + "pycolmap>=0.3.0", # NOTE: pycolmap==0.3.0 is not available on newer python versions "diffusers==0.16.1", "opencv-stubs==0.0.7", "transformers==4.29.2", diff --git a/tests/field_components/test_temporal_grid.py b/tests/field_components/test_temporal_grid.py deleted file mode 100644 index 977b6a419..000000000 --- a/tests/field_components/test_temporal_grid.py +++ /dev/null @@ -1,49 +0,0 @@ -""" -Test if temporal grid run properly (forward and backward) -""" -import torch - -from nerfstudio.field_components import temporal_grid - - -def test_temporal_grid(): - """Test temporal grid""" - if not torch.cuda.is_available(): - print("Unable to test temporal grid without GPU, since CUDA kernels involved.") - return - - model = temporal_grid.TemporalGridEncoder( - temporal_dim=2, - input_dim=1, - num_levels=1, - level_dim=1, - per_level_scale=1, - base_resolution=1, - log2_hashmap_size=2, - desired_resolution=None, - gridtype="tiled", - align_corners=False, - ).cuda() - random_embedding = torch.rand_like(model.embeddings) - random_embedding[:, 0] = torch.arange(8).to(model.embeddings) - model.embeddings = torch.nn.Parameter(random_embedding, requires_grad=True) - - x = torch.zeros([1024, 1]).cuda() - t = torch.zeros([1024, 1]).cuda() - out = model(x, t) - weight = torch.randn_like(out) - (out * weight).sum().backward() - assert torch.all(out == 0.5) - assert model.embeddings.grad is not None - assert model.embeddings.grad.sum() - weight.sum() < 0.01 - assert torch.all(model.embeddings.grad[2:, :] == 0) - assert torch.all(model.embeddings.grad[:, 1:] == 0) - # TODO: test temporal_tv_loss - # model.get_temporal_tv_loss() - - # TODO: Any better way to numerically test it? Especially for the gradients. - # (maybe add some randomness and multiple cases for the testing?) - - -if __name__ == "__main__": - test_temporal_grid() diff --git a/tests/pipelines/test_vanilla_pipeline.py b/tests/pipelines/test_vanilla_pipeline.py index 2218294b7..c27aa2069 100644 --- a/tests/pipelines/test_vanilla_pipeline.py +++ b/tests/pipelines/test_vanilla_pipeline.py @@ -11,10 +11,10 @@ from nerfstudio.data.datasets.base_dataset import DataparserOutputs, InputDatase from nerfstudio.pipelines.base_pipeline import ( Model, ModelConfig, - VanillaDataManagerConfig, VanillaPipeline, VanillaPipelineConfig, ) +from nerfstudio.data.datamanagers.base_datamanager import VanillaDataManagerConfig class MockedDataManager: diff --git a/tests/test_train.py b/tests/test_train.py index 5cc5dcb51..d5d25c141 100644 --- a/tests/test_train.py +++ b/tests/test_train.py @@ -24,9 +24,8 @@ BLACKLIST = [ "volinga", "phototourism", "depth-nerfacto", - "nerfplayer-ngp", - "nerfplayer-nerfacto", "neus", + "generfacto", "neus-facto", ] diff --git a/tests/utils/test_math.py b/tests/utils/test_math.py new file mode 100644 index 000000000..c0e1edc43 --- /dev/null +++ b/tests/utils/test_math.py @@ -0,0 +1,16 @@ +import pytest +import torch + +from nerfstudio.utils.math import components_from_spherical_harmonics + + +@pytest.mark.parametrize("components", list(range(1, 5 + 1))) +def test_spherical_harmonics(components): + torch.manual_seed(0) + N = 1000000 + + dx = torch.normal(0, 1, size=(N, 3)) + dx = dx / torch.linalg.norm(dx, dim=-1, keepdim=True) + sh = components_from_spherical_harmonics(components, dx) + matrix = (sh.T @ sh) / N * 4 * torch.pi + torch.testing.assert_close(matrix, torch.eye(components**2), rtol=0, atol=1e-2)