Table of Contents

Class InstantNGP<T>

Namespace
AiDotNet.NeuralRadianceFields.Models
Assembly
AiDotNet.dll

Implements Instant Neural Graphics Primitives (Instant-NGP) for fast NeRF training and rendering.

public class InstantNGP<T> : NeuralNetworkBase<T>, INeuralNetworkModel<T>, IInterpretableModel<T>, IInputGradientComputable<T>, IDisposable, IRadianceField<T>, INeuralNetwork<T>, IFullModel<T, Tensor<T>, Tensor<T>>, IModel<Tensor<T>, Tensor<T>, ModelMetadata<T>>, IModelSerializer, ICheckpointableModel, IParameterizable<T, Tensor<T>, Tensor<T>>, IFeatureAware, IFeatureImportance<T>, ICloneable<IFullModel<T, Tensor<T>, Tensor<T>>>, IGradientComputable<T, Tensor<T>, Tensor<T>>, IJitCompilable<T>

Type Parameters

T

The numeric type used for calculations (e.g., float, double).

Inheritance
InstantNGP<T>
Implements
IFullModel<T, Tensor<T>, Tensor<T>>
IModel<Tensor<T>, Tensor<T>, ModelMetadata<T>>
IParameterizable<T, Tensor<T>, Tensor<T>>
ICloneable<IFullModel<T, Tensor<T>, Tensor<T>>>
IGradientComputable<T, Tensor<T>, Tensor<T>>
Inherited Members
Extension Methods

Remarks

For Beginners: Instant-NGP is a dramatically faster version of NeRF, making it practical for real-time use.

Speed comparison: - Original NeRF: Hours to train, seconds to render each image - Instant-NGP: Minutes to train, milliseconds to render each image - Speedup: ~100× faster training, ~1000× faster rendering

Key innovations: 1. Multiresolution hash encoding: Replace expensive positional encoding 2. Tiny MLP: Much smaller network (2-4 layers vs 8 layers) 3. CUDA optimization: Highly optimized GPU kernels 4. Occupancy grids: Skip empty space efficiently

Multiresolution hash encoding explained: - Traditional NeRF: Encode position with sin/cos functions (expensive) - Instant-NGP: Look up features from a hash table (very fast)

How it works:

  1. Multiple levels of resolution (coarse to fine)
  2. At each level: Hash 3D position to table index
  3. Look up learned features at that index
  4. Interpolate features from nearby grid points
  5. Concatenate features from all levels
  6. Feed to small MLP for final color/density

Example with 3 levels:

  • Level 0: Coarse grid (16³ cells) for large-scale features
  • Level 1: Medium grid (64³ cells) for mid-scale features
  • Level 2: Fine grid (256³ cells) for fine details
  • Total table size: Much smaller than full 256³ grid
  • Hash function maps 3D position to table index

Why hash tables are fast: - No expensive trigonometric operations - Direct memory lookup (O(1) time) - Cache-friendly access patterns - Parallelizes extremely well on GPU

Why hash collisions are okay:

  • Multiple positions may hash to same index
  • Network learns to handle collisions
  • Collisions mostly affect similar regions
  • Final quality is still excellent

Tiny MLP architecture: - Original NeRF: 8 layers × 256 units = ~1M parameters - Instant-NGP: 2 layers × 64 units = ~10K parameters - Most representation power is in hash table, not MLP - MLP just needs to combine hash features

Occupancy grids: - Discretize space into voxel grid - Mark which voxels contain geometry (occupancy) - Skip sampling in empty voxels - Huge speedup: Don't waste time on empty space

Example:

  • Room scene: Most space is empty air
  • Occupancy grid: Mark only voxels with walls/furniture
  • Rendering: Skip ~90% of samples (the empty ones)
  • Result: ~10× faster rendering

