From 03af0803ca9b781a13426590ceee1d56e00b2b5b Mon Sep 17 00:00:00 2001
From: Matthew Tancik
Date: Mon, 16 Jan 2023 11:24:16 -0800
Subject: [PATCH 01/28] zqm linting (#1233)
---
nerfstudio/viewer/server/server.py | 2 +-
nerfstudio/viewer/server/visualizer.py | 2 +-
2 files changed, 2 insertions(+), 2 deletions(-)
diff --git a/nerfstudio/viewer/server/server.py b/nerfstudio/viewer/server/server.py
index a8169513a..5c67f87fb 100644
--- a/nerfstudio/viewer/server/server.py
+++ b/nerfstudio/viewer/server/server.py
@@ -98,7 +98,7 @@ class ZMQWebSocketBridge:
websocket_port: websocket port to connect to. Defaults to None.
"""
- context = zmq.Context()
+ context = zmq.Context() # pylint: disable=abstract-class-instantiated
def __init__(self, zmq_port: int, websocket_port: int, ip_address: str):
self.zmq_port = zmq_port
diff --git a/nerfstudio/viewer/server/visualizer.py b/nerfstudio/viewer/server/visualizer.py
index d10185a86..a30500771 100644
--- a/nerfstudio/viewer/server/visualizer.py
+++ b/nerfstudio/viewer/server/visualizer.py
@@ -36,7 +36,7 @@ class ViewerWindow:
ip_address: The ip address of the bridge server.
"""
- context = zmq.Context()
+ context = zmq.Context() # pylint: disable=abstract-class-instantiated
def __init__(self, zmq_port, ip_address="127.0.0.1"):
self.zmq_port = zmq_port
From 53c23ba356700f5f3910fb54b371ac108539b771 Mon Sep 17 00:00:00 2001
From: Matthew Tancik
Date: Mon, 16 Jan 2023 12:00:44 -0800
Subject: [PATCH 02/28] Add mask conventions to docs (#1234)
---
docs/quickstart/data_conventions.md | 42 ++++++++++++++++++++++++++---
1 file changed, 39 insertions(+), 3 deletions(-)
diff --git a/docs/quickstart/data_conventions.md b/docs/quickstart/data_conventions.md
index 6cd959274..bf6463312 100644
--- a/docs/quickstart/data_conventions.md
+++ b/docs/quickstart/data_conventions.md
@@ -18,7 +18,7 @@ Our world space is oriented such that the up vector is +Z. The XY plane is paral
Our explanation here is for the nerfstudio data format. The `transforms.json` has a similar format to [Instant NGP](https://github.com/NVlabs/instant-ngp).
-**Camera intrinsics**
+### Camera intrinsics
At the top of the file, we specify the camera intrinsics. We assume that all the intrinsics parameters are the same for every camera in the dataset. The following is an example
@@ -43,7 +43,7 @@ At the top of the file, we specify the camera intrinsics. We assume that all the
The valid `camera_model` strings are currently "OPENCV" and "OPENCV_FISHEYE". "OPENCV" (i.e., perspective) uses k1-2 and p1-2. "OPENCV_FISHEYE" uses k1-4.
-**Camera extrinsics**
+### Camera extrinsics
For a transform matrix, the first 3 columns are the +X, +Y, and +Z defining the camera orientation, and the X, Y, Z values define the origin. The last row is to be compatible with homogeneous coordinates.
@@ -63,11 +63,47 @@ For a transform matrix, the first 3 columns are the +X, +Y, and +Z defining the
[0.0, 0.0, 1.0, 0.0],
[0.0, 0.0, 0.0, 1.0]
]
+ // Additional per-frame info
}
]
}
```
-**Depth images**
+### Depth images
To train with depth supervision, you can also provide a `depth_file_path` for each frame in your `transforms.json` and use one of the methods that support additional depth losses (e.g., depth-nerfacto). The depths are assumed to be 16-bit or 32-bit and to be in millimeters to remain consistent with [Polyform](https://github.com/PolyCam/polyform). You can adjust this scaling factor using the `depth_unit_scale_factor` parameter in `NerfstudioDataParserConfig`. Note that by default, we resize the depth images to match the shape of the RGB images.
+
+```json
+{
+ "frames": {
+ // ...
+ "depth_file_path": "depth/0001.png"
+ }
+}
+```
+
+### Masks
+
+:::{admonition} Warning
+:class: Warning
+
+The current implementation of masking is inefficient and will cause large memory allocations.
+:::
+
+There may be parts of the training image that should not be used during training (ie. moving objects such as people). These images can be masked out using an additional mask image that is specified in the `frame` data.
+
+```json
+{
+ "frames": {
+ // ...
+ "mask_path": "masks/mask.jpeg"
+ }
+}
+```
+
+The following mask requirements must be met:
+
+- Must be 1 channel with only black and white pixels
+- Must be the same resolution as the training image
+- Black corresponds to regions to ignore
+- If used, all images must have a mask
From 408ab709ec62c2d4981aa218e7a53ed534761919 Mon Sep 17 00:00:00 2001
From: matsuren
Date: Tue, 17 Jan 2023 05:12:55 +0900
Subject: [PATCH 03/28] Fix typo (#1231)
* Fix typo COLAMP->COLMAP
* Fix more typo
Co-authored-by: Matthew Tancik
---
docs/developer_guides/pipelines/datamanagers.md | 2 +-
docs/developer_guides/pipelines/dataparsers.md | 2 +-
docs/developer_guides/pipelines/fields.md | 2 +-
docs/nerfology/model_components/index.md | 2 +-
docs/quickstart/custom_dataset.md | 2 +-
docs/quickstart/export_geometry.md | 2 +-
docs/reference/contributing.md | 2 +-
nerfstudio/cameras/camera_optimizers.py | 2 +-
nerfstudio/cameras/camera_paths.py | 2 +-
nerfstudio/cameras/camera_utils.py | 2 +-
nerfstudio/cameras/cameras.py | 2 +-
nerfstudio/cameras/lie_groups.py | 4 ++--
nerfstudio/cameras/rays.py | 2 +-
nerfstudio/configs/base_config.py | 4 ++--
nerfstudio/data/datamanagers/base_datamanager.py | 6 +++---
.../data/dataparsers/nerfstudio_dataparser.py | 4 ++--
nerfstudio/data/dataparsers/nuscenes_dataparser.py | 4 ++--
nerfstudio/engine/callbacks.py | 2 +-
nerfstudio/engine/trainer.py | 2 +-
.../field_components/base_field_component.py | 2 +-
nerfstudio/field_components/encodings.py | 10 +++++-----
nerfstudio/field_components/field_heads.py | 2 +-
nerfstudio/fields/base_field.py | 2 +-
nerfstudio/fields/nerfw_field.py | 2 +-
nerfstudio/fields/semantic_nerf_field.py | 2 +-
nerfstudio/fields/vanilla_nerf_field.py | 2 +-
nerfstudio/model_components/losses.py | 4 ++--
nerfstudio/model_components/ray_generators.py | 4 ++--
nerfstudio/model_components/ray_samplers.py | 14 +++++++-------
nerfstudio/models/depth_nerfacto.py | 6 +++---
nerfstudio/models/nerfacto.py | 2 +-
nerfstudio/pipelines/base_pipeline.py | 4 ++--
nerfstudio/process_data/colmap_utils.py | 4 ++--
nerfstudio/process_data/insta360_utils.py | 8 ++++----
nerfstudio/process_data/metashape_utils.py | 2 +-
nerfstudio/process_data/process_data_utils.py | 2 +-
nerfstudio/utils/eval_utils.py | 2 +-
nerfstudio/utils/math.py | 2 +-
nerfstudio/utils/plotly_utils.py | 4 ++--
nerfstudio/utils/poses.py | 2 +-
nerfstudio/utils/writer.py | 2 +-
nerfstudio/viewer/server/path.py | 2 +-
nerfstudio/viewer/server/server.py | 2 +-
nerfstudio/viewer/server/utils.py | 4 ++--
scripts/docs/add_nb_tags.py | 2 +-
45 files changed, 72 insertions(+), 72 deletions(-)
diff --git a/docs/developer_guides/pipelines/datamanagers.md b/docs/developer_guides/pipelines/datamanagers.md
index eb361c209..bbe3413d9 100644
--- a/docs/developer_guides/pipelines/datamanagers.md
+++ b/docs/developer_guides/pipelines/datamanagers.md
@@ -34,7 +34,7 @@ class DataManager(nn.Module):
"""Returns the next eval image.
Returns:
- The image index from the eval datset, the CameraRayBundle, and the RayGT dictionary.
+ The image index from the eval dataset, the CameraRayBundle, and the RayGT dictionary.
"""
```
diff --git a/docs/developer_guides/pipelines/dataparsers.md b/docs/developer_guides/pipelines/dataparsers.md
index 458abdeb5..40ef7f4fd 100644
--- a/docs/developer_guides/pipelines/dataparsers.md
+++ b/docs/developer_guides/pipelines/dataparsers.md
@@ -103,7 +103,7 @@ dataparser_outputs = dataparser.get_dataparser_outputs(split="train")
input_dataset = InputDataset(dataparser_outputs)
```
-You can also pull out information from the DataParserOutputs for other DataMangager componenets, such as the RayGenerator. The RayGenerator generates RayBundle objects from camera and pixel indices.
+You can also pull out information from the DataParserOutputs for other DataMangager components, such as the RayGenerator. The RayGenerator generates RayBundle objects from camera and pixel indices.
```python
ray_generator = RayGenerator(dataparser_outputs.cameras)
diff --git a/docs/developer_guides/pipelines/fields.md b/docs/developer_guides/pipelines/fields.md
index f4c9c6d2e..5533db49b 100644
--- a/docs/developer_guides/pipelines/fields.md
+++ b/docs/developer_guides/pipelines/fields.md
@@ -56,7 +56,7 @@ class Field(nn.Module):
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 quantiites. Our implemented FieldHeads have the following FieldHeadNames names.
+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):
diff --git a/docs/nerfology/model_components/index.md b/docs/nerfology/model_components/index.md
index e3619d89e..513826edd 100644
--- a/docs/nerfology/model_components/index.md
+++ b/docs/nerfology/model_components/index.md
@@ -1,6 +1,6 @@
# Model components
-It can be difficult getting started with NeRFs. The reserach field is still quite new and most of the key nuggets are burried in academic papers. For this reason, we have consoladated many of the key concepts into a series of guides.
+It can be difficult getting started with NeRFs. The research field is still quite new and most of the key nuggets are buried in academic papers. For this reason, we have consolidated many of the key concepts into a series of guides.
```{toctree}
:maxdepth: 1
diff --git a/docs/quickstart/custom_dataset.md b/docs/quickstart/custom_dataset.md
index ea508a661..8192273e5 100644
--- a/docs/quickstart/custom_dataset.md
+++ b/docs/quickstart/custom_dataset.md
@@ -145,7 +145,7 @@ A LiDAR enabled iPhone or iPad is necessary.
:alt: polycam settings
```
-Devoloper settings must be enabled in Polycam. To do this, navigate to the settings screen and select `Developer mode`. Note that this will only apply for future captures, you will not be able to process existing captures with nerfstudio.
+Developer settings must be enabled in Polycam. To do this, navigate to the settings screen and select `Developer mode`. Note that this will only apply for future captures, you will not be able to process existing captures with nerfstudio.
### Process data
diff --git a/docs/quickstart/export_geometry.md b/docs/quickstart/export_geometry.md
index 0a50e8a0d..2b6323f35 100644
--- a/docs/quickstart/export_geometry.md
+++ b/docs/quickstart/export_geometry.md
@@ -42,7 +42,7 @@ ns-export pointcloud --help
## Other exporting methods
-Run the folowing command to see other export methods that may exist.
+Run the following command to see other export methods that may exist.
```python
ns-export --help
diff --git a/docs/reference/contributing.md b/docs/reference/contributing.md
index 45111c373..74c1c584e 100644
--- a/docs/reference/contributing.md
+++ b/docs/reference/contributing.md
@@ -93,7 +93,7 @@ sphinx-autobuild docs docs/_build/html
### Adding notebooks
-We support jupyter notbooks in our documentation. To improve the readability, the following custom tags can be added to the top of each code cell to hide or collapse the code.
+We support jupyter notebooks in our documentation. To improve the readability, the following custom tags can be added to the top of each code cell to hide or collapse the code.
| Tag | Effect |
| ------------- | ---------------------------------------------------- |
diff --git a/nerfstudio/cameras/camera_optimizers.py b/nerfstudio/cameras/camera_optimizers.py
index b8d846f02..20aaef3bc 100644
--- a/nerfstudio/cameras/camera_optimizers.py
+++ b/nerfstudio/cameras/camera_optimizers.py
@@ -104,7 +104,7 @@ class CameraOptimizer(nn.Module):
Args:
indices: indices of Cameras to optimize.
Returns:
- Tranformation matrices from optimized camera coordinates coordinates
+ Transformation matrices from optimized camera coordinates
to given camera coordinates.
"""
outputs = []
diff --git a/nerfstudio/cameras/camera_paths.py b/nerfstudio/cameras/camera_paths.py
index 475814f5d..61c489edf 100644
--- a/nerfstudio/cameras/camera_paths.py
+++ b/nerfstudio/cameras/camera_paths.py
@@ -54,7 +54,7 @@ def get_spiral_path(
zrate: float = 0.5,
) -> Cameras:
"""
- Returns a list of camera in a sprial trajectory.
+ Returns a list of camera in a spiral trajectory.
Args:
camera: The camera to start the spiral from.
diff --git a/nerfstudio/cameras/camera_utils.py b/nerfstudio/cameras/camera_utils.py
index ef7152dfb..bb6430717 100644
--- a/nerfstudio/cameras/camera_utils.py
+++ b/nerfstudio/cameras/camera_utils.py
@@ -361,7 +361,7 @@ def radial_and_tangential_undistort(
max_iterations: int = 10,
) -> torch.Tensor:
"""Computes undistorted coords given opencv distortion parameters.
- Addapted from MultiNeRF
+ Adapted from MultiNeRF
https://github.com/google-research/multinerf/blob/b02228160d3179300c7d499dca28cb9ca3677f32/internal/camera_utils.py#L477-L509
Args:
diff --git a/nerfstudio/cameras/cameras.py b/nerfstudio/cameras/cameras.py
index d56ac9a6f..68da40c82 100644
--- a/nerfstudio/cameras/cameras.py
+++ b/nerfstudio/cameras/cameras.py
@@ -338,7 +338,7 @@ class Cameras(TensorDataclass):
When coords == None (ie: when we render out the whole image associated with this camera), we run into problems
since there's no way to stack each coordinate map as all coordinate maps are all different shapes. In this case,
we will need to flatten each individual coordinate map and concatenate them, giving us only one batch dimension,
- regaurdless of the number of prepended extra batch dimensions in the camera_indices tensor.
+ regardless of the number of prepended extra batch dimensions in the camera_indices tensor.
Args:
diff --git a/nerfstudio/cameras/lie_groups.py b/nerfstudio/cameras/lie_groups.py
index 718eadad6..55f8d2b16 100644
--- a/nerfstudio/cameras/lie_groups.py
+++ b/nerfstudio/cameras/lie_groups.py
@@ -28,7 +28,7 @@ def exp_map_SO3xR3(tangent_vector: TensorType["b", 6]) -> TensorType["b", 3, 4]:
Args:
tangent_vector: Tangent vector; length-3 translations, followed by an `so(3)` tangent vector.
Returns:
- [R|t] tranformation matrices.
+ [R|t] transformation matrices.
"""
# code for SO3 map grabbed from pytorch3d and stripped down to bare-bones
log_rot = tangent_vector[:, 3:]
@@ -67,7 +67,7 @@ def exp_map_SE3(tangent_vector: TensorType["b", 6]) -> TensorType["b", 3, 4]: #
tangent_vector: A tangent vector from `se(3)`.
Returns:
- [R|t] tranformation matrices.
+ [R|t] transformation matrices.
"""
tangent_vector_lin = tangent_vector[:, :3].view(-1, 3, 1)
diff --git a/nerfstudio/cameras/rays.py b/nerfstudio/cameras/rays.py
index d9dbaba0b..e81e52642 100644
--- a/nerfstudio/cameras/rays.py
+++ b/nerfstudio/cameras/rays.py
@@ -186,7 +186,7 @@ class RayBundle(TensorDataclass):
return self[indices]
def get_row_major_sliced_ray_bundle(self, start_idx: int, end_idx: int) -> "RayBundle":
- """Flattens RayBundle and extracts chunk given start and end indicies.
+ """Flattens RayBundle and extracts chunk given start and end indices.
Args:
start_idx: Start index of RayBundle chunk.
diff --git a/nerfstudio/configs/base_config.py b/nerfstudio/configs/base_config.py
index 9131a50d5..548324069 100644
--- a/nerfstudio/configs/base_config.py
+++ b/nerfstudio/configs/base_config.py
@@ -63,7 +63,7 @@ class MachineConfig(PrintableConfig):
"""Configuration of machine setup"""
seed: int = 42
- """random seed initilization"""
+ """random seed initialization"""
num_gpus: int = 1
"""total number of gpus available for train/eval"""
num_machines: int = 1
@@ -113,7 +113,7 @@ class LoggingConfig(PrintableConfig):
"""number of steps between logging stats"""
max_buffer_size: int = 20
"""maximum history size to keep for computing running averages of stats.
- e.g. if 20, averages will be computed over past 20 occurances."""
+ e.g. if 20, averages will be computed over past 20 occurrences."""
local_writer: LocalWriterConfig = LocalWriterConfig(enable=True)
"""if provided, will print stats locally. if None, will disable printing"""
enable_profiler: bool = True
diff --git a/nerfstudio/data/datamanagers/base_datamanager.py b/nerfstudio/data/datamanagers/base_datamanager.py
index 26642a87c..4fc1822dd 100644
--- a/nerfstudio/data/datamanagers/base_datamanager.py
+++ b/nerfstudio/data/datamanagers/base_datamanager.py
@@ -94,7 +94,7 @@ class DataManager(nn.Module):
This data manager's next_train and next_eval methods will return 2 things:
1. A Raybundle: This will contain the rays we are sampling, with latents and
conditionals attached (everything needed at inference)
- 2. A "batch" of auxilury information: This will contain the mask, the ground truth
+ 2. A "batch" of auxiliary information: This will contain the mask, the ground truth
pixels, etc needed to actually train, score, etc the model
Rationale:
@@ -172,7 +172,7 @@ class DataManager(nn.Module):
def get_train_iterable(self, length=-1) -> IterableWrapper:
"""Gets a trivial pythonic iterator that will use the iter_train and next_train functions
- as __iter__ and __next__ methods respectivley.
+ as __iter__ and __next__ methods respectively.
This basically is just a little utility if you want to do something like:
| for ray_bundle, batch in datamanager.get_train_iterable():
@@ -184,7 +184,7 @@ class DataManager(nn.Module):
def get_eval_iterable(self, length=-1) -> IterableWrapper:
"""Gets a trivial pythonic iterator that will use the iter_eval and next_eval functions
- as __iter__ and __next__ methods respectivley.
+ as __iter__ and __next__ methods respectively.
This basically is just a little utility if you want to do something like:
| for ray_bundle, batch in datamanager.get_eval_iterable():
diff --git a/nerfstudio/data/dataparsers/nerfstudio_dataparser.py b/nerfstudio/data/dataparsers/nerfstudio_dataparser.py
index 07adab431..e419bdf2d 100644
--- a/nerfstudio/data/dataparsers/nerfstudio_dataparser.py
+++ b/nerfstudio/data/dataparsers/nerfstudio_dataparser.py
@@ -63,7 +63,7 @@ class NerfstudioDataParserConfig(DataParserConfig):
train_split_percentage: float = 0.9
"""The percent 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 millimiter to meter conversion."""
+ """Scales the depth values to meters. Default value is 0.001 for a millimeter to meter conversion."""
@dataclass
@@ -290,7 +290,7 @@ class Nerfstudio(DataParser):
def _get_fname(self, filepath: PurePath, data_dir: PurePath, downsample_folder_prefix="images_") -> Path:
"""Get the filename of the image file.
- downsample_folder_prefix can be used to point to auxillary image data, e.g. masks
+ downsample_folder_prefix can be used to point to auxiliary image data, e.g. masks
filepath: the base file name of the transformations.
data_dir: the directory of the data that contains the transform file
diff --git a/nerfstudio/data/dataparsers/nuscenes_dataparser.py b/nerfstudio/data/dataparsers/nuscenes_dataparser.py
index 7a274530d..9269f555f 100644
--- a/nerfstudio/data/dataparsers/nuscenes_dataparser.py
+++ b/nerfstudio/data/dataparsers/nuscenes_dataparser.py
@@ -47,8 +47,8 @@ def rotation_translation_to_pose(r_vec, t_vec):
class NuScenesDataParserConfig(DataParserConfig):
"""NuScenes dataset config.
NuScenes (https://www.nuscenes.org/nuscenes) is an autonomous driving dataset containing 1000 20s clips.
- Each clip was recorded with a suite of sensors including 6 souround cameras.
- It also includes 3D cuboid annotations around obects.
+ Each clip was recorded with a suite of sensors including 6 surround cameras.
+ It also includes 3D cuboid annotations around objects.
We optionally use these cuboids to mask dynamic objects by specifying the mask_dir flag.
To create these masks use scripts/datasets/process_nuscenes_masks.py.
"""
diff --git a/nerfstudio/engine/callbacks.py b/nerfstudio/engine/callbacks.py
index 25f73d8d2..3c7219d67 100644
--- a/nerfstudio/engine/callbacks.py
+++ b/nerfstudio/engine/callbacks.py
@@ -52,7 +52,7 @@ class TrainingCallback:
including at iteration 0. The function is called after the training iteration.
Args:
- where_to_run: List of locations for when to run callbak (before/after iteration)
+ where_to_run: List of locations for when to run callback (before/after iteration)
func: The function that will be called.
update_every_num_iters: How often to call the function `func`.
iters: Tuple of iteration steps to perform callback
diff --git a/nerfstudio/engine/trainer.py b/nerfstudio/engine/trainer.py
index 68c1182c8..30945a4c7 100644
--- a/nerfstudio/engine/trainer.py
+++ b/nerfstudio/engine/trainer.py
@@ -137,7 +137,7 @@ class Trainer:
Args:
test_mode:
'val': loads train/val datasets into memory
- 'test': loads train/test datset into memory
+ 'test': loads train/test datasets into memory
'inference': does not load any dataset into memory
"""
self.pipeline = self.config.pipeline.setup(
diff --git a/nerfstudio/field_components/base_field_component.py b/nerfstudio/field_components/base_field_component.py
index bea2b3085..88a2a00ad 100644
--- a/nerfstudio/field_components/base_field_component.py
+++ b/nerfstudio/field_components/base_field_component.py
@@ -27,7 +27,7 @@ class FieldComponent(nn.Module):
Args:
in_dim: Input dimension to module.
- out_dim: Ouput dimension to module.
+ out_dim: Output dimension to module.
"""
def __init__(self, in_dim: Optional[int] = None, out_dim: Optional[int] = None) -> None:
diff --git a/nerfstudio/field_components/encodings.py b/nerfstudio/field_components/encodings.py
index 942bfd89f..9cdd85e61 100644
--- a/nerfstudio/field_components/encodings.py
+++ b/nerfstudio/field_components/encodings.py
@@ -73,7 +73,7 @@ class Identity(Encoding):
class ScalingAndOffset(Encoding):
- """Simple scaling and offet to input
+ """Simple scaling and offset to input
Args:
in_dim: Input dimension of tensor
@@ -97,7 +97,7 @@ class ScalingAndOffset(Encoding):
class NeRFEncoding(Encoding):
- """Multi-scale sinousoidal encodings. Support ``integrated positional encodings`` if covariances are provided.
+ """Multi-scale sinusoidal encodings. Support ``integrated positional encodings`` if covariances are provided.
Each axis is encoded with frequencies ranging from 2^min_freq_exp to 2^max_freq_exp.
Args:
@@ -459,7 +459,7 @@ class TensorVMEncoding(Encoding):
@torch.no_grad()
def upsample_grid(self, resolution: int) -> None:
- """Upsamples underyling feature grid
+ """Upsamples underlying feature grid
Args:
resolution: Target resolution.
@@ -478,14 +478,14 @@ class SHEncoding(Encoding):
"""Spherical harmonic encoding
Args:
- levels: Number of spherical hamonic levels to encode.
+ levels: Number of spherical harmonic levels to encode.
"""
def __init__(self, levels: int = 4) -> None:
super().__init__(in_dim=3)
if levels <= 0 or levels > 4:
- raise ValueError(f"Spherical harmonic encoding only suports 1 to 4 levels, requested {levels}")
+ raise ValueError(f"Spherical harmonic encoding only supports 1 to 4 levels, requested {levels}")
self.levels = levels
diff --git a/nerfstudio/field_components/field_heads.py b/nerfstudio/field_components/field_heads.py
index 15b7822cb..cba0ee7ea 100644
--- a/nerfstudio/field_components/field_heads.py
+++ b/nerfstudio/field_components/field_heads.py
@@ -84,7 +84,7 @@ class FieldHead(FieldComponent):
Render head output
"""
if not self.net:
- raise SystemError("in_dim not set. Must be provided to construtor, or set_in_dim() should be called.")
+ raise SystemError("in_dim not set. Must be provided to constructor, or set_in_dim() should be called.")
out_tensor = self.net(in_tensor)
if self.activation:
out_tensor = self.activation(out_tensor)
diff --git a/nerfstudio/fields/base_field.py b/nerfstudio/fields/base_field.py
index c24d9659c..5bf49bf5e 100644
--- a/nerfstudio/fields/base_field.py
+++ b/nerfstudio/fields/base_field.py
@@ -41,7 +41,7 @@ class Field(nn.Module):
Args:
positions: the origin of the samples/frustums
"""
- # Need to figure out a better way to descibe positions with a ray.
+ # Need to figure out a better way to describe positions with a ray.
ray_samples = RaySamples(
frustums=Frustums(
origins=positions,
diff --git a/nerfstudio/fields/nerfw_field.py b/nerfstudio/fields/nerfw_field.py
index b2916fef4..483f5b502 100644
--- a/nerfstudio/fields/nerfw_field.py
+++ b/nerfstudio/fields/nerfw_field.py
@@ -44,7 +44,7 @@ class VanillaNerfWField(Field):
direction_encoding: Direction encoder.
base_mlp_num_layers: Number of layers for base MLP.
base_mlp_layer_width: Width of base MLP layers.
- head_mlp_num_layers: Number of layer for ourput head MLP.
+ head_mlp_num_layers: Number of layer for output head MLP.
head_mlp_layer_width: Width of output head MLP layers.
appearance_embedding_dim:: Dimension of appearance embedding.
transient_embedding_dim:: Dimension of transient embedding.
diff --git a/nerfstudio/fields/semantic_nerf_field.py b/nerfstudio/fields/semantic_nerf_field.py
index fa53a9313..11fdb142a 100644
--- a/nerfstudio/fields/semantic_nerf_field.py
+++ b/nerfstudio/fields/semantic_nerf_field.py
@@ -42,7 +42,7 @@ class SemanticNerfField(Field):
direction_encoding: Direction encoder.
base_mlp_num_layers: Number of layers for base MLP.
base_mlp_layer_width: Width of base MLP layers.
- head_mlp_num_layers: Number of layer for ourput head MLP.
+ head_mlp_num_layers: Number of layer for output head MLP.
head_mlp_layer_width: Width of output head MLP layers.
skip_connections: Where to add skip connection in base MLP.
"""
diff --git a/nerfstudio/fields/vanilla_nerf_field.py b/nerfstudio/fields/vanilla_nerf_field.py
index a30582d14..45511c1d1 100644
--- a/nerfstudio/fields/vanilla_nerf_field.py
+++ b/nerfstudio/fields/vanilla_nerf_field.py
@@ -42,7 +42,7 @@ class NeRFField(Field):
direction_encoding: Direction encoder.
base_mlp_num_layers: Number of layers for base MLP.
base_mlp_layer_width: Width of base MLP layers.
- head_mlp_num_layers: Number of layer for ourput head MLP.
+ head_mlp_num_layers: Number of layer for output head MLP.
head_mlp_layer_width: Width of output head MLP layers.
skip_connections: Where to add skip connection in base MLP.
use_integrated_encoding: Used integrated samples as encoding input.
diff --git a/nerfstudio/model_components/losses.py b/nerfstudio/model_components/losses.py
index 983bee555..9624ad02d 100644
--- a/nerfstudio/model_components/losses.py
+++ b/nerfstudio/model_components/losses.py
@@ -86,7 +86,7 @@ def lossfun_outer(
Args:
t: interval edges
w: weights
- t_env: interval edges of the upper bound enveloping historgram
+ t_env: interval edges of the upper bound enveloping histogram
w_env: weights that should upper bound the inner (t,w) histogram
"""
w_outer = outer(t[..., :-1], t[..., 1:], t_env[..., :-1], t_env[..., 1:], w_env)
@@ -284,7 +284,7 @@ def depth_loss(
predicted_depth: Depth prediction from the network.
sigma: Uncertainty around depth value.
directions_norm: Norms of ray direction vectors in the camera frame.
- is_euclidean: Whether ground truth depths correponds to normalized direction vectors.
+ is_euclidean: Whether ground truth depths corresponds to normalized direction vectors.
depth_loss_type: Type of depth loss to apply.
Returns:
diff --git a/nerfstudio/model_components/ray_generators.py b/nerfstudio/model_components/ray_generators.py
index a740f8141..87a30cf67 100644
--- a/nerfstudio/model_components/ray_generators.py
+++ b/nerfstudio/model_components/ray_generators.py
@@ -29,7 +29,7 @@ class RayGenerator(nn.Module):
Args:
cameras: Camera objects containing camera info.
- pose_optimizer: pose optimization module, for optimizing noisy camera intrisics/extrinsics.
+ pose_optimizer: pose optimization module, for optimizing noisy camera intrinsics/extrinsics.
"""
def __init__(self, cameras: Cameras, pose_optimizer: CameraOptimizer) -> None:
@@ -42,7 +42,7 @@ class RayGenerator(nn.Module):
"""Index into the cameras to generate the rays.
Args:
- ray_indices: Contains camera, row, and col indicies for target rays.
+ ray_indices: Contains camera, row, and col indices for target rays.
"""
c = ray_indices[:, 0] # camera indices
y = ray_indices[:, 1] # row indices
diff --git a/nerfstudio/model_components/ray_samplers.py b/nerfstudio/model_components/ray_samplers.py
index 89a238c72..eef905101 100644
--- a/nerfstudio/model_components/ray_samplers.py
+++ b/nerfstudio/model_components/ray_samplers.py
@@ -58,7 +58,7 @@ class SpacedSampler(Sampler):
num_samples: Number of samples per ray
spacing_fn: Function that dictates sample spacing (ie `lambda x : x` is uniform).
spacing_fn_inv: The inverse of spacing_fn.
- train_stratified: Use stratified sampling during training. Defults to True
+ train_stratified: Use stratified sampling during training. Defaults to True
single_jitter: Use a same random jitter for all samples along a ray. Defaults to False
"""
@@ -81,7 +81,7 @@ class SpacedSampler(Sampler):
ray_bundle: Optional[RayBundle] = None,
num_samples: Optional[int] = None,
) -> RaySamples:
- """Generates position samples accoring to spacing function.
+ """Generates position samples according to spacing function.
Args:
ray_bundle: Rays to generate samples for
@@ -131,7 +131,7 @@ class UniformSampler(SpacedSampler):
Args:
num_samples: Number of samples per ray
- train_stratified: Use stratified sampling during training. Defults to True
+ train_stratified: Use stratified sampling during training. Defaults to True
single_jitter: Use a same random jitter for all samples along a ray. Defaults to False
"""
@@ -155,7 +155,7 @@ class LinearDisparitySampler(SpacedSampler):
Args:
num_samples: Number of samples per ray
- train_stratified: Use stratified sampling during training. Defults to True
+ train_stratified: Use stratified sampling during training. Defaults to True
single_jitter: Use a same random jitter for all samples along a ray. Defaults to False
"""
@@ -179,7 +179,7 @@ class SqrtSampler(SpacedSampler):
Args:
num_samples: Number of samples per ray
- train_stratified: Use stratified sampling during training. Defults to True
+ train_stratified: Use stratified sampling during training. Defaults to True
"""
def __init__(
@@ -202,7 +202,7 @@ class LogSampler(SpacedSampler):
Args:
num_samples: Number of samples per ray
- train_stratified: Use stratified sampling during training. Defults to True
+ train_stratified: Use stratified sampling during training. Defaults to True
"""
def __init__(
@@ -227,7 +227,7 @@ class UniformLinDispPiecewiseSampler(SpacedSampler):
Args:
num_samples: Number of samples per ray
- train_stratified: Use stratified sampling during training. Defults to True
+ train_stratified: Use stratified sampling during training. Defaults to True
single_jitter: Use a same random jitter for all samples along a ray. Defaults to False
"""
diff --git a/nerfstudio/models/depth_nerfacto.py b/nerfstudio/models/depth_nerfacto.py
index 727173b7d..da4c59002 100644
--- a/nerfstudio/models/depth_nerfacto.py
+++ b/nerfstudio/models/depth_nerfacto.py
@@ -13,7 +13,7 @@
# limitations under the License.
"""
-Nerfacto augumented with depth supervision.
+Nerfacto augmented with depth supervision.
"""
from __future__ import annotations
@@ -45,13 +45,13 @@ class DepthNerfactoModelConfig(NerfactoModelConfig):
starting_depth_sigma: float = 0.2
"""Starting uncertainty around depth values in meters (defaults to 0.2m)."""
sigma_decay_rate: float = 0.99985
- """Rate of exponetial decay."""
+ """Rate of exponential decay."""
depth_loss_type: DephtLossType = DephtLossType.DS_NERF
"""Depth loss type."""
class DepthNerfactoModel(NerfactoModel):
- """Depth loss augumented nerfacto model.
+ """Depth loss augmented nerfacto model.
Args:
config: Nerfacto configuration to instantiate model
diff --git a/nerfstudio/models/nerfacto.py b/nerfstudio/models/nerfacto.py
index 4e619ad21..42ea0f50a 100644
--- a/nerfstudio/models/nerfacto.py
+++ b/nerfstudio/models/nerfacto.py
@@ -99,7 +99,7 @@ class NerfactoModelConfig(ModelConfig):
distortion_loss_mult: float = 0.002
"""Distortion loss multiplier."""
orientation_loss_mult: float = 0.0001
- """Orientation loss multipier on computed noramls."""
+ """Orientation loss multiplier on computed normals."""
pred_normal_loss_mult: float = 0.001
"""Predicted normal loss multiplier."""
use_proposal_weight_anneal: bool = True
diff --git a/nerfstudio/pipelines/base_pipeline.py b/nerfstudio/pipelines/base_pipeline.py
index d45cda16c..9dc50fa27 100644
--- a/nerfstudio/pipelines/base_pipeline.py
+++ b/nerfstudio/pipelines/base_pipeline.py
@@ -80,7 +80,7 @@ class Pipeline(nn.Module):
device: location to place model and data
test_mode:
'train': loads train/eval datasets into memory
- 'test': loads train/test datset into memory
+ 'test': loads train/test dataset into memory
'inference': does not load any dataset into memory
world_size: total number of machines available
local_rank: rank of current machine
@@ -197,7 +197,7 @@ class VanillaPipeline(Pipeline):
device: location to place model and data
test_mode:
'val': loads train/val datasets into memory
- 'test': loads train/test datset into memory
+ 'test': loads train/test dataset into memory
'inference': does not load any dataset into memory
world_size: total number of machines available
local_rank: rank of current machine
diff --git a/nerfstudio/process_data/colmap_utils.py b/nerfstudio/process_data/colmap_utils.py
index c36cc7d5f..b8e91bd29 100644
--- a/nerfstudio/process_data/colmap_utils.py
+++ b/nerfstudio/process_data/colmap_utils.py
@@ -364,7 +364,7 @@ def detect_model_format(path: Path, ext: str) -> bool:
path: Path to the model file.
ext: Extension to test.
Returns:
- True if the model file is the tested extenstion, False otherwise.
+ True if the model file is the tested extension, False otherwise.
"""
if (
@@ -663,7 +663,7 @@ def get_matching_summary(num_intial_frames: int, num_matched_frames: int) -> str
"""
match_ratio = num_matched_frames / num_intial_frames
if match_ratio == 1:
- return "[bold green]COLAMP found poses for all images, CONGRATS!"
+ return "[bold green]COLMAP found poses for all images, CONGRATS!"
if match_ratio < 0.4:
result = f"[bold red]COLMAP only found poses for {num_matched_frames / num_intial_frames * 100:.2f}%"
result += " of the images. This is low.\nThis can be caused by a variety of reasons,"
diff --git a/nerfstudio/process_data/insta360_utils.py b/nerfstudio/process_data/insta360_utils.py
index 4babc1504..febdc7308 100644
--- a/nerfstudio/process_data/insta360_utils.py
+++ b/nerfstudio/process_data/insta360_utils.py
@@ -66,7 +66,7 @@ def convert_insta360_to_images(
video_back: Path to the back video.
output_dir: Path to the output directory.
num_frames_target: Number of frames to extract.
- crop_percentage: Percentage used to calculate the cropped dimentions of extracted frames. Currently used to crop
+ crop_percentage: Percentage used to calculate the cropped dimensions of extracted frames. Currently used to crop
out the curved portions of the fish-eye lens.
verbose: If True, logs the output of the command.
Returns:
@@ -94,7 +94,7 @@ def convert_insta360_to_images(
if spacing > 1:
vf_cmds = [f"thumbnail={spacing}", "setpts=N/TB"]
else:
- CONSOLE.print("[bold red]Can't satify requested number of frames. Extracting all frames.")
+ CONSOLE.print("[bold red]Can't satisfy requested number of frames. Extracting all frames.")
vf_cmds.append(f"crop=iw*{crop_percentage}:ih*{crop_percentage}")
@@ -135,7 +135,7 @@ def convert_insta360_single_file_to_images(
video: Path to the video.
output_dir: Path to the output directory.
num_frames_target: Number of frames to extract.
- crop_percentage: Percentage used to calculate the cropped dimentions of extracted frames. Currently used to crop
+ crop_percentage: Percentage used to calculate the cropped dimensions of extracted frames. Currently used to crop
out the curved portions of the fish-eye lens.
verbose: If True, logs the output of the command.
Returns:
@@ -159,7 +159,7 @@ def convert_insta360_single_file_to_images(
if spacing > 1:
vf_cmds = [f"thumbnail={spacing}", "setpts=N/TB"]
else:
- CONSOLE.print("[bold red]Can't satify requested number of frames. Extracting all frames.")
+ CONSOLE.print("[bold red]Can't satisfy requested number of frames. Extracting all frames.")
vf_cmds_back = vf_cmds.copy()
vf_cmds_front = vf_cmds.copy()
diff --git a/nerfstudio/process_data/metashape_utils.py b/nerfstudio/process_data/metashape_utils.py
index 4b5e60ba5..491c06a2c 100644
--- a/nerfstudio/process_data/metashape_utils.py
+++ b/nerfstudio/process_data/metashape_utils.py
@@ -44,7 +44,7 @@ def metashape_to_json( # pylint: disable=too-many-statements
Args:
image_filename_map: Mapping of original image filenames to their saved locations.
- xml_filename: Path to the metashap cameras xml file.
+ xml_filename: Path to the metashape cameras xml file.
output_dir: Path to the output directory.
verbose: Whether to print verbose output.
diff --git a/nerfstudio/process_data/process_data_utils.py b/nerfstudio/process_data/process_data_utils.py
index 907a0af98..b03dcd8cb 100644
--- a/nerfstudio/process_data/process_data_utils.py
+++ b/nerfstudio/process_data/process_data_utils.py
@@ -93,7 +93,7 @@ def convert_video_to_images(
if spacing > 1:
ffmpeg_cmd += f" -vf thumbnail={spacing},setpts=N/TB -r 1"
else:
- CONSOLE.print("[bold red]Can't satify requested number of frames. Extracting all frames.")
+ CONSOLE.print("[bold red]Can't satisfy requested number of frames. Extracting all frames.")
ffmpeg_cmd += " -pix_fmt bgr8"
ffmpeg_cmd += f" {out_filename}"
diff --git a/nerfstudio/utils/eval_utils.py b/nerfstudio/utils/eval_utils.py
index 40f9e212e..17b0d4b06 100644
--- a/nerfstudio/utils/eval_utils.py
+++ b/nerfstudio/utils/eval_utils.py
@@ -76,7 +76,7 @@ def eval_setup(
eval_num_rays_per_chunk: Number of rays per forward pass
test_mode:
'val': loads train/val datasets into memory
- 'test': loads train/test datset into memory
+ 'test': loads train/test dataset into memory
'inference': does not load any dataset into memory
diff --git a/nerfstudio/utils/math.py b/nerfstudio/utils/math.py
index d5ed57f94..bca98ee83 100644
--- a/nerfstudio/utils/math.py
+++ b/nerfstudio/utils/math.py
@@ -26,7 +26,7 @@ def components_from_spherical_harmonics(levels: int, directions: TensorType[...,
Args:
levels: Number of spherical harmonic levels to compute.
- directions: Spherical hamonic coefficients
+ directions: Spherical harmonic coefficients
"""
num_components = levels**2
components = torch.zeros((*directions.shape[:-1], num_components), device=directions.device)
diff --git a/nerfstudio/utils/plotly_utils.py b/nerfstudio/utils/plotly_utils.py
index a06476f88..03eb4bcf3 100644
--- a/nerfstudio/utils/plotly_utils.py
+++ b/nerfstudio/utils/plotly_utils.py
@@ -266,7 +266,7 @@ def get_gaussian_ellipsiod(
Args:
mean: mean of the Gaussian.
cov: covariance of the Gaussian.
- n_std: Standard devation to visualize. Defaults to 2 (95% confidence).
+ n_std: Standard deviation to visualize. Defaults to 2 (95% confidence).
color: Color of the ellipsoid. Defaults to None.
opacity: Opacity of the ellipsoid. Defaults to 0.5.
resolution: Resolution of the ellipsoid. Defaults to 20.
@@ -437,7 +437,7 @@ def get_frustum_points(
Args:
frustum: Frustums to visualize.
opacity: Opacity of the points. Defaults to 0.3.
- color: Color of the poinst. Defaults to "forestgreen".
+ color: Color of the points. Defaults to "forestgreen".
size: Size of points. Defaults to 10.
Returns:
diff --git a/nerfstudio/utils/poses.py b/nerfstudio/utils/poses.py
index b5944e8ae..2cf0925f9 100644
--- a/nerfstudio/utils/poses.py
+++ b/nerfstudio/utils/poses.py
@@ -55,7 +55,7 @@ def multiply(pose_a: TensorType[..., 3, 4], pose_b: TensorType[..., 3, 4]) -> Te
Args:
pose_a: Left pose matrix, usually a transformation applied to the right.
- pose_b: Right pose matrix, usually a camera pose that will be tranformed by pose_a.
+ pose_b: Right pose matrix, usually a camera pose that will be transformed by pose_a.
Returns:
Camera pose matrix where pose_a was applied to pose_b.
diff --git a/nerfstudio/utils/writer.py b/nerfstudio/utils/writer.py
index d90e13b92..720d1d449 100644
--- a/nerfstudio/utils/writer.py
+++ b/nerfstudio/utils/writer.py
@@ -361,7 +361,7 @@ class LocalWriter:
TODO: migrate to prettyprint
Args:
- config: configuration to instatiate class
+ config: configuration to instantiate class
banner_messages: list of messages to always display at bottom of screen
"""
diff --git a/nerfstudio/viewer/server/path.py b/nerfstudio/viewer/server/path.py
index 2054862c4..65fb26e1b 100644
--- a/nerfstudio/viewer/server/path.py
+++ b/nerfstudio/viewer/server/path.py
@@ -34,7 +34,7 @@ class Path:
self.entries = entries
def append(self, other: str) -> "Path":
- """Methodthat appends a new component and returns new Path
+ """Method that appends a new component and returns new Path
Args:
other: _description_
diff --git a/nerfstudio/viewer/server/server.py b/nerfstudio/viewer/server/server.py
index 5c67f87fb..6c2c45476 100644
--- a/nerfstudio/viewer/server/server.py
+++ b/nerfstudio/viewer/server/server.py
@@ -12,7 +12,7 @@
# See the License for the specific language governing permissions and
# limitations under the License.
-"""Server bridge to faciliate interactions between python backend and javascript front end"""
+"""Server bridge to facilitate interactions between python backend and javascript front end"""
import sys
from typing import List, Optional, Tuple
diff --git a/nerfstudio/viewer/server/utils.py b/nerfstudio/viewer/server/utils.py
index 9c3e003ec..b0763b6d1 100644
--- a/nerfstudio/viewer/server/utils.py
+++ b/nerfstudio/viewer/server/utils.py
@@ -28,7 +28,7 @@ from aiortc.rtcrtpsender import RTCRtpSender
def get_chunks(
lst: List[float], num_chunks: Optional[int] = None, size_of_chunk: Optional[int] = None
) -> List[List[float]]:
- """Returns list of n elements, constaining a sublist.
+ """Returns list of n elements, containing a sublist.
Args:
lst: List to be chunked up
@@ -129,7 +129,7 @@ def find_available_port(func: Callable, default_port: int, max_attempts: int = 1
def force_codec(pc: RTCPeerConnection, sender: RTCRtpSender, forced_codec: str) -> None:
- """Sets the codec preferences on a connection between sender and reciever
+ """Sets the codec preferences on a connection between sender and receiver
Args:
pc: peer connection point
diff --git a/scripts/docs/add_nb_tags.py b/scripts/docs/add_nb_tags.py
index 37a5900f8..4a7d97fe0 100755
--- a/scripts/docs/add_nb_tags.py
+++ b/scripts/docs/add_nb_tags.py
@@ -13,7 +13,7 @@ CONSOLE = Console(width=120)
def main(check: bool = False):
"""Add tags to notebooks based on cell comments.
- In notebook cells, you can add the folling tags to the notebook by adding a comment:
+ In notebook cells, you can add the following tags to the notebook by adding a comment:
"# HIDDEN" - This cell will be hidden from the notebook.
"# OUTPUT_ONLY" - This cell will only show the output.
"# COLLAPSED" - Hide the code and include a button to show the code.
From e575f128d7ea05def3a5ed41e3165878b28ed0a1 Mon Sep 17 00:00:00 2001
From: JamesPerlman
Date: Mon, 16 Jan 2023 12:42:22 -0800
Subject: [PATCH 04/28] Update incorrect comment (#1226)
---
nerfstudio/models/instant_ngp.py | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/nerfstudio/models/instant_ngp.py b/nerfstudio/models/instant_ngp.py
index 0e9a6392d..736cd0870 100644
--- a/nerfstudio/models/instant_ngp.py
+++ b/nerfstudio/models/instant_ngp.py
@@ -66,7 +66,7 @@ class InstantNGPModelConfig(ModelConfig):
grid_resolution: int = 128
"""Resolution of the grid used for the field."""
contraction_type: ContractionType = ContractionType.UN_BOUNDED_SPHERE
- """Resolution of the grid used for the field."""
+ """Contraction type used for spatial deformation of the field."""
cone_angle: float = 0.004
"""Should be set to 0.0 for blender scenes but 1./256 for real scenes."""
render_step_size: float = 0.01
From f0b4f5b35e5616a2d807e7b640623af5c05bb1ae Mon Sep 17 00:00:00 2001
From: Mason McGough
Date: Mon, 16 Jan 2023 17:56:13 -0500
Subject: [PATCH 05/28] Update Quickstart instructions to remove '--dataset'
(#1222) (#1230)
Update quickstart instructions to remove '--dataset' (#1222)
Co-authored-by: Matthew Tancik
---
README.md | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/README.md b/README.md
index c4f346993..0ec27e431 100644
--- a/README.md
+++ b/README.md
@@ -129,7 +129,7 @@ The following will train a _nerfacto_ model, our recommended model for real worl
```bash
# Download some test data:
-ns-download-data --dataset nerfstudio --capture-name=poster
+ns-download-data nerfstudio --capture-name=poster
# Train model
ns-train nerfacto --data data/nerfstudio/poster
```
From 23ca7a7cc832f1cffa14f1d6842860579df3ecae Mon Sep 17 00:00:00 2001
From: Matthew Tancik
Date: Mon, 16 Jan 2023 15:12:59 -0800
Subject: [PATCH 06/28] Non-strict loading of checkpoints (#1235)
---
nerfstudio/pipelines/base_pipeline.py | 8 +-------
1 file changed, 1 insertion(+), 7 deletions(-)
diff --git a/nerfstudio/pipelines/base_pipeline.py b/nerfstudio/pipelines/base_pipeline.py
index 9dc50fa27..343cf5104 100644
--- a/nerfstudio/pipelines/base_pipeline.py
+++ b/nerfstudio/pipelines/base_pipeline.py
@@ -359,13 +359,7 @@ class VanillaPipeline(Pipeline):
loaded_state: pre-trained model state dict
"""
state = {key.replace("module.", ""): value for key, value in loaded_state.items()}
- if self.test_mode == "inference":
- state.pop("datamanager.train_camera_optimizer.pose_adjustment", None)
- state.pop("datamanager.train_ray_generator.image_coords", None)
- state.pop("datamanager.train_ray_generator.pose_optimizer.pose_adjustment", None)
- state.pop("datamanager.eval_ray_generator.image_coords", None)
- state.pop("datamanager.eval_ray_generator.pose_optimizer.pose_adjustment", None)
- self.load_state_dict(state) # type: ignore
+ self.load_state_dict(state, strict=False)
def get_training_callbacks(
self, training_callback_attributes: TrainingCallbackAttributes
From bd1060ee83acf9c9ebd9b39197badbd9af9466df Mon Sep 17 00:00:00 2001
From: hturki
Date: Mon, 16 Jan 2023 18:21:44 -0500
Subject: [PATCH 07/28] save image_coords as non-persistent buffer (#1216)
Co-authored-by: Matthew Tancik
---
nerfstudio/model_components/ray_generators.py | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/nerfstudio/model_components/ray_generators.py b/nerfstudio/model_components/ray_generators.py
index 87a30cf67..a894da854 100644
--- a/nerfstudio/model_components/ray_generators.py
+++ b/nerfstudio/model_components/ray_generators.py
@@ -36,7 +36,7 @@ class RayGenerator(nn.Module):
super().__init__()
self.cameras = cameras
self.pose_optimizer = pose_optimizer
- self.image_coords = nn.Parameter(cameras.get_image_coords(), requires_grad=False)
+ self.register_buffer("image_coords", cameras.get_image_coords(), persistent=False)
def forward(self, ray_indices: TensorType["num_rays", 3]) -> RayBundle:
"""Index into the cameras to generate the rays.
From 5b50740f45f573dc9a259252370bd2d3c850de8a Mon Sep 17 00:00:00 2001
From: Matthew Tancik
Date: Mon, 16 Jan 2023 15:34:20 -0800
Subject: [PATCH 08/28] Add cropping options to data processing (#1236)
---
nerfstudio/data/datasets/base_dataset.py | 3 +
nerfstudio/data/utils/data_utils.py | 2 +
nerfstudio/process_data/colmap_utils.py | 17 ++-
nerfstudio/process_data/process_data_utils.py | 114 ++++++++++++++++++
scripts/process_data.py | 26 +++-
5 files changed, 159 insertions(+), 3 deletions(-)
diff --git a/nerfstudio/data/datasets/base_dataset.py b/nerfstudio/data/datasets/base_dataset.py
index c01d26739..45aa188ef 100644
--- a/nerfstudio/data/datasets/base_dataset.py
+++ b/nerfstudio/data/datasets/base_dataset.py
@@ -99,6 +99,9 @@ class InputDataset(Dataset):
if self.has_masks:
mask_filepath = self._dataparser_outputs.mask_filenames[image_idx]
data["mask"] = get_image_mask_tensor_from_path(filepath=mask_filepath, scale_factor=self.scale_factor)
+ assert (
+ data["mask"].shape[:2] == data["image"].shape[:2]
+ ), f"Mask and image have different shapes. Got {data['mask'].shape[:2]} and {data['image'].shape[:2]}"
metadata = self.get_metadata(data)
data.update(metadata)
return data
diff --git a/nerfstudio/data/utils/data_utils.py b/nerfstudio/data/utils/data_utils.py
index 22a3438dd..c4b21febd 100644
--- a/nerfstudio/data/utils/data_utils.py
+++ b/nerfstudio/data/utils/data_utils.py
@@ -32,6 +32,8 @@ def get_image_mask_tensor_from_path(filepath: Path, scale_factor: float = 1.0) -
newsize = (int(width * scale_factor), int(height * scale_factor))
pil_mask = pil_mask.resize(newsize, resample=Image.NEAREST)
mask_tensor = torch.from_numpy(np.array(pil_mask)).unsqueeze(-1).bool()
+ if len(mask_tensor.shape) != 3:
+ raise ValueError("The mask image should have 1 channel")
return mask_tensor
diff --git a/nerfstudio/process_data/colmap_utils.py b/nerfstudio/process_data/colmap_utils.py
index b8e91bd29..9db20647f 100644
--- a/nerfstudio/process_data/colmap_utils.py
+++ b/nerfstudio/process_data/colmap_utils.py
@@ -492,6 +492,7 @@ def run_colmap(
image_dir: Path,
colmap_dir: Path,
camera_model: CameraModel,
+ camera_mask_path: Optional[Path] = None,
gpu: bool = True,
verbose: bool = False,
matching_method: Literal["vocab_tree", "exhaustive", "sequential"] = "vocab_tree",
@@ -503,8 +504,11 @@ def run_colmap(
image_dir: Path to the directory containing the images.
colmap_dir: Path to the output directory.
camera_model: Camera model to use.
+ camera_mask_path: Path to the camera mask.
gpu: If True, use GPU.
verbose: If True, logs the output of the command.
+ matching_method: Matching method to use.
+ colmap_cmd: Path to the COLMAP executable.
"""
colmap_version = get_colmap_version(colmap_cmd)
@@ -523,6 +527,8 @@ def run_colmap(
f"--ImageReader.camera_model {camera_model.value}",
f"--SiftExtraction.use_gpu {int(gpu)}",
]
+ if camera_mask_path is not None:
+ feature_extractor_cmd.append(f"--ImageReader.camera_mask_path {camera_mask_path}")
feature_extractor_cmd = " ".join(feature_extractor_cmd)
with status(msg="[bold yellow]Running COLMAP feature extractor...", spinner="moon", verbose=verbose):
run_command(feature_extractor_cmd, verbose=verbose)
@@ -575,13 +581,20 @@ def run_colmap(
CONSOLE.log("[bold green]:tada: Done refining intrinsics.")
-def colmap_to_json(cameras_path: Path, images_path: Path, output_dir: Path, camera_model: CameraModel) -> int:
+def colmap_to_json(
+ cameras_path: Path,
+ images_path: Path,
+ output_dir: Path,
+ camera_model: CameraModel,
+ camera_mask_path: Optional[Path] = None,
+) -> int:
"""Converts COLMAP's cameras.bin and images.bin to a JSON file.
Args:
cameras_path: Path to the cameras.bin file.
images_path: Path to the images.bin file.
output_dir: Path to the output directory.
+ camera_mask_path: Path to the camera mask.
camera_model: Camera model used.
Returns:
@@ -612,6 +625,8 @@ def colmap_to_json(cameras_path: Path, images_path: Path, output_dir: Path, came
"file_path": name.as_posix(),
"transform_matrix": c2w.tolist(),
}
+ if camera_mask_path is not None:
+ frame["mask_path"] = camera_mask_path.relative_to(camera_mask_path.parent.parent).as_posix()
frames.append(frame)
out = {
diff --git a/nerfstudio/process_data/process_data_utils.py b/nerfstudio/process_data/process_data_utils.py
index b03dcd8cb..24797658b 100644
--- a/nerfstudio/process_data/process_data_utils.py
+++ b/nerfstudio/process_data/process_data_utils.py
@@ -20,6 +20,8 @@ from enum import Enum
from pathlib import Path
from typing import List, Optional, Tuple
+import cv2
+import numpy as np
from rich.console import Console
from typing_extensions import Literal
@@ -268,3 +270,115 @@ def find_tool_feature_matcher_combination(
return (sfm_tool, feature_type, matcher_type)
return (None, None, None)
+
+
+def generate_circle_mask(height: int, width: int, percent_radius) -> Optional[np.ndarray]:
+ """generate a circle mask of the given size.
+
+ Args:
+ height: The height of the mask.
+ width: The width of the mask.
+ percent_radius: The radius of the circle as a percentage of the image diagonal size.
+
+ Returns:
+ The mask or None if the radius is too large.
+ """
+ if percent_radius <= 0.0:
+ CONSOLE.log("[bold red]:skull: The radius of the circle mask must be positive.")
+ sys.exit(1)
+ if percent_radius >= 1.0:
+ return None
+ mask = np.zeros((height, width), dtype=np.uint8)
+ center = (width // 2, height // 2)
+ radius = int(percent_radius * np.sqrt(width**2 + height**2) / 2.0)
+ cv2.circle(mask, center, radius, 1, -1)
+ return mask
+
+
+def generate_crop_mask(
+ height: int, width: int, percent_crop: Tuple[float, float, float, float]
+) -> Optional[np.ndarray]:
+ """generate a crop mask of the given size.
+
+ Args:
+ height: The height of the mask.
+ width: The width of the mask.
+ percent_crop: The percent of the image to crop in each direction [top, bottom, left, right].
+
+ Returns:
+ The mask or None if no cropping is performed.
+ """
+ if np.all(np.array(percent_crop) == 0.0):
+ return None
+ if np.any(np.array(percent_crop) < 0.0) or np.any(np.array(percent_crop) > 1.0):
+ CONSOLE.log("[bold red]Invalid crop percentage, must be between 0 and 1.")
+ sys.exit(1)
+ top, bottom, left, right = percent_crop
+ mask = np.zeros((height, width), dtype=np.uint8)
+ top = int(top * height)
+ bottom = int(bottom * height)
+ left = int(left * width)
+ right = int(right * width)
+ mask[top : height - bottom, left : width - right] = 1.0
+ return mask
+
+
+def generate_mask(
+ height: int, width: int, percent_crop: Tuple[float, float, float, float], percent_radius: float
+) -> Optional[np.ndarray]:
+ """generate a mask of the given size.
+
+ Args:
+ height: The height of the mask.
+ width: The width of the mask.
+ percent_crop: The percent of the image to crop in each direction [top, bottom, left, right].
+ percent_radius: The radius of the circle as a percentage of the image diagonal size.
+
+ Returns:
+ The mask or None if no mask is needed.
+ """
+ crop_mask = generate_crop_mask(height, width, percent_crop)
+ circle_mask = generate_circle_mask(height, width, percent_radius)
+ if crop_mask is None:
+ return circle_mask
+ if circle_mask is None:
+ return crop_mask
+ return crop_mask * circle_mask
+
+
+def save_mask(
+ image_dir: Path,
+ num_downscales: int,
+ percent_crop: Tuple[float, float, float, float] = (0, 0, 0, 0),
+ percent_radius: float = 1.0,
+) -> Optional[Path]:
+ """Save a mask for each image in the image directory.
+
+ Args:
+ image_dir: The directory containing the images.
+ num_downscales: The number of downscaling levels.
+ percent_crop: The percent of the image to crop in each direction [top, bottom, left, right].
+ percent_radius: The radius of the circle as a percentage of the image diagonal size.
+
+ Returns:
+ The path to the mask file or None if no mask is needed.
+ """
+ image_path = next(image_dir.glob("frame_*"))
+ image = cv2.imread(str(image_path))
+ height, width = image.shape[:2]
+ mask = generate_mask(height, width, percent_crop, percent_radius)
+ if mask is None:
+ return None
+ mask *= 255
+ mask_path = image_dir.parent / "masks"
+ mask_path.mkdir(exist_ok=True)
+ cv2.imwrite(str(mask_path / "mask.png"), mask)
+ downscale_factors = [2**i for i in range(num_downscales + 1)[1:]]
+ for downscale in downscale_factors:
+ mask_path_i = image_dir.parent / f"masks_{downscale}"
+ mask_path_i.mkdir(exist_ok=True)
+ mask_path_i = mask_path_i / "mask.png"
+ mask_i = cv2.resize(mask, (width // downscale, height // downscale), interpolation=cv2.INTER_NEAREST)
+ cv2.imwrite(str(mask_path_i), mask_i)
+ CONSOLE.log(":tada: Generated and saved masks.")
+ return mask_path / "mask.png"
diff --git a/scripts/process_data.py b/scripts/process_data.py
index fcea3fb44..483735911 100755
--- a/scripts/process_data.py
+++ b/scripts/process_data.py
@@ -7,7 +7,7 @@ import sys
import zipfile
from dataclasses import dataclass
from pathlib import Path
-from typing import Union
+from typing import Tuple, Union
import numpy as np
import tyro
@@ -201,6 +201,10 @@ class ProcessVideo:
"""If True, skips COLMAP and generates transforms.json if possible."""
colmap_cmd: str = "colmap"
"""How to call the COLMAP executable."""
+ percent_radius_crop: float = 1.0
+ """Create circle crop mask. The radius is the percent of the image diagonal."""
+ percent_crop: Tuple[float, float, float, float] = (0.0, 0.0, 0.0, 0.0)
+ """Percent of the image to crop. (top, bottom, left, right)"""
gpu: bool = True
"""If True, use GPU."""
verbose: bool = False
@@ -215,12 +219,23 @@ class ProcessVideo:
image_dir = self.output_dir / "images"
image_dir.mkdir(parents=True, exist_ok=True)
+ summary_log = []
# Convert video to images
summary_log, num_extracted_frames = process_data_utils.convert_video_to_images(
self.data, image_dir=image_dir, num_frames_target=self.num_frames_target, verbose=self.verbose
)
- # Downscale images
+ # Create mask
+ mask_path = process_data_utils.save_mask(
+ image_dir=image_dir,
+ num_downscales=self.num_downscales,
+ percent_crop=self.percent_crop,
+ percent_radius=self.percent_radius_crop,
+ )
+ if mask_path is not None:
+ summary_log.append(f"Saved mask to {mask_path}")
+
+ # # Downscale images
summary_log.append(process_data_utils.downscale_images(image_dir, self.num_downscales, verbose=self.verbose))
# Run Colmap
@@ -237,12 +252,18 @@ class ProcessVideo:
image_dir=image_dir,
colmap_dir=colmap_dir,
camera_model=CAMERA_MODELS[self.camera_type],
+ camera_mask_path=mask_path,
gpu=self.gpu,
verbose=self.verbose,
matching_method=self.matching_method,
colmap_cmd=self.colmap_cmd,
)
elif sfm_tool == "hloc":
+ if mask_path is not None:
+ CONSOLE.log(
+ "[bold red]Cannot use a mask with hloc. Please remove the cropping options and try again."
+ )
+ sys.exit(1)
hloc_utils.run_hloc(
image_dir=image_dir,
colmap_dir=colmap_dir,
@@ -264,6 +285,7 @@ class ProcessVideo:
images_path=colmap_dir / "sparse" / "0" / "images.bin",
output_dir=self.output_dir,
camera_model=CAMERA_MODELS[self.camera_type],
+ camera_mask_path=mask_path,
)
summary_log.append(f"Colmap matched {num_matched_frames} images")
summary_log.append(colmap_utils.get_matching_summary(num_extracted_frames, num_matched_frames))
From b88747dd20cbabc1a6454e49076967a0b3bf7d73 Mon Sep 17 00:00:00 2001
From: Matthew Tancik
Date: Mon, 16 Jan 2023 15:37:44 -0800
Subject: [PATCH 09/28] v0.1.15 (#1237)
---
pyproject.toml | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/pyproject.toml b/pyproject.toml
index a61773e65..32e68d257 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
[project]
name = "nerfstudio"
-version = "0.1.14"
+version = "0.1.15"
description = "All-in-one repository for state-of-the-art NeRFs"
readme = "README.md"
license = { text="Apache 2.0"}
From 0fe155923bdd2fa25383a244b7fab73f1deb122d Mon Sep 17 00:00:00 2001
From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com>
Date: Mon, 16 Jan 2023 15:53:38 -0800
Subject: [PATCH 10/28] Bump json5 from 1.0.1 to 1.0.2 in
/nerfstudio/viewer/app (#1238)
Bumps [json5](https://github.com/json5/json5) from 1.0.1 to 1.0.2.
- [Release notes](https://github.com/json5/json5/releases)
- [Changelog](https://github.com/json5/json5/blob/main/CHANGELOG.md)
- [Commits](https://github.com/json5/json5/compare/v1.0.1...v1.0.2)
---
updated-dependencies:
- dependency-name: json5
dependency-type: indirect
...
Signed-off-by: dependabot[bot]
Signed-off-by: dependabot[bot]
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
---
nerfstudio/viewer/app/yarn.lock | 12 ++++++------
1 file changed, 6 insertions(+), 6 deletions(-)
diff --git a/nerfstudio/viewer/app/yarn.lock b/nerfstudio/viewer/app/yarn.lock
index edccda676..b57fe28d7 100644
--- a/nerfstudio/viewer/app/yarn.lock
+++ b/nerfstudio/viewer/app/yarn.lock
@@ -6643,9 +6643,9 @@ json-stable-stringify-without-jsonify@^1.0.1:
integrity sha512-Bdboy+l7tA3OGW6FjyFHWkP5LuByj1Tk33Ljyq0axyzdk9//JSi2u3fP1QSmd1KNwq6VOKYGlAu87CisVir6Pw==
json5@^1.0.1:
- version "1.0.1"
- resolved "https://registry.npmjs.org/json5/-/json5-1.0.1.tgz"
- integrity sha512-aKS4WQjPenRxiQsC93MNfjx+nbF4PAdYzmd/1JIj8HYzqfbu86beTuNgXDzPknWk0n0uARlyewZo4s++ES36Ow==
+ version "1.0.2"
+ resolved "https://registry.yarnpkg.com/json5/-/json5-1.0.2.tgz#63d98d60f21b313b77c4d6da18bfa69d80e1d593"
+ integrity sha512-g1MWMLBiz8FKi1e4w0UyVL3w+iJceWAFBAaBnnGKOpNa5f8TLktkbre1+s6oICydWAm+HRUGTmI+//xv2hvXYA==
dependencies:
minimist "^1.2.0"
@@ -7004,9 +7004,9 @@ minimatch@^5.0.1:
brace-expansion "^2.0.1"
minimist@^1.2.0, minimist@^1.2.5, minimist@^1.2.6:
- version "1.2.6"
- resolved "https://registry.npmjs.org/minimist/-/minimist-1.2.6.tgz"
- integrity sha512-Jsjnk4bw3YJqYzbdyBiNsPWHPfO++UGG749Cxs6peCu5Xg4nrena6OVxOYxrQTqww0Jmwt+Ref8rggumkTLz9Q==
+ version "1.2.7"
+ resolved "https://registry.yarnpkg.com/minimist/-/minimist-1.2.7.tgz#daa1c4d91f507390437c6a8bc01078e7000c4d18"
+ integrity sha512-bzfL1YUZsP41gmu/qjrEk0Q6i2ix/cVeAhbCbqH9u3zYutS1cLg00qhrD0M2MVdCcx4Sc0UpP2eBWo9rotpq6g==
mixin-deep@^1.2.0:
version "1.3.2"
From 2082d6bcaf98dd47cd7d65ad3c9ad80288d667cb Mon Sep 17 00:00:00 2001
From: Matthew Tancik
Date: Mon, 16 Jan 2023 17:00:05 -0800
Subject: [PATCH 11/28] Loosen dependencies (#1240)
* remove protobuf pinned version requirement
* Loosen dependencies
* Protobuf can't be too new
---
pyproject.toml | 36 ++++++++++++++++++------------------
1 file changed, 18 insertions(+), 18 deletions(-)
diff --git a/pyproject.toml b/pyproject.toml
index 32e68d257..83292b873 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -14,33 +14,33 @@ classifiers = [
"Programming Language :: Python",
]
dependencies = [
- "aiohttp==3.8.1",
- "aiortc==1.3.2",
+ "aiohttp>=3.8.1",
+ "aiortc>=1.3.2",
"appdirs>=1.4",
- "av==9.2.0",
+ "av>=9.2.0",
"tyro>=0.3.31",
- "gdown==4.6.0",
- "ninja==1.10.2.3",
+ "gdown>=4.6.0",
+ "ninja>=1.10",
"functorch==0.2.1",
"h5py>=2.9.0",
- "imageio==2.21.1",
+ "imageio>=2.21.1",
"ipywidgets>=7.6",
- "jupyterlab==3.3.4",
- "matplotlib==3.5.3",
- "mediapy==1.1.0",
- "msgpack==1.0.4",
- "msgpack_numpy==0.4.8",
+ "jupyterlab>=3.3.4",
+ "matplotlib>=3.5.3",
+ "mediapy>=1.1.0",
+ "msgpack>=1.0.4",
+ "msgpack_numpy>=0.4.8",
"nerfacc==0.3.2",
"open3d>=0.16.0",
"opencv-python==4.6.0.66",
- "plotly==5.7.0",
- "protobuf==3.20.0",
- "pymeshlab==2022.2.post2",
- "pyngrok==5.1.0",
- "python-socketio==5.7.1",
+ "plotly>=5.7.0",
+ "protobuf<=3.20.3.*,!=3.20.0",
+ "pymeshlab>=2022.2.post2",
+ "pyngrok>=5.1.0",
+ "python-socketio>=5.7.1",
"requests",
- "rich==12.5.1",
- "scikit-image==0.19.3",
+ "rich>=12.5.1",
+ "scikit-image>=0.19.3",
"tensorboard==2.9.0",
"torch==1.12.1",
"torchmetrics[image]>=0.9.3",
From 92636c343409883da10175bebac9c86f64956dd1 Mon Sep 17 00:00:00 2001
From: Mason McGough
Date: Tue, 17 Jan 2023 12:28:20 -0500
Subject: [PATCH 12/28] Docs fix (#1244)
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
* Add the following fixes to documentation:
* Fix trailing backslash in “Use docker image” section
* Replace escaped backslash with double-escaped backslash (see Sphinx issue: https://github.com/sphinx-doc/sphinx/issues/6730)
* Close backtick in `contributing.md`
* Add “run” to instructions for “Render Video”
* Remove unnecessary “,” in “Render Video”
* Correct “before preceding” to “before proceeding”
* Correct “viewpoinrts” to “viewpoints”
* Add missing “.” in “Process data”
* Specify “bash” for code blocks (for consistency with other blocks in the page)
* Fix code block in `viewer_quickstart.rst` (”Copy to clipboard” widget now works)
* Fix some code formatting issues in `export_geometry.md`
* Correct "harmoincs" to "harmonics" in docs.
---
README.md | 8 ++---
.../model_components/visualize_encoders.ipynb | 3 +-
docs/quickstart/custom_dataset.md | 10 +++---
docs/quickstart/export_geometry.md | 32 +++++++++----------
docs/quickstart/first_nerf.md | 10 +++---
docs/quickstart/installation.md | 6 ++--
docs/quickstart/viewer_quickstart.rst | 7 ++--
docs/reference/contributing.md | 2 +-
8 files changed, 39 insertions(+), 39 deletions(-)
diff --git a/README.md b/README.md
index 0ec27e431..d4c29ce9c 100644
--- a/README.md
+++ b/README.md
@@ -162,9 +162,9 @@ Once you have a NeRF model you can either render out a video or export a point c
### Render Video
-First we must create a path for the camera to follow. This can be done in the viewer under the "RENDER" tab. Orient your 3D view to the location where you wish the video to start, then press "ADD CAMERA". This will set the first camera key frame. Continue to new viewpoints adding additional cameras to create the camera path. We provide other parameters to further refine your camera path. Once satisfied, press "RENDER" which will display a modal that contains the command needed to render the video. Kill the training job (or create a new terminal if you have lots of compute) and the command to generate the video.
+First we must create a path for the camera to follow. This can be done in the viewer under the "RENDER" tab. Orient your 3D view to the location where you wish the video to start, then press "ADD CAMERA". This will set the first camera key frame. Continue to new viewpoints adding additional cameras to create the camera path. We provide other parameters to further refine your camera path. Once satisfied, press "RENDER" which will display a modal that contains the command needed to render the video. Kill the training job (or create a new terminal if you have lots of compute) and run the command to generate the video.
-Other video export options are available, learn more by running,
+Other video export options are available, learn more by running
```bash
ns-render --help
@@ -174,7 +174,7 @@ ns-render --help
While NeRF models are not designed to generate point clouds, it is still possible. Navigate to the "EXPORT" tab in the 3D viewer and select "POINT CLOUD". If the crop option is selected, everything in the yellow square will be exported into a point cloud. Modify the settings as desired then run the command at the bottom of the panel in your command line.
-Alternatively you can use the CLI without the viewer. Learn about the export options by running,
+Alternatively you can use the CLI without the viewer. Learn about the export options by running
```bash
ns-export pointcloud --help
@@ -198,7 +198,7 @@ Using an existing dataset is great, but likely you want to use your own data! We
### Training models other than nerfacto
-We provide other models than nerfacto, for example if you want to train the original nerf model, use the following command,
+We provide other models than nerfacto, for example if you want to train the original nerf model, use the following command
```bash
ns-train vanilla-nerf --data DATA_PATH
diff --git a/docs/nerfology/model_components/visualize_encoders.ipynb b/docs/nerfology/model_components/visualize_encoders.ipynb
index 6ef2c0950..84b86e1b7 100644
--- a/docs/nerfology/model_components/visualize_encoders.ipynb
+++ b/docs/nerfology/model_components/visualize_encoders.ipynb
@@ -415,12 +415,13 @@
]
},
{
+ "attachments": {},
"cell_type": "markdown",
"metadata": {},
"source": [
"(spherical)=\n",
"## Spherical Harmonic Encoding\n",
- "Encode direction using spherical harmoincs. (Mostly used to encode viewing direction)"
+ "Encode direction using spherical harmonics. (Mostly used to encode viewing direction)"
]
},
{
diff --git a/docs/quickstart/custom_dataset.md b/docs/quickstart/custom_dataset.md
index 8192273e5..a7fe05a05 100644
--- a/docs/quickstart/custom_dataset.md
+++ b/docs/quickstart/custom_dataset.md
@@ -130,7 +130,7 @@ cd vcpkg
Nerfstudio can also be trained directly from captures from the [Polycam app](https://poly.cam//). This avoids the need to use COLMAP. Polycam's poses are globally optimized which make them more robust to drift (an issue with ARKit or SLAM methods).
-To get the best results, try to reduce motion blur as much as possible and try to view the target from as many viewpoinrts as possible. Polycam recommends having good lighting and moving the camera slowly if using auto mode. Or, even better, use the manual shutter mode to capture less blurry images.
+To get the best results, try to reduce motion blur as much as possible and try to view the target from as many viewpoints as possible. Polycam recommends having good lighting and moving the camera slowly if using auto mode. Or, even better, use the manual shutter mode to capture less blurry images.
:::{admonition} Note
:class: info
@@ -210,7 +210,7 @@ After downloading the app, `Developer Mode` needs to be enabled. A toggle can be
3. Tap the `+` button to create a new capture.
-4. Choose `Camera pose` as the capture option
+4. Choose `Camera pose` as the capture option.
5. Capture the scene and provide a name.
@@ -218,7 +218,7 @@ After downloading the app, `Developer Mode` needs to be enabled. A toggle can be
7. Unzip the file and run the training script (`ns-process-data` is not necessary).
-```
+```bash
ns-train nerfacto --data {kiri output directory}
```
@@ -249,7 +249,7 @@ ns-process-data record3d --data {data directory} --output-dir {output directory}
4. Train with nerfstudio!
-```
+```bash
ns-train nerfacto --data {output directory}
```
@@ -281,6 +281,6 @@ ns-process-data metashape --data {data directory} --xml {xml file} --output-dir
4. Train with nerfstudio!
-```
+```bash
ns-train nerfacto --data {output directory}
```
diff --git a/docs/quickstart/export_geometry.md b/docs/quickstart/export_geometry.md
index 2b6323f35..28d29fc54 100644
--- a/docs/quickstart/export_geometry.md
+++ b/docs/quickstart/export_geometry.md
@@ -6,33 +6,31 @@ Here we document how to export point clouds and meshes from nerfstudio. The main
### 1. TSDF Fusion
- TSDF (truncated signed distance function) Fusion is a meshing algorithm that uses depth maps to extract a surface as a mesh. This method works for all models.
+TSDF (truncated signed distance function) Fusion is a meshing algorithm that uses depth maps to extract a surface as a mesh. This method works for all models.
- ```python
- ns-export tsdf --load-config CONFIG.yml --output-dir OUTPUT_DIR
- ```
+```python
+ns-export tsdf --load-config CONFIG.yml --output-dir OUTPUT_DIR
+```
### 2. Poisson surface reconstruction
- Poisson surface reconstruction gives the highest quality meshes. See the steps below to use Poisson surface reconstruction in our repo.
+Poisson surface reconstruction gives the highest quality meshes. See the steps below to use Poisson surface reconstruction in our repo.
- :::{admonition} Note
- :class: info
+> **Note:**
+> This will only work with a Model that computes or predicts normals, e.g., nerfacto.
- This will only work with a Model that computes or predicts normals, e.g., nerfacto.
- :::
- 1. Train nerfacto with network settings that predict normals.
+1. Train nerfacto with network settings that predict normals.
- ```bash
- ns-train nerfacto --pipeline.model.predict-normals True
- ```
+```bash
+ns-train nerfacto --pipeline.model.predict-normals True
+```
- 2. Export a mesh with the Poisson meshing algorithm.
+2. Export a mesh with the Poisson meshing algorithm.
- ```bash
- ns-export poisson --load-config CONFIG.yml --output-dir OUTPUT_DIR
- ```
+```bash
+ns-export poisson --load-config CONFIG.yml --output-dir OUTPUT_DIR
+```
## Exporting a point cloud
diff --git a/docs/quickstart/first_nerf.md b/docs/quickstart/first_nerf.md
index 30143814f..e7071c329 100644
--- a/docs/quickstart/first_nerf.md
+++ b/docs/quickstart/first_nerf.md
@@ -46,9 +46,9 @@ Once you have a NeRF model you can either render out a video or export a point c
### Render Video
-First we must create a path for the camera to follow. This can be done in the viewer under the "RENDER" tab. Orient your 3D view to the location where you wish the video to start, then press "ADD CAMERA". This will set the first camera key frame. Continue to new viewpoints adding additional cameras to create the camera path. We provide other parameters to further refine your camera path. Once satisfied, press "RENDER" which will display a modal that contains the command needed to render the video. Kill the training job (or create a new terminal if you have lots of compute) and the command to generate the video.
+First we must create a path for the camera to follow. This can be done in the viewer under the "RENDER" tab. Orient your 3D view to the location where you wish the video to start, then press "ADD CAMERA". This will set the first camera key frame. Continue to new viewpoints adding additional cameras to create the camera path. We provide other parameters to further refine your camera path. Once satisfied, press "RENDER" which will display a modal that contains the command needed to render the video. Kill the training job (or create a new terminal if you have lots of compute) and run the command to generate the video.
-Other video export options are available, learn more by running,
+Other video export options are available, learn more by running
```bash
ns-render --help
@@ -58,7 +58,7 @@ ns-render --help
While NeRF models are not designed to generate point clouds, it is still possible. Navigate to the "EXPORT" tab in the 3D viewer and select "POINT CLOUD". If the crop option is selected, everything in the yellow square will be exported into a point cloud. Modify the settings as desired then run the command at the bottom of the panel in your command line.
-Alternatively you can use the CLI without the viewer. Learn about the export options by running,
+Alternatively you can use the CLI without the viewer. Learn about the export options by running
```bash
ns-export pointcloud --help
@@ -70,7 +70,7 @@ Nerfstudio allows customization of training and eval configs from the CLI in a p
The most demonstrative and helpful example of the CLI structure is the difference in output between the following commands:
-The following will list the supported models,
+The following will list the supported models
```bash
ns-train --help
@@ -82,7 +82,7 @@ Applying `--help` after the model specification will provide the model and train
ns-train nerfacto --help
```
-At the end of the command you can specify the dataparser used. By default we use the _nerfstudio-data_ dataparser. We include other dataparsers such as _Blender_, _NuScenes_, ect. For a list of dataparse specific arguments, add `--help` to the end of the command,
+At the end of the command you can specify the dataparser used. By default we use the _nerfstudio-data_ dataparser. We include other dataparsers such as _Blender_, _NuScenes_, ect. For a list of dataparse specific arguments, add `--help` to the end of the command
```bash
ns-train nerfacto nerfstudio-data --help
diff --git a/docs/quickstart/installation.md b/docs/quickstart/installation.md
index cf08348c8..ae6a17cc9 100644
--- a/docs/quickstart/installation.md
+++ b/docs/quickstart/installation.md
@@ -6,7 +6,7 @@ CUDA must be installed on the system. This library has been tested with version
## Create environment
-Nerfstudio requires `python >= 3.7`. We recommend using conda to manage dependencies. Make sure to install [Conda](https://docs.conda.io/en/latest/miniconda.html) before preceding.
+Nerfstudio requires `python >= 3.7`. We recommend using conda to manage dependencies. Make sure to install [Conda](https://docs.conda.io/en/latest/miniconda.html) before proceeding.
```bash
conda create --name nerfstudio -y python=3.8
@@ -64,7 +64,7 @@ pip install -e .[docs]
```
## Use docker image
-Instead of installing and compiling prerequisites, setting up the environment and installing dependencies, a ready to use docker image is provided. \
+Instead of installing and compiling prerequisites, setting up the environment and installing dependencies, a ready to use docker image is provided.
### Prerequisites
Docker ([get docker](https://docs.docker.com/get-docker/)) and nvidia GPU drivers ([get nvidia drivers](https://www.nvidia.de/Download/index.aspx?lang=de)), capable of working with CUDA 11.7, must be installed.
The docker image can then either be pulled from [here](https://hub.docker.com/r/dromni/nerfstudio/tags) (replace with the actual version, e.g. 0.1.10)
@@ -95,7 +95,7 @@ docker run --gpus all -v /folder/of/your/data:/workspace/ -v /home//.
```
### Note
- The container works on Linux and Windows, depending on your OS some additional setup steps might be required to provide access to your GPU inside containers.
-- Paths on Windows use backslash '\\' while unix based systems use a frontslash '/' for paths, where backslashes might require an escape character depending on where they are used (e.g. C:\\\\folder1\\\\folder2...). Ensure to use the correct paths when mounting folders or providing paths as parameters.
+- Paths on Windows use backslash '\\\\' while unix based systems use a frontslash '/' for paths, where backslashes might require an escape character depending on where they are used (e.g. C:\\\\folder1\\\\folder2...). Ensure to use the correct paths when mounting folders or providing paths as parameters.
- Everything inside the container, what is not in a mounted folder (workspace in the above example), will be permanently removed after destroying the container. Always do all your tasks and output folder in workdir!
- The user inside the container is called 'user' and is mapped to the local user with ID 1000 (usually the first non-root user on Linux systems).
- The container currently is based on nvidia/cuda:11.7.1-devel-ubuntu22.04, consequently it comes with CUDA 11.7 which must be supported by the nvidia driver. No local CUDA installation is required or will be affected by using the docker image.
diff --git a/docs/quickstart/viewer_quickstart.rst b/docs/quickstart/viewer_quickstart.rst
index 64a09f8fe..6d110e7c0 100644
--- a/docs/quickstart/viewer_quickstart.rst
+++ b/docs/quickstart/viewer_quickstart.rst
@@ -63,9 +63,10 @@ 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:
-```bash
-ssh -L 7007:localhost:7007 @
-```
+.. code-block:: bash
+
+ ssh -L 7007:localhost:7007 @
+
.. admonition:: Note
diff --git a/docs/reference/contributing.md b/docs/reference/contributing.md
index 74c1c584e..a9651cbed 100644
--- a/docs/reference/contributing.md
+++ b/docs/reference/contributing.md
@@ -72,7 +72,7 @@ python scripts/docs/build_docs.py
:class: info
- Rerun `make html` when documentation changes are made
-- make clean` is necessary if the documentation structure changes.
+- `make clean` is necessary if the documentation structure changes.
:::
### Auto build
From f350650f1b720b563674688f8826853827685af1 Mon Sep 17 00:00:00 2001
From: machenmusik
Date: Tue, 17 Jan 2023 12:40:26 -0500
Subject: [PATCH 13/28] create video writer later, to adapt to render image's
width and height (fixes #1242) (#1245)
* create video writer later, to adapt to render image's width and height
* fix rendering with multiple output names
---
scripts/render.py | 38 +++++++++++++-------------------------
1 file changed, 13 insertions(+), 25 deletions(-)
diff --git a/scripts/render.py b/scripts/render.py
index 30b551228..357b902ed 100644
--- a/scripts/render.py
+++ b/scripts/render.py
@@ -42,8 +42,6 @@ def _render_trajectory_video(
cameras: Cameras,
output_filename: Path,
rendered_output_names: List[str],
- render_width: int,
- render_height: int,
rendered_resolution_scaling_factor: float = 1.0,
seconds: float = 5.0,
output_format: Literal["images", "video"] = "video",
@@ -56,8 +54,6 @@ def _render_trajectory_video(
cameras: Cameras to render.
output_filename: Name of the output file.
rendered_output_names: List of outputs to visualise.
- render_width: Video width to render.
- render_height: Video height to render.
rendered_resolution_scaling_factor: Scaling factor to apply to the camera image resolution.
seconds: Length of output video.
output_format: How to save output data.
@@ -89,20 +85,8 @@ def _render_trajectory_video(
# but we don't know how big the video file will be, so it's not certain!)
with ExitStack() as stack:
- writer = (
- stack.enter_context(
- media.VideoWriter(
- path=output_filename,
- shape=(
- int(render_height * rendered_resolution_scaling_factor),
- int(render_width * rendered_resolution_scaling_factor) * len(rendered_output_names),
- ),
- fps=fps,
- )
- )
- if output_format == "video"
- else None
- )
+ writer = None
+
with progress:
for camera_idx in progress.track(range(cameras.size), description=""):
camera_ray_bundle = cameras.generate_rays(camera_indices=camera_idx)
@@ -124,7 +108,17 @@ def _render_trajectory_video(
render_image = np.concatenate(render_image, axis=1)
if output_format == "images":
media.write_image(output_image_dir / f"{camera_idx:05d}.png", render_image)
- if output_format == "video" and writer is not None:
+ if output_format == "video":
+ if writer is None:
+ render_width = int(render_image.shape[1] * rendered_resolution_scaling_factor)
+ render_height = int(render_image.shape[0] * rendered_resolution_scaling_factor)
+ writer = stack.enter_context(
+ media.VideoWriter(
+ path=output_filename,
+ shape=(render_height, render_width),
+ fps=fps,
+ )
+ )
writer.add_image(render_image)
if output_format == "video":
@@ -242,8 +236,6 @@ class RenderTrajectory:
camera_start = pipeline.datamanager.eval_dataloader.get_camera(image_idx=0).flatten()
# TODO(ethan): pass in the up direction of the camera
camera_type = CameraType.PERSPECTIVE
- render_width = 952
- render_height = 736
camera_path = get_spiral_path(camera_start, steps=30, radius=0.1)
elif self.traj == "filename":
with open(self.camera_path_filename, "r", encoding="utf-8") as f:
@@ -257,8 +249,6 @@ class RenderTrajectory:
camera_type = CameraType.EQUIRECTANGULAR
else:
camera_type = CameraType.PERSPECTIVE
- render_width = camera_path["render_width"]
- render_height = camera_path["render_height"]
camera_path = get_path_from_json(camera_path)
else:
assert_never(self.traj)
@@ -272,8 +262,6 @@ class RenderTrajectory:
seconds=seconds,
output_format=self.output_format,
camera_type=camera_type,
- render_width=render_width,
- render_height=render_height,
)
From ea45c15e014db4f3e98fba3159ee6a4448d3859a Mon Sep 17 00:00:00 2001
From: Matthew Tancik
Date: Tue, 17 Jan 2023 10:53:22 -0800
Subject: [PATCH 14/28] Update transform.json docs (#1246)
Update transoform.json docs
---
docs/quickstart/data_conventions.md | 57 ++++++++++++++++++-----------
1 file changed, 36 insertions(+), 21 deletions(-)
diff --git a/docs/quickstart/data_conventions.md b/docs/quickstart/data_conventions.md
index bf6463312..34324e30e 100644
--- a/docs/quickstart/data_conventions.md
+++ b/docs/quickstart/data_conventions.md
@@ -20,28 +20,39 @@ Our explanation here is for the nerfstudio data format. The `transforms.json` ha
### Camera intrinsics
-At the top of the file, we specify the camera intrinsics. We assume that all the intrinsics parameters are the same for every camera in the dataset. The following is an example
+If all of the images share the same camera intrinsics, the values can be placed at the top of the file.
```json
{
- "fl_x": 1072.281897246229, // focal length x
- "fl_y": 1068.6906965388932, // focal length y
+ "camera_model": "OPENCV_FISHEYE", // camera model type [OPENCV, OPENCV_FISHEYE]
+ "fl_x": 1072.0, // focal length x
+ "fl_y": 1068.0, // focal length y
"cx": 1504.0, // principal point x
"cy": 1000.0, // principal point y
"w": 3008, // image width
"h": 2000, // image height
- "camera_model": "OPENCV_FISHEYE", // camera model type
- "k1": 0.03126218448029553, // first radial distorial parameter
- "k2": 0.005177020067511987, // second radial distorial parameter
- "k3": 0.0006640977794272005, // third radial distorial parameter
- "k4": 0.00010067035656515042, // fourth radial distorial parameter
- "p1": -6.472477652140879e-5, // first tangential distortion parameter
- "p2": -1.374647851912992e-7, // second tangential distortion parameter
- "frames": // ... extrinsics parameters explained below
+ "k1": 0.0312, // first radial distorial parameter, used by [OPENCV, OPENCV_FISHEYE]
+ "k2": 0.0051, // second radial distorial parameter, used by [OPENCV, OPENCV_FISHEYE]
+ "k3": 0.0006, // third radial distorial parameter, used by [OPENCV_FISHEYE]
+ "k4": 0.0001, // fourth radial distorial parameter, used by [OPENCV_FISHEYE]
+ "p1": -6.47e-5, // first tangential distortion parameter, used by [OPENCV]
+ "p2": -1.37e-7, // second tangential distortion parameter, used by [OPENCV]
+ "frames": // ... per-frame intrinsics and extrinsics parameters
}
```
-The valid `camera_model` strings are currently "OPENCV" and "OPENCV_FISHEYE". "OPENCV" (i.e., perspective) uses k1-2 and p1-2. "OPENCV_FISHEYE" uses k1-4.
+Per-frame intrinsics can also be defined in the `frames` field. If defined for a field (ie. `fl_x`), all images must have per-image intrinsics defined for that field. Per-frame `camera_model` is not supported.
+
+```json
+{
+ // ...
+ "frames": [
+ {
+ "fl_x": 1234
+ }
+ ]
+}
+```
### Camera extrinsics
@@ -49,7 +60,7 @@ For a transform matrix, the first 3 columns are the +X, +Y, and +Z defining the
```json
{
- // ... intrinsics parameters
+ // ...
"frames": [
{
"file_path": "images/frame_00001.jpeg",
@@ -75,10 +86,12 @@ To train with depth supervision, you can also provide a `depth_file_path` for ea
```json
{
- "frames": {
- // ...
- "depth_file_path": "depth/0001.png"
- }
+ "frames": [
+ {
+ // ...
+ "depth_file_path": "depth/0001.png"
+ }
+ ]
}
```
@@ -94,10 +107,12 @@ There may be parts of the training image that should not be used during training
```json
{
- "frames": {
- // ...
- "mask_path": "masks/mask.jpeg"
- }
+ "frames": [
+ {
+ // ...
+ "mask_path": "masks/mask.jpeg"
+ }
+ ]
}
```
From 628e4fe1a638e7fb3b7ad33d4d91a4b1d63a9b68 Mon Sep 17 00:00:00 2001
From: Matthew Tancik
Date: Tue, 17 Jan 2023 17:46:28 -0800
Subject: [PATCH 15/28] Bump nerfacc to 0.3.3 (#1249)
---
pyproject.toml | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/pyproject.toml b/pyproject.toml
index 83292b873..c6da7fa44 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -30,7 +30,7 @@ dependencies = [
"mediapy>=1.1.0",
"msgpack>=1.0.4",
"msgpack_numpy>=0.4.8",
- "nerfacc==0.3.2",
+ "nerfacc==0.3.3",
"open3d>=0.16.0",
"opencv-python==4.6.0.66",
"plotly>=5.7.0",
From 0846e45fe144168bc0d6b04ecf7a09ea5775f361 Mon Sep 17 00:00:00 2001
From: Terrance Wang
Date: Wed, 18 Jan 2023 10:01:10 -0800
Subject: [PATCH 16/28] setting tensorf default from wandb to viewer (#1250)
---
nerfstudio/configs/method_configs.py | 5 +++++
1 file changed, 5 insertions(+)
diff --git a/nerfstudio/configs/method_configs.py b/nerfstudio/configs/method_configs.py
index d11c377b5..30682a242 100644
--- a/nerfstudio/configs/method_configs.py
+++ b/nerfstudio/configs/method_configs.py
@@ -248,6 +248,9 @@ method_configs["vanilla-nerf"] = TrainerConfig(
method_configs["tensorf"] = TrainerConfig(
method_name="tensorf",
+ steps_per_eval_batch=500,
+ steps_per_save=2000,
+ max_num_iterations=30000,
mixed_precision=False,
pipeline=VanillaPipelineConfig(
datamanager=VanillaDataManagerConfig(
@@ -265,6 +268,8 @@ method_configs["tensorf"] = TrainerConfig(
"scheduler": SchedulerConfig(lr_final=0.002, max_steps=30000),
},
},
+ viewer=ViewerConfig(num_rays_per_chunk=1 << 15),
+ vis="viewer",
)
method_configs["dnerf"] = TrainerConfig(
From a4b023b171eb162d2352b617b648765807ee61bc Mon Sep 17 00:00:00 2001
From: machenmusik
Date: Wed, 18 Jan 2023 18:20:03 -0500
Subject: [PATCH 17/28] Rollback cryptography to fully working version (pre-39;
38 works) (#1254)
---
pyproject.toml | 1 +
1 file changed, 1 insertion(+)
diff --git a/pyproject.toml b/pyproject.toml
index c6da7fa44..b8f8fc11a 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -18,6 +18,7 @@ dependencies = [
"aiortc>=1.3.2",
"appdirs>=1.4",
"av>=9.2.0",
+ "cryptography>=38,<39",
"tyro>=0.3.31",
"gdown>=4.6.0",
"ninja>=1.10",
From b170e175edea410fc7ce75733bf36135eb64503c Mon Sep 17 00:00:00 2001
From: LSong <12553253+lsongx@users.noreply.github.com>
Date: Wed, 18 Jan 2023 18:57:55 -0800
Subject: [PATCH 18/28] NeRFPlayer sliding window implementation (#1255)
* NeRFPlayer sliding window implementation
* add comments
---
nerfstudio/field_components/cuda/__init__.py | 32 +
nerfstudio/field_components/cuda/_backend.py | 57 ++
.../cuda/csrc/include/temporal_gridencoder.h | 62 ++
.../field_components/cuda/csrc/pybind.cu | 14 +
.../cuda/csrc/temporal_gridencoder.cu | 667 ++++++++++++++++++
nerfstudio/field_components/temporal_grid.py | 357 ++++++++++
tests/field_components/test_temporal_grid.py | 47 ++
7 files changed, 1236 insertions(+)
create mode 100644 nerfstudio/field_components/cuda/__init__.py
create mode 100644 nerfstudio/field_components/cuda/_backend.py
create mode 100644 nerfstudio/field_components/cuda/csrc/include/temporal_gridencoder.h
create mode 100644 nerfstudio/field_components/cuda/csrc/pybind.cu
create mode 100644 nerfstudio/field_components/cuda/csrc/temporal_gridencoder.cu
create mode 100644 nerfstudio/field_components/temporal_grid.py
create mode 100644 tests/field_components/test_temporal_grid.py
diff --git a/nerfstudio/field_components/cuda/__init__.py b/nerfstudio/field_components/cuda/__init__.py
new file mode 100644
index 000000000..f92662b85
--- /dev/null
+++ b/nerfstudio/field_components/cuda/__init__.py
@@ -0,0 +1,32 @@
+# 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.
+
+"""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):
+ # pylint: disable=import-outside-toplevel
+ 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
new file mode 100644
index 000000000..d4269b9ee
--- /dev/null
+++ b/nerfstudio/field_components/cuda/_backend.py
@@ -0,0 +1,57 @@
+# 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.
+
+"""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.path.exists(os.path.join(BUILD_DIR, f"{NAME}.so")):
+ # If the build exists, we assume the extension has been built
+ # and we can load it.
+ _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
new file mode 100644
index 000000000..7b5ad3d28
--- /dev/null
+++ b/nerfstudio/field_components/cuda/csrc/include/temporal_gridencoder.h
@@ -0,0 +1,62 @@
+/*
+ * 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
new file mode 100644
index 000000000..877b386ca
--- /dev/null
+++ b/nerfstudio/field_components/cuda/csrc/pybind.cu
@@ -0,0 +1,14 @@
+/*
+ * 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
new file mode 100644
index 000000000..b0ca666eb
--- /dev/null
+++ b/nerfstudio/field_components/cuda/csrc/temporal_gridencoder.cu
@@ -0,0 +1,667 @@
+/*
+ * 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/temporal_grid.py b/nerfstudio/field_components/temporal_grid.py
new file mode 100644
index 000000000..c4f5e20c5
--- /dev/null
+++ b/nerfstudio/field_components/temporal_grid.py
@@ -0,0 +1,357 @@
+# 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.
+
+"""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 torch import nn
+from torch.autograd import Function
+from torch.cuda.amp import custom_bwd, custom_fwd
+from torchtyping import TensorType
+
+import nerfstudio.field_components.cuda as _C
+
+
+# pylint: disable=abstract-method, arguments-differ
+class TemporalGridEncodeFunc(Function):
+ """Class for autograd in pytorch."""
+
+ @staticmethod
+ @custom_fwd
+ def forward(
+ ctx,
+ inputs: TensorType["bs", "input_dim"],
+ temporal_row_index: TensorType["bs", "temporal_index_dim"],
+ embeddings: TensorType["table_size", "embed_dim"],
+ offsets: TensorType["num_levels+1"],
+ per_level_scale: float,
+ base_resolution: int,
+ calc_grad_inputs: bool = False,
+ gridtype: int = 0,
+ align_corners: bool = False,
+ ) -> TensorType["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
+ """
+
+ def __init__(
+ self,
+ temporal_dim: int = 64,
+ input_dim: int = 3,
+ num_levels: int = 16,
+ level_dim: int = 2,
+ per_level_scale: int = 2,
+ 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: TensorType["bs"]) -> TensorType["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: TensorType["bs", "input_dim"], time: TensorType["bs", 1]) -> TensorType["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]),
+ self.embeddings,
+ self.offsets,
+ self.per_level_scale,
+ self.base_resolution,
+ xyz.requires_grad,
+ self.gridtype_id,
+ self.align_corners,
+ )
+ return outputs
+
+ def get_temporal_tv_loss(self) -> TensorType[()]:
+ """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]).item()
+ feat_idx = self.index_list[row_idx]
+ return (self.embeddings[:, feat_idx[0]] - self.embeddings[:, feat_idx[1]]).abs().mean()
diff --git a/tests/field_components/test_temporal_grid.py b/tests/field_components/test_temporal_grid.py
new file mode 100644
index 000000000..a83450c38
--- /dev/null
+++ b/tests/field_components/test_temporal_grid.py
@@ -0,0 +1,47 @@
+"""
+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
+
+ params = dict(
+ 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,
+ )
+ model = temporal_grid.TemporalGridEncoder(**params).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.sum() - weight.sum() < 0.01
+ assert torch.all(model.embeddings.grad[2:, :] == 0)
+ assert torch.all(model.embeddings.grad[:, 1:] == 0)
+ 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()
From 7466788b2e0a4fa54b9d7283f7d1c8899fac726a Mon Sep 17 00:00:00 2001
From: machenmusik
Date: Thu, 19 Jan 2023 13:02:43 -0500
Subject: [PATCH 19/28] downsample all images (#1259)
CottageMiniature sample dataset was only downsampling first image correctly prior to this fix.
---
nerfstudio/process_data/process_data_utils.py | 21 +++++++++++--------
1 file changed, 12 insertions(+), 9 deletions(-)
diff --git a/nerfstudio/process_data/process_data_utils.py b/nerfstudio/process_data/process_data_utils.py
index 24797658b..d5da2541d 100644
--- a/nerfstudio/process_data/process_data_utils.py
+++ b/nerfstudio/process_data/process_data_utils.py
@@ -14,6 +14,7 @@
"""Helper utils for processing data into the nerfstudio format."""
+import os
import shutil
import sys
from enum import Enum
@@ -203,15 +204,17 @@ def downscale_images(image_dir: Path, num_downscales: int, verbose: bool = False
assert isinstance(downscale_factor, int)
downscale_dir = image_dir.parent / f"images_{downscale_factor}"
downscale_dir.mkdir(parents=True, exist_ok=True)
- file_type = image_dir.glob("frame_*").__next__().suffix
- filename = f"frame_%05d{file_type}"
- ffmpeg_cmd = [
- f"ffmpeg -i {image_dir / filename} ",
- f"-q:v 2 -vf scale=iw/{downscale_factor}:ih/{downscale_factor} ",
- f"{downscale_dir / filename}",
- ]
- ffmpeg_cmd = " ".join(ffmpeg_cmd)
- run_command(ffmpeg_cmd, verbose=verbose)
+ # Using %05d ffmpeg commands appears to be unreliable (skips images), so use scandir.
+ files = os.scandir(image_dir)
+ for f in files:
+ filename = f.name
+ ffmpeg_cmd = [
+ f"ffmpeg -y -i {image_dir / filename} ",
+ f"-q:v 2 -vf scale=iw/{downscale_factor}:ih/{downscale_factor} ",
+ f"{downscale_dir / filename}",
+ ]
+ ffmpeg_cmd = " ".join(ffmpeg_cmd)
+ run_command(ffmpeg_cmd, verbose=verbose)
CONSOLE.log("[bold green]:tada: Done downscaling images.")
downscale_text = [f"[bold blue]{2**(i+1)}x[/bold blue]" for i in range(num_downscales)]
From fef6b861be0fcc986165543d1bebf0ca880e2ab3 Mon Sep 17 00:00:00 2001
From: Rohan Mathur
Date: Thu, 19 Jan 2023 17:41:05 -0500
Subject: [PATCH 20/28] Camera path (#1251)
* added eta to base config
* added code to save camera paths to dated name in data folder
* updated camera path name customization
* removed unnecessary comments
* added new version to viewer package.json
* more clean up and also I left a print statement in
* fixed validation message
---
nerfstudio/engine/trainer.py | 4 ++-
nerfstudio/viewer/app/package.json | 2 +-
.../src/modules/RenderModal/RenderModal.jsx | 30 ++++++++-----------
.../SidePanel/CameraPanel/CameraPanel.jsx | 9 +++---
.../SidePanel/CameraPanel/CameraPropPanel.jsx | 26 ++++++++++++++++
nerfstudio/viewer/app/src/reducer.js | 3 ++
nerfstudio/viewer/server/viewer_utils.py | 26 ++++++++++++----
7 files changed, 70 insertions(+), 30 deletions(-)
diff --git a/nerfstudio/engine/trainer.py b/nerfstudio/engine/trainer.py
index 30945a4c7..49879c31d 100644
--- a/nerfstudio/engine/trainer.py
+++ b/nerfstudio/engine/trainer.py
@@ -122,7 +122,9 @@ class Trainer:
viewer_log_path = self.base_dir / config.viewer.relative_log_filename
self.viewer_state, banner_messages = None, None
if self.config.is_viewer_enabled() and local_rank == 0:
- self.viewer_state, banner_messages = viewer_utils.setup_viewer(config.viewer, log_filename=viewer_log_path)
+ self.viewer_state, banner_messages = viewer_utils.setup_viewer(
+ config.viewer, log_filename=viewer_log_path, datapath=config.pipeline.datamanager.dataparser.data
+ )
self._check_viewer_warnings()
# set up writers/profilers if enabled
writer_log_path = self.base_dir / config.logging.relative_log_dir
diff --git a/nerfstudio/viewer/app/package.json b/nerfstudio/viewer/app/package.json
index 78d4997f3..ccaa2fa1c 100644
--- a/nerfstudio/viewer/app/package.json
+++ b/nerfstudio/viewer/app/package.json
@@ -1,7 +1,7 @@
{
"name": "viewer",
"homepage": ".",
- "version": "22-12-16-0",
+ "version": "23-01-19-0",
"private": true,
"dependencies": {
"@emotion/react": "^11.10.4",
diff --git a/nerfstudio/viewer/app/src/modules/RenderModal/RenderModal.jsx b/nerfstudio/viewer/app/src/modules/RenderModal/RenderModal.jsx
index 6305d4043..c9cea8f1b 100644
--- a/nerfstudio/viewer/app/src/modules/RenderModal/RenderModal.jsx
+++ b/nerfstudio/viewer/app/src/modules/RenderModal/RenderModal.jsx
@@ -1,7 +1,7 @@
/* eslint-disable react/jsx-props-no-spreading */
import * as React from 'react';
-import { Box, Button, Modal, TextField, Typography } from '@mui/material';
+import { Box, Button, Modal, Typography } from '@mui/material';
import { useSelector } from 'react-redux';
import ContentCopyRoundedIcon from '@mui/icons-material/ContentCopyRounded';
@@ -19,15 +19,22 @@ export default function RenderModal(props: RenderModalProps) {
(state) => state.renderingState.config_base_dir,
);
+ const export_path = useSelector(
+ (state) => state.renderingState.export_path,
+ );
+
+ const data_base_dir = useSelector(
+ (state) => state.renderingState.data_base_dir,
+ );
+
// react state
- const [filename, setFilename] = React.useState('render_output');
const handleClose = () => setOpen(false);
// Copy the text inside the text field
const config_filename = `${config_base_dir}/config.yml`;
- const camera_path_filename = `${config_base_dir}/camera_path.json`;
- const cmd = `ns-render --load-config ${config_filename} --traj filename --camera-path-filename ${camera_path_filename} --output-path renders/${filename}.mp4`;
+ const camera_path_filename = `${export_path}.json`;
+ const cmd = `ns-render --load-config ${config_filename} --traj filename --camera-path-filename ${data_base_dir}/camera_paths/${camera_path_filename} --output-path renders/${data_base_dir}/${export_path}.mp4`;
const text_intro = `To render a full resolution video, run the following command in a terminal.`;
@@ -56,22 +63,11 @@ export default function RenderModal(props: RenderModalProps) {
The video will be saved to{' '}
- ./renders/{filename}.mp4
+ ./renders/{data_base_dir}/{export_path}.mp4
.