A PyTorch re-implementation of Neural Radiance Fields

Overview

nerf-pytorch

A PyTorch re-implementation

Project | Video | Paper

Open Tiny-NeRF in Colab

NeRF: Representing Scenes as Neural Radiance Fields for View Synthesis
Ben Mildenhall*1, Pratul P. Srinivasan*1, Matthew Tancik*1, Jonathan T. Barron2, Ravi Ramamoorthi3, Ren Ng1
1UC Berkeley, 2Google Research, 3UC San Diego
*denotes equal contribution

A PyTorch re-implementation of Neural Radiance Fields.

Speed matters!

The current implementation is blazing fast! (~5-9x faster than the original release, ~2-4x faster than this concurrent pytorch implementation)

What's the secret sauce behind this speedup?

Multiple aspects. Besides obvious enhancements such as data caching, effective memory management, etc. I drilled down through the entire NeRF codebase, and reduced data transfer b/w CPU and GPU, vectorized code where possible, and used efficient variants of pytorch ops (wrote some where unavailable). But for these changes, everything else is a faithful reproduction of the NeRF technique we all admire :)

Sample results from the repo

On synthetic data

On real data

Tiny-NeRF on Google Colab

The NeRF code release has an accompanying Colab notebook, that showcases training a feature-limited version of NeRF on a "tiny" scene. It's equivalent PyTorch notebook can be found at the following URL:

https://colab.research.google.com/drive/1rO8xo0TemN67d4mTpakrKrLp03b9bgCX

What is a NeRF?

A neural radiance field is a simple fully connected network (weights are ~5MB) trained to reproduce input views of a single scene using a rendering loss. The network directly maps from spatial location and viewing direction (5D input) to color and opacity (4D output), acting as the "volume" so we can use volume rendering to differentiably render new views.

Optimizing a NeRF takes between a few hours and a day or two (depending on resolution) and only requires a single GPU. Rendering an image from an optimized NeRF takes somewhere between less than a second and ~30 seconds, again depending on resolution.

How to train your NeRF super-quickly!

To train a "full" NeRF model (i.e., using 3D coordinates as well as ray directions, and the hierarchical sampling procedure), first setup dependencies.

Option 1: Using pip

In a new conda or virtualenv environment, run

pip install -r requirements.txt

Option 2: Using conda

Use the provided environment.yml file to install the dependencies into an environment named nerf (edit the environment.yml if you wish to change the name of the conda environment).

conda env create
conda activate nerf

Run training!

Once everything is setup, to run experiments, first edit config/lego.yml to specify your own parameters.

The training script can be invoked by running

python train_nerf.py --config config/lego.yml

Optional: Resume training from a checkpoint

Optionally, if resuming training from a previous checkpoint, run

python train_nerf.py --config config/lego.yml --load-checkpoint path/to/checkpoint.ckpt

Optional: Cache rays from the dataset

An optional, yet simple preprocessing step of caching rays from the dataset results in substantial compute time savings (reduced carbon footprint, yay!), especially when running multiple experiments. It's super-simple: run

python cache_dataset.py --datapath cache/nerf_synthetic/lego/ --halfres False --savedir cache/legocache/legofull --num-random-rays 8192 --num-variations 50

This samples 8192 rays per image from the lego dataset. Each image is 800 x 800 (since halfres is set to False), and 500 such random samples (8192 rays each) are drawn per image. The script takes about 10 minutes to run, but the good thing is, this needs to be run only once per dataset.

NOTE: Do NOT forget to update the cachedir option (under dataset) in your config (.yml) file!

(Full) NeRF on Google Colab

A Colab notebook for the full NeRF model (albeit on low-resolution data) can be accessed here.

Render fun videos (from a pretrained model)

Once you've trained your NeRF, it's time to use that to render the scene. Use the eval_nerf.py script to do that. For the lego-lowres example, this would be

python eval_nerf.py --config pretrained/lego-lowres/config.yml --checkpoint pretrained/lego-lowres/checkpoint199999.ckpt --savedir cache/rendered/lego-lowres

You can create a gif out of the saved images, for instance, by using Imagemagick.