Training process: 1. Initialize hash tables randomly 2. Initialize occupancy grid (start assuming all occupied) 3. For each training iteration: - Sample rays from training images - Use occupancy grid to skip empty space - Query hash tables + tiny MLP - Compute rendering loss - Backprop to update hash tables and MLP - Periodically update occupancy grid 4. Converges in minutes instead of hours

Applications: - Interactive 3D scanning: Scan object, view it seconds later - Real-time novel view synthesis: Move camera and render instantly - AR/VR: Low latency is critical for immersion - Robotics: Build 3D maps in real-time - Game development: Capture real objects for games

Limitations: - Requires good GPU (CUDA implementation is fastest) - Hash table size is a trade-off: - Larger: Better quality, more memory - Smaller: Faster, lower quality - Still requires multiple images from different views - Per-scene optimization (not a general model)

Comparison with NeRF:

Feature NeRF Instant-NGP
Training time 1-2 days 5-10 minutes
Rendering speed 30s/image 30ms/image
Model size ~5MB ~50MB (with hash tables)
Quality Excellent Excellent
Memory usage Low Medium
GPU requirement Any CUDA (for best performance)

Reference: "Instant Neural Graphics Primitives with a Multiresolution Hash Encoding" by Müller et al., ACM Transactions on Graphics 2022

Constructors

InstantNGP()

public InstantNGP()

InstantNGP(InstantNGPOptions<T>, ILossFunction<T>?)

public InstantNGP(InstantNGPOptions<T> options, ILossFunction<T>? lossFunction = null)

Parameters

options InstantNGPOptions<T>
lossFunction ILossFunction<T>

InstantNGP(int, int, int, int, int, int, int, int, double, double, double, int, Vector<T>?, Vector<T>?, ILossFunction<T>?)

Initializes a new instance of the InstantNGP class.

public InstantNGP(int hashTableSize = 524288, int numLevels = 16, int featuresPerLevel = 2, int finestResolution = 2048, int coarsestResolution = 16, int mlpHiddenDim = 64, int mlpNumLayers = 2, int occupancyGridResolution = 128, double learningRate = 0.01, double occupancyDecay = 0.95, double occupancyThreshold = 0.01, int occupancyUpdateInterval = 16, Vector<T>? sceneMin = null, Vector<T>? sceneMax = null, ILossFunction<T>? lossFunction = null)

Parameters

hashTableSize int

Size of each hash table (typical: 2^19 = 524,288).

numLevels int

Number of resolution levels (typical: 16).

featuresPerLevel int

Number of features per hash table level (typical: 2).

finestResolution int

Finest grid resolution (typical: 512-2048).

coarsestResolution int

Coarsest grid resolution (typical: 16).

mlpHiddenDim int

Hidden dimension of tiny MLP (typical: 64).

mlpNumLayers int

Number of MLP layers (typical: 2).

occupancyGridResolution int

Resolution of occupancy grid (typical: 128).

learningRate double

Learning rate for hash table and MLP updates.

occupancyDecay double

EMA decay for occupancy grid updates.

occupancyThreshold double

Density threshold for occupancy.

occupancyUpdateInterval int

Training steps between occupancy updates.

sceneMin Vector<T>

Optional scene bounds minimum (defaults to [0, 0, 0]).

sceneMax Vector<T>

Optional scene bounds maximum (defaults to [1, 1, 1]).

lossFunction ILossFunction<T>

Optional loss function for training.

Remarks

For Beginners: Creates an Instant-NGP model for fast 3D scene representation.

