diff --git a/README.md b/README.md index c4f346993..d4c29ce9c 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 ``` @@ -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/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/index.md b/docs/index.md index ae2270986..53d45784d 100644 --- a/docs/index.md +++ b/docs/index.md @@ -52,6 +52,7 @@ quickstart/custom_dataset quickstart/viewer_quickstart quickstart/export_geometry quickstart/data_conventions +quickstart/blender_addon Contributing ``` 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/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/blender_addon.md b/docs/quickstart/blender_addon.md new file mode 100644 index 000000000..425a873df --- /dev/null +++ b/docs/quickstart/blender_addon.md @@ -0,0 +1,115 @@ +# Blender VFX add-on + +

+ image +

+ + +## Overview + +This Blender add-on allows for compositing with a Nerfstudio render as a background layer by generating a camera path JSON file from the Blender camera path, as well as a way to import Nerfstudio JSON files as a Blender camera baked with the Nerfstudio camera path. This is achieved by importing a mesh or point-cloud representation of the NeRF scene from Nerfstudio into Blender and getting the camera coordinates relative to the transformations of the NeRF representation. Dynamic FOV from the Blender camera is supported and will match the Nerfstudio render. Perspective and equirectangular cameras are also supported. + +## Prerequisites + +[Blender](https://www.blender.org/) on Mac or Windows. The python file add-on can be downloaded from the main repo in the `scripts/blender` folder. Before starting, export the mesh or point cloud representation of the NeRF from Nerfstudio, which will be used as reference for the actual NeRF in the Blender scene. Mesh export at a good quality is preferred, however, if the export is not clear or the NeRF is very large, a detailed point cloud export will also work. + +## Add-on Setup Instructions + +1. Open a new or existing scene to add the NeRF background in. + + +2. Install and enable the add-on in Blender in Edit → Preferences → Add-Ons. The add-on will be visible in the Render Properties tab on the right panel. +

+ image + image +

+ +3. Import the mesh or point cloud representation of the NeRF into the scene. It is preferred that a mesh is used at a good enough fidelity. You may need to crop the mesh further. Since it is used as a reference and won't be visible in the final render, only the parts that the blender animation will interact with may be necessary to import. + +4. Resize, position, or rotate the NeRF representation to fit your scene. + + +## Generate Nerfstudio JSON Camera Path from Blender Camera + +1. There are a few ways to hide the reference mesh for the Blender render + - In object properties, select "Shadow Catcher". This makes the representation invisible in the render, but all shadows cast on it will render. You may have to switch to the cycles renderer to see the shadow catcher option. + image + + - Note: This may not give ideal results if the mesh is not very clear or occludes other objects in the scene. If this is the case, you can hide the mesh from the render instead by clicking the camera button in the Outliner next to its name. + image + + +2. Verify that the animation plays and the NeRF representation does not occlude the camera. +3. Go to the Nerfstudio Add-on in Render Properties and expand the "Nerfstudio Path Generator" tab in the panel. Use the object selector to select the NeRF representation. Then, select the file path for the output JSON camera path file. +4. Click "Generate JSON file". The output JSON file is named `camera_path_blender.json`. +image + + +5. Render the NeRF with the generated camera path using Nerfstudio in the command prompt or terminal. + +6. Before rendering the Blender animation, go to the Render Properties and in the Film settings select "Transparent" so that the render will be rendered with a clear background to allow it to be composited over the NeRF render. +image + + +7. Now the scene can be rendered and composited over the camera aligned Nerfstudio render. +image + +### Examples + +

+ image + image +

+ +### Additional details + +- You can also apply an environment texture to the Blender scene by using Nerfstudio to render an equirectangular image (360 image) of the NeRF from a place in the scene. +- The settings for the Blender equirectangular camera are: "Panoramic" camera type and panorama type of "Equirectangular". +image + +- The generated JSON camera path follows the user specified frame start, end, and step fields in the Output Properties in Blender. The JSON file specifies the user specified x and y render resolutions at the given % in the Output Properties. +- The add-on computes the camera coordinates based on the active camera in the scene. +- FOV animated changes of the camera will be matched with the NeRF render. +- Perspective and equirectangular cameras are supported and can be selected within Blender. +- The generated JSON file can be imported into Nerfstudio. Each keyframe of the camera transform in the frame sequence in Blender will be a keyframe in Nerfstudio. The exported JSON camera path is baked, where each frame in the sequence is a keyframe. This is to ensure that frame interpolation across Nerfstudio and Blender do not differ. + image +- It is recommended to run the camera path in the Nerfstudio web interface with the NeRF to ensure that the NeRF is visible throughout the camera path. +- The fps and keyframe timestamps are based on the "Frame Rate" setting in the Output Properties in Blender. +- The NeRF representation can also be transformed (position, rotation, and scale) as well as animated. +- It is recommended to export a high fidelity mesh as the NeRF representation from Nerfstudio. However if that is not possible or the scene is too large, a point cloud representation also works. +- For compositing, it is recommended to convert the video render into image frames to ensure the Blender and NeRF renders are in sync. +- Currently, dynamic camera focus is not supported. +- Fisheye and orthographic cameras are not supported. + +## Create Blender Camera from Nerfstudio JSON Camera Path + +