convert cache/rendered/lego-lowres/*.png cache/rendered/lego-lowres.gif

This should give you a gif like this.

A note on reproducibility

All said, this is not an official code release, and is instead a reproduction from the original code (released by the authors here).

The code is thoroughly tested (to the best of my abilities) to match the original implementation (and be much faster)! In particular, I have ensured that

  • Every individual module exactly (numerically) matches that of the TensorFlow implementation. This Colab notebook has all the tests, matching op for op (but is very scratchy to look at)!
  • Training works as expected (for Lego and LLFF scenes).

The organization of code WILL change around a lot, because I'm actively experimenting with this.

Pretrained models: Pretrained models for the following scenes are available in the pretrained directory (all of them are currently lowres). I will continue adding models herein.

# Synthetic (Blender) scenes
chair
drums
hotdog
lego
materials
ship

# Real (LLFF) scenes
fern

Contributing / Issues?

Feel free to raise GitHub issues if you find anything concerning. Pull requests adding additional features are welcome too.

LICENSE

nerf-pytorch is available under the MIT License. For more details see: LICENSE and ACKNOWLEDGEMENTS.

Misc

Also, a shoutout to yenchenlin for his cool PyTorch implementation, whose volume rendering function replaced mine (my initial impl was inefficient in comparison).

Comments
  • Config is not fully applied

    Config is not fully applied

    For example here

    https://github.com/krrish94/nerf-pytorch/blob/a14357da6cada433d28bf11a45c7bcaace76c06e/train_nerf.py#L117-L123

    The hidden_size in the config is never applied... which means it will always be set to the default value 128 no matter what you set in the config file... I suspect that there are still many places where the config is not fully applied, which means your implementation might differ a lot from the original repo.

    I was first astonished at the speed you mentioned in the readme, but now it seems that your model is not the same as the original repo... yours is tinier (hidden_size=128 in contrast to original 256), so no wonder your speed is faster!

    Could you please carefully check again, or mention in the readme that you use a smaller model? Otherwise it is misleading.

    The code is thoroughly tested (to the best of my abilities) to match the original implementation (and be much faster)! In particular, I have ensured that

    Every individual module exactly (numerically) matches that of the TensorFlow implementation. This Colab notebook has all the tests, matching op for op (but is very scratchy to look at)! Training works as expected (for Lego and LLFF scenes).

    opened by kwea123 12
  • Reproducing Table 4 of supplementary material

    Reproducing Table 4 of supplementary material

    Hey,

    Thank you for the awesome work on this implementation.

    I have been playing around with it quite a bit. I however can't get any results close to that of Table 4, found in the supplementary material of the paper. For instance, they report a PSNR of ~30 on the Lego scene of their synthetic dataset.

    In my experiments, either using the pre-trained model of yours or my own trained from scratch, I get a PSNR of only ~20.

    opened by slippylolo 8
  • Getting 'Killed' whenever trying to train

    Getting 'Killed' whenever trying to train

    Hi, Whenever I try to train I am getting 'Killed' as an output. This is the same even when trying to cache rays from the output. Can I have some suggestions for resolving this problem? Thanks in advance.

    opened by joy-alen 4
  • Getting started

    Getting started

    I followed the instructions in the README. After installing, I ran the command

    python train_nerf.py --config config/lego.yml

    and got the following error

    Traceback (most recent call last):
      File "train_nerf.py", line 404, in <module>
        main()
      File "train_nerf.py", line 59, in main
        testskip=cfg.dataset.testskip,
      File "D:\dev\nerf\nerf\load_blender.py", line 44, in load_blender_data
        with open(os.path.join(basedir, f"transforms_{s}.json"), "r") as fp:
    FileNotFoundError: [Errno 2] No such file or directory: 'cache/nerf_synthetic/lego\\transforms_train.json'
    

    This is on Windows with Python 3.7.

    opened by tobysharp 4
  • requirements.txt missing

    requirements.txt missing

    First, great work and thanks for making the effort to port this work to pytorch. In the readme you mention a requirements.txt which is used for installing dependencies, but it looks like it is missing in the repository.

    opened by holzers 2
  • Why multiply dists with normalized ray_directions in volume rendering?

    Why multiply dists with normalized ray_directions in volume rendering?

    What is the point of this line of code? dists = dists * ray_directions[..., None, :].norm(p=2, dim=-1) on line 24 in volume_rendering_utils.py ? The paper only mentions the dists but not multiplying it with the ray directions.

    opened by SrinjaySarkar 1
  • How to download the dataset

    How to download the dataset

    I don't know whether you are using the NERF author's released blender data. I have not find the 'transforms_train.json' in that data. Could you help with this?

    opened by JasonBoy1 1
  • conda environment

    conda environment

    Hello and thank you for great work!

    I’m not sure requrements.txt is fully up to date, so please accept created with care environment.yml. To create an environment simply cd nerf-pytorch and run conda env create. To activate an environment you run conda activate nerf and you’re good to run training! There is no need to go to the torchsearchsorted repo and follow the readme, it’s installed automatically with proper GPU support (cudatoolkit-dev package contains nvcc and sets CUDA_HOME). If you’d like I also can update the README.

    opened by mgrankin 1
  • how to convert the nerf model to onnx format

    how to convert the nerf model to onnx format

    Hi, Lately I have been working on nerf and found your repo really helpful. Is there a way to convert the model to Open Neural Network Exchange (.onnx) format?

    opened by navuboy 0
  • Results of Google Colab's example

    Results of Google Colab's example

    Hi, nice work with NeRF, but I have a question: I try to run the example on https://colab.research.google.com/drive/1L6QExI2lw5xhJ-MLlIwpbgf7rxW7fcz3, but even with 92.450 iter the result is close to 0.17 to Val Loss and 7.6 to PSNR without images for coarse and fine. So, why did this happen? or did I lose something? Adjunct an image with this.

    Captura de Pantalla 2022-07-19 a la(s) 09 42 44

    Another thing I did was uncommenting ReplicateNeRFModel, because another error appeared with this;

    Captura de Pantalla 2022-07-20 a la(s) 13 13 36

    Only with this action did the example run

    model_coarse = ReplicateNeRFModel(
        hidden_size=128,
        num_encoding_fn_xyz=num_encoding_fn_xyz,
        num_encoding_fn_dir=num_encoding_fn_dir,
        include_input_xyz=include_input_xyz,
        include_input_dir=include_input_dir
    )
    # model_coarse = VeryTinyNeRFModel()
    model_coarse.to(device)
    
    # Initialize a fine-resolution model, if specified.
    model_fine = ReplicateNeRFModel(
        hidden_size=128,
        num_encoding_fn_xyz=num_encoding_fn_xyz,
        num_encoding_fn_dir=num_encoding_fn_dir,
        include_input_xyz=include_input_xyz,
        include_input_dir=include_input_dir
    )
    # model_fine = VeryTinyNeRFModel()
    model_fine.to(device)
    

    Thx

    opened by jdiazram 2
  • Tiny Nerf Colab Evaluation Bug

    Tiny Nerf Colab Evaluation Bug

    It looks like when evaluating the loss in the last cell of the colab, the code uses loss = torch.nn.functional.mse_loss(rgb_predicted, target_img)

    But believe this should actually be loss = torch.nn.functional.mse_loss(rgb_predicted, testimg)

    Since we use testpose for rgb_predicted we should compare to testimg not target_img, which is just a random training sample.

    opened by johnmaxh 0
  • about function get_ray_bundle

    about function get_ray_bundle

    thanks for your great work! I have question about getting ray_directions. can you give me some sepcific introduction? ` ii, jj = meshgrid_xy( torch.arange( width, dtype=tform_cam2world.dtype, device=tform_cam2world.device ).to(tform_cam2world), torch.arange( height, dtype=tform_cam2world.dtype, device=tform_cam2world.device ), )

    directions = torch.stack(
        [
            (ii - width * 0.5) / focal_length,
            -(jj - height * 0.5) / focal_length,
            -torch.ones_like(ii),
        ],
        dim=-1,
    )
    ray_directions = torch.sum(
        directions[..., None, :] * tform_cam2world[:3, :3], dim=-1
    )`
    
    opened by UestcJay 2
  • During caching, the --num-variations argument is broken

    During caching, the --num-variations argument is broken

    https://github.com/krrish94/nerf-pytorch/blob/a14357da6cada433d28bf11a45c7bcaace76c06e/cache_dataset.py#L70

    The caching code does loop num-variations times to sample rays from the source images, but it saves the current ray batch into the same file from within the loop, overwriting the file each time. So in the end the cache of each source file only contains the last variation.

    opened by JoanCharmant 0
Owner
Krishna Murthy
PhD candidate @mila-udem @montrealrobotics. Blending robotics and computer vision with deep learning.
Krishna Murthy
A PyTorch implementation of NeRF (Neural Radiance Fields) that reproduces the results.

NeRF-pytorch NeRF (Neural Radiance Fields) is a method that achieves state-of-the-art results for synthesizing novel views of complex scenes. Here are

Yen-Chen Lin 3.2k Jan 8, 2023
A PyTorch re-implementation of Neural Radiance Fields

nerf-pytorch A PyTorch re-implementation Project | Video | Paper NeRF: Representing Scenes as Neural Radiance Fields for View Synthesis Ben Mildenhall

Krishna Murthy 709 Jan 9, 2023
Pytorch implementation for A-NeRF: Articulated Neural Radiance Fields for Learning Human Shape, Appearance, and Pose

A-NeRF: Articulated Neural Radiance Fields for Learning Human Shape, Appearance, and Pose Paper | Website | Data A-NeRF: Articulated Neural Radiance F

Shih-Yang Su 172 Dec 22, 2022
Neural Radiance Fields Using PyTorch

This project is a PyTorch implementation of Neural Radiance Fields (NeRF) for reproduction of results whilst running at a faster speed.

Vedant Ghodke 1 Feb 11, 2022
SatelliteNeRF - PyTorch-based Neural Radiance Fields adapted to satellite domain

SatelliteNeRF PyTorch-based Neural Radiance Fields adapted to satellite domain.

Kai Zhang 46 Nov 20, 2022
Unofficial & improved implementation of NeRF--: Neural Radiance Fields Without Known Camera Parameters

[Unofficial code-base] NeRF--: Neural Radiance Fields Without Known Camera Parameters [ Project | Paper | Official code base ] ⬅️ Thanks the original

Jianfei Guo 239 Dec 22, 2022
This is a JAX implementation of Neural Radiance Fields for learning purposes.

learn-nerf This is a JAX implementation of Neural Radiance Fields for learning purposes. I've been curious about NeRF and its follow-up work for a whi

Alex Nichol 62 Dec 20, 2022
A minimal TPU compatible Jax implementation of NeRF: Representing Scenes as Neural Radiance Fields for View Synthesis

NeRF Minimal Jax implementation of NeRF: Representing Scenes as Neural Radiance Fields for View Synthesis. Result of Tiny-NeRF RGB Depth

Soumik Rakshit 11 Jul 24, 2022
Implementation of "Generalizable Neural Performer: Learning Robust Radiance Fields for Human Novel View Synthesis"

Generalizable Neural Performer: Learning Robust Radiance Fields for Human Novel View Synthesis Abstract: This work targets at using a general deep lea

null 163 Dec 14, 2022
This is the code for Deformable Neural Radiance Fields, a.k.a. Nerfies.

Deformable Neural Radiance Fields This is the code for Deformable Neural Radiance Fields, a.k.a. Nerfies. Project Page Paper Video This codebase conta

Google 1k Jan 9, 2023
Open source repository for the code accompanying the paper 'Non-Rigid Neural Radiance Fields Reconstruction and Novel View Synthesis of a Deforming Scene from Monocular Video'.

Non-Rigid Neural Radiance Fields This is the official repository for the project "Non-Rigid Neural Radiance Fields: Reconstruction and Novel View Synt

Facebook Research 296 Dec 29, 2022
(Arxiv 2021) NeRF--: Neural Radiance Fields Without Known Camera Parameters

NeRF--: Neural Radiance Fields Without Known Camera Parameters Project Page | Arxiv | Colab Notebook | Data Zirui Wang¹, Shangzhe Wu², Weidi Xie², Min

Active Vision Laboratory 411 Dec 26, 2022
Mip-NeRF: A Multiscale Representation for Anti-Aliasing Neural Radiance Fields.

This repository contains the code release for Mip-NeRF: A Multiscale Representation for Anti-Aliasing Neural Radiance Fields. This implementation is written in JAX, and is a fork of Google's JaxNeRF implementation. Contact Jon Barron if you encounter any issues.

Google 625 Dec 30, 2022
Code for KiloNeRF: Speeding up Neural Radiance Fields with Thousands of Tiny MLPs

KiloNeRF: Speeding up Neural Radiance Fields with Thousands of Tiny MLPs Check out the paper on arXiv: https://arxiv.org/abs/2103.13744 This repo cont

Christian Reiser 373 Dec 20, 2022
Code release for DS-NeRF (Depth-supervised Neural Radiance Fields)

Depth-supervised NeRF: Fewer Views and Faster Training for Free Project | Paper | YouTube Pytorch implementation of our method for learning neural rad

null 524 Jan 8, 2023
This repository contains the source code for the paper "DONeRF: Towards Real-Time Rendering of Compact Neural Radiance Fields using Depth Oracle Networks",

DONeRF: Towards Real-Time Rendering of Compact Neural Radiance Fields using Depth Oracle Networks Project Page | Video | Presentation | Paper | Data L

Facebook Research 281 Dec 22, 2022
BARF: Bundle-Adjusting Neural Radiance Fields 🤮 (ICCV 2021 oral)

BARF ?? : Bundle-Adjusting Neural Radiance Fields Chen-Hsuan Lin, Wei-Chiu Ma, Antonio Torralba, and Simon Lucey IEEE International Conference on Comp

Chen-Hsuan Lin 539 Dec 28, 2022
[ICCV21] Self-Calibrating Neural Radiance Fields

Self-Calibrating Neural Radiance Fields, ICCV, 2021 Project Page | Paper | Video Author Information Yoonwoo Jeong [Google Scholar] Seokjun Ahn [Google

null 381 Dec 30, 2022
[ICCV 2021 Oral] NerfingMVS: Guided Optimization of Neural Radiance Fields for Indoor Multi-view Stereo

NerfingMVS Project Page | Paper | Video | Data NerfingMVS: Guided Optimization of Neural Radiance Fields for Indoor Multi-view Stereo Yi Wei, Shaohui

Yi Wei 369 Dec 24, 2022