Parameters explained:

  • hashTableSize: How many entries in each hash table

    • Larger = better quality, more memory
    • Typical: 2^19 = 524K entries
    • Total memory: numLevels × hashTableSize × featuresPerLevel × 4 bytes
    • Example: 16 × 524K × 2 × 4 = 64MB
  • numLevels: How many resolution scales

    • More levels = capture more frequency details
    • Typical: 16 levels
    • Geometric spacing: each level is ~1.5× finer than previous
  • featuresPerLevel: Features stored per hash entry

    • Typical: 2 (good balance of quality vs speed)
    • Higher = more expressive but slower
  • finestResolution: Highest detail level

    • Typical: 512-2048
    • Higher = capture finer details
    • Limited by hash table size (collisions increase)
  • coarsestResolution: Lowest detail level

    • Typical: 16
    • Captures overall structure
  • mlpHiddenDim: Size of tiny MLP hidden layers

    • Typical: 64 (much smaller than NeRF's 256)
    • Smaller is faster, sufficient because hash encoding does heavy lifting
  • mlpNumLayers: Depth of tiny MLP

    • Typical: 2 (vs NeRF's 8)
    • Simpler network is sufficient with good hash features
  • occupancyGridResolution: Voxel grid resolution for empty space skipping

    • Typical: 128 (128³ = 2M voxels)
    • Higher = more precise but more memory

Standard Instant-NGP configuration for bounded scenes: new InstantNGP( hashTableSize: 524288, // 2^19 numLevels: 16, featuresPerLevel: 2, finestResolution: 2048, coarsestResolution: 16, mlpHiddenDim: 64, mlpNumLayers: 2, occupancyGridResolution: 128 );

Memory usage estimate:

  • Hash tables: ~64MB
  • Occupancy grid: ~2MB
  • MLP weights: ~50KB
  • Total: ~66MB (vs ~5MB for NeRF, but 100× faster)

Properties

SupportsTraining

Indicates whether this network supports training (learning from data).

public override bool SupportsTraining { get; }

Property Value

bool

Remarks

For Beginners: Not all neural networks can learn. Some are designed only for making predictions with pre-set parameters. This property tells you if the network can learn from data.

Methods

Backpropagate(Tensor<T>)

Performs backpropagation to compute gradients for network parameters.

public override Tensor<T> Backpropagate(Tensor<T> outputGradient)

Parameters

outputGradient Tensor<T>

Returns

Tensor<T>

The gradients of the loss with respect to the network inputs.

Remarks

For Beginners: Backpropagation is how neural networks learn. After making a prediction, the network calculates how wrong it was (the error). Then it works backward through the layers to figure out how each parameter contributed to that error. This method handles that backward flow of information.

The "gradients" are numbers that tell us how to adjust each parameter to reduce the error.

API Change Note: The signature changed from Vector<T> to Tensor<T> to support multi-dimensional gradients. This is a breaking change. If you need backward compatibility, consider adding an overload that accepts Vector<T> and converts it internally to Tensor<T>.

Exceptions

InvalidOperationException

Thrown when the network is not in training mode or doesn't support training.

CreateNewInstance()

Creates a new instance of the same type as this neural network.

protected override IFullModel<T, Tensor<T>, Tensor<T>> CreateNewInstance()

Returns

IFullModel<T, Tensor<T>, Tensor<T>>

A new instance of the same neural network type.

Remarks

For Beginners: This creates a blank version of the same type of neural network.

It's used internally by methods like DeepCopy and Clone to create the right type of network before copying the data into it.

DeserializeNetworkSpecificData(BinaryReader)

Deserializes network-specific data that was not covered by the general deserialization process.

protected override void DeserializeNetworkSpecificData(BinaryReader reader)

Parameters

reader BinaryReader

The BinaryReader to read the data from.

Remarks

This method is called at the end of the general deserialization process to allow derived classes to read any additional data specific to their implementation.

For Beginners: Continuing the suitcase analogy, this is like unpacking that special compartment. After the main deserialization method has unpacked the common items (layers, parameters), this method allows each specific type of neural network to unpack its own unique items that were stored during serialization.

ForwardWithMemory(Tensor<T>)

Performs a forward pass through the network while storing intermediate values for backpropagation.

public override Tensor<T> ForwardWithMemory(Tensor<T> input)

Parameters

input Tensor<T>

The input data to the network.

Returns

Tensor<T>

The output of the network.

Remarks

For Beginners: This method passes data through the network from input to output, but also remembers all the intermediate values. This is necessary for the learning process, as the network needs to know these values when figuring out how to improve.

API Change Note: The signature changed from Vector<T> to Tensor<T> to support multi-dimensional inputs. This is a breaking change. For backward compatibility, consider adding an overload that accepts Vector<T> and converts it internally to Tensor<T>.

Exceptions

InvalidOperationException

Thrown when the network doesn't support training.

GetModelMetadata()

Gets the metadata for this neural network model.

public override ModelMetadata<T> GetModelMetadata()

Returns

ModelMetadata<T>

A ModelMetaData object containing information about the model.

InitializeLayers()

Initializes the layers of the neural network based on the architecture.

protected override void InitializeLayers()

Remarks

For Beginners: This method sets up all the layers in your neural network according to the architecture you've defined. It's like assembling the parts of your network before you can use it.

Predict(Tensor<T>)

Makes a prediction using the neural network.

public override Tensor<T> Predict(Tensor<T> input)

Parameters

input Tensor<T>

The input data to process.

Returns

Tensor<T>

The network's prediction.

Remarks

For Beginners: This is the main method you'll use to get results from your trained neural network. You provide some input data (like an image or text), and the network processes it through all its layers to produce an output (like a classification or prediction).

QueryField(Tensor<T>, Tensor<T>)

Queries the radiance field at specific 3D positions and viewing directions.

public (Tensor<T> rgb, Tensor<T> density) QueryField(Tensor<T> positions, Tensor<T> viewingDirections)

Parameters

positions Tensor<T>

Tensor of 3D positions [N, 3] where N is number of query points.

viewingDirections Tensor<T>

Tensor of viewing directions [N, 3] (unit vectors).

Returns

(Tensor<T> grad1, Tensor<T> grad2)

A tuple containing RGB colors [N, 3] and density values [N, 1].

Remarks

For Beginners: This is the core operation of a radiance field.

For each query point:

  • Position (x, y, z): Where in 3D space are we looking?
  • Direction (dx, dy, dz): Which direction are we looking from?

The network returns:

  • RGB (r, g, b): The color at that point from that direction
  • Density σ: How "solid" or "opaque" that point is

Example query:

  • Position: (2.5, 1.0, -3.0) - a point in space
  • Direction: (0.0, 0.0, -1.0) - looking straight down negative Z axis
  • Result: (Red: 0.8, Green: 0.3, Blue: 0.1, Density: 5.2) This means the point appears orange when viewed from that direction, and it's fairly opaque (high density)

Density interpretation:

  • Density = 0: Completely transparent (empty space)
  • Density > 0: Increasingly opaque (solid material)
  • Higher density = light is more likely to stop at this point

RenderImage(Vector<T>, Matrix<T>, int, int, T)

Renders an image from a specific camera position and orientation.

public Tensor<T> RenderImage(Vector<T> cameraPosition, Matrix<T> cameraRotation, int imageWidth, int imageHeight, T focalLength)

Parameters

cameraPosition Vector<T>

3D position of the camera [3].

cameraRotation Matrix<T>

Rotation matrix of the camera [3, 3].

imageWidth int

Width of the output image in pixels.

imageHeight int

Height of the output image in pixels.

focalLength T

Camera focal length.

Returns

Tensor<T>

Rendered RGB image tensor [height, width, 3].

Remarks

For Beginners: This renders a 2D image from the 3D scene representation.

The rendering process:

  1. For each pixel in the output image:
    • Cast a ray from camera through that pixel
    • Sample points along the ray
    • Query radiance field at each sample point
    • Combine colors using volume rendering (accumulate with alpha blending)

Volume rendering equation:

  • For each ray, accumulate: Color = Σ(transmittance × color × alpha)
  • Transmittance: How much light passes through previous points
  • Alpha: How much light is absorbed at this point (based on density)

Example:

  • Camera at (0, 0, 5) looking at origin
  • Image 512×512 pixels
  • Cast 512×512 = 262,144 rays
  • Sample 64 points per ray = 16.8 million queries
  • Blend results to get final image

This is why NeRF rendering can be slow - many network queries! Optimizations like Instant-NGP speed this up significantly.

RenderRays(Tensor<T>, Tensor<T>, int, T, T)

Renders rays through the radiance field using volume rendering.

public Tensor<T> RenderRays(Tensor<T> rayOrigins, Tensor<T> rayDirections, int numSamples, T nearBound, T farBound)

Parameters

rayOrigins Tensor<T>

Origins of rays to render [N, 3].

rayDirections Tensor<T>

Directions of rays (unit vectors) [N, 3].

numSamples int

Number of samples per ray.

nearBound T

Near clipping distance.

farBound T

Far clipping distance.

Returns

Tensor<T>

Rendered RGB colors for each ray [N, 3].

Remarks

For Beginners: Volume rendering is how we convert the radiance field into images.

For each ray:

  1. Sample points: Generate sample positions between near and far bounds
  2. Query field: Get RGB and density at each sample
  3. Compute alpha: Convert density to opacity for each segment
  4. Accumulate color: Blend colors front-to-back

The algorithm:

For each sample i along ray:
  alpha_i = 1 - exp(-density_i * distance_i)
  transmittance_i = exp(-sum of all previous densities)
  color_contribution_i = transmittance_i * alpha_i * color_i
  total_color += color_contribution_i

Example with 4 samples:

  • Sample 0: Empty space (density ≈ 0) → contributes little
  • Sample 1: Empty space (density ≈ 0) → contributes little
  • Sample 2: Surface (density high) → contributes most of the color
  • Sample 3: Behind surface → mostly blocked by sample 2

Parameters:

  • numSamples: More samples = better quality but slower (typical: 64-192)
  • nearBound/farBound: Define region to sample (e.g., 0.1 to 10.0 meters)

SerializeNetworkSpecificData(BinaryWriter)

Serializes network-specific data that is not covered by the general serialization process.

protected override void SerializeNetworkSpecificData(BinaryWriter writer)

Parameters

writer BinaryWriter

The BinaryWriter to write the data to.

Remarks

This method is called at the end of the general serialization process to allow derived classes to write any additional data specific to their implementation.

For Beginners: Think of this as packing a special compartment in your suitcase. While the main serialization method packs the common items (layers, parameters), this method allows each specific type of neural network to pack its own unique items that other networks might not have.

Train(Tensor<T>, Tensor<T>)

Trains the neural network on a single input-output pair.

public override void Train(Tensor<T> input, Tensor<T> expectedOutput)

Parameters

input Tensor<T>

The input data.

expectedOutput Tensor<T>

The expected output for the given input.

Remarks

This method performs one training step on the neural network using the provided input and expected output. It updates the network's parameters to reduce the error between the network's prediction and the expected output.

For Beginners: This is how your neural network learns. You provide: - An input (what the network should process) - The expected output (what the correct answer should be)

The network then:

  1. Makes a prediction based on the input
  2. Compares its prediction to the expected output
  3. Calculates how wrong it was (the loss)
  4. Adjusts its internal values to do better next time

After training, you can get the loss value using the GetLastLoss() method to see how well the network is learning.

UpdateParameters(Vector<T>)

Updates the network's parameters with new values.

public override void UpdateParameters(Vector<T> parameters)

Parameters

parameters Vector<T>

The new parameter values to set.

Remarks

For Beginners: During training, a neural network's internal values (parameters) get adjusted to improve its performance. This method allows you to update all those values at once by providing a complete set of new parameters.

This is typically used by optimization algorithms that calculate better parameter values based on training data.