+ image +

+ + +1. Expand the "Nerfstudio Camera Generator" tab in the panel. After inputting the NeRF representation, select the JSON Nerfstudio file and click "Create Camera from JSON" + +2. A new camera named "NerfstudioCamera" should appear in the viewport with the camera path and FOV of the input file. This camera's type will match the Nerfstudio input file, except fisheye cameras. + +### Additional details + +- Since only the camera path, camera type, and FOV are applied on the created Blender camera, the timing and duration of the animation may need to be adjusted. +- Fisheye cameras imported from Nerfstudio are not supported and will default to perspective cameras. +- Animated NeRF representations will not be reflected in the imported camera path animation. +- The newly created camera is not active by default, so you may need to right click and select "Set Active Camera". +- The newly created Blender camera animation is baked, where each frame in the sequence is a keyframe. This is to ensure that frame interpolation across Nerfstudio and Blender do not differ. +- The resolution settings from the input JSON file do not affect the Blender render settings +- Scale of the camera is not keyframed from the Nerfstudio camera path. +- This newly created camera has a sensor fit of "Vertical" + + +## Implementation Details + +For generating the JSON camera path, we iterate over the scene frame sequence (from the start to the end with step intervals) and get the camera 4x4 world matrix at each frame. The world transformation matrix gives the position, rotation, and scale of the camera. We then obtain the world matrix of the NeRF representation at each frame and transform the camera coordinates with this to get the final camera world matrix. This allows us to re-position, rotate, and scale the NeRF representation in Blender and generate the right camera path to render the NeRF accordingly in Nerfstudio. Additionally, we calculate the FOV of the camera at each frame based on the sensor fit (horizontal or vertical), angle of view, and aspect ratio. +Next, we construct the list of keyframes which is very similar to the world matrices of the transformed camera matrix. +Camera properties in the JSON file are based on user specified fields such as resolution (user specified in Output Properties in Blender), camera type (Perspective or Equirectangular). In the JSON file, `aspect` is specified as 1.0, `smoothness_value` is set to 0, and `is_cycle` is set to false. The Nerfstudio render is the fps specified in Blender where the duration is the total number of frames divided by the fps. +Finally, we construct the full JSON object and write it to the file path specified by the user. + +For generating the camera from the JSON file, we create a new Blender camera based on the input file and iterate through the `camera_path` field in the JSON to get the world matrix of the object from the `matrix_to_world` and similarly get the FOV from the `fov` fields. At each iteration, we set the camera to these parameters and insert a keyframe based on the position, rotation, and scale of the camera as well as the focal length of the camera based on the vertical FOV input. + diff --git a/docs/quickstart/custom_dataset.md b/docs/quickstart/custom_dataset.md index ea508a661..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 @@ -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 @@ -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/data_conventions.md b/docs/quickstart/data_conventions.md index 6cd959274..34324e30e 100644 --- a/docs/quickstart/data_conventions.md +++ b/docs/quickstart/data_conventions.md @@ -18,38 +18,49 @@ 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 +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. -**Camera extrinsics** +```json +{ + // ... + "frames": [ + { + "fl_x": 1234 + } + ] +} +``` + +### 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. ```json { - // ... intrinsics parameters + // ... "frames": [ { "file_path": "images/frame_00001.jpeg", @@ -63,11 +74,51 @@ 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 diff --git a/docs/quickstart/export_geometry.md b/docs/quickstart/export_geometry.md index 0a50e8a0d..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 @@ -42,7 +40,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/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 45111c373..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 @@ -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 68da40c82..f2020916f 100644 --- a/nerfstudio/cameras/cameras.py +++ b/nerfstudio/cameras/cameras.py @@ -16,19 +16,25 @@ Camera Models """ import base64 +import importlib import math +import os from dataclasses import dataclass +from distutils.util import strtobool from enum import Enum, auto from typing import Dict, List, Optional, Tuple, Union import cv2 import torch import torchvision +from torch.nn import Parameter from torchtyping import TensorType +import nerfstudio.utils.math import nerfstudio.utils.poses as pose_utils from nerfstudio.cameras import camera_utils from nerfstudio.cameras.rays import RayBundle +from nerfstudio.data.scene_box import SceneBox from nerfstudio.utils.tensor_dataclass import TensorDataclass @@ -308,6 +314,7 @@ class Cameras(TensorDataclass): distortion_params_delta: Optional[TensorType["num_rays":..., 6]] = None, keep_shape: Optional[bool] = None, disable_distortion: bool = False, + aabb_box: SceneBox = None, ) -> RayBundle: """Generates rays for the given camera indices. @@ -350,6 +357,7 @@ class Cameras(TensorDataclass): keeping dimensions. If False, we flatten at the end. If True, then we keep the shape of the camera_indices and coords tensors (if we can). disable_distortion: If True, disables distortion. + aabb_box: if not None will calculate nears and fars of the ray according to aabb box intesection Returns: Rays for the given camera indices and coords. @@ -449,6 +457,31 @@ class Cameras(TensorDataclass): if keep_shape is False: raybundle = raybundle.flatten() + if aabb_box: + with torch.no_grad(): + tensor_aabb = Parameter(aabb_box.aabb.flatten(), requires_grad=False) + + rays_o = raybundle.origins.contiguous() + rays_d = raybundle.directions.contiguous() + + tensor_aabb = tensor_aabb.to(rays_o.device) + shape = rays_o.shape + + rays_o = rays_o.reshape((-1, 3)) + rays_d = rays_d.reshape((-1, 3)) + + if strtobool(os.environ.get("INTERSECT_WITH_NERFACC", "TRUE")): + nerfacc = importlib.import_module("nerfacc") + t_min, t_max = nerfacc.ray_aabb_intersect(rays_o, rays_d, tensor_aabb) + else: + t_min, t_max = nerfstudio.utils.math.intersect_aabb(rays_o, rays_d, tensor_aabb) + + t_min = t_min.reshape([shape[0], shape[1], 1]) + t_max = t_max.reshape([shape[0], shape[1], 1]) + + raybundle.nears = t_min + raybundle.fars = t_max + # TODO: We should have to squeeze the last dimension here if we started with zero batch dims, but never have to, # so there might be a rogue squeeze happening somewhere, and this may cause some unintended behaviour # that we haven't caught yet with tests 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/configs/method_configs.py b/nerfstudio/configs/method_configs.py index a587f2202..14ed3c8a2 100644 --- a/nerfstudio/configs/method_configs.py +++ b/nerfstudio/configs/method_configs.py @@ -261,6 +261,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( @@ -278,6 +281,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( 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..0980a62ac 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 @@ -136,12 +136,12 @@ class Nerfstudio(DataParser): if not distort_fixed: distort.append( camera_utils.get_distortion_params( - k1=float(meta["k1"]) if "k1" in meta else 0.0, - k2=float(meta["k2"]) if "k2" in meta else 0.0, - k3=float(meta["k3"]) if "k3" in meta else 0.0, - k4=float(meta["k4"]) if "k4" in meta else 0.0, - p1=float(meta["p1"]) if "p1" in meta else 0.0, - p2=float(meta["p2"]) if "p2" in meta else 0.0, + k1=float(frame["k1"]) if "k1" in frame else 0.0, + k2=float(frame["k2"]) if "k2" in frame else 0.0, + k3=float(frame["k3"]) if "k3" in frame else 0.0, + k4=float(frame["k4"]) if "k4" in frame else 0.0, + p1=float(frame["p1"]) if "p1" in frame else 0.0, + p2=float(frame["p2"]) if "p2" in frame else 0.0, ) ) @@ -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/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/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 63d7cea05..b8632839c 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 @@ -137,7 +139,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( @@ -314,7 +316,7 @@ class Trainer: loaded_state = torch.load(load_path, map_location="cpu") self._start_step = loaded_state["step"] + 1 # load the checkpoints for pipeline, optimizers, and gradient scalar - self.pipeline.load_pipeline(loaded_state["pipeline"]) + self.pipeline.load_pipeline(loaded_state["pipeline"], loaded_state["step"]) self.optimizers.load_optimizers(loaded_state["optimizers"]) self.grad_scaler.load_state_dict(loaded_state["scalers"]) CONSOLE.print(f"done loading checkpoint from {load_path}") 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/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/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 3207a6026..aa3cd3f3c 100644 --- a/nerfstudio/field_components/field_heads.py +++ b/nerfstudio/field_components/field_heads.py @@ -85,7 +85,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/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/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 daaa69c54..7fcfe0419 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..a894da854 100644 --- a/nerfstudio/model_components/ray_generators.py +++ b/nerfstudio/model_components/ray_generators.py @@ -29,20 +29,20 @@ 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: 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. 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..e41416053 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 """ @@ -449,6 +449,15 @@ class VolumetricSampler(Sampler): rays_o = ray_bundle.origins.contiguous() rays_d = ray_bundle.directions.contiguous() + + if ray_bundle.nears is not None and ray_bundle.fars is not None: + t_min = ray_bundle.nears.contiguous().reshape(-1) + t_max = ray_bundle.fars.contiguous().reshape(-1) + + else: + t_min = None + t_max = None + if ray_bundle.camera_indices is not None: camera_indices = ray_bundle.camera_indices.contiguous() else: @@ -457,6 +466,8 @@ class VolumetricSampler(Sampler): ray_indices, starts, ends = nerfacc.ray_marching( rays_o=rays_o, rays_d=rays_d, + t_min=t_min, + t_max=t_max, scene_aabb=self.scene_aabb, grid=self.occupancy_grid, # this is a workaround - using density causes crash and damage quality. should be fixed diff --git a/nerfstudio/model_components/renderers.py b/nerfstudio/model_components/renderers.py index 947b0ce63..9b48c22c8 100644 --- a/nerfstudio/model_components/renderers.py +++ b/nerfstudio/model_components/renderers.py @@ -26,8 +26,9 @@ Example: rgb = rgb_renderer(rgb=field_outputs[FieldHeadNames.RGB], weights=weights) """ +import contextlib import math -from typing import Optional, Union +from typing import Generator, Optional, Union import nerfacc import torch @@ -38,6 +39,20 @@ from typing_extensions import Literal from nerfstudio.cameras.rays import RaySamples from nerfstudio.utils.math import components_from_spherical_harmonics +BACKGROUND_MODE_OVERRIDE: Optional[Literal["last_sample", "black", "random"]] = None + + +@contextlib.contextmanager +def background_mode_override_context(mode: Literal["last_sample", "black"]) -> Generator[None, None, None]: + """Context manager for setting background mode.""" + global BACKGROUND_MODE_OVERRIDE # pylint: disable=global-statement + old_background_mode = BACKGROUND_MODE_OVERRIDE + try: + BACKGROUND_MODE_OVERRIDE = mode + yield + finally: + BACKGROUND_MODE_OVERRIDE = old_background_mode + class RGBRenderer(nn.Module): """Standard volumetic rendering. @@ -55,7 +70,7 @@ class RGBRenderer(nn.Module): cls, rgb: TensorType["bs":..., "num_samples", 3], weights: TensorType["bs":..., "num_samples", 1], - background_color: Union[Literal["random", "last_sample"], TensorType[3]] = "random", + background_color: Union[Literal["random", "black", "last_sample"], TensorType[3]] = "random", ray_indices: Optional[TensorType["num_samples"]] = None, num_rays: Optional[int] = None, ) -> TensorType["bs":..., 3]: @@ -81,10 +96,14 @@ class RGBRenderer(nn.Module): comp_rgb = torch.sum(weights * rgb, dim=-2) accumulated_weight = torch.sum(weights, dim=-2) + if BACKGROUND_MODE_OVERRIDE is not None: + background_color = BACKGROUND_MODE_OVERRIDE if background_color == "last_sample": background_color = rgb[..., -1, :] if background_color == "random": background_color = torch.rand_like(comp_rgb).to(rgb.device) + if background_color == "black": + background_color = torch.zeros_like(comp_rgb).to(rgb.device) assert isinstance(background_color, torch.Tensor) comp_rgb = comp_rgb + background_color.to(weights.device) * (1.0 - accumulated_weight) diff --git a/nerfstudio/models/base_model.py b/nerfstudio/models/base_model.py index 6be459343..3cc5fa2ec 100644 --- a/nerfstudio/models/base_model.py +++ b/nerfstudio/models/base_model.py @@ -74,6 +74,7 @@ class Model(nn.Module): super().__init__() self.config = config self.scene_box = scene_box + self.render_aabb = None # the box that we want to render - should be a subset of scene_box self.num_train_data = num_train_data self.kwargs = kwargs self.collider = None @@ -209,3 +210,11 @@ class Model(nn.Module): """ state = {key.replace("module.", ""): value for key, value in loaded_state["model"].items()} self.load_state_dict(state) # type: ignore + + def update_to_step(self, step: int) -> None: + """Called when loading a model from a checkpoint. Sets any model parameters that change over + training to the correct value, based on the training step of the checkpoint. + + Args: + step: training step of the loaded checkpoint + """ 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/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 diff --git a/nerfstudio/models/nerfacto.py b/nerfstudio/models/nerfacto.py index 6d43b227a..42ea0f50a 100644 --- a/nerfstudio/models/nerfacto.py +++ b/nerfstudio/models/nerfacto.py @@ -98,9 +98,9 @@ class NerfactoModelConfig(ModelConfig): """Proposal loss multiplier.""" distortion_loss_mult: float = 0.002 """Distortion loss multiplier.""" - orientation_loss_mult: float = 0.01 - """Orientation loss multipier on computed normals.""" - pred_normal_loss_mult: float = 0.0003 + orientation_loss_mult: float = 0.0001 + """Orientation loss multiplier on computed normals.""" + pred_normal_loss_mult: float = 0.001 """Predicted normal loss multiplier.""" use_proposal_weight_anneal: bool = True """Whether to use proposal weight annealing.""" diff --git a/nerfstudio/models/tensorf.py b/nerfstudio/models/tensorf.py index 11e6e24bc..60fec9706 100644 --- a/nerfstudio/models/tensorf.py +++ b/nerfstudio/models/tensorf.py @@ -114,7 +114,8 @@ class TensoRFModel(Model): def reinitialize_optimizer( self, training_callback_attributes: TrainingCallbackAttributes, step: int # pylint: disable=unused-argument ): - resolution = self.upsampling_steps.pop(0) + index = self.upsampling_iters.index(step) + resolution = self.upsampling_steps[index] # upsample the position and direction grids self.field.density_encoding.upsample_grid(resolution) @@ -143,6 +144,19 @@ class TensoRFModel(Model): ] return callbacks + def update_to_step(self, step: int) -> None: + if step < self.upsampling_iters[0]: + return + + new_iters = list(self.upsampling_iters) + [step + 1] + new_iters.sort() + + index = new_iters.index(step + 1) + new_grid_resolution = self.upsampling_steps[index - 1] + + self.field.density_encoding.upsample_grid(new_grid_resolution) # type: ignore + self.field.color_encoding.upsample_grid(new_grid_resolution) # type: ignore + def populate_modules(self): """Set the fields and modules""" super().populate_modules() diff --git a/nerfstudio/pipelines/base_pipeline.py b/nerfstudio/pipelines/base_pipeline.py index d63710cc0..46b479b94 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 @@ -159,11 +159,12 @@ class Pipeline(nn.Module): def get_average_eval_image_metrics(self, step: Optional[int] = None): """Iterate over all the images in the eval dataset and get the average.""" - def load_pipeline(self, loaded_state: Dict[str, Any]) -> None: + def load_pipeline(self, loaded_state: Dict[str, Any], step: int) -> None: """Load the checkpoint from the given path Args: loaded_state: pre-trained model state dict + step: training step of the loaded checkpoint """ def get_training_callbacks( @@ -198,7 +199,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 @@ -355,20 +356,16 @@ class VanillaPipeline(Pipeline): self.train() return metrics_dict - def load_pipeline(self, loaded_state: Dict[str, Any]) -> None: + def load_pipeline(self, loaded_state: Dict[str, Any], step: int) -> None: """Load the checkpoint from the given path Args: loaded_state: pre-trained model state dict + step: training step of the loaded checkpoint """ 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._model.update_to_step(step) + self.load_state_dict(state, strict=False) def get_training_callbacks( self, training_callback_attributes: TrainingCallbackAttributes diff --git a/nerfstudio/process_data/colmap_utils.py b/nerfstudio/process_data/colmap_utils.py index c36cc7d5f..9db20647f 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 ( @@ -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 = { @@ -663,7 +678,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..e6e58f184 100644 --- a/nerfstudio/process_data/process_data_utils.py +++ b/nerfstudio/process_data/process_data_utils.py @@ -14,12 +14,15 @@ """Helper utils for processing data into the nerfstudio format.""" +import os import shutil import sys 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 @@ -42,6 +45,29 @@ CAMERA_MODELS = { } +def get_image_filenames(directory: Path, max_num_images: int = -1) -> Tuple[List[Path], int]: + """Returns a list of image filenames in a directory. + + Args: + dir: Path to the directory. + max_num_images: The maximum number of images to return. -1 means no limit. + Returns: + A tuple of A list of image filenames, number of original image paths. + """ + allowed_exts = [".jpg", ".jpeg", ".png", ".tif", ".tiff"] + image_paths = sorted([p for p in directory.glob("[!.]*") if p.suffix.lower() in allowed_exts]) + num_orig_images = len(image_paths) + + if max_num_images != -1 and num_orig_images > max_num_images: + idx = np.round(np.linspace(0, num_orig_images - 1, max_num_images)).astype(int) + else: + idx = np.arange(num_orig_images) + + image_filenames = list(np.array(image_paths)[idx]) + + return image_filenames, num_orig_images + + def get_num_frames_in_video(video: Path) -> int: """Returns the number of frames in a video. @@ -93,7 +119,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}" @@ -141,7 +167,7 @@ def copy_images_list( file_type = image_paths[0].suffix filename = f"frame_%05d{file_type}" crop = f"crop=iw-{crop_border_pixels*2}:ih-{crop_border_pixels*2}" - ffmpeg_cmd = f"ffmpeg -y -i {image_dir / filename} -q:v 2 -vf {crop} {image_dir / filename}" + ffmpeg_cmd = f"ffmpeg -y -noautorotate -i {image_dir / filename} -q:v 2 -vf {crop} {image_dir / filename}" run_command(ffmpeg_cmd, verbose=verbose) num_frames = len(image_paths) @@ -201,15 +227,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 -noautorotate -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)] @@ -268,3 +296,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/nerfstudio/process_data/realitycapture_utils.py b/nerfstudio/process_data/realitycapture_utils.py new file mode 100644 index 000000000..eaba5aeb0 --- /dev/null +++ b/nerfstudio/process_data/realitycapture_utils.py @@ -0,0 +1,119 @@ +# 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. + +"""Helper utils for processing polycam data into the nerfstudio format.""" + +import csv +import json +from pathlib import Path +from typing import List + +import numpy as np +from PIL import Image +from rich.console import Console + +from nerfstudio.process_data.process_data_utils import CAMERA_MODELS + +CONSOLE = Console(width=120) + + +def realitycapture_to_json( + image_filename_map: List[Path], + csv_filename: Path, + output_dir: Path, +) -> List[str]: + """Convert RealityCapture data into a nerfstudio dataset. + + Args: + image_filenames: List of paths to the original images. + csv_filename: Path to the csv file containing the camera poses. + output_dir: Path to the output directory. + verbose: Whether to print verbose output. + + Returns: + Summary of the conversion. + """ + data = {} + data["camera_model"] = CAMERA_MODELS["perspective"].value + # Needs to be a string for camera_utils.auto_orient_and_center_poses + data["orientation_override"] = "none" + + frames = [] + + with open(csv_filename, encoding="UTF-8") as file: + reader = csv.DictReader(file) + cameras = {} + for row in reader: + for column, value in row.items(): + cameras.setdefault(column, []).append(value) + + img = np.array(Image.open(output_dir / image_filename_map[cameras["#name"][0].split(".")[0]])) + height, width, _ = img.shape + + data["h"] = int(height) + data["w"] = int(width) + + for i, name in enumerate(cameras["#name"]): + frame = {} + frame["file_path"] = image_filename_map[name.split(".")[0]].as_posix() + frame["fl_x"] = float(cameras["f"][i]) * max(width, height) / 36 + frame["fl_y"] = float(cameras["f"][i]) * max(width, height) / 36 + # TODO: Unclear how to get the principal point from RealityCapture, here a guess... + frame["cx"] = float(cameras["px"][i]) / 36.0 + width / 2.0 + frame["cy"] = float(cameras["py"][i]) / 36.0 + height / 2.0 + # TODO: Not sure if RealityCapture uses this distortion model + frame["k1"] = cameras["k1"][i] + frame["k2"] = cameras["k2"][i] + frame["k3"] = cameras["k3"][i] + frame["k4"] = cameras["k4"][i] + frame["p1"] = cameras["t1"][i] + frame["p2"] = cameras["t2"][i] + + # Transform matrix to nerfstudio format. Please refer to the documentation for coordinate system conventions. + rot = _get_rotation_matrix(-float(cameras["heading"][i]), float(cameras["pitch"][i]), float(cameras["roll"][i])) + + transform = np.eye(4) + transform[:3, :3] = rot + transform[:3, 3] = np.array([float(cameras["x"][i]), float(cameras["y"][i]), float(cameras["alt"][i])]) + + frame["transform_matrix"] = transform.tolist() + frames.append(frame) + data["frames"] = frames + + with open(output_dir / "transforms.json", "w", encoding="utf-8") as f: + json.dump(data, f, indent=4) + + summary = [] + if len(frames) < len(image_filename_map): + summary.append(f"Missing camera data for {len(image_filename_map) - len(frames)} frames.") + summary.append(f"Final dataset is {len(frames)} frames.") + + return summary + + +def _get_rotation_matrix(yaw, pitch, roll): + """Returns a rotation matrix given euler angles.""" + + s_yaw = np.sin(np.deg2rad(yaw)) + c_yaw = np.cos(np.deg2rad(yaw)) + s_pitch = np.sin(np.deg2rad(pitch)) + c_pitch = np.cos(np.deg2rad(pitch)) + s_roll = np.sin(np.deg2rad(roll)) + c_roll = np.cos(np.deg2rad(roll)) + + rot_x = np.array([[1, 0, 0], [0, c_pitch, -s_pitch], [0, s_pitch, c_pitch]]) + rot_y = np.array([[c_roll, 0, s_roll], [0, 1, 0], [-s_roll, 0, c_roll]]) + rot_z = np.array([[c_yaw, -s_yaw, 0], [s_yaw, c_yaw, 0], [0, 0, 1]]) + + return rot_z @ rot_x @ rot_y diff --git a/nerfstudio/utils/colormaps.py b/nerfstudio/utils/colormaps.py index 9d51606c7..18d7aa86f 100644 --- a/nerfstudio/utils/colormaps.py +++ b/nerfstudio/utils/colormaps.py @@ -36,6 +36,7 @@ def apply_colormap(image: TensorType["bs":..., 1], cmap="viridis") -> TensorType colormap = cm.get_cmap(cmap) colormap = torch.tensor(colormap.colors).to(image.device) # type: ignore + image = torch.nan_to_num(image, 0) image_long = (image * 255).long() image_long_min = torch.min(image_long) image_long_max = torch.max(image_long) diff --git a/nerfstudio/utils/eval_utils.py b/nerfstudio/utils/eval_utils.py index 40f9e212e..3431b20a3 100644 --- a/nerfstudio/utils/eval_utils.py +++ b/nerfstudio/utils/eval_utils.py @@ -59,7 +59,7 @@ def eval_load_checkpoint(config: TrainerConfig, pipeline: Pipeline) -> Path: load_path = config.load_dir / f"step-{load_step:09d}.ckpt" assert load_path.exists(), f"Checkpoint {load_path} does not exist" loaded_state = torch.load(load_path, map_location="cpu") - pipeline.load_pipeline(loaded_state["pipeline"]) + pipeline.load_pipeline(loaded_state["pipeline"], loaded_state["step"]) CONSOLE.print(f":white_check_mark: Done loading checkpoint from {load_path}") return load_path @@ -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 cf93874bf..8e1ebe24b 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) @@ -197,3 +197,49 @@ def expected_sin(x_means: torch.Tensor, x_vars: torch.Tensor) -> torch.Tensor: def safe_normalize(x, eps=1e-20): """Safe normalization w/o divide by zero issues""" return x / torch.sqrt(torch.clamp(torch.sum(x * x, -1, keepdim=True), min=eps)) + + +def intersect_aabb(origins, directions, aabb): + """ + pytorch implementation of ray intersection with AABB box + :param origin: N,3 tensor of 3d positions + :param direction: N,3 tensor of normalized directions + :param aabb: 6,1 array of aabb box in the form of [x_min, y_min, z_min, x_max, y_max, z_max] + :return: t_min, t_max - two tensors of shapes N,1 representing the intersection signed distance from + the origin. t_min is clipped to 0 in case it is negative, in case of no intersection t_min is 1e10. + """ + + max_bound = 1e10 + + tx_min = (aabb[0] - origins[:, 0]) / directions[:, 0] + tx_max = (aabb[3] - origins[:, 0]) / directions[:, 0] + t_min = torch.min(tx_min, tx_max) + t_max = torch.max(tx_min, tx_max) + + ty_min_temp = (aabb[1] - origins[:, 1]) / directions[:, 1] + ty_max_temp = (aabb[4] - origins[:, 1]) / directions[:, 1] + ty_min = torch.min(ty_min_temp, ty_max_temp) + ty_max = torch.max(ty_min_temp, ty_max_temp) + + cond = torch.logical_or((t_min > ty_max), (ty_min > t_max)) + t_min = torch.where(cond, max_bound, t_min) + t_max = torch.where(cond, max_bound, t_max) + + t_min = torch.max(t_min, ty_min) + t_max = torch.min(t_max, ty_max) + + tz_min_temp = (aabb[2] - origins[:, 2]) / directions[:, 2] + tz_max_temp = (aabb[5] - origins[:, 2]) / directions[:, 2] + tz_min = torch.min(tz_min_temp, tz_max_temp) + tz_max = torch.max(tz_min_temp, tz_max_temp) + + cond = torch.logical_or((t_min > tz_max), tz_min > t_max) + t_min = torch.where(cond, max_bound, t_min) + t_max = torch.where(cond, max_bound, t_max) + + t_min = torch.max(t_min, tz_min) + t_max = torch.min(t_max, tz_max) + t_min = torch.where(t_min > 0, t_min, 0) + t_max = torch.where(t_min == max_bound, max_bound, t_max) + + return t_min, t_max 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/app/package.json b/nerfstudio/viewer/app/package.json index 78d4997f3..848e1dddc 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-20-0", "private": true, "dependencies": { "@emotion/react": "^11.10.4", diff --git a/nerfstudio/viewer/app/src/modules/ConfigPanel/ConfigPanel.jsx b/nerfstudio/viewer/app/src/modules/ConfigPanel/ConfigPanel.jsx index 2b03f2cc1..e710b6733 100644 --- a/nerfstudio/viewer/app/src/modules/ConfigPanel/ConfigPanel.jsx +++ b/nerfstudio/viewer/app/src/modules/ConfigPanel/ConfigPanel.jsx @@ -6,6 +6,22 @@ import { WebSocketContext } from '../WebSocket/WebSocket'; const msgpack = require('msgpack-lite'); +function dispatch_and_send(websocket, dispatch, path, data) { + dispatch({ + type: 'write', + path, + data, + }); + if (websocket.readyState === WebSocket.OPEN) { + const message = msgpack.encode({ + type: 'write', + path, + data, + }); + websocket.send(message); + } +} + export function RenderControls() { // connection status indicators const websocket = useContext(WebSocketContext).socket; @@ -27,136 +43,58 @@ export function RenderControls() { const target_train_util = useSelector( (state) => state.renderingState.targetTrainUtil, ); - const render_time = useSelector( - (state) => state.renderingState.renderTime, + const render_time = useSelector((state) => state.renderingState.renderTime); + const crop_enabled = useSelector( + (state) => state.renderingState.crop_enabled, ); + const box_size = useSelector((state) => state.renderingState.box_size); + + const crop_scale = useSelector((state) => state.renderingState.crop_scale); + + const crop_center = useSelector((state) => state.renderingState.crop_center); + const dispatch = useDispatch(); - const set_max_resolution = (value) => { - if (websocket.readyState === WebSocket.OPEN) { - dispatch({ - type: 'write', - path: 'renderingState/maxResolution', - data: value, - }); - const cmd = 'write'; - const path = 'renderingState/maxResolution'; - const data = { - type: cmd, - path, - data: value, - }; - const message = msgpack.encode(data); - websocket.send(message); - } - }; - - const set_target_train_util = (value) => { - if (websocket.readyState === WebSocket.OPEN) { - dispatch({ - type: 'write', - path: 'renderingState/targetTrainUtil', - data: value, - }); - const cmd = 'write'; - const path = 'renderingState/targetTrainUtil'; - const data = { - type: cmd, - path, - data: value, - }; - const message = msgpack.encode(data); - websocket.send(message); - } - }; - - const set_output_choice = (value) => { - if (websocket.readyState === WebSocket.OPEN) { - dispatch({ - type: 'write', - path: 'renderingState/output_choice', - data: value, - }); - const cmd = 'write'; - const path = 'renderingState/output_choice'; - const data = { - type: cmd, - path, - data: value, - }; - const message = msgpack.encode(data); - websocket.send(message); - } - }; - - const set_colormap_choice = (value) => { - if (websocket.readyState === WebSocket.OPEN) { - dispatch({ - type: 'write', - path: 'renderingState/colormap_choice', - data: value, - }); - const cmd = 'write'; - const path = 'renderingState/colormap_choice'; - const data = { - type: cmd, - path, - data: value, - }; - const message = msgpack.encode(data); - websocket.send(message); - } - }; - const [display_render_time, set_display_render_time] = useState(false); - const receive_temporal_dist = e => { - const msg = msgpack.decode(new Uint8Array(e.data)); - if (msg.path === "/model/has_temporal_distortion") { - set_display_render_time(msg.data === "true"); - websocket.removeEventListener("message", receive_temporal_dist); - } - } - websocket.addEventListener('message', receive_temporal_dist); - - const set_render_time = (value) => { - if (websocket.readyState === WebSocket.OPEN) { - const path = 'renderingState/render_time'; - dispatch({ - type: 'write', - path, - data: value, - }); - const cmd = 'write'; - const data = { - type: cmd, - path, - data: value, - }; - const message = msgpack.encode(data); - websocket.send(message); + const receive_temporal_dist = (e) => { + const msg = msgpack.decode(new Uint8Array(e.data)); + if (msg.path === '/model/has_temporal_distortion') { + set_display_render_time(msg.data === 'true'); + websocket.removeEventListener('message', receive_temporal_dist); } }; + websocket.addEventListener('message', receive_temporal_dist); const [, setControls] = useControls( () => ({ // training speed - 'Train Speed': buttonGroup({ - Fast: () => - setControls({ target_train_util: 0.9, max_resolution: 512 }), - Balanced: () => - setControls({ target_train_util: 0.7, max_resolution: 1024 }), - Slow: () => - setControls({ target_train_util: 0.1, max_resolution: 2048 }), + SpeedButtonGroup: buttonGroup({ + label: `Train Speed`, + hint: 'Select the training speed, affects viewer render quality, not final render quality', + opts: { + Fast: () => + setControls({ target_train_util: 0.9, max_resolution: 512 }), + Balanced: () => + setControls({ target_train_util: 0.7, max_resolution: 1024 }), + Slow: () => + setControls({ target_train_util: 0.1, max_resolution: 2048 }), + }, }), // output_options output_options: { label: 'Output Render', options: [...new Set(outputOptions)], value: outputChoice, + hint: 'Select the output to render', onChange: (v) => { - set_output_choice(v); + dispatch_and_send( + websocket, + dispatch, + 'renderingState/output_choice', + v, + ); }, }, // colormap_options @@ -164,8 +102,14 @@ export function RenderControls() { label: 'Colormap', options: colormapOptions, value: colormapChoice, + hint: 'Select the colormap to use', onChange: (v) => { - set_colormap_choice(v); + dispatch_and_send( + websocket, + dispatch, + 'renderingState/colormap_choice', + v, + ); }, disabled: colormapOptions.length === 1, }, @@ -176,8 +120,14 @@ export function RenderControls() { min: 0, max: 1, step: 0.05, + hint: "Target training utilization, 0.0 is slow, 1.0 is fast, doesn't affect final render quality", onChange: (v) => { - set_target_train_util(v); + dispatch_and_send( + websocket, + dispatch, + 'renderingState/targetTrainUtil', + v, + ); }, }, // resolution @@ -187,8 +137,14 @@ export function RenderControls() { min: 256, max: 2048, step: 1, + hint: 'Maximum resolution to render in viewport', onChange: (v) => { - set_max_resolution(v); + dispatch_and_send( + websocket, + dispatch, + 'renderingState/maxResolution', + v, + ); }, }, ' ': buttonGroup({ @@ -197,17 +153,72 @@ export function RenderControls() { '1024px': () => setControls({ max_resolution: 1024 }), '2048px': () => setControls({ max_resolution: 2048 }), }), - // Dynamic NeRF rendering time - ...(display_render_time ? {render_time: { - label: 'Render Timestep', - value: render_time, - min: 0, - max: 1, - step: 0.01, - onChange: (v) => { - set_render_time(v); + // Enable Crop + crop_options: { + label: 'Crop Viewport', + value: crop_enabled, + hint: 'Crop the viewport to the selected box', + onChange: (value) => { + dispatch_and_send( + websocket, + dispatch, + 'renderingState/crop_enabled', + value, + ); }, - }} : {}), + }, + crop_scale: { + label: '| Scale', + value: crop_scale, + min: 0, + max: 10, + step: 0.05, + render: (get) => get('crop_options'), + onChange: (v) => { + dispatch_and_send( + websocket, + dispatch, + 'renderingState/crop_scale', + v, + ); + }, + }, + crop_center: { + label: '| Center', + value: crop_center, + min: -10, + max: 10, + step: 0.05, + render: (get) => get('crop_options'), + onChange: (v) => { + dispatch_and_send( + websocket, + dispatch, + 'renderingState/crop_center', + v, + ); + }, + }, + // Dynamic NeRF rendering time + ...(display_render_time + ? { + render_time: { + label: 'Render Timestep', + value: render_time, + min: 0, + max: 1, + step: 0.01, + onChange: (v) => { + dispatch_and_send( + websocket, + dispatch, + 'renderingState/render_time', + v, + ); + }, + }, + } + : {}), }), [ outputOptions, @@ -215,6 +226,8 @@ export function RenderControls() { colormapOptions, colormapChoice, max_resolution, + crop_enabled, + box_size, target_train_util, render_time, display_render_time, 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 .

- { - setFilename(e.target.value); - }} - value={filename} - variant="standard" - /> +
{cmd}