> ## Documentation Index
> Fetch the complete documentation index at: https://aegean.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# Neural Radiance Fields

> A scene stored as color and density, fitted to photos.

[![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/pantelis/eng-ai-agents/blob/main/notebooks/3d-reconstruction/neural-radiance-fields/index.ipynb)

In [Images and Geometry](https://aegean.ai/aiml-common/lectures/3d-reconstruction/images-and-geometry/index.md) a small network $f_\theta(x, y)$ stored an image: you asked it for a coordinate and it returned an intensity. A neural radiance field (NeRF) applies the same idea to a whole scene. The network takes a 3D point and a viewing direction and returns a color and a density. A renderer turns these into pixels. You fit the network until its renderings match a set of photos taken from known camera poses.

This section follows Chapter 45, [Radiance Fields](https://visionbook.mit.edu/nerf.html), of *Foundations of Computer Vision* by Torralba, Isola and Freeman, and the original paper by Mildenhall et al. (Mildenhall2020-bc). You build every part in PyTorch:

1. the volume rendering sum that turns densities and colors along a ray into a pixel color,
2. the positional encoding that lets a small network represent fine detail,
3. hierarchical sampling, which spends network evaluations where the ray actually stops,
4. a fitted field for the Mip-NeRF 360 *garden* scene, with camera poses from [Structure from Motion](https://aegean.ai/aiml-common/lectures/3d-reconstruction/structure-from-motion/index.md).

The same scene, image size and test views appear in [Gaussian Splatting](https://aegean.ai/aiml-common/lectures/3d-reconstruction/gaussian-splatting/index.md), so you can compare the two methods number for number.

> [accordion] Code
>
> ```python theme={null}
> import os
> import math
> import time
> import struct
> from pathlib import Path
>
> import cv2
> import numpy as np
> import torch
> import torch.nn as nn
> import torch.nn.functional as F
> import matplotlib.pyplot as plt
>
> from cycler import cycler
> from matplotlib_inline.backend_inline import set_matplotlib_formats
> set_matplotlib_formats("svg")
> FIG_GRAY = "#808080"
> FIG_COLORS = ["#0072B2", "#D55E00", "#009E73", "#cb77a6", "#c28600", "#1d99e0", "#7f7f7f"]
> plt.rcParams.update({
>     "figure.facecolor": "none", "axes.facecolor": "none",
>     "savefig.facecolor": "none", "savefig.transparent": True,
>     "text.color": FIG_GRAY, "axes.labelcolor": FIG_GRAY, "axes.edgecolor": FIG_GRAY,
>     "xtick.color": FIG_GRAY, "ytick.color": FIG_GRAY,
>     "grid.color": FIG_GRAY, "grid.alpha": 0.25,
>     "legend.facecolor": "none", "legend.edgecolor": FIG_GRAY, "legend.framealpha": 0,
>     "axes.prop_cycle": cycler(color=FIG_COLORS),
>     "svg.hashsalt": "aiml", "svg.fonttype": "path",
> })
>
> DEVICE = torch.device("cuda" if torch.cuda.is_available() else "cpu")
> torch.backends.cuda.matmul.allow_tf32 = True
> torch.backends.cudnn.allow_tf32 = True
> torch.manual_seed(0)
> np.random.seed(0)
>
> # Training length. The default is the full run; a smaller value gives a quick check.
> NERF_ITERS = int(os.environ.get("NERF_ITERS", "12000"))
> print("device:", DEVICE, torch.cuda.get_device_name(0) if DEVICE.type == "cuda" else "")
> ```

```output theme={null}
device: cuda NVIDIA RTX PRO 6000 Blackwell Max-Q Workstation Edition
```

## From the plenoptic function to a radiance field

The plenoptic function records the light that travels through every point of space in every direction. Chapter 1 of the book sets it aside because it is too large to measure. A radiance field is a version of it that you can fit. It assigns to each point $\mathbf{x} = (X, Y, Z)$ and viewing direction $\mathbf{d}$ two quantities:

$F_\theta(\mathbf{x}, \mathbf{d}) = (\mathbf{c}, \sigma).$

The color $\mathbf{c} = (r, g, b)$ is the light that the point sends toward direction $\mathbf{d}$. It depends on the direction, so a shiny surface can look different from different sides. The density $\sigma \ge 0$ measures how much matter sits at $\mathbf{x}$. It depends only on the point, because a surface is either there or not, whichever way you look at it.

A NeRF stores $F_\theta$ as a multilayer perceptron. Like the SIREN image, the network has no grid. You can query it at any point, and the network weights $\theta$ are the scene.

## Volume rendering

A camera pixel looks along a ray $\mathbf{r}(t) = \mathbf{o} + t\,\mathbf{d}$ that leaves the camera center $\mathbf{o}$. Think of the density as the rate at which the ray hits a particle: over a short step $dt$ the chance of a hit is $\sigma(\mathbf{r}(t))\,dt$. Let $T(t)$ be the probability that the ray travels from the near bound $t_n$ to $t$ without a hit. It falls at a rate set by the density,

$\frac{dT}{dt} = -\sigma(\mathbf{r}(t))\,T(t), \qquad T(t) = \exp\!\Big(-\int_{t_n}^{t} \sigma(\mathbf{r}(s))\,ds\Big).$

$T$ is called the transmittance. The ray stops in $[t, t + dt]$ with probability $T(t)\,\sigma(\mathbf{r}(t))\,dt$: it must survive up to $t$ and then hit something. The pixel color is the color at the stopping point, averaged over that distribution:

$C(\mathbf{r}) = \int_{t_n}^{t_f} T(t)\,\sigma(\mathbf{r}(t))\,\mathbf{c}(\mathbf{r}(t), \mathbf{d})\,dt.$

To compute the integral, split the ray at sample points $t_1 < \dots < t_N$ with gaps $\delta_i = t_{i+1} - t_i$, and assume $\sigma$ and $\mathbf{c}$ are constant on each gap. The integral of $T\sigma$ over gap $i$ is then exact, and the color becomes a weighted sum:

$$
\begin{aligned}
\alpha_i &= 1 - e^{-\sigma_i \delta_i}, \\
T_i &= \textstyle\prod_{j<i} (1 - \alpha_j), \\
w_i &= T_i\,\alpha_i, \\
\hat C(\mathbf{r}) &= \textstyle\sum_{i=1}^{N} w_i\,\mathbf{c}_i .
\end{aligned}
$$

$\alpha_i$ is the probability that the ray stops inside gap $i$ given that it reached it, and $w_i$ is the probability that it stops there at all. The weights sum to $1 - T_{N+1} \le 1$. They are a probability distribution over where the ray stops, plus the leftover chance that it passes through everything. The same weights give an expected depth, $\sum_i w_i t_i$.

The cell below draws one ray through a density with two bumps: a faint haze near $t = 2$ and a solid surface near $t = 4$.

> [accordion] Code
>
> ```python theme={null}
> def composite(sigma, t, far_delta=1e10):
>     """Volume rendering weights for densities sigma at sorted points t (last dim).
>
>     Returns the weights w_i = T_i * alpha_i and the transmittance T_i.
>     The gap after the last point is far_delta.
>     """
>     delta = torch.diff(t, dim=-1)
>     delta = torch.cat([delta, torch.full_like(delta[..., :1], far_delta)], dim=-1)
>     alpha = 1.0 - torch.exp(-sigma * delta)
>     # T_i = prod_{j<i} (1 - alpha_j), computed as exp of a cumulative sum for stability
>     log_T = torch.cumsum(torch.log1p(-alpha.clamp(max=1 - 1e-7)), dim=-1)
>     T = torch.exp(torch.cat([torch.zeros_like(log_T[..., :1]), log_T[..., :-1]], dim=-1))
>     return T * alpha, T
>
>
> def toy_sigma(t):
>     """A faint haze around t = 2 and a solid surface around t = 4."""
>     return 0.8 * torch.exp(-0.5 * ((t - 2.0) / 0.25) ** 2) + 40.0 * torch.sigmoid((t - 4.0) / 0.03)
>
>
> t_dense = torch.linspace(0.0, 6.0, 2001, dtype=torch.float64)
> w_dense, T_dense = composite(toy_sigma(t_dense), t_dense)
> print(f"sum of weights: {w_dense.sum():.4f}")
> print(f"chance of stopping in the haze (t < 3): {w_dense[t_dense < 3].sum():.3f}")
> print(f"expected depth: {(w_dense * t_dense).sum():.3f}")
> ```

```output theme={null}
sum of weights: 1.0000
chance of stopping in the haze (t < 3): 0.394
expected depth: 3.192
```

![Output from cell 3](https://mintcdn.com/aegeanaiinc/dLMqX5MXOVYfDcDh/aiml-common/lectures/3d-reconstruction/neural-radiance-fields/images/cell_3_output_1.svg?fit=max\&auto=format\&n=dLMqX5MXOVYfDcDh\&q=85\&s=53f4ca44f8e1de488a21236612fe1ba3)

The haze lowers the transmittance from 1 to about 0.6, so about 40% of the rays stop there and take the haze's color. The rest reach the surface and stop within about a tenth of a unit, because its density is large. The stopping density has one small, wide bump and one tall, narrow spike. A pixel on this ray mixes the two colors in that proportion.

## Positional encoding

A plain MLP fed with raw coordinates learns smooth functions first and fine detail very slowly. NeRF passes each coordinate $p$ through a fixed map before the network,

$\gamma(p) = \big(\sin(2^0 \pi p), \cos(2^0 \pi p), \dots, \sin(2^{L-1} \pi p), \cos(2^{L-1} \pi p)\big),$

with $L = 10$ for positions and $L = 4$ for directions. The book links this to the positional encodings of transformers. The purpose here is different: the high-frequency sines let the network build sharp changes from a few combinations of its inputs. Tancik et al. analyze this effect (Tancik2020-hy).

The experiment fits the same network to a 1D signal made of a slow sine, a square wave with 12 periods and a fast sine with 30 periods. It fits once on the raw coordinate and once on $\gamma(p)$ with $L = 8$.

> [accordion] Code
>
> ```python theme={null}
> def fourier_encode(p, n_freqs):
>     """gamma(p): the input followed by sin and cos at frequencies 2^k * pi, k < n_freqs."""
>     freqs = (2.0 ** torch.arange(n_freqs, device=p.device, dtype=p.dtype)) * math.pi
>     angles = p[..., None] * freqs                       # (..., D, L)
>     enc = torch.cat([torch.sin(angles), torch.cos(angles)], dim=-1)
>     return torch.cat([p, enc.flatten(-2)], dim=-1)
>
>
> def mlp(d_in, width=128, depth=4, d_out=1):
>     layers, d = [], d_in
>     for _ in range(depth):
>         layers += [nn.Linear(d, width), nn.ReLU()]
>         d = width
>     return nn.Sequential(*layers, nn.Linear(d, d_out))
>
>
> x1 = torch.linspace(-1, 1, 2048, device=DEVICE)[:, None]
> target = (0.4 * torch.sin(2 * math.pi * x1) + 0.3 * torch.sign(torch.sin(24 * math.pi * x1))
>           + 0.2 * torch.sin(60 * math.pi * x1)).float()
>
> fits = {}
> for name, n_freqs in [("raw coordinate", 0), ("encoded, L = 8", 8)]:
>     torch.manual_seed(0)
>     inp = x1 if n_freqs == 0 else fourier_encode(x1, n_freqs)
>     net = mlp(inp.shape[-1]).to(DEVICE)
>     opt = torch.optim.Adam(net.parameters(), lr=1e-3)
>     for step in range(3000):
>         loss = F.mse_loss(net(inp), target)
>         opt.zero_grad()
>         loss.backward()
>         opt.step()
>     fits[name] = (net(inp).detach(), loss.item())
>     print(f"{name:16s} final mean squared error {loss.item():.5f}")
> ```

```output theme={null}
raw coordinate   final mean squared error 0.05880
encoded, L = 8   final mean squared error 0.00003
```

![Output from cell 5](https://mintcdn.com/aegeanaiinc/dLMqX5MXOVYfDcDh/aiml-common/lectures/3d-reconstruction/neural-radiance-fields/images/cell_5_output_1.svg?fit=max\&auto=format\&n=dLMqX5MXOVYfDcDh\&q=85\&s=bdf6f668cae7759dc70c8468a9fc0f83)

The network on raw coordinates finds the slow sine but rounds off the steps and misses the fast sine. With the encoding, the same network, optimizer and number of steps reproduce both. A NeRF with raw coordinates renders the garden as a blur for the same reason.

## Hierarchical sampling

The weights show that a ray only needs samples near where it stops. Evenly spaced samples waste most network evaluations on empty air or on space hidden behind the first surface. NeRF therefore samples each ray twice:

1. A *coarse* network is evaluated at $N_c$ points spread evenly with a random jitter (stratified sampling). Its weights $w_i$ give a rough picture of where the ray stops.
2. The normalized weights $\hat w_i = w_i / \sum_j w_j$ define a piecewise-constant probability density along the ray. $N_f$ more points are drawn from it by inverse transform sampling: draw $u \sim \mathcal{U}[0, 1]$, find the bin where the cumulative distribution crosses $u$, and interpolate linearly inside that bin.
3. A *fine* network is evaluated at all $N_c + N_f$ points, sorted, and the volume rendering sum gives the final color.

Both networks are trained, each against the pixel colors, so that the coarse weights stay a good guide. The paper uses $N_c = 64$ and $N_f = 128$. The paper also points out a difference from textbook importance sampling. The fine points are not reweighted by $1/\hat w_i$. They only form a denser, uneven set of sample points for the same rendering sum.

The figure runs both stages on the toy ray with 16 coarse points and 64 fine points.

> [accordion] Code
>
> ```python theme={null}
> def stratified(n, n_rays, device, jitter=True):
>     """n sorted points per ray in [0, 1]: one per equal bin, jittered or at bin centers."""
>     edges = torch.linspace(0.0, 1.0, n + 1, device=device)
>     lo, hi = edges[:-1], edges[1:]
>     u = torch.rand(n_rays, n, device=device) if jitter else torch.full((n_rays, n), 0.5, device=device)
>     return lo + (hi - lo) * u
>
>
> def sample_pdf(bins, weights, n, jitter=True):
>     """Inverse transform sampling from the piecewise-constant density on bins.
>
>     bins: (R, M+1) bin edges, weights: (R, M) unnormalized bin weights. Returns (R, n) points.
>     """
>     w = weights + 1e-5
>     pdf = w / w.sum(-1, keepdim=True)
>     cdf = torch.cat([torch.zeros_like(pdf[..., :1]), torch.cumsum(pdf, -1)], -1)  # (R, M+1)
>     R = bins.shape[0]
>     if jitter:
>         u = (torch.arange(n, device=bins.device) + torch.rand(R, n, device=bins.device)) / n
>     else:
>         u = ((torch.arange(n, device=bins.device) + 0.5) / n).expand(R, n)
>     u = u.contiguous().to(cdf.dtype)
>     idx = torch.searchsorted(cdf, u, right=True)
>     below = (idx - 1).clamp(min=0)
>     above = idx.clamp(max=cdf.shape[-1] - 1)
>     cdf_b, cdf_a = cdf.gather(-1, below), cdf.gather(-1, above)
>     bin_b, bin_a = bins.gather(-1, below), bins.gather(-1, above)
>     denom = torch.where(cdf_a - cdf_b < 1e-5, torch.ones_like(cdf_a), cdf_a - cdf_b)
>     return bin_b + (u - cdf_b) / denom * (bin_a - bin_b)
>
>
> torch.manual_seed(1)
> T_RANGE = 6.0
> t_coarse = T_RANGE * stratified(16, 1, "cpu", jitter=False).double()
> w_coarse, _ = composite(toy_sigma(t_coarse), t_coarse)
> # Bins between coarse points: midpoints, with the interior weights
> mids = 0.5 * (t_coarse[:, 1:] + t_coarse[:, :-1])
> t_fine = sample_pdf(mids, w_coarse[:, 1:-1], 64).double()
> t_all, _ = torch.sort(torch.cat([t_coarse, t_fine], -1), -1)
> print("fine points in the haze (t < 3):", int((t_fine < 3).sum()),
>       " near the surface (3.8 < t < 4.4):", int(((t_fine > 3.8) & (t_fine < 4.4)).sum()))
> ```

```output theme={null}
fine points in the haze (t < 3): 25  near the surface (3.8 < t < 4.4): 33
```

![Output from cell 7](https://mintcdn.com/aegeanaiinc/dLMqX5MXOVYfDcDh/aiml-common/lectures/3d-reconstruction/neural-radiance-fields/images/cell_7_output_1.svg?fit=max\&auto=format\&n=dLMqX5MXOVYfDcDh\&q=85\&s=d2671d06078da4f3c0c1375db0f2c282)

The coarse pass sees the surface in one bin and the haze in a few. The fine samples pile up in those bins, mostly at the surface, and almost none land in the empty space before the haze or behind the surface. With 80 points in total, most of them sit where the weights are large.

## The garden scene

The real scene is *garden* from the Mip-NeRF 360 dataset: 185 photos of a table in a garden, taken while walking around it. The dataset ships with the output of COLMAP, the structure-from-motion program that [Structure from Motion](https://aegean.ai/aiml-common/lectures/3d-reconstruction/structure-from-motion/index.md) explains. COLMAP writes three binary files, described in [Structure from Motion at Scale](https://aegean.ai/aiml-common/lectures/3d-reconstruction/colmap/index.md#output-files-and-conventions). `cameras.bin` holds the intrinsics. `images.bin` holds one pose per photo. `points3D.bin` holds the sparse point cloud.

You use the copy of the photos reduced 8 times and then halve them again, to $324 \times 210$ pixels, so that a NeRF trains in minutes. Every 8th photo (sorted by name) is held out for testing. [Gaussian Splatting](https://aegean.ai/aiml-common/lectures/3d-reconstruction/gaussian-splatting/index.md) uses exactly the same images and split.

> [accordion] Code
>
> ```python theme={null}
> import warnings
> warnings.filterwarnings("ignore", message="IProgress not found")
> os.environ["HF_HUB_DISABLE_PROGRESS_BARS"] = "1"
> from huggingface_hub import snapshot_download
>
> root = Path(snapshot_download(
>     "mileleap/mipnerf360", repo_type="dataset",
>     allow_patterns=["garden/images_8/*", "garden/sparse/*"],
> )) / "garden"
> print(sorted(p.name for p in (root / "sparse" / "0").iterdir()))
> print(len(list((root / "images_8").glob("*.JPG"))), "photos")
> ```

```output theme={null}
['cameras.bin', 'images.bin', 'points3D.bin']
185 photos
```

> [accordion] Code
>
> ```python theme={null}
> # COLMAP camera models: id -> (name, number of parameters)
> CAMERA_MODELS = {0: ("SIMPLE_PINHOLE", 3), 1: ("PINHOLE", 4), 2: ("SIMPLE_RADIAL", 4),
>                  3: ("RADIAL", 5), 4: ("OPENCV", 8)}
>
>
> def read_cameras_bin(path):
>     cams = {}
>     with open(path, "rb") as f:
>         n = struct.unpack("<Q", f.read(8))[0]
>         for _ in range(n):
>             cam_id, model_id, w, h = struct.unpack("<iiQQ", f.read(24))
>             name, n_params = CAMERA_MODELS[model_id]
>             params = np.array(struct.unpack(f"<{n_params}d", f.read(8 * n_params)))
>             cams[cam_id] = {"model": name, "width": w, "height": h, "params": params}
>     return cams
>
>
> def read_images_bin(path):
>     images = {}
>     with open(path, "rb") as f:
>         n = struct.unpack("<Q", f.read(8))[0]
>         for _ in range(n):
>             image_id = struct.unpack("<i", f.read(4))[0]
>             qvec = np.array(struct.unpack("<4d", f.read(32)))   # w, x, y, z
>             tvec = np.array(struct.unpack("<3d", f.read(24)))
>             cam_id = struct.unpack("<i", f.read(4))[0]
>             name = b""
>             while (ch := f.read(1)) != b"\x00":
>                 name += ch
>             n_pts = struct.unpack("<Q", f.read(8))[0]
>             f.seek(24 * n_pts, 1)                               # skip the 2D keypoints
>             images[image_id] = {"name": name.decode(), "qvec": qvec, "tvec": tvec, "camera_id": cam_id}
>     return images
>
>
> def read_points3d_bin(path):
>     xyz, rgb = [], []
>     with open(path, "rb") as f:
>         n = struct.unpack("<Q", f.read(8))[0]
>         for _ in range(n):
>             vals = struct.unpack("<Q3d3Bd", f.read(43))
>             xyz.append(vals[1:4])
>             rgb.append(vals[4:7])
>             track_len = struct.unpack("<Q", f.read(8))[0]
>             f.seek(8 * track_len, 1)                            # skip (image id, keypoint id) pairs
>     return np.array(xyz), np.array(rgb, dtype=np.uint8)
>
>
> def qvec_to_rotmat(q):
>     w, x, y, z = q
>     return np.array([
>         [1 - 2 * (y * y + z * z), 2 * (x * y - w * z), 2 * (x * z + w * y)],
>         [2 * (x * y + w * z), 1 - 2 * (x * x + z * z), 2 * (y * z - w * x)],
>         [2 * (x * z - w * y), 2 * (y * z + w * x), 1 - 2 * (x * x + y * y)],
>     ])
>
>
> sparse = root / "sparse" / "0"
> cameras = read_cameras_bin(sparse / "cameras.bin")
> images = read_images_bin(sparse / "images.bin")
> points_xyz, points_rgb = read_points3d_bin(sparse / "points3D.bin")
> print({k: (v["model"], v["width"], v["height"]) for k, v in cameras.items()})
> print(len(images), "posed images,", len(points_xyz), "sparse points")
> ```

```output theme={null}
{1: ('PINHOLE', 5187, 3361)}
185 posed images, 138766 sparse points
```

COLMAP stores each pose as world-to-camera: a point $\mathbf{X}$ in world coordinates lands at $R\mathbf{X} + \mathbf{t}$ in camera coordinates, with $x$ to the right, $y$ down and $z$ forward. The camera center in the world is therefore $\mathbf{o} = -R^\top \mathbf{t}$. A pixel $(u, v)$, measured to the pixel center, looks along

$\mathbf{d} \propto R^\top \begin{pmatrix} (u + \tfrac12 - c_x)/f_x \\ (v + \tfrac12 - c_y)/f_y \\ 1 \end{pmatrix},$

which inverts the pinhole projection of [Stereo Vision](https://aegean.ai/aiml-common/lectures/3d-reconstruction/stereo-vision/index.md). Downscaling an image by a factor $s$ scales $f_x, f_y, c_x, c_y$ by $s$.

The scene has no fixed scale, so you choose one. Here the world is shifted so that the mean camera center is the origin and scaled so that the farthest camera sits at distance 1. The table and everything near it then lie inside the unit ball.

> [accordion] Code
>
> ```python theme={null}
> records = sorted(images.values(), key=lambda r: r["name"])
> imgs, Ks, c2ws = [], [], []
> for rec in records:
>     bgr = cv2.imread(str(root / "images_8" / rec["name"]), cv2.IMREAD_COLOR)
>     h8, w8 = bgr.shape[:2]
>     small = cv2.resize(bgr, (w8 // 2, h8 // 2), interpolation=cv2.INTER_AREA)
>     imgs.append(cv2.cvtColor(small, cv2.COLOR_BGR2RGB).astype(np.float32) / 255.0)
>     cam = cameras[rec["camera_id"]]
>     assert cam["model"] == "PINHOLE", cam["model"]
>     fx, fy, cx, cy = cam["params"]
>     sx, sy = small.shape[1] / cam["width"], small.shape[0] / cam["height"]
>     Ks.append(np.array([fx * sx, fy * sy, cx * sx, cy * sy]))
>     R = qvec_to_rotmat(rec["qvec"])
>     c2w = np.eye(4)
>     c2w[:3, :3] = R.T
>     c2w[:3, 3] = -R.T @ rec["tvec"]
>     c2ws.append(c2w)
>
> imgs = np.stack(imgs)
> Ks = np.stack(Ks)
> c2ws = np.stack(c2ws)
> H, W = imgs.shape[1:3]
>
> # Normalize: mean camera center to the origin, farthest camera at distance 1
> center = c2ws[:, :3, 3].mean(0)
> scale = 1.0 / np.linalg.norm(c2ws[:, :3, 3] - center, axis=1).max()
> c2ws[:, :3, 3] = (c2ws[:, :3, 3] - center) * scale
> pts_n = (points_xyz - center) * scale
>
> test_idx = np.arange(len(imgs))[np.arange(len(imgs)) % 8 == 0]
> train_idx = np.arange(len(imgs))[np.arange(len(imgs)) % 8 != 0]
> print(f"image size {W} x {H}; {len(train_idx)} training views, {len(test_idx)} test views")
> print(f"scene scale factor {scale:.4f}")
> print("sparse points inside the unit ball:", f"{(np.linalg.norm(pts_n, axis=1) < 1).mean():.0%}")
> ```

```output theme={null}
image size 324 x 210; 161 training views, 24 test views
scene scale factor 0.2229
sparse points inside the unit ball: 39%
```

![Output from cell 11](https://mintcdn.com/aegeanaiinc/dLMqX5MXOVYfDcDh/aiml-common/lectures/3d-reconstruction/neural-radiance-fields/images/cell_11_output_1.svg?fit=max\&auto=format\&n=dLMqX5MXOVYfDcDh\&q=85\&s=8f88b40bebf28727637c3337882c1931)

### An unbounded scene

The photos also show trees and a house far behind the table. Their distance has no useful upper limit, so evenly spaced samples along $[t_n, t_f]$ cannot cover both the table and the background. Mip-NeRF 360 (Barron2021-nb) solves this with a contraction that maps all of space into a ball of radius 2:

$$
\operatorname{contract}(\mathbf{x}) =
\begin{cases}
\mathbf{x}, & \lVert\mathbf{x}\rVert \le 1,\\[2pt]
\Big(2 - \dfrac{1}{\lVert\mathbf{x}\rVert}\Big)\dfrac{\mathbf{x}}{\lVert\mathbf{x}\rVert}, & \lVert\mathbf{x}\rVert > 1 .
\end{cases}
$$

Inside the unit ball nothing changes. Outside, a point at distance $r$ moves to distance $2 - 1/r$, so the whole region from the unit sphere to infinity fits in the shell between radius 1 and 2. The network sees only contracted points. Along each ray you place half the coarse samples evenly in distance up to the unit sphere, and the other half evenly in disparity $1/t$ from the sphere out to $t = 1000$. Samples evenly spaced in disparity land roughly evenly spaced in the contracted shell, so the network spends about as much effort on the background as on the table.

In code, the samples live in a coordinate $s \in [0, 1]$. The first half of $s$ maps linearly to distance and the second half maps linearly to disparity. Hierarchical sampling also works in $s$.

> [accordion] Code
>
> ```python theme={null}
> NEAR, FAR = 0.02, 1000.0
>
>
> def contract(x):
>     r = x.norm(dim=-1, keepdim=True).clamp(min=1e-9)
>     return torch.where(r <= 1.0, x, (2.0 - 1.0 / r) * x / r)
>
>
> def sphere_exit(o, d):
>     """Distance along unit direction d at which a ray from o leaves the unit sphere."""
>     b = (o * d).sum(-1)
>     c = (o * o).sum(-1) - 1.0
>     t = -b + torch.sqrt((b * b - c).clamp(min=0.0))
>     return t.clamp(min=NEAR + 1e-3)
>
>
> def s_to_t(s, t_exit):
>     """Map s in [0, 1] to distance: linear up to the sphere, then linear in disparity."""
>     t_exit = t_exit[..., None]
>     lin = NEAR + (t_exit - NEAR) * (s / 0.5)
>     disp = 1.0 / t_exit + (1.0 / FAR - 1.0 / t_exit) * ((s - 0.5) / 0.5)
>     return torch.where(s < 0.5, lin, 1.0 / disp)
>
>
> def get_rays(K, c2w):
>     """Origins and unit directions for every pixel of one view, in normalized world coordinates."""
>     fx, fy, cx, cy = K
>     v, u = np.meshgrid(np.arange(H), np.arange(W), indexing="ij")
>     dirs = np.stack([(u + 0.5 - cx) / fx, (v + 0.5 - cy) / fy, np.ones_like(u, dtype=np.float64)], -1)
>     d = dirs @ c2w[:3, :3].T
>     d /= np.linalg.norm(d, axis=-1, keepdims=True)
>     o = np.broadcast_to(c2w[:3, 3], d.shape)
>     return o.reshape(-1, 3), d.reshape(-1, 3)
>
>
> def rays_for(indices):
>     os_, ds_, cs_ = [], [], []
>     for i in indices:
>         o, d = get_rays(Ks[i], c2ws[i])
>         os_.append(o)
>         ds_.append(d)
>         cs_.append(imgs[i].reshape(-1, 3))
>     to = lambda a: torch.tensor(np.concatenate(a), dtype=torch.float32, device=DEVICE)
>     return to(os_), to(ds_), to(cs_)
>
>
> train_o, train_d, train_c = rays_for(train_idx)
> print(f"{train_o.shape[0]:,} training rays")
> ```

```output theme={null}
10,954,440 training rays
```

## Fitting the field

The field network follows the paper's layout at a smaller size for the coarse pass. Positions are contracted, divided by 2 so they lie in $[-1, 1]$, and encoded with $L = 10$. The position MLP has a skip connection that feeds the encoding in again halfway. Its last layer gives the density and a feature vector. The color head takes the feature vector and the encoded direction ($L = 4$), so only the color can depend on the direction. A softplus keeps the density non-negative, and a sigmoid keeps the color in $[0, 1]$.

The loss is the paper's squared error on both renderings for a batch $\mathcal{R}$ of random rays drawn from all training photos:

$\mathcal{L} = \sum_{\mathbf{r} \in \mathcal{R}} \big\lVert \hat C_c(\mathbf{r}) - C(\mathbf{r}) \big\rVert^2 + \big\lVert \hat C_f(\mathbf{r}) - C(\mathbf{r}) \big\rVert^2 .$

Each step uses 4096 rays, $N_c = 64$ and $N_f = 128$, and Adam with a learning rate that decays from $5 \times 10^{-4}$ to $5 \times 10^{-5}$, as in the paper. Quality is measured by the peak signal-to-noise ratio, $\mathrm{PSNR} = -10 \log_{10} \mathrm{MSE}$ for colors in $[0, 1]$. Higher is better, and each 1 dB is about a 21% smaller squared error.

> [accordion] Code
>
> ```python theme={null}
> class RadianceField(nn.Module):
>     def __init__(self, width=256, depth=8, skip=4, L_x=10, L_d=4):
>         super().__init__()
>         self.L_x, self.L_d, self.skip = L_x, L_d, skip
>         d_x, d_d = 3 + 6 * L_x, 3 + 6 * L_d
>         self.layers = nn.ModuleList()
>         d = d_x
>         for i in range(depth):
>             self.layers.append(nn.Linear(d + (d_x if i == skip else 0), width))
>             d = width
>         self.sigma_out = nn.Linear(width, 1)
>         self.feature = nn.Linear(width, width)
>         self.color = nn.Sequential(nn.Linear(width + d_d, width // 2), nn.ReLU(),
>                                    nn.Linear(width // 2, 3))
>
>     def forward(self, x, d):
>         ex = fourier_encode(contract(x) / 2.0, self.L_x)
>         h = ex
>         for i, layer in enumerate(self.layers):
>             if i == self.skip:
>                 h = torch.cat([h, ex], -1)
>             h = F.relu(layer(h))
>         sigma = F.softplus(self.sigma_out(h).squeeze(-1) - 1.0)
>         rgb = torch.sigmoid(self.color(torch.cat([self.feature(h), fourier_encode(d, self.L_d)], -1)))
>         return rgb, sigma
>
>
> def render_rays(model_c, model_f, o, d, jitter=True, n_c=64, n_f=128):
>     """Coarse and fine colors, plus fine weights and sample distances, for a batch of rays."""
>     t_exit = sphere_exit(o, d)
>     s_c = stratified(n_c, o.shape[0], o.device, jitter)
>     t_c = s_to_t(s_c, t_exit)
>     x_c = o[:, None] + t_c[..., None] * d[:, None]
>     dirs_c = d[:, None].expand_as(x_c)
>     with torch.autocast("cuda", dtype=torch.bfloat16, enabled=o.is_cuda):
>         rgb_c, sig_c = model_c(x_c, dirs_c)
>     w_c, _ = composite(sig_c.float(), t_c)
>     color_c = (w_c[..., None] * rgb_c.float()).sum(1)
>
>     s_mid = 0.5 * (s_c[:, 1:] + s_c[:, :-1])
>     s_f = sample_pdf(s_mid, w_c[:, 1:-1].detach(), n_f, jitter)
>     s_all, _ = torch.sort(torch.cat([s_c, s_f.detach()], -1), -1)
>     t_all = s_to_t(s_all, t_exit)
>     x_f = o[:, None] + t_all[..., None] * d[:, None]
>     with torch.autocast("cuda", dtype=torch.bfloat16, enabled=o.is_cuda):
>         rgb_f, sig_f = model_f(x_f, d[:, None].expand_as(x_f))
>     w_f, _ = composite(sig_f.float(), t_all)
>     color_f = (w_f[..., None] * rgb_f.float()).sum(1)
>     return color_c, color_f, w_f, t_all
>
>
> def psnr(mse):
>     return -10.0 * math.log10(max(mse, 1e-10))
>
>
> torch.manual_seed(0)
> model_c = RadianceField(width=128, depth=4, skip=2).to(DEVICE)
> model_f = RadianceField(width=256, depth=8, skip=4).to(DEVICE)
> params = list(model_c.parameters()) + list(model_f.parameters())
> print(f"coarse network {sum(p.numel() for p in model_c.parameters()):,} parameters, "
>       f"fine network {sum(p.numel() for p in model_f.parameters()):,}")
> ```

```output theme={null}
coarse network 92,612 parameters, fine network 595,844
```

> [accordion] Code
>
> ```python theme={null}
> BATCH = 4096
> LR0, LR1 = 5e-4, 5e-5
> opt = torch.optim.Adam(params, lr=LR0, fused=DEVICE.type == "cuda")
> history = {"step": [], "loss": [], "psnr": []}
> n_rays = train_o.shape[0]
>
> if DEVICE.type == "cuda":
>     torch.cuda.synchronize()
> t0 = time.time()
> running = []
> for step in range(1, NERF_ITERS + 1):
>     idx = torch.randint(0, n_rays, (BATCH,), device=DEVICE)
>     color_c, color_f, _, _ = render_rays(model_c, model_f, train_o[idx], train_d[idx])
>     target_c = train_c[idx]
>     mse_f = F.mse_loss(color_f, target_c)
>     loss = F.mse_loss(color_c, target_c) + mse_f
>     opt.zero_grad(set_to_none=True)
>     loss.backward()
>     opt.step()
>     for g in opt.param_groups:
>         g["lr"] = LR0 * (LR1 / LR0) ** (step / NERF_ITERS)
>     running.append(mse_f.detach())
>     if step % 250 == 0 or step == NERF_ITERS:
>         m = torch.stack(running).mean().item()
>         running = []
>         history["step"].append(step)
>         history["loss"].append(m)
>         history["psnr"].append(psnr(m))
>     if step % 5000 == 0:
>         print(f"step {step:6d}  training PSNR {history['psnr'][-1]:.2f} dB  "
>               f"elapsed {(time.time() - t0) / 60:.1f} min")
> if DEVICE.type == "cuda":
>     torch.cuda.synchronize()
> train_minutes = (time.time() - t0) / 60
> print(f"training: {NERF_ITERS} steps in {train_minutes:.1f} min")
> ```

```output theme={null}
step   5000  training PSNR 22.96 dB  elapsed 8.4 min
step  10000  training PSNR 23.83 dB  elapsed 17.8 min
training: 12000 steps in 21.7 min
```

![Output from cell 15](https://mintcdn.com/aegeanaiinc/dLMqX5MXOVYfDcDh/aiml-common/lectures/3d-reconstruction/neural-radiance-fields/images/cell_15_output_1.svg?fit=max\&auto=format\&n=dLMqX5MXOVYfDcDh\&q=85\&s=e76dbbfd1a5354d0563f01927eb8ca7f)

## Rendering the test views

To render a full image you cast one ray per pixel, with no jitter: the coarse points sit at bin centers and the fine points at evenly spaced values of $u$. The expected distance $\sum_i w_i t_i$ from the fine weights gives a depth map at no extra cost. The figure shows it as disparity, $1/\text{depth}$, so that near objects are bright and the far background is dark.

> [accordion] Code
>
> ```python theme={null}
> @torch.no_grad()
> def render_view(i, chunk=16384):
>     o, d = get_rays(Ks[i], c2ws[i])
>     o = torch.tensor(o, dtype=torch.float32, device=DEVICE)
>     d = torch.tensor(d, dtype=torch.float32, device=DEVICE)
>     rgb, depth = [], []
>     for k in range(0, o.shape[0], chunk):
>         _, c_f, w_f, t_f = render_rays(model_c, model_f, o[k:k + chunk], d[k:k + chunk], jitter=False)
>         rgb.append(c_f)
>         depth.append((w_f * t_f).sum(-1) / w_f.sum(-1).clamp(min=1e-6))
>     return (torch.cat(rgb).reshape(H, W, 3).clamp(0, 1).cpu().numpy(),
>             torch.cat(depth).reshape(H, W).cpu().numpy())
>
>
> renders, depths, psnrs = {}, {}, []
> if DEVICE.type == "cuda":
>     torch.cuda.synchronize()
> t0 = time.time()
> for i in test_idx:
>     rgb, depth = render_view(i)
>     renders[i], depths[i] = rgb, depth
>     psnrs.append(psnr(float(((rgb - imgs[i]) ** 2).mean())))
> if DEVICE.type == "cuda":
>     torch.cuda.synchronize()
> render_seconds = (time.time() - t0) / len(test_idx)
>
> NERF_TEST_PSNR = float(np.mean(psnrs))
> print(f"NeRF test PSNR: {NERF_TEST_PSNR:.2f} dB (mean over {len(test_idx)} test views, {W} x {H})")
> print(f"NeRF training time: {train_minutes:.1f} min for {NERF_ITERS} steps")
> print(f"NeRF render time: {render_seconds:.2f} s per {W} x {H} image")
> ```

```output theme={null}
NeRF test PSNR: 23.80 dB (mean over 24 test views, 324 x 210)
NeRF training time: 21.7 min for 12000 steps
NeRF render time: 0.86 s per 324 x 210 image
```

![Output from cell 17](https://mintcdn.com/aegeanaiinc/dLMqX5MXOVYfDcDh/aiml-common/lectures/3d-reconstruction/neural-radiance-fields/images/cell_17_output_1.svg?fit=max\&auto=format\&n=dLMqX5MXOVYfDcDh\&q=85\&s=4d6705564329f45e28d99d61c9b7da9c)

![Output from cell 18](https://mintcdn.com/aegeanaiinc/dLMqX5MXOVYfDcDh/aiml-common/lectures/3d-reconstruction/neural-radiance-fields/images/cell_18_output_1.svg?fit=max\&auto=format\&n=dLMqX5MXOVYfDcDh\&q=85\&s=5b9a02788bb8d195b7c4730769609305)

The network never saw the held-out photos. It renders them from a field fitted to the other 161, which means it has recovered geometry that agrees across views, not 161 separate pictures. The disparity map separates the table top, its legs, the vase and the ground, although no depth was ever given to the network. The mean test score is the number printed above, about 24 dB. The weakest views look past the table toward the house and the trees. There the distant background fills much of the frame, and the contraction squeezes it into a thin shell, so the field resolves it only coarsely. Fine texture such as the joints between the paving stones and the leaves is softer than in the photos, because this run stops at 12,000 steps while the paper trains for 100,000 to 300,000.

## What a radiance field cannot do

A NeRF is fitted to one scene. It holds no knowledge that carries over to a new set of photos, and every new scene starts from random weights. It also depends on the camera poses: if structure from motion gets a pose wrong, the field blurs the content of that photo across space.

Rendering is slow. Each pixel costs 192 network evaluations here, which is why one small test image takes the render time printed with the test score. Faster versions replace most of the network with lookup tables, such as the hash grid of Instant-NGP (Müller et al., 2022).

The field also has no notion of light sources. Volume rendering lets light leave a point and reach the camera in a straight line, with no bounces. The book makes this point with the rendering equation: shadows, reflections and highlights become part of the fitted color, so you cannot move a light or change a material without fitting again.

[Gaussian Splatting](https://aegean.ai/aiml-common/lectures/3d-reconstruction/gaussian-splatting/index.md) keeps the rendering weights $w_i = T_i \alpha_i$ from this section but replaces the network with millions of explicit 3D Gaussians that start at the sparse COLMAP points (Kerbl et al., 2023). Rendering then needs no network evaluations at all, and it runs in real time.

## References

* Kerbl, B., Kopanas, G., Leimkühler, T., Drettakis, G. (2023). *3D Gaussian splatting for real-time radiance Field rendering*. arXiv \[cs.GR]. [Link](http://arxiv.org/abs/2308.04079)
* Müller, T., Evans, A., Schied, C., Keller, A. (2022). *Instant neural graphics primitives with a multiresolution hash encoding*. arXiv \[cs.CV]. [DOI](https://doi.org/10.48550/arXiv.2201.05989)

***

Found an error on this page? [Report an issue](https://github.com/aegean-ai/eaia-feedback/issues/new?template=page-issue.yml\&page=/aiml-common/lectures/3d-reconstruction/neural-radiance-fields).


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.