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

# Scenes Made of 3D Gaussians

> Rendering and fitting a scene as depth-sorted 3D Gaussians.

[![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/gaussian-splatting/index.ipynb)

A radiance field stores a scene as a function that you query at any point in space. [Neural Radiance Fields](https://aegean.ai/aiml-common/lectures/3d-reconstruction/neural-radiance-fields/index.md) fits that function with a network and renders a pixel by sampling it along the pixel's ray. Gaussian splatting keeps the rendering rule and changes the storage. The scene becomes a list of 3D Gaussians, each with a position, a shape, an opacity and a color, and a pixel is rendered by blending the Gaussians that cover it in depth order (Kerbl et al., 2023).

The book's chapter on [radiance fields](https://visionbook.mit.edu/nerf.html) lists a mixture of Gaussians as one of several ways to parameterize the same field. This section builds that parameterization from the ground up. You write the projection of a Gaussian onto the image, the compositing rule and the training loop yourself, fit the garden scene of the Mip-NeRF 360 dataset, and then check your renderer against gsplat, a reference implementation (Ye et al., 2024).

## From samples on a ray to Gaussians on a ray

A NeRF renders the pixel with ray $\mathbf{r}$ from $N$ samples at depths $t_1 < \dots < t_N$. Sample $i$ has density $\sigma_i$, color $\mathbf{c}_i$ and spacing $\delta_i = t_{i+1} - t_i$. The rendered color is

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

$\alpha_i$ is the probability that the ray stops in interval $i$ given that it reached it, and $T_i$ is the probability that it reached interval $i$ at all. The weights $w_i$ sum to at most one.

Gaussian splatting uses the same sum. The samples are replaced by the Gaussians whose footprint covers the pixel, sorted by the depth of their centers. For Gaussian $i$ with opacity $o_i$ and projected 2D density $G_i$, evaluated at pixel $\mathbf{p}$,

$$
\alpha_i = o_i\, G_i(\mathbf{p}), \qquad w_i = \alpha_i \prod_{j<i} (1 - \alpha_j).
$$

Nothing is sampled along the ray. The list of Gaussians plays the role of the samples, and their order along the ray comes from sorting. Sorting by the center is an approximation: two Gaussians that overlap in depth are still blended as if one were entirely in front of the other.

> [accordion] Code
>
> ```python theme={null}
> import os
> import sys
> import time
> import math
> import struct
> import subprocess
>
> os.environ.setdefault("HF_HUB_DISABLE_PROGRESS_BARS", "1")
> if "google.colab" in sys.modules:
>     subprocess.run([sys.executable, "-m", "pip", "install", "-q", "gsplat"], check=True)
>
> import numpy as np
> import torch
> import torch.nn.functional as F
> import cv2
> import matplotlib.pyplot as plt
> from matplotlib.patches import Ellipse
> from scipy.spatial import cKDTree
> from huggingface_hub import snapshot_download
>
> 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.manual_seed(0)
> np.random.seed(0)
>
> # training length; the page's numbers come from the default
> GS_ITERS = int(os.environ.get("GS_ITERS", "3000"))
> 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
```

## A Gaussian in three dimensions

Each Gaussian has a mean $\boldsymbol{\mu} \in \mathbb{R}^3$ and a covariance $\Sigma$, a symmetric $3 \times 3$ matrix that sets its size and orientation. Gradient descent on the six entries of $\Sigma$ could produce a matrix with a negative eigenvalue, which is not a covariance. The parameterization avoids this. Each Gaussian stores a rotation as a unit quaternion $\mathbf{q}$ and three log-scales $\mathbf{s}$, and the covariance is built from them:

$$
\Sigma = R(\mathbf{q})\, S\, S^\top R(\mathbf{q})^\top, \qquad S = \operatorname{diag}(e^{s_1}, e^{s_2}, e^{s_3}).
$$

For any vector $\mathbf{v}$, $\mathbf{v}^\top \Sigma \mathbf{v} = \lVert S^\top R^\top \mathbf{v} \rVert^2 \ge 0$, so every parameter value gives a valid covariance. The eigenvectors of $\Sigma$ are the columns of $R$, and its eigenvalues are the squared scales. The quaternion is normalized before use, so its length does not matter either.

The opacity is $o = \operatorname{sigmoid}(a)$ for an unconstrained number $a$, which keeps it in $(0, 1)$.

Color may depend on the viewing direction, because a surface can look brighter from one side. Each Gaussian stores the color as a short expansion in spherical harmonics, functions on the sphere of directions. With degree 0 and degree 1 terms, the color seen along the unit direction $\mathbf{d} = (d_x, d_y, d_z)$ from the camera to the Gaussian is

$$
\mathbf{c}(\mathbf{d}) = \tfrac{1}{2} + C_0 \mathbf{f}_0 + C_1 \left( -d_y \mathbf{f}_1 + d_z \mathbf{f}_2 - d_x \mathbf{f}_3 \right),
$$

with $C_0 = 1/(2\sqrt{\pi})$ and $C_1 = \sqrt{3/(4\pi)}$, clipped below at zero. The vectors $\mathbf{f}_0, \dots, \mathbf{f}_3 \in \mathbb{R}^3$ are learned per Gaussian. $\mathbf{f}_0$ is the view-independent color, and the degree 1 terms add a color that changes linearly with direction. The original method uses degree 3. Degree 1 keeps the parameter count small at this image size.

```python theme={null}
SH_C0 = 0.28209479177387814
SH_C1 = 0.4886025119029199


def quat_to_rot(q):
    # q = (w, x, y, z), normalized here, shape (N, 4) -> (N, 3, 3)
    q = F.normalize(q, dim=-1)
    w, x, y, z = q.unbind(-1)
    return torch.stack([
        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),
    ], -1).reshape(-1, 3, 3)


def covariance_3d(quats, log_scales):
    M = quat_to_rot(quats) * log_scales.exp()[:, None, :]   # R S
    return M @ M.transpose(1, 2)                             # R S S^T R^T


def sh_to_rgb(sh, dirs):
    # sh: (N, 4, 3) coefficients, dirs: (N, 3) unit vectors from the camera to the Gaussians
    x, y, z = dirs[:, 0:1], dirs[:, 1:2], dirs[:, 2:3]
    c = SH_C0 * sh[:, 0] - SH_C1 * y * sh[:, 1] + SH_C1 * z * sh[:, 2] - SH_C1 * x * sh[:, 3]
    return (c + 0.5).clamp_min(0.0)
```

## Projecting a Gaussian onto the image

A camera with rotation $W$ and translation $\mathbf{t}$ maps a world point to camera coordinates, $\mathbf{x} = W \boldsymbol{\mu} + \mathbf{t}$. The pinhole model of [Camera Modeling](https://aegean.ai/aiml-common/lectures/sensor-models/cameras/camera-modeling/index.md) then maps $\mathbf{x} = (x, y, z)$ to the pixel

$$
\pi(\mathbf{x}) = \begin{pmatrix} f_x\, x / z + c_x \\ f_y\, y / z + c_y \end{pmatrix}.
$$

The mean of the Gaussian goes to $\pi(W\boldsymbol{\mu} + \mathbf{t})$. The shape is harder, because a Gaussian pushed through a nonlinear map is no longer Gaussian. Around the mean, the projection is replaced by its first-order Taylor expansion, as in EWA splatting (Zwicker2005-au). The Jacobian of $\pi$ at $\mathbf{x}$ is

$$
J = \begin{pmatrix} f_x / z & 0 & -f_x x / z^2 \\ 0 & f_y / z & -f_y y / z^2 \end{pmatrix}.
$$

A linear map $A$ sends a Gaussian with covariance $\Sigma$ to one with covariance $A \Sigma A^\top$. The map from world coordinates to pixels is approximately $A = J W$, so the projected covariance is

$$
\Sigma' = J W \Sigma W^\top J^\top + 0.3\, I_2 .
$$

The Taylor expansion is poor for a Gaussian whose center lies far outside the field of view, where $x/z$ or $y/z$ is large. In $J$, these ratios are therefore clamped to a little beyond the image border, $30\%$ of the half field of view past each edge. The mean itself is projected exactly.

The term $0.3\, I_2$ widens every footprint by about half a pixel. It acts as a low-pass filter, so that a Gaussian smaller than a pixel still covers at least one pixel center instead of slipping between them.

With $\mathbf{u} = \pi(W\boldsymbol{\mu} + \mathbf{t})$ and $\mathbf{d} = \mathbf{p} - \mathbf{u}$ for pixel $\mathbf{p}$, the opacity of the Gaussian at that pixel is

$$
\alpha = \min\left(0.99,\; o \exp\left( -\tfrac{1}{2}\, \mathbf{d}^\top \Sigma'^{-1} \mathbf{d} \right)\right).
$$

The cap at $0.99$ keeps $1 - \alpha$ away from zero, so the gradient can still reach the Gaussians behind. Values below $1/255$ are set to zero, because they cannot change an 8-bit pixel. The footprint is cut off at three standard deviations along its long axis, a radius of $3\sqrt{\lambda_{\max}(\Sigma')}$ pixels.

```python theme={null}
def project(means, cov3d, W, t, K, width, height):
    # world -> camera -> pixel for the means, and the 2D covariance of each footprint
    xc = means @ W.T + t
    x, y, z = xc.unbind(-1)
    zc = z.clamp_min(1e-6)
    fx, fy, cx, cy = K[0, 0], K[1, 1], K[0, 2], K[1, 2]
    means2d = torch.stack([fx * x / zc + cx, fy * y / zc + cy], -1)
    # the Jacobian is evaluated at x/z and y/z clamped to slightly beyond the image
    tan_x, tan_y = 0.5 * width / fx, 0.5 * height / fy
    xz = (x / zc).clamp(-(cx / fx + 0.3 * tan_x), (width - cx) / fx + 0.3 * tan_x)
    yz = (y / zc).clamp(-(cy / fy + 0.3 * tan_y), (height - cy) / fy + 0.3 * tan_y)
    zero = torch.zeros_like(zc)
    J = torch.stack([
        torch.stack([fx / zc, zero, -fx * xz / zc], -1),
        torch.stack([zero, fy / zc, -fy * yz / zc], -1),
    ], -2)                                                  # (N, 2, 3)
    JW = J @ W
    cov2d = JW @ cov3d @ JW.transpose(1, 2)
    cov2d = cov2d + 0.3 * torch.eye(2, device=means.device)
    return means2d, z, cov2d


def conic_and_radius(cov2d):
    # inverse of each 2x2 covariance as (a, b, c) and the 3-sigma radius in pixels
    a, b, c = cov2d[:, 0, 0], cov2d[:, 0, 1], cov2d[:, 1, 1]
    det = (a * c - b * b).clamp_min(1e-12)
    conic = torch.stack([c / det, -b / det, a / det], -1)
    mid = 0.5 * (a + c)
    lam_max = mid + torch.sqrt((mid * mid - det).clamp_min(0.1))
    radius = torch.ceil(3.0 * torch.sqrt(lam_max))
    return conic, radius
```

## Compositing in depth order

Your renderer follows the formulas directly. It projects all Gaussians, drops those behind the camera or outside the image, sorts the rest by camera depth $z$, and evaluates the compositing sum at every pixel. The product $T_i$ is an exclusive cumulative product of $1 - \alpha_j$ over the sorted list.

Evaluating every Gaussian at every pixel would need memory proportional to their product. The image is therefore split into square tiles of $16 \times 16$ pixels. A Gaussian is assigned to every tile that its three-sigma square touches, which gives one pair per tile and Gaussian. Sorting the pairs by tile, with a sort that keeps the depth order of equal keys, lists every tile's Gaussians front to back. Tiles with lists of similar length are then processed together, each list padded to the longest one in its batch.

The rasterizer of the original paper does the same computation on the GPU. It builds the same pairs, encodes each as one 64-bit key from the tile index and the depth, and sorts all keys with one radix sort. Each tile is then a contiguous run of the sorted keys. One thread block handles one tile, one thread handles one pixel, and a thread stops as soon as its transmittance falls below $10^{-4}$. The backward pass walks the same list from back to front. The result is the same image, computed much faster, as the timing at the end of this section shows.

```python theme={null}
TILE = 16


def render(params, cam, H, W, tile=TILE, max_elems=1.5e8):
    # differentiable rendering of Gaussians; returns the image, the 2D means and a visibility mask
    means, quats, log_scales = params["means"], params["quats"], params["log_scales"]
    dev = means.device
    opac = torch.sigmoid(params["opacity"])
    cov3d = covariance_3d(quats, log_scales)
    means2d, depth, cov2d = project(means, cov3d, cam["W"], cam["t"], cam["K"], W, H)
    if means2d.requires_grad:
        means2d.retain_grad()            # its gradient drives the density control
    conic, radius = conic_and_radius(cov2d)
    color = sh_to_rgb(params["sh"], F.normalize(means - cam["center"], dim=-1))

    # 1. cull and sort front to back
    u, v = means2d[:, 0].detach(), means2d[:, 1].detach()
    visible = (depth.detach() > 0.01) & (u + radius > 0) & (u - radius < W) \
        & (v + radius > 0) & (v - radius < H)
    idx = visible.nonzero().squeeze(1)
    idx = idx[torch.argsort(depth.detach()[idx])]
    mu, cn, op, col, r = means2d[idx], conic[idx], opac[idx], color[idx], radius[idx]

    # 2. one (tile, Gaussian) pair for every tile that a footprint touches
    ntx, nty = math.ceil(W / tile), math.ceil(H / tile)
    tx0 = ((mu[:, 0].detach() - r) / tile).floor().clamp(0, ntx - 1).long()
    tx1 = ((mu[:, 0].detach() + r) / tile).floor().clamp(0, ntx - 1).long()
    ty0 = ((mu[:, 1].detach() - r) / tile).floor().clamp(0, nty - 1).long()
    ty1 = ((mu[:, 1].detach() + r) / tile).floor().clamp(0, nty - 1).long()
    nx = tx1 - tx0 + 1
    cnt = nx * (ty1 - ty0 + 1)
    g = torch.repeat_interleave(torch.arange(len(idx), device=dev), cnt)
    local = torch.arange(len(g), device=dev) - torch.repeat_interleave(torch.cumsum(cnt, 0) - cnt, cnt)
    tile_id = (ty0[g] + local // nx[g]) * ntx + tx0[g] + local % nx[g]
    order = torch.argsort(tile_id, stable=True)      # stable: depth order survives inside a tile
    tile_id, g = tile_id[order], g[order]
    n_tiles = ntx * nty
    counts = torch.bincount(tile_id, minlength=n_tiles)
    starts = torch.cumsum(counts, 0) - counts

    # 3. composite batches of tiles with similar list lengths, each list padded to the longest
    P = tile * tile
    ly, lx = torch.meshgrid(torch.arange(tile, device=dev), torch.arange(tile, device=dev), indexing="ij")
    tiles_by_len = torch.argsort(counts, descending=True)
    lens = counts[tiles_by_len].tolist()
    done, outs, i = [], [], 0
    while i < n_tiles:
        L = max(lens[i], 1)
        b = max(1, int(max_elems // (P * L)))
        batch = tiles_by_len[i:i + b]
        ar = torch.arange(L, device=dev)
        valid = ar[None] < counts[batch][:, None]                        # (b, L)
        gi = g[(starts[batch][:, None] + ar[None]).clamp(max=max(len(g) - 1, 0))] if len(g) else \
            torch.zeros(len(batch), L, dtype=torch.long, device=dev)
        px = ((batch % ntx)[:, None] * tile + lx.reshape(1, P)).float() + 0.5   # pixel centers
        py = ((batch // ntx)[:, None] * tile + ly.reshape(1, P)).float() + 0.5
        dx = px[:, :, None] - mu[gi, 0][:, None, :]                      # (b, P, L)
        dy = py[:, :, None] - mu[gi, 1][:, None, :]
        a, bb, c = cn[gi, 0][:, None], cn[gi, 1][:, None], cn[gi, 2][:, None]
        alpha = (op[gi][:, None] * torch.exp(-0.5 * (a * dx * dx + 2 * bb * dx * dy + c * dy * dy)))
        alpha = alpha.clamp_max(0.99) * valid[:, None, :]
        alpha = torch.where(alpha < 1.0 / 255.0, torch.zeros_like(alpha), alpha)
        T = torch.cumprod(1.0 - alpha, dim=-1)
        T = torch.cat([torch.ones_like(T[..., :1]), T[..., :-1]], dim=-1)   # exclusive product
        outs.append(torch.einsum("bpl,blc->bpc", T * alpha, col[gi]))
        done.append(batch)
        i += b
    tiles_rgb = torch.zeros(n_tiles, P, 3, device=dev).index_copy(0, torch.cat(done), torch.cat(outs))
    image = tiles_rgb.reshape(nty, ntx, tile, tile, 3).permute(0, 2, 1, 3, 4)
    image = image.reshape(nty * tile, ntx * tile, 3)[:H, :W]
    return image, means2d, visible
```

The figure shows four Gaussians in front of a camera. The left panel draws each projected covariance $\Sigma'$ as its one- and two-sigma ellipses. The right panel is the output of the renderer. Where the orange Gaussian passes in front of the blue one, the blue one shows through only as far as $T_i$ allows.

> [accordion] Code
>
> ```python theme={null}
> toy_cam = {
>     "W": torch.eye(3, device=DEVICE), "t": torch.zeros(3, device=DEVICE),
>     "K": torch.tensor([[150.0, 0, 80], [0, 150.0, 60], [0, 0, 1]], device=DEVICE),
>     "center": torch.zeros(3, device=DEVICE),
> }
> toy_rgb = torch.tensor([[0.0, 0.447, 0.698], [0.835, 0.369, 0.0], [0.0, 0.62, 0.451], [0.80, 0.47, 0.65]])
> toy = {
>     "means": torch.tensor([[-0.25, -0.05, 3.0], [0.05, 0.05, 2.2], [0.35, -0.2, 2.8], [-0.1, 0.3, 2.5]]),
>     "quats": F.normalize(torch.tensor([[1.0, 0, 0, 0], [0.92, 0.0, 0.0, 0.39], [0.92, 0.2, 0.3, -0.1],
>                                        [0.7, 0.0, 0.0, 0.7]]), dim=-1),
>     "log_scales": torch.log(torch.tensor([[0.25, 0.12, 0.1], [0.3, 0.05, 0.1],
>                                           [0.08, 0.08, 0.08], [0.2, 0.04, 0.04]])),
>     "opacity": torch.logit(torch.tensor([0.9, 0.7, 0.95, 0.8])),
>     "sh": torch.cat([((toy_rgb - 0.5) / SH_C0)[:, None], torch.zeros(4, 3, 3)], 1),
> }
> toy = {k: v.to(DEVICE) for k, v in toy.items()}
> with torch.no_grad():
>     toy_img, _, _ = render(toy, toy_cam, 120, 160)
>     m2d, _, c2d = project(toy["means"], covariance_3d(toy["quats"], toy["log_scales"]),
>                           toy_cam["W"], toy_cam["t"], toy_cam["K"], 160, 120)
> ```

![Left: four projected Gaussians drawn as solid one-sigma and dashed two-sigma ellipses in blue, orange, green and pink on a 160 by 120 pixel image plane. Right: the renderer's image of the same four Gaussians, soft colored blobs on black, with the orange one in front of the blue one.](https://mintcdn.com/aegeanaiinc/dLMqX5MXOVYfDcDh/aiml-common/lectures/3d-reconstruction/gaussian-splatting/images/cell_6_output_1.svg?fit=max\&auto=format\&n=dLMqX5MXOVYfDcDh\&q=85\&s=062ba54ce5d9424074ab930698706251)

## The garden scene

The scene is the garden of the Mip-NeRF 360 dataset: 185 photos of a table with a vase, taken on a circle around it, together with the camera poses and sparse 3D points that [Structure from Motion](https://aegean.ai/aiml-common/lectures/3d-reconstruction/structure-from-motion/index.md) recovered from them. You read the three binary files of that reconstruction directly: the camera intrinsics, one pose per image, and the 3D points with their colors.

The photos are used at one sixteenth of their full width, $324 \times 210$ pixels, with the intrinsics scaled to match. Every eighth image, in name order, is held out for testing, and the rest are used for training. [Neural Radiance Fields](https://aegean.ai/aiml-common/lectures/3d-reconstruction/neural-radiance-fields/index.md) uses the same images and the same split, so the test scores of the two pages compare directly.

> [accordion] Code
>
> ```python theme={null}
> DATA = snapshot_download(repo_id="mileleap/mipnerf360", repo_type="dataset",
>                          allow_patterns=["garden/images_8/*", "garden/sparse/*"])
> SCENE = os.path.join(DATA, "garden")
>
>
> def read_colmap(sparse_dir):
>     # minimal reader for COLMAP's cameras.bin, images.bin and points3D.bin
>     def rd(f, fmt):
>         return struct.unpack("<" + fmt, f.read(struct.calcsize("<" + fmt)))
>
>     cameras = {}
>     with open(os.path.join(sparse_dir, "cameras.bin"), "rb") as f:
>         for _ in range(rd(f, "Q")[0]):
>             cam_id, model, width, height = rd(f, "iiQQ")
>             n_params = {0: 3, 1: 4, 2: 4, 3: 5}[model]
>             p = rd(f, "d" * n_params)
>             fx, fy, cx, cy = (p[0], p[1], p[2], p[3]) if model == 1 else (p[0], p[0], p[1], p[2])
>             cameras[cam_id] = dict(width=width, height=height, fx=fx, fy=fy, cx=cx, cy=cy)
>     images = []
>     with open(os.path.join(sparse_dir, "images.bin"), "rb") as f:
>         for _ in range(rd(f, "Q")[0]):
>             vals = rd(f, "i7di")
>             name = b""
>             while (ch := f.read(1)) != b"\x00":
>                 name += ch
>             n2d = rd(f, "Q")[0]
>             f.seek(24 * n2d, 1)                       # skip the 2D observations
>             images.append(dict(name=name.decode(), q=np.array(vals[1:5]),
>                                t=np.array(vals[5:8]), camera=vals[8]))
>     with open(os.path.join(sparse_dir, "points3D.bin"), "rb") as f:
>         n = rd(f, "Q")[0]
>         xyz, rgb = np.empty((n, 3)), np.empty((n, 3))
>         for k in range(n):
>             vals = rd(f, "Q3d3Bd")
>             xyz[k], rgb[k] = vals[1:4], vals[4:7]
>             f.seek(8 * rd(f, "Q")[0], 1)              # skip the track
>     return cameras, sorted(images, key=lambda im: im["name"]), xyz, rgb / 255.0
>
>
> cameras, images, points_xyz, points_rgb = read_colmap(os.path.join(SCENE, "sparse", "0"))
> print(f"{len(images)} images, {len(points_xyz)} sparse points")
> ```

```output theme={null}
185 images, 138766 sparse points
```

> [accordion] Code
>
> ```python theme={null}
> 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)],
>     ])
>
>
> views, cams = [], []
> for im in images:
>     bgr = cv2.imread(os.path.join(SCENE, "images_8", im["name"]))
>     h8, w8 = bgr.shape[:2]
>     small = cv2.resize(bgr, (w8 // 2, h8 // 2), interpolation=cv2.INTER_AREA)
>     views.append(torch.tensor(small[..., ::-1].copy(), dtype=torch.float32, device=DEVICE) / 255.0)
>     H, W = small.shape[:2]
>     c = cameras[im["camera"]]
>     sx, sy = W / c["width"], H / c["height"]
>     K = torch.tensor([[c["fx"] * sx, 0, c["cx"] * sx], [0, c["fy"] * sy, c["cy"] * sy], [0, 0, 1]],
>                      dtype=torch.float32, device=DEVICE)
>     R = qvec_to_rotmat(im["q"])
>     cams.append({
>         "W": torch.tensor(R, dtype=torch.float32, device=DEVICE),
>         "t": torch.tensor(im["t"], dtype=torch.float32, device=DEVICE),
>         "K": K,
>         "center": torch.tensor(-R.T @ im["t"], dtype=torch.float32, device=DEVICE),
>     })
>
> test_ids = [i for i in range(len(views)) if i % 8 == 0]
> train_ids = [i for i in range(len(views)) if i % 8 != 0]
> centers = torch.stack([c["center"] for c in cams])
> extent = 1.1 * (centers - centers.mean(0)).norm(dim=1).max().item()
> print(f"image size {W} x {H}, {len(train_ids)} training and {len(test_ids)} test views, "
>       f"scene extent {extent:.2f}")
> ```

```output theme={null}
image size 324 x 210, 161 training and 24 test views, scene extent 4.94
```

## Starting from the sparse points

Fitting Gaussians from random positions works poorly, because a Gaussian far from any surface receives almost no gradient. The sparse points of structure from motion already lie on the surfaces, so each point becomes one Gaussian. Its mean is the point, its color is the point's color, its opacity is $0.1$, and it starts as a sphere whose radius is the mean distance to its three nearest neighbors. Dense regions get small Gaussians and sparse regions get large ones, so the scene starts out roughly covered.

The figure shows the sparse points projected into a training view next to the photo, and the image that the initial Gaussians render from the same camera.

> [accordion] Code
>
> ```python theme={null}
> GS_INIT = 40_000          # initial Gaussians, a random subset of the sparse points
> GS_MAX = 120_000          # cap on the number of Gaussians during training
>
> rng = np.random.default_rng(0)
> sel = rng.choice(len(points_xyz), size=min(GS_INIT, len(points_xyz)), replace=False)
> xyz0, rgb0 = points_xyz[sel], points_rgb[sel]
> dist, _ = cKDTree(xyz0).query(xyz0, k=4)
> scale0 = np.clip(dist[:, 1:].mean(1), 1e-4, None)
>
> init_params = {
>     "means": torch.tensor(xyz0, dtype=torch.float32),
>     "quats": torch.tensor([[1.0, 0.0, 0.0, 0.0]]).repeat(len(sel), 1),
>     "log_scales": torch.log(torch.tensor(scale0, dtype=torch.float32))[:, None].repeat(1, 3),
>     "opacity": torch.logit(torch.full((len(sel),), 0.1)),
>     "sh": torch.cat([((torch.tensor(rgb0, dtype=torch.float32) - 0.5) / SH_C0)[:, None],
>                      torch.zeros(len(sel), 3, 3)], 1),
> }
> init_params = {k: v.to(DEVICE) for k, v in init_params.items()}
> print(f"{len(sel)} initial Gaussians")
> ```

```output theme={null}
40000 initial Gaussians
```

![Three panels for one training camera of the garden scene: the photo of a round table with a vase on a lawn; the sparse 3D points projected into the view as colored dots that trace the table, vase and background; and the blurry image rendered from the initial spherical Gaussians.](https://mintcdn.com/aegeanaiinc/dLMqX5MXOVYfDcDh/aiml-common/lectures/3d-reconstruction/gaussian-splatting/images/cell_10_output_1.svg?fit=max\&auto=format\&n=dLMqX5MXOVYfDcDh\&q=85\&s=0fd142eefe5bdcad8f7018b1c3358761)

## The loss

Training compares the rendered image $\hat{I}$ with the photo $I$ from the same camera. The loss mixes a per-pixel error with a structural one:

$$
\mathcal{L} = (1 - \lambda)\, \lVert \hat{I} - I \rVert_1 + \lambda \left( 1 - \operatorname{SSIM}(\hat{I}, I) \right), \qquad \lambda = 0.2 .
$$

The $\ell_1$ term is the mean absolute difference over pixels and channels. SSIM, the structural similarity index, compares local means, variances and covariances of the two images inside a Gaussian window of standard deviation $1.5$ pixels. For local statistics $m$, $s^2$ and $s_{12}$,

$$
\operatorname{SSIM} = \frac{(2 m_1 m_2 + k_1)(2 s_{12} + k_2)}{(m_1^2 + m_2^2 + k_1)(s_1^2 + s_2^2 + k_2)},
$$

averaged over the image, with $k_1 = 0.01^2$ and $k_2 = 0.03^2$. It rewards renders whose edges and textures line up with the photo even where the absolute colors differ slightly.

```python theme={null}
def ssim(x, y, window=11, sigma=1.5):
    # x, y: (H, W, 3) in [0, 1]
    x, y = x.permute(2, 0, 1)[None], y.permute(2, 0, 1)[None]
    g = torch.exp(-((torch.arange(window, device=x.device) - window // 2) ** 2) / (2 * sigma**2))
    g = g / g.sum()
    w = (g[:, None] * g[None, :]).expand(3, 1, window, window)
    conv = lambda z: F.conv2d(z, w, padding=window // 2, groups=3)
    m1, m2 = conv(x), conv(y)
    s1, s2, s12 = conv(x * x) - m1**2, conv(y * y) - m2**2, conv(x * y) - m1 * m2
    k1, k2 = 0.01**2, 0.03**2
    s = ((2 * m1 * m2 + k1) * (2 * s12 + k2)) / ((m1**2 + m2**2 + k1) * (s1 + s2 + k2))
    return s.mean()


def loss_fn(pred, target, lam=0.2):
    return (1 - lam) * (pred - target).abs().mean() + lam * (1 - ssim(pred, target))


def psnr(pred, target):
    return (-10 * torch.log10(((pred.clamp(0, 1) - target) ** 2).mean())).item()
```

## Adding and removing Gaussians

The initial Gaussians are too few in some places and too many in others. Every 100 steps, training changes the set itself. The rule uses the gradient of the loss with respect to each projected mean $\mathbf{u}_i$. A large gradient means that the Gaussian keeps being pulled to cover an area that it cannot cover alone.

Each step adds $\lVert \partial \mathcal{L} / \partial \mathbf{u}_i \rVert$ to a running sum for every visible Gaussian, with the gradient expressed in normalized image coordinates, where the image spans $[-1, 1]$. When the average exceeds $0.0002$, the Gaussian is changed:

* If its largest scale is at most $1\%$ of the scene extent, it is cloned. The copy starts at the same place and moves apart under later gradients. This fills regions that are under-reconstructed.
* If it is larger, it is split into two Gaussians drawn from the original as a distribution, each with its scales divided by $1.6$. This breaks up large Gaussians that cover detail they cannot represent.

The total number of Gaussians is capped at 120,000. Gaussians whose opacity falls below $0.005$ are removed. One third of the way through training, every opacity is reset to at most $0.01$. Gaussians that matter recover their opacity within a few hundred steps, and the rest fall below the threshold and are removed. After the reset, Gaussians larger than $10\%$ of the scene extent are removed too. Splitting and cloning stop after $60\%$ of the steps, so the final set is refined without changing size.

```python theme={null}
LR = {"means": 1.6e-4 * extent, "quats": 1e-3, "log_scales": 5e-3, "opacity": 5e-2, "sh": 2.5e-3}


def make_optimizer(params):
    groups = [{"params": [params[k]], "lr": LR[k], "name": k} for k in params]
    return torch.optim.Adam(groups, eps=1e-15)


def replace_rows(opt, params, keep, new=None):
    # keep a subset of rows of every parameter, append new rows, and carry Adam's moments along
    for g in opt.param_groups:
        name, p = g["name"], g["params"][0]
        state = opt.state.pop(p, None)
        extra = new[name] if new is not None else p.data[:0]
        q = torch.nn.Parameter(torch.cat([p.data[keep], extra]))
        if state is not None:
            for key in ("exp_avg", "exp_avg_sq"):
                state[key] = torch.cat([state[key][keep], torch.zeros_like(extra)])
            opt.state[q] = state
        g["params"][0] = q
        params[name] = q


def densify(opt, params, grad_avg, prune_large):
    smax = params["log_scales"].exp().max(dim=1).values
    big = grad_avg > 0.0002
    clone = big & (smax <= 0.01 * extent)
    split = big & (smax > 0.01 * extent)
    n = params["means"].shape[0]
    budget = max(GS_MAX - n, 0)
    cand = (clone | split).nonzero().squeeze(1)
    if cand.numel() > budget:            # keep the largest gradients within the cap
        top = cand[torch.argsort(grad_avg[cand], descending=True)[:budget]]
        chosen = torch.zeros_like(big)
        chosen[top] = True
        clone, split = clone & chosen, split & chosen

    new = {k: v.data[clone] for k, v in params.items()}
    s_idx = split.nonzero().squeeze(1)
    if s_idx.numel() > 0:
        R = quat_to_rot(params["quats"].data[s_idx])
        s = params["log_scales"].data[s_idx].exp()
        for _ in range(2):
            offset = (R @ (s * torch.randn_like(s))[..., None]).squeeze(-1)
            child = {k: v.data[s_idx] for k, v in params.items()}
            child["means"] = child["means"] + offset
            child["log_scales"] = child["log_scales"] - math.log(1.6)
            new = {k: torch.cat([new[k], child[k]]) for k in new}

    prune = torch.sigmoid(params["opacity"].data) < 0.005
    if prune_large:
        prune |= smax > 0.1 * extent
    replace_rows(opt, params, ~(split | prune), new)


def reset_opacity(opt, params):
    with torch.no_grad():
        params["opacity"].data = torch.minimum(params["opacity"].data,
                                               torch.logit(torch.tensor(0.01, device=DEVICE)))
    for g in opt.param_groups:
        if g["name"] == "opacity":
            st = opt.state.get(g["params"][0])
            if st:
                st["exp_avg"].zero_()
                st["exp_avg_sq"].zero_()
```

## Training

Each step picks one training view at random, renders it, and takes one Adam step on all parameters. The learning rate of the means decays exponentially by a factor of 100 over training, so that the positions settle at the end. The training loop takes the renderer as an argument, which lets you run it later with a different rasterizer.

> [accordion] Code
>
> ```python theme={null}
> def train(render_fn, iters=GS_ITERS, seed=0, log_every=50):
>     params = {k: torch.nn.Parameter(v.clone()) for k, v in init_params.items()}
>     opt = make_optimizer(params)
>     densify_from, densify_until, every = int(0.1 * iters), int(0.6 * iters), 100
>     reset_at = iters // 3
>     grad_sum = torch.zeros(params["means"].shape[0], device=DEVICE)
>     grad_cnt = torch.zeros_like(grad_sum)
>     hist = {"step": [], "loss": [], "count": []}
>     rng = np.random.default_rng(seed)
>     lr0, lr1 = LR["means"], LR["means"] / 100
>     if DEVICE.type == "cuda":
>         torch.cuda.synchronize()
>     t0 = time.time()
>     for it in range(1, iters + 1):
>         i = train_ids[rng.integers(len(train_ids))]
>         img, means2d, visible = render_fn(params, cams[i], H, W)
>         loss = loss_fn(img, views[i])
>         opt.zero_grad(set_to_none=True)
>         loss.backward()
>         with torch.no_grad():
>             g = means2d.grad.reshape(-1, 2) * torch.tensor([W / 2, H / 2], device=DEVICE)
>             grad_sum[visible] += g.norm(dim=1)[visible]
>             grad_cnt[visible] += 1
>         for grp in opt.param_groups:
>             if grp["name"] == "means":
>                 grp["lr"] = lr0 * (lr1 / lr0) ** (it / iters)
>         opt.step()
>
>         if densify_from <= it <= densify_until and it % every == 0:
>             densify(opt, params, grad_sum / grad_cnt.clamp_min(1), prune_large=it > reset_at)
>             grad_sum = torch.zeros(params["means"].shape[0], device=DEVICE)
>             grad_cnt = torch.zeros_like(grad_sum)
>         if it == reset_at:
>             reset_opacity(opt, params)
>         if it % log_every == 0:
>             hist["step"].append(it)
>             hist["loss"].append(loss.item())
>             hist["count"].append(params["means"].shape[0])
>     if DEVICE.type == "cuda":
>         torch.cuda.synchronize()
>     return params, hist, time.time() - t0
>
>
> def test_psnr(params, render_fn):
>     with torch.no_grad():
>         return float(np.mean([psnr(render_fn(params, cams[i], H, W)[0], views[i]) for i in test_ids]))
>
>
> params, hist, train_time = train(render)
> ours_psnr = test_psnr(params, render)
> print(f"trained {GS_ITERS} steps in {train_time / 60:.1f} min, "
>       f"{params['means'].shape[0]} Gaussians, test PSNR {ours_psnr:.2f} dB")
> ```

```output theme={null}
trained 3000 steps in 8.1 min, 119843 Gaussians, test PSNR 26.91 dB
```

![Left: the training loss falling over the training steps, raw values faint and a moving average solid. Right: the number of Gaussians over the steps, rising to the cap of 120,000 by about step 700, dipping briefly after the opacity reset marked by a dashed line, then staying at the cap.](https://mintcdn.com/aegeanaiinc/dLMqX5MXOVYfDcDh/aiml-common/lectures/3d-reconstruction/gaussian-splatting/images/cell_14_output_1.svg?fit=max\&auto=format\&n=dLMqX5MXOVYfDcDh\&q=85\&s=81724d97c621e8cdcd59bbfb4a020946)

The test views were never used for training. The figure compares three of them with the renders from the trained Gaussians.

![Two rows of three images. Top: held-out photos of the garden table from three viewpoints. Bottom: the renders of the trained Gaussians from the same cameras, each titled with its PSNR in decibels.](https://mintcdn.com/aegeanaiinc/dLMqX5MXOVYfDcDh/aiml-common/lectures/3d-reconstruction/gaussian-splatting/images/cell_15_output_1.svg?fit=max\&auto=format\&n=dLMqX5MXOVYfDcDh\&q=85\&s=fd2cea2c9ca38a0226a198ef0bbc9891)

The compositing weights along one pixel's ray make the link to NeRF concrete. For a pixel on the table, the figure lists the Gaussians that cover it in depth order, with their $\alpha_i$, the transmittance $T_i$ in front of each, and the weights $w_i = T_i \alpha_i$. The weights concentrate on the few Gaussians at the surface, just as NeRF's weights concentrate on the samples where the ray stops.

![Bar chart over the Gaussians that cover one pixel, in depth order: blue bars for alpha, orange bars for the weight T times alpha, and a green line for the transmittance T, which starts at one and drops to near zero after a few Gaussians where the weights are concentrated.](https://mintcdn.com/aegeanaiinc/dLMqX5MXOVYfDcDh/aiml-common/lectures/3d-reconstruction/gaussian-splatting/images/cell_16_output_1.svg?fit=max\&auto=format\&n=dLMqX5MXOVYfDcDh\&q=85\&s=3c2da9815eee1ee5d75d58341fe89e5b)

```output theme={null}
71 Gaussians cover the pixel; the weights sum to 0.998
```

## Checking the renderer against gsplat

gsplat implements the tiled rasterizer of the paper in CUDA (Ye et al., 2024). Given the same Gaussians and the same camera, it should produce the same image as your renderer. It projects with the same clamped Jacobian, adds the same $0.3\, I_2$ and uses the same $1/255$ cutoff. Two details differ. gsplat stops compositing a pixel once its transmittance falls below $10^{-4}$, while your renderer adds every remaining Gaussian, and the two add their terms in a different order in floating point. The mean difference stays far below one gray level of an 8-bit image, and the largest is a few gray levels.

> [accordion] Code
>
> ```python theme={null}
> from gsplat import rasterization
>
>
> def viewmat(cam):
>     m = torch.eye(4, device=DEVICE)
>     m[:3, :3], m[:3, 3] = cam["W"], cam["t"]
>     return m
>
>
> def render_gsplat(params, cam, H, W):
>     img, _, meta = rasterization(
>         means=params["means"], quats=params["quats"], scales=params["log_scales"].exp(),
>         opacities=torch.sigmoid(params["opacity"]), colors=params["sh"],
>         viewmats=viewmat(cam)[None], Ks=cam["K"][None], width=W, height=H,
>         sh_degree=1, packed=False, near_plane=0.01, eps2d=0.3)
>     means2d = meta["means2d"]
>     if means2d.requires_grad:
>         means2d.retain_grad()
>     radii = meta["radii"][0]
>     visible = (radii > 0).all(-1) if radii.dim() == 2 else radii > 0
>     return img[0], means2d, visible
>
>
> i_chk = test_ids[1]
> with torch.no_grad():
>     ours = render(params, cams[i_chk], H, W)[0]
>     ref = render_gsplat(params, cams[i_chk], H, W)[0]
> diff = (ours - ref).abs()
> print(f"max abs difference {diff.max().item():.4f}, mean abs difference {diff.mean().item():.2e} "
>       f"(pixel values in [0, 1])")
> ```

```output theme={null}
max abs difference 0.0092, mean abs difference 1.27e-05 (pixel values in [0, 1])
```

![Three panels for one test camera: the image from the page's renderer, the image from gsplat with the same Gaussians, and a heat map of their per-pixel absolute difference with a color bar; the difference is near zero almost everywhere.](https://mintcdn.com/aegeanaiinc/dLMqX5MXOVYfDcDh/aiml-common/lectures/3d-reconstruction/gaussian-splatting/images/cell_18_output_1.svg?fit=max\&auto=format\&n=dLMqX5MXOVYfDcDh\&q=85\&s=bef8f6941b098bcbf9f5ddb8fe50234c)

## The same training with a tiled CUDA rasterizer

The training loop runs unchanged with gsplat as the renderer: same initial Gaussians, same loss, same density control, same number of steps. Only the rasterizer differs, so any difference in training time comes from it.

> [accordion] Code
>
> ```python theme={null}
> params_g, hist_g, train_time_g = train(render_gsplat)
> gsplat_psnr = test_psnr(params_g, render_gsplat)
>
>
> def frame_ms(render_fn, p, n=10):
>     with torch.no_grad():
>         render_fn(p, cams[test_ids[0]], H, W)
>         if DEVICE.type == "cuda":
>             torch.cuda.synchronize()
>         t0 = time.time()
>         for _ in range(n):
>             render_fn(p, cams[test_ids[0]], H, W)
>         if DEVICE.type == "cuda":
>             torch.cuda.synchronize()
>     return 1000 * (time.time() - t0) / n
>
>
> rows = [
>     ("your renderer", train_time, ours_psnr, params["means"].shape[0], frame_ms(render, params)),
>     ("gsplat", train_time_g, gsplat_psnr, params_g["means"].shape[0], frame_ms(render_gsplat, params_g)),
> ]
> print(f"{'rasterizer':<15}{'train (min)':>12}{'test PSNR (dB)':>16}{'Gaussians':>11}{'ms per frame':>14}")
> for name, tt, p, n, ms in rows:
>     print(f"{name:<15}{tt / 60:>12.2f}{p:>16.2f}{n:>11d}{ms:>14.1f}")
> print(f"training speedup {train_time / train_time_g:.0f}x")
> ```

```output theme={null}
rasterizer      train (min)  test PSNR (dB)  Gaussians  ms per frame
your renderer          8.11           26.91     119843          62.0
gsplat                 0.91           26.91     119840           5.5
training speedup 9x
```

The two runs reach similar test scores, because they optimize the same model with the same rule. The tiled CUDA rasterizer is what makes splatting fast. It processes all tiles in parallel and stops each pixel early, while your renderer loops over tiles in Python and evaluates every Gaussian in a tile at every pixel. The published method trains for 30,000 steps on full-resolution images with spherical harmonics of degree 3, and reaches real-time rendering at 1080p.

## Gaussians and radiance fields compared

Both representations are fitted with the same compositing rule, so the comparison is about what each stores.

* Rendering speed. A NeRF evaluates a network at every sample on every ray. Gaussians are projected once per frame and blended, which is fast enough for real-time display.
* Explicit and editable. Each Gaussian is a small object with a position and a color. You can select, delete, move or recolor parts of the scene directly, which a network's weights do not allow.
* Memory. A NeRF network is a few megabytes whatever the scene. A Gaussian scene grows with its detail, often to millions of Gaussians and hundreds of megabytes.
* View-dependent effects. Spherical harmonics of low degree capture gentle changes of color with direction. A NeRF's network can represent sharper reflections, at the cost of evaluating it everywhere.
* Empty space. A NeRF must learn that most of space is empty and spends samples there. Gaussians exist only where the scene has content.

[Neural Radiance Fields](https://aegean.ai/aiml-common/lectures/3d-reconstruction/neural-radiance-fields/index.md) reports its test PSNR on the same images and split, so you can compare the two numbers directly. Before a robot simulator can use a splat scene, the scene has to be placed in the robot's frame with real units. [Registering a Scan to the Robot](https://aegean.ai/aiml-common/lectures/sim2real/frame-alignment/index.md) covers that step.

## 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)
* Ye, V., Li, R., Kerr, J., Turkulainen, M., Yi, B., et al. (2024). *gsplat: An Open-Source Library for Gaussian Splatting*. [DOI](https://doi.org/10.48550/ARXIV.2409.06765)

***

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/gaussian-splatting).


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