mirror of
https://github.com/nerfstudio-project/nerfstudio.git
synced 2026-11-24 18:14:16 +08:00
deploy: 50e0e3c70c
This commit is contained in:
commit
0cc78c2e59
480 files changed
+584024
No files matched your search
@@ -0,0 +1,226 @@
|
||||
# DataManagers
|
||||
|
||||
```{image} imgs/pipeline_datamanager-light.png
|
||||
:align: center
|
||||
:class: only-light
|
||||
:width: 600
|
||||
```
|
||||
|
||||
```{image} imgs/pipeline_datamanager-dark.png
|
||||
:align: center
|
||||
:class: only-dark
|
||||
:width: 600
|
||||
```
|
||||
|
||||
## What is a DataManager?
|
||||
|
||||
The DataManager batches and returns two components from an input dataset:
|
||||
|
||||
1. A representation of viewpoint (either cameras or rays).
|
||||
- For splatting methods (`FullImageDataManager`): a `Cameras` object.
|
||||
- For ray sampling methods (`VanillaDataManager`): a `RayBundle` object.
|
||||
2. A dictionary of ground truth data.
|
||||
- For splatting methods (`FullImageDataManager`): dictionary contains complete images.
|
||||
- For ray sampling methods (`VanillaDataManager`): dictionary contains per-ray information.
|
||||
|
||||
Behaviors are defined by implementing the abstract methods required by the DataManager:
|
||||
|
||||
```python
|
||||
class DataManager(nn.Module):
|
||||
"""Generic data manager's abstract class
|
||||
"""
|
||||
|
||||
@abstractmethod
|
||||
def next_train(self, step: int) -> Tuple[Union[RayBundle, Cameras], Dict]:
|
||||
"""Returns the next batch of data for train."""
|
||||
|
||||
@abstractmethod
|
||||
def next_eval(self, step: int) -> Tuple[Union[RayBundle, Cameras], Dict]:
|
||||
"""Returns the next batch of data for eval."""
|
||||
|
||||
@abstractmethod
|
||||
def next_eval_image(self, step: int) -> Tuple[int, RayBundle, Dict]:
|
||||
"""Returns the next eval image.
|
||||
|
||||
Returns:
|
||||
The image index from the eval dataset, the CameraRayBundle, and the RayGT dictionary.
|
||||
"""
|
||||
```
|
||||
|
||||
## Example
|
||||
|
||||
We've implemented a VanillaDataManager that implements the standard logic of most NeRF papers. It will randomly sample training rays with corresponding ground truth information, in RayBundle and RayGT objects respectively. The config for the VanillaDataManager is the following.
|
||||
|
||||
```python
|
||||
@dataclass
|
||||
class VanillaDataManagerConfig(InstantiateConfig):
|
||||
"""Configuration for data manager instantiation; DataManager is in charge of keeping the train/eval dataparsers;
|
||||
After instantiation, data manager holds both train/eval datasets and is in charge of returning unpacked
|
||||
train/eval data at each iteration
|
||||
"""
|
||||
|
||||
_target: Type = field(default_factory=lambda: VanillaDataManager)
|
||||
"""target class to instantiate"""
|
||||
dataparser: AnnotatedDataParserUnion = BlenderDataParserConfig()
|
||||
"""specifies the dataparser used to unpack the data"""
|
||||
train_num_rays_per_batch: int = 1024
|
||||
"""number of rays per batch to use per training iteration"""
|
||||
train_num_images_to_sample_from: int = -1
|
||||
"""number of images to sample during training iteration"""
|
||||
eval_num_rays_per_batch: int = 1024
|
||||
"""number of rays per batch to use per eval iteration"""
|
||||
eval_num_images_to_sample_from: int = -1
|
||||
"""number of images to sample during eval iteration"""
|
||||
camera_optimizer: CameraOptimizerConfig = CameraOptimizerConfig()
|
||||
"""specifies the camera pose optimizer used during training"""
|
||||
```
|
||||
|
||||
Let's take a quick look at how the `next_train` method is implemented. Here we sample images, then pixels, and then return the RayBundle and RayGT information.
|
||||
|
||||
```python
|
||||
def next_train(self, step: int) -> Tuple[RayBundle, Dict]:
|
||||
"""Returns the next batch of data from the train dataloader."""
|
||||
self.train_count += 1
|
||||
# sample a batch of images
|
||||
image_batch = next(self.iter_train_image_dataloader)
|
||||
# sample pixels from this batch of images
|
||||
batch = self.train_pixel_sampler.sample(image_batch)
|
||||
ray_indices = batch["indices"]
|
||||
# generate rays from this image and pixel indices
|
||||
ray_bundle = self.train_ray_generator(ray_indices)
|
||||
# return RayBundle and RayGT information
|
||||
return ray_bundle, batch
|
||||
```
|
||||
|
||||
You can see our code for more details.
|
||||
|
||||
```{button-link} https://github.com/nerfstudio-project/nerfstudio/blob/main/nerfstudio/data/datamanagers/base_datamanager.py
|
||||
:color: primary
|
||||
:outline:
|
||||
See the code!
|
||||
```
|
||||
|
||||
## Creating Your Own
|
||||
|
||||
We currently don't have other implementations because most papers follow the VanillaDataManager implementation. However, it should be straightforward to add a VanillaDataManager with logic that progressively adds cameras, for instance, by relying on the step and modifying RayBundle and RayGT generation logic.
|
||||
|
||||
## Disk Caching for Large Datasets
|
||||
As of January 2025, the FullImageDatamanager and ParallelImageDatamanager implementations now support parallelized dataloading and dataloading from disk to avoid Out-Of-Memory errors and support very large datasets. To train a NeRF-based method with a large dataset that's unable to fit in memory, please add the `load_from_disk` flag to your `ns-train` command. For example with nerfacto:
|
||||
```bash
|
||||
ns-train nerfacto --data {PROCESSED_DATA_DIR} --pipeline.datamanager.load-from-disk
|
||||
```
|
||||
|
||||
To train splatfacto with a large dataset that's unable to fit in memory, please set the device of `cache_images` to `"disk"`. For example with splatfacto:
|
||||
```bash
|
||||
ns-train splatfacto --data {PROCESSED_DATA_DIR} --pipeline.datamanager.cache-images disk
|
||||
```
|
||||
|
||||
Checkout these flowcharts for more customization on large datasets!
|
||||
|
||||
```{image} imgs/DatamanagerGuide-LargeNeRF-light.png
|
||||
:align: center
|
||||
:class: only-light
|
||||
:width: 600
|
||||
```
|
||||
|
||||
```{image} imgs/DatamanagerGuide-LargeNeRF-dark.png
|
||||
:align: center
|
||||
:class: only-dark
|
||||
:width: 600
|
||||
```
|
||||
|
||||
```{image} imgs/DatamanagerGuide-Large3DGS-light.png
|
||||
:align: center
|
||||
:class: only-light
|
||||
:width: 600
|
||||
```
|
||||
|
||||
```{image} imgs/DatamanagerGuide-Large3DGS-dark.png
|
||||
:align: center
|
||||
:class: only-dark
|
||||
:width: 600
|
||||
```
|
||||
|
||||
## Migrating Your DataManager to the new DataManager
|
||||
Many methods subclass a DataManager and add extra data to it. If you would like your custom datamanager to also support new parallel features, you can migrate any custom dataloading logic to the new `custom_ray_processor()` API. This function takes in a full training batch (either image or ray bundle) and allows the user to modify or add to it. Let's take a look at an example for the LERF method, which was built on Nerfstudio's VanillaDataManager. This API provides an interface to attach new information to the RayBundle (for ray based methods), Cameras object (for splatting based methods), or ground truth dictionary. It runs in a background process if disk caching is enabled, otherwise it runs in the main process.
|
||||
|
||||
Naively transfering code to `custom_ray_processor` may still OOM on very large datasets if initialization code requires computing something over the whole dataset. To fully take advantage of parallelization make sure your subclassed datamanager computes new information inside the `custom_ray_processor`, or caches a subset of the whole dataset. This can also still be slow if pre-computation requires GPU-heavy steps on the same GPU used for training.
|
||||
|
||||
**Note**: Because the parallel DataManager uses background processes, any member of the DataManager needs to be *picklable* to be used inside `custom_ray_processor`.
|
||||
|
||||
```python
|
||||
class LERFDataManager(VanillaDataManager):
|
||||
"""Subclass VanillaDataManager to add extra data processing
|
||||
|
||||
Args:
|
||||
config: the DataManagerConfig used to instantiate class
|
||||
"""
|
||||
|
||||
config: LERFDataManagerConfig
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
config: LERFDataManagerConfig,
|
||||
device: Union[torch.device, str] = "cpu",
|
||||
test_mode: Literal["test", "val", "inference"] = "val",
|
||||
world_size: int = 1,
|
||||
local_rank: int = 0,
|
||||
**kwargs,
|
||||
):
|
||||
super().__init__(
|
||||
config=config, device=device, test_mode=test_mode, world_size=world_size, local_rank=local_rank, **kwargs
|
||||
)
|
||||
# Some code to initialize all the CLIP and DINO feature encoders.
|
||||
self.image_encoder: BaseImageEncoder = kwargs["image_encoder"]
|
||||
self.dino_dataloader = ...
|
||||
self.clip_interpolator = ...
|
||||
|
||||
def next_train(self, step: int) -> Tuple[RayBundle, Dict]:
|
||||
"""Returns the next batch of data from the train dataloader.
|
||||
|
||||
In this custom DataManager we need to add on the data that LERF needs, namely CLIP and DINO features.
|
||||
"""
|
||||
self.train_count += 1
|
||||
image_batch = next(self.iter_train_image_dataloader)
|
||||
assert self.train_pixel_sampler is not None
|
||||
batch = self.train_pixel_sampler.sample(image_batch)
|
||||
ray_indices = batch["indices"]
|
||||
ray_bundle = self.train_ray_generator(ray_indices)
|
||||
batch["clip"], clip_scale = self.clip_interpolator(ray_indices)
|
||||
batch["dino"] = self.dino_dataloader(ray_indices)
|
||||
ray_bundle.metadata["clip_scales"] = clip_scale
|
||||
# assume all cameras have the same focal length and image width
|
||||
ray_bundle.metadata["fx"] = self.train_dataset.cameras[0].fx.item()
|
||||
ray_bundle.metadata["width"] = self.train_dataset.cameras[0].width.item()
|
||||
ray_bundle.metadata["fy"] = self.train_dataset.cameras[0].fy.item()
|
||||
ray_bundle.metadata["height"] = self.train_dataset.cameras[0].height.item()
|
||||
return ray_bundle, batch
|
||||
```
|
||||
|
||||
To migrate this custom datamanager to the new datamanager, we'll subclass the new ParallelDataManager and shift the data customization process from `next_train()` to `custom_ray_processor()`.
|
||||
The function `custom_ray_processor()` is called with a fully populated ray bundle and ground truth batch, just like the subclassed `next_train` in the above code. This code, however, is run in a background process.
|
||||
|
||||
```python
|
||||
class LERFDataManager(ParallelDataManager, Generic[TDataset]):
|
||||
"""
|
||||
__init__ stays the same
|
||||
"""
|
||||
|
||||
...
|
||||
|
||||
def custom_ray_processor(
|
||||
self, ray_bundle: RayBundle, batch: Dict
|
||||
) -> Tuple[RayBundle, Dict]:
|
||||
"""An API to add latents, metadata, or other further customization to the RayBundle dataloading process that is parallelized."""
|
||||
ray_indices = batch["indices"]
|
||||
batch["clip"], clip_scale = self.clip_interpolator(ray_indices)
|
||||
batch["dino"] = self.dino_dataloader(ray_indices)
|
||||
ray_bundle.metadata["clip_scales"] = clip_scale
|
||||
|
||||
# Assume all cameras have the same focal length and image dimensions.
|
||||
ray_bundle.metadata["fx"] = self.train_dataset.cameras[0].fx.item()
|
||||
ray_bundle.metadata["width"] = self.train_dataset.cameras[0].width.item()
|
||||
ray_bundle.metadata["fy"] = self.train_dataset.cameras[0].fy.item()
|
||||
ray_bundle.metadata["height"] = self.train_dataset.cameras[0].height.item()
|
||||
return ray_bundle, batch
|
||||
```
|
||||
@@ -0,0 +1,134 @@
|
||||
# DataParsers
|
||||
|
||||
```{image} imgs/pipeline_parser-light.png
|
||||
:align: center
|
||||
:class: only-light
|
||||
:width: 600
|
||||
```
|
||||
|
||||
```{image} imgs/pipeline_parser-dark.png
|
||||
:align: center
|
||||
:class: only-dark
|
||||
:width: 600
|
||||
```
|
||||
|
||||
## What is a DataParser?
|
||||
|
||||
The dataparser returns `DataparserOutputs`, which puts all the various datasets into a common format. The DataparserOutputs should be lightweight, containing filenames or other meta information which can later be processed by actual PyTorch Datasets and Dataloaders. The common format makes it easy to add another DataParser. All you have to do is implement the private method `_generate_dataparser_outputs` shown below.
|
||||
|
||||
```python
|
||||
@dataclass
|
||||
class DataparserOutputs:
|
||||
"""Dataparser outputs for the which will be used by the DataManager
|
||||
for creating RayBundle and RayGT objects."""
|
||||
|
||||
image_filenames: List[Path]
|
||||
"""Filenames for the images."""
|
||||
cameras: Cameras
|
||||
"""Camera object storing collection of camera information in dataset."""
|
||||
alpha_color: Optional[TensorType[3]] = None
|
||||
"""Color of dataset background."""
|
||||
scene_box: SceneBox = SceneBox()
|
||||
"""Scene box of dataset. Used to bound the scene or provide the scene scale depending on model."""
|
||||
mask_filenames: Optional[List[Path]] = None
|
||||
"""Filenames for any masks that are required"""
|
||||
metadata: Dict[str, Any] = to_immutable_dict({})
|
||||
"""Dictionary of any metadata that be required for the given experiment.
|
||||
Will be processed by the InputDataset to create any additional tensors that may be required.
|
||||
"""
|
||||
dataparser_transform: TensorType[3, 4] = torch.eye(4)[:3, :]
|
||||
"""Transform applied by the dataparser."""
|
||||
dataparser_scale: float = 1.0
|
||||
"""Scale applied by the dataparser."""
|
||||
|
||||
@dataclass
|
||||
class DataParser:
|
||||
|
||||
@abstractmethod
|
||||
def _generate_dataparser_outputs(self, split: str = "train") -> DataparserOutputs:
|
||||
"""Abstract method that returns the dataparser outputs for the given split.
|
||||
|
||||
Args:
|
||||
split: Which dataset split to generate (train/test).
|
||||
|
||||
Returns:
|
||||
DataparserOutputs containing data for the specified dataset and split
|
||||
"""
|
||||
```
|
||||
|
||||
## Example
|
||||
|
||||
Here is an example where we implement a DataParser for our Nerfstudio data format.
|
||||
|
||||
```python
|
||||
@dataclass
|
||||
class NerfstudioDataParserConfig(DataParserConfig):
|
||||
"""Nerfstudio dataset config"""
|
||||
|
||||
_target: Type = field(default_factory=lambda: Nerfstudio)
|
||||
"""target class to instantiate"""
|
||||
data: Path = Path("data/nerfstudio/poster")
|
||||
"""Directory specifying location of data."""
|
||||
scale_factor: float = 1.0
|
||||
"""How much to scale the camera origins by."""
|
||||
downscale_factor: Optional[int] = None
|
||||
"""How much to downscale images. If not set, images are chosen such that the max dimension is <1600px."""
|
||||
scene_scale: float = 1.0
|
||||
"""How much to scale the region of interest by."""
|
||||
orientation_method: Literal["pca", "up", "vertical", "none"] = "up"
|
||||
"""The method to use for orientation."""
|
||||
center_method: Literal["poses", "focus", "none"] = "poses"
|
||||
"""The method to use to center the poses."""
|
||||
auto_scale_poses: bool = True
|
||||
"""Whether to automatically scale the poses to fit in +/- 1 bounding box."""
|
||||
train_split_fraction: float = 0.9
|
||||
"""The fraction of images to use for training. The remaining images are for eval."""
|
||||
depth_unit_scale_factor: float = 1e-3
|
||||
"""Scales the depth values to meters. Default value is 0.001 for a millimeter to meter conversion."""
|
||||
|
||||
@dataclass
|
||||
class Nerfstudio(DataParser):
|
||||
"""Nerfstudio DatasetParser"""
|
||||
|
||||
config: NerfstudioDataParserConfig
|
||||
|
||||
def _generate_dataparser_outputs(self, split="train"):
|
||||
meta = load_from_json(self.config.data / "transforms.json")
|
||||
image_filenames = []
|
||||
poses = []
|
||||
...
|
||||
dataparser_outputs = DataparserOutputs(
|
||||
image_filenames=image_filenames,
|
||||
cameras=cameras,
|
||||
scene_box=scene_box,
|
||||
)
|
||||
return dataparser_outputs
|
||||
```
|
||||
|
||||
## Train and Eval Logic
|
||||
|
||||
The DataParser will generate a train and eval DataparserOutputs depending on the `split` argument. For example, here is how you'd initialize some `InputDataset` classes that live in the DataManager. Because our DataparserOutputs maintain a common form, our Datasets should be plug-and-play. These datasets will load images needed to supervise the model with `RayGT` objects.
|
||||
|
||||
```python
|
||||
config = NerfstudioDataParserConfig()
|
||||
dataparser = config.setup()
|
||||
# train dataparser
|
||||
dataparser_outputs = dataparser.get_dataparser_outputs(split="train")
|
||||
input_dataset = InputDataset(dataparser_outputs)
|
||||
```
|
||||
|
||||
You can also pull out information from the DataParserOutputs for other DataManager components, such as the RayGenerator. The RayGenerator generates RayBundle objects from camera and pixel indices.
|
||||
|
||||
```python
|
||||
ray_generator = RayGenerator(dataparser_outputs.cameras)
|
||||
```
|
||||
|
||||
## Included DataParsers
|
||||
|
||||
```{toctree}
|
||||
---
|
||||
maxdepth: 2
|
||||
---
|
||||
|
||||
../../reference/api/data/dataparsers
|
||||
```
|
||||
@@ -0,0 +1,118 @@
|
||||
# Fields
|
||||
|
||||
```{image} imgs/pipeline_field-light.png
|
||||
:align: center
|
||||
:class: only-light
|
||||
:width: 600
|
||||
```
|
||||
|
||||
```{image} imgs/pipeline_field-dark.png
|
||||
:align: center
|
||||
:class: only-dark
|
||||
:width: 600
|
||||
```
|
||||
|
||||
## What is a Field?
|
||||
|
||||
A Field is a model component that associates a region of space with some sort of quantity. In the most typical case, the input to a field is a 3D location and viewing direction, and the output is density and color. Let's take a look at the code.
|
||||
|
||||
```python
|
||||
class Field(nn.Module):
|
||||
"""Base class for fields."""
|
||||
|
||||
@abstractmethod
|
||||
def get_density(self, ray_samples: RaySamples) -> Tuple[TensorType[..., 1], TensorType[..., "num_features"]]:
|
||||
"""Computes and returns the densities. Returns a tensor of densities and a tensor of features.
|
||||
|
||||
Args:
|
||||
ray_samples: Samples locations to compute density.
|
||||
"""
|
||||
|
||||
@abstractmethod
|
||||
def get_outputs(
|
||||
self, ray_samples: RaySamples, density_embedding: Optional[TensorType] = None
|
||||
) -> Dict[FieldHeadNames, TensorType]:
|
||||
"""Computes and returns the colors. Returns output field values.
|
||||
|
||||
Args:
|
||||
ray_samples: Samples locations to compute outputs.
|
||||
density_embedding: Density embeddings to condition on.
|
||||
"""
|
||||
|
||||
def forward(self, ray_samples: RaySamples):
|
||||
"""Evaluates the field at points along the ray.
|
||||
|
||||
Args:
|
||||
ray_samples: Samples to evaluate field on.
|
||||
"""
|
||||
density, density_embedding = self.get_density(ray_samples)
|
||||
field_outputs = self.get_outputs(ray_samples, density_embedding=density_embedding)
|
||||
|
||||
field_outputs[FieldHeadNames.DENSITY] = density # type: ignore
|
||||
return field_outputs
|
||||
```
|
||||
|
||||
## Separate density and outputs
|
||||
|
||||
The forward function is the main function you'll use, which takes in RaySamples returns quantities for each sample. You'll notice that the get_density function is called for every field, followed by the get_outputs function.
|
||||
|
||||
The get_outputs function is what you need to implement to return custom data. For example, check out of SemanticNerfField where we rely on different FieldHeads to produce correct dimensional outputs for typical quantities. Our implemented FieldHeads have the following FieldHeadNames names.
|
||||
|
||||
```python
|
||||
class FieldHeadNames(Enum):
|
||||
"""Possible field outputs"""
|
||||
|
||||
RGB = "rgb"
|
||||
SH = "sh"
|
||||
DENSITY = "density"
|
||||
UNCERTAINTY = "uncertainty"
|
||||
TRANSIENT_RGB = "transient_rgb"
|
||||
TRANSIENT_DENSITY = "transient_density"
|
||||
SEMANTICS = "semantics"
|
||||
```
|
||||
|
||||
```{button-link} https://github.com/nerfstudio-project/nerfstudio/blob/master/nerfstudio/field_components/field_heads.py
|
||||
:color: primary
|
||||
:outline:
|
||||
See the code!
|
||||
```
|
||||
|
||||
Sometimes all you need is the density from a Field, so we have a helper method called density_fn which takes positions and returns densities.
|
||||
|
||||
## Using Frustums instead of positions
|
||||
|
||||
Let's say you want to query a region of space, rather than a point. Our RaySamples data structure contains Frustums which can be used for exactly this purpose. This enables methods like Mip-NeRF to be implemented in our framework.
|
||||
|
||||
```python
|
||||
@dataclass
|
||||
class RaySamples(TensorDataclass):
|
||||
"""Samples along a ray"""
|
||||
|
||||
frustums: Frustums
|
||||
"""Frustums along ray."""
|
||||
...
|
||||
|
||||
@dataclass
|
||||
class Frustums(TensorDataclass):
|
||||
"""Describes region of space as a frustum."""
|
||||
|
||||
origins: TensorType["bs":..., 3]
|
||||
"""xyz coordinate for ray origin."""
|
||||
directions: TensorType["bs":..., 3]
|
||||
"""Direction of ray."""
|
||||
starts: TensorType["bs":..., 1]
|
||||
"""Where the frustum starts along a ray."""
|
||||
ends: TensorType["bs":..., 1]
|
||||
"""Where the frustum ends along a ray."""
|
||||
pixel_area: TensorType["bs":..., 1]
|
||||
"""Projected area of pixel a distance 1 away from origin."""
|
||||
...
|
||||
```
|
||||
|
||||
Take a look at our RaySamples class for more information on the input to our Field classes.
|
||||
|
||||
```{button-link} https://github.com/nerfstudio-project/nerfstudio/blob/master/nerfstudio/fields/base_field.py
|
||||
:color: primary
|
||||
:outline:
|
||||
See the code!
|
||||
```
|
||||
@@ -0,0 +1,49 @@
|
||||
Pipelines overview
|
||||
-------------------------
|
||||
|
||||
Here we describe what a Pipeline is and how it works. You can see an overview figure with the major Pipeline components below.
|
||||
|
||||
.. image:: imgs/pipeline_overview-light.png
|
||||
:width: 600
|
||||
:align: center
|
||||
:alt: pipeline figure
|
||||
:class: only-light
|
||||
|
||||
.. image:: imgs/pipeline_overview-dark.png
|
||||
:width: 600
|
||||
:align: center
|
||||
:alt: pipeline figure
|
||||
:class: only-dark
|
||||
|
||||
|
||||
.. admonition:: Note
|
||||
|
||||
RayGT and RayOutputs are currently dictionaries. In the future, they will be typed objects.
|
||||
|
||||
|
||||
Why Pipelines?
|
||||
==========================
|
||||
|
||||
Our goal is for any NeRF paper to be implemented as a Pipeline.
|
||||
|
||||
The Pipeline is composed of two major components, namely the DataManager and the Model. The DataManager is responsible for loading data and generating RayBundle and RayGT objects. RayBundles are the input to the forward pass of the Model. These are needed for both training and inference time. RayGT objects, however, are needed only during training to calculate the losses in the Loss Dict.
|
||||
|
||||
RayBundle objects describe origins and viewing directions. The model will take these rays and render them into quantities as RayOutputs. RayGT contains the necessary ground truth (GT) information needed to compute losses. For example, the GT pixel values can be used to supervise the rendered rays with an L2 loss.
|
||||
|
||||
In the following sections, we describe the Pipeline components and look at their code.
|
||||
|
||||
.. toctree::
|
||||
:maxdepth: 1
|
||||
|
||||
dataparsers
|
||||
datamanagers
|
||||
models
|
||||
fields
|
||||
pipelines
|
||||
|
||||
Implementing NeRF Papers
|
||||
==========================
|
||||
|
||||
Let's say you want to create a custom Pipeline that has a custom DataManager and a custom Model. Perhaps you care about dynamically adding cameras to the DataManager during training or you want to importance sample and generate rays from pixels where the loss is high. This can be accomplished by mixing and matching components into a Pipeline. The following guide will take you through an example of this.
|
||||
|
||||
This guide is coming soon!
|
||||
@@ -0,0 +1,152 @@
|
||||
# Models
|
||||
|
||||
```{image} imgs/pipeline_model-light.png
|
||||
:align: center
|
||||
:class: only-light
|
||||
:width: 600
|
||||
```
|
||||
|
||||
```{image} imgs/pipeline_model-dark.png
|
||||
:align: center
|
||||
:class: only-dark
|
||||
:width: 600
|
||||
```
|
||||
|
||||
## What is a Model?
|
||||
|
||||
A Model is probably what you think of when you think of a NeRF paper. Often the phrases "Model" and "Method" are used interchangeably and for this reason, our implemented [Methods](/nerfology/methods/index) typically only change the model code.
|
||||
|
||||
A model, at a high level, takes in regions of space described by RayBundle objects, samples points along these rays, and returns rendered values for each ray. So, let's take a look at what it takes to create your own model!
|
||||
|
||||
## Functions to Implement
|
||||
|
||||
[The code](https://github.com/nerfstudio-project/nerfstudio/blob/master/nerfstudio/models/base_model.py) is quite verbose, so here we distill the most important functions with succint descriptions.
|
||||
|
||||
```python
|
||||
class Model:
|
||||
|
||||
config: ModelConfig
|
||||
"""Set the model config so that Python gives you typed autocomplete!"""
|
||||
|
||||
def populate_modules(self):
|
||||
"""Set the fields and modules."""
|
||||
|
||||
# Fields
|
||||
|
||||
# Ray Samplers
|
||||
|
||||
# Colliders
|
||||
|
||||
# Renderers
|
||||
|
||||
# Losses
|
||||
|
||||
# Metrics
|
||||
|
||||
def get_param_groups(self) -> Dict[str, List[Parameter]]:
|
||||
"""Returns the parameter groups needed to optimizer your model components."""
|
||||
|
||||
def get_training_callbacks(
|
||||
self, training_callback_attributes: TrainingCallbackAttributes
|
||||
) -> List[TrainingCallback]:
|
||||
"""Returns the training callbacks, such as updating a density grid for Instant NGP."""
|
||||
|
||||
def get_outputs(self, ray_bundle: RayBundle):
|
||||
"""Process a RayBundle object and return RayOutputs describing quanties for each ray."""
|
||||
|
||||
def get_metrics_dict(self, outputs, batch):
|
||||
"""Returns metrics dictionary which will be plotted with comet, wandb or tensorboard."""
|
||||
|
||||
def get_loss_dict(self, outputs, batch, metrics_dict=None):
|
||||
"""Returns a dictionary of losses to be summed which will be your loss."""
|
||||
|
||||
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]]:
|
||||
"""Returns a dictionary of images and metrics to plot. Here you can apply your colormaps."""
|
||||
```
|
||||
|
||||
## Pythonic Configs with Models
|
||||
|
||||
Our config system is most useful when it comes to models. Let's take a look at our Nerfacto model config.
|
||||
|
||||
```python
|
||||
@dataclass
|
||||
class NerfactoModelConfig(ModelConfig):
|
||||
"""Nerfacto Model Config"""
|
||||
|
||||
_target: Type = field(default_factory=lambda: NerfactoModel)
|
||||
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["background", "last_sample"] = "last_sample"
|
||||
"""Whether to randomize the background color."""
|
||||
num_proposal_samples_per_ray: Tuple[int] = (64,)
|
||||
"""Number of samples per ray for the proposal network."""
|
||||
num_nerf_samples_per_ray: int = 64
|
||||
"""Number of samples per ray for the nerf network."""
|
||||
num_proposal_network_iterations: int = 1
|
||||
"""Number of proposal network iterations."""
|
||||
use_same_proposal_network: bool = False
|
||||
"""Use the same proposal network. Otherwise use different ones."""
|
||||
interlevel_loss_mult: float = 1.0
|
||||
"""Proposal loss multiplier."""
|
||||
distortion_loss_mult: float = 0.002
|
||||
"""Distortion loss multiplier."""
|
||||
use_proposal_weight_anneal: bool = True
|
||||
"""Whether to use proposal weight annealing."""
|
||||
use_average_appearance_embedding: bool = True
|
||||
"""Whether to use average appearance embedding or zeros for inference."""
|
||||
proposal_weights_anneal_slope: float = 10.0
|
||||
"""Slope of the annealing function for the proposal weights."""
|
||||
proposal_weights_anneal_max_num_iters: int = 1000
|
||||
"""Max num iterations for the annealing function."""
|
||||
use_single_jitter: bool = True
|
||||
"""Whether use single jitter or not for the proposal networks."""
|
||||
```
|
||||
|
||||
There are a lot of options! Thankfully, our config system makes this easy to handle. If you want to add another argument, you simply add a value to this config and when you type in `ns-train nerfacto --help`, it will show in the terminal as a value you can modify.
|
||||
|
||||
Furthermore, you have Python autocomplete and static checking working in your favor. At the top of every Model, we specify the config and then can easily pull of values throughout the implementation. Let's take a look at the beginning of the NerfactoModel implementation.
|
||||
|
||||
```python
|
||||
class NerfactoModel(Model):
|
||||
"""Nerfacto model
|
||||
|
||||
Args:
|
||||
config: Nerfacto configuration to instantiate model
|
||||
"""
|
||||
|
||||
config: NerfactoModelConfig
|
||||
|
||||
def populate_modules(self):
|
||||
"""Set the fields and modules."""
|
||||
...
|
||||
# Fields
|
||||
self.field = TCNNNerfactoField(
|
||||
self.scene_box.aabb,
|
||||
spatial_distortion=scene_contraction,
|
||||
num_images=self.num_train_data,
|
||||
use_average_appearance_embedding=self.config.use_average_appearance_embedding, # notice self.config
|
||||
)
|
||||
...
|
||||
# Renderers
|
||||
self.renderer_rgb = RGBRenderer(background_color=self.config.background_color) # notice self.config
|
||||
self.renderer_accumulation = AccumulationRenderer()
|
||||
self.renderer_depth = DepthRenderer()
|
||||
```
|
||||
|
||||
We invite you to take a look at the Nerfacto model and others to see how our models are formatted.
|
||||
|
||||
```{button-link} https://github.com/nerfstudio-project/nerfstudio/blob/master/nerfstudio/models/nerfacto.py
|
||||
:color: primary
|
||||
:outline:
|
||||
See the code!
|
||||
```
|
||||
|
||||
## Implementing a Model
|
||||
|
||||
Now that you understand how the model is structured, you can create a model by populating these functions. We provide a library of model components to pull from when creating your model. Check out those tutorials here!
|
||||
|
||||
One of these components is a Field, which you can learn more about in the next section. Fields associate a quantity of space with a value (e.g., density and color) and are used in every model.
|
||||
@@ -0,0 +1,73 @@
|
||||
# Pipelines
|
||||
|
||||
```{image} imgs/pipeline_pipeline-light.png
|
||||
:align: center
|
||||
:class: only-light
|
||||
:width: 600
|
||||
```
|
||||
|
||||
```{image} imgs/pipeline_pipeline-dark.png
|
||||
:align: center
|
||||
:class: only-dark
|
||||
:width: 600
|
||||
```
|
||||
|
||||
## What is a Pipeline?
|
||||
|
||||
The Pipeline contains all the code you need to implement a NeRF method. There are two main functions that you need to implement for the Pipeline.
|
||||
|
||||
```python
|
||||
class Pipeline(nn.Module):
|
||||
|
||||
datamanager: DataManager
|
||||
model: Model
|
||||
|
||||
@profiler.time_function
|
||||
def get_train_loss_dict(self, step: int):
|
||||
"""This function gets your training loss dict. This will be responsible for
|
||||
getting the next batch of data from the DataManager and interfacing with the
|
||||
Model class, feeding the data to the model's forward function.
|
||||
|
||||
Args:
|
||||
step: current iteration step to update sampler if using DDP (distributed)
|
||||
"""
|
||||
|
||||
@profiler.time_function
|
||||
def get_eval_loss_dict(self, step: int):
|
||||
"""This function gets your evaluation loss dict. It needs to get the data
|
||||
from the DataManager and feed it to the model's forward function
|
||||
|
||||
Args:
|
||||
step: current iteration step
|
||||
"""
|
||||
```
|
||||
|
||||
## Vanilla Implementation
|
||||
|
||||
Here you can see a simple implementation of the get_train_loss_dict from the VanillaPipeline. Essentially, all the pipeline has to do is route data from the DataManager to the Model.
|
||||
|
||||
```python
|
||||
@profiler.time_function
|
||||
def get_train_loss_dict(self, step: int):
|
||||
ray_bundle, batch = self.datamanager.next_train(step)
|
||||
model_outputs = self.model(ray_bundle)
|
||||
metrics_dict = self.model.get_metrics_dict(model_outputs, batch)
|
||||
loss_dict = self.model.get_loss_dict(model_outputs, batch, metrics_dict)
|
||||
return model_outputs, loss_dict, metrics_dict
|
||||
```
|
||||
|
||||
## Creating Custom Methods
|
||||
|
||||
:::{admonition} Note
|
||||
:class: info
|
||||
|
||||
The VanillaPipeline works for most of our methods.
|
||||
:::
|
||||
|
||||
We also have a DynamicBatchPipeline that is used with InstantNGP to dynamically choose the number of rays to use per training and evaluation iteration.
|
||||
|
||||
```{button-link} https://github.com/nerfstudio-project/nerfstudio/blob/master/nerfstudio/pipelines/dynamic_batch.py
|
||||
:color: primary
|
||||
:outline:
|
||||
See the code!
|
||||
```
|
||||
Reference in new issue
Block a user