From 38344a998728738d8ffd25377bcd5d06ccdbce12 Mon Sep 17 00:00:00 2001
From: Senne Cools <113857183+sennecools@users.noreply.github.com>
Date: Mon, 16 Nov 2026 22:13:36 +0100
Subject: [PATCH 1/4] Fix edge coverage, add nvdiffrast compatibility and cube
maps
Rasterization: a pixel centre on a shared edge now belongs to one
triangle only (top-left rule), and the Triton visibility kernels run
without FP fusion, which left holes on such edges. Zero-area and
non-finite triangles are not drawn. Adds range mode, the glctx
parameter name and output_db on contexts.
Texture: cube maps, custom mip lists, texture_construct_mip, and
area-weighted mip levels for odd sizes. Out-of-range input behaves
the same on both backends.
Antialias: no NaN gradients on axis-aligned edges, pixels on a
silhouette are half covered whatever the fill rule, edge adjacency is
cached per tri tensor, and pos may be shared across the batch.
Compatibility: diffrast.torch, RasterizeGLContext,
install_as_nvdiffrast, the log-level functions, validated indices,
and an empty out_da instead of None. Triton backward passes raise on
second-order gradients, and interpolate skips attribute gradients
that are not needed.
---
src/diffrast/__init__.py | 24 +-
src/diffrast/_cache.py | 82 ++
src/diffrast/backends/_autograd.py | 35 +
src/diffrast/backends/_cube.py | 143 ++++
src/diffrast/backends/_triton_antialias.py | 156 ++--
src/diffrast/backends/_triton_interpolate.py | 57 +-
src/diffrast/backends/_triton_rasterize.py | 83 +-
src/diffrast/backends/_triton_resolve.py | 27 +-
src/diffrast/backends/_triton_texture.py | 328 +++++---
src/diffrast/backends/reference.py | 592 +++++++++++---
src/diffrast/backends/triton.py | 29 +-
src/diffrast/compat.py | 74 ++
src/diffrast/context.py | 95 ++-
src/diffrast/log.py | 38 +
src/diffrast/ops.py | 532 ++++++++++--
src/diffrast/peeling.py | 69 +-
src/diffrast/topology.py | 72 ++
src/diffrast/torch.py | 19 +
tests/test_antialias_fixes.py | 442 ++++++++++
tests/test_compat.py | 614 ++++++++++++++
tests/test_coverage.py | 818 ++++++++++++++++++
tests/test_cube.py | 819 +++++++++++++++++++
tests/test_input_checks.py | 401 +++++++++
tests/test_interpolate.py | 2 +-
tests/test_mip.py | 776 ++++++++++++++++++
tests/test_peeling.py | 4 +-
tests/test_ranges.py | 307 +++++++
tests/test_topology.py | 414 ++++++++++
tests/test_triton.py | 21 +-
tests/test_validation.py | 13 +-
30 files changed, 6673 insertions(+), 413 deletions(-)
create mode 100644 src/diffrast/_cache.py
create mode 100644 src/diffrast/backends/_autograd.py
create mode 100644 src/diffrast/backends/_cube.py
create mode 100644 src/diffrast/compat.py
create mode 100644 src/diffrast/log.py
create mode 100644 src/diffrast/topology.py
create mode 100644 src/diffrast/torch.py
create mode 100644 tests/test_antialias_fixes.py
create mode 100644 tests/test_compat.py
create mode 100644 tests/test_coverage.py
create mode 100644 tests/test_cube.py
create mode 100644 tests/test_input_checks.py
create mode 100644 tests/test_mip.py
create mode 100644 tests/test_ranges.py
create mode 100644 tests/test_topology.py
diff --git a/src/diffrast/__init__.py b/src/diffrast/__init__.py
index b2277d7..dd82aaf 100644
--- a/src/diffrast/__init__.py
+++ b/src/diffrast/__init__.py
@@ -1,21 +1,41 @@
"""Portable differentiable mesh rasterization for PyTorch."""
from diffrast.backends import get_backend_name, set_backend
-from diffrast.context import RasterizeContext, RasterizeCudaContext
-from diffrast.ops import antialias, interpolate, rasterize, texture
+from diffrast.compat import install_as_nvdiffrast, uninstall_as_nvdiffrast
+from diffrast.context import RasterizeContext, RasterizeCudaContext, RasterizeGLContext
+from diffrast.log import get_log_level, set_log_level
+from diffrast.ops import (
+ MipStack,
+ antialias,
+ antialias_construct_topology_hash,
+ interpolate,
+ rasterize,
+ texture,
+ texture_construct_mip,
+)
from diffrast.peeling import DepthPeeler
+from diffrast.topology import TopologyHash
__version__ = "0.1.0.dev0"
__all__ = [
"DepthPeeler",
+ "MipStack",
"RasterizeContext",
"RasterizeCudaContext",
+ "RasterizeGLContext",
+ "TopologyHash",
"__version__",
"antialias",
+ "antialias_construct_topology_hash",
"get_backend_name",
+ "get_log_level",
+ "install_as_nvdiffrast",
"interpolate",
"rasterize",
"set_backend",
+ "set_log_level",
"texture",
+ "texture_construct_mip",
+ "uninstall_as_nvdiffrast",
]
diff --git a/src/diffrast/_cache.py b/src/diffrast/_cache.py
new file mode 100644
index 0000000..cb2182b
--- /dev/null
+++ b/src/diffrast/_cache.py
@@ -0,0 +1,82 @@
+"""Cache for values derived from the contents of a tensor."""
+
+from __future__ import annotations
+
+import threading
+import weakref
+from collections import OrderedDict
+from collections.abc import Callable
+from typing import Generic, TypeVar
+
+from torch import Tensor
+
+T = TypeVar("T")
+
+
+def stamp(tensor: Tensor) -> tuple | None:
+ """A value that changes when ``tensor`` is modified, or ``None`` if that cannot be told.
+
+ It combines the version counter, which PyTorch increments on every in-place operation, also
+ one made through a view, with the address and shape of the data, which change when the
+ tensor is given new storage. Writes that bypass the version counter are not seen: in-place
+ operations on ``tensor.data``, and writes to memory shared with NumPy or another library.
+ """
+ if tensor.is_inference():
+ # Inference tensors have no version counter.
+ return None
+ return tensor._version, tensor.data_ptr(), tensor.shape
+
+
+class TensorCache(Generic[T]):
+ """Remembers ``compute(tensor)`` per tensor object until the tensor is modified or freed.
+
+ An entry is keyed on the identity of the tensor object and holds a weak reference to it
+ together with its :func:`stamp`. A lookup only hits when both still match, so a modified
+ tensor and a new tensor with the same contents are computed again, and an entry is dropped
+ as soon as its tensor is freed.
+
+ Args:
+ compute: Function of the tensor whose result is cached. The result must not keep the
+ tensor alive.
+ max_entries: Number of tensors remembered before the oldest entry is dropped.
+ """
+
+ def __init__(self, compute: Callable[[Tensor], T], max_entries: int = 64) -> None:
+ self._compute = compute
+ self._max_entries = max_entries
+ self._entries: OrderedDict[int, tuple[weakref.ref[Tensor], tuple, T]] = OrderedDict()
+ # Re-entrant, because a weak reference callback can run while this thread holds it.
+ self._lock = threading.RLock()
+
+ def __len__(self) -> int:
+ return len(self._entries)
+
+ def get(self, tensor: Tensor) -> T:
+ """Return ``compute(tensor)``, reusing the stored result while ``tensor`` is unchanged."""
+ current = stamp(tensor)
+ if current is None:
+ return self._compute(tensor)
+ key = id(tensor)
+ entry = self._entries.get(key)
+ if entry is not None and entry[0]() is tensor and entry[1] == current:
+ return entry[2]
+
+ value = self._compute(tensor)
+ ref = weakref.ref(tensor, lambda ref: self._discard(key, ref))
+ with self._lock:
+ self._entries.pop(key, None)
+ self._entries[key] = (ref, current, value)
+ while len(self._entries) > self._max_entries:
+ self._entries.popitem(last=False)
+ return value
+
+ def clear(self) -> None:
+ """Forget all stored results."""
+ with self._lock:
+ self._entries.clear()
+
+ def _discard(self, key: int, ref: weakref.ref[Tensor]) -> None:
+ with self._lock:
+ entry = self._entries.get(key)
+ if entry is not None and entry[0] is ref:
+ del self._entries[key]
diff --git a/src/diffrast/backends/_autograd.py b/src/diffrast/backends/_autograd.py
new file mode 100644
index 0000000..83795b1
--- /dev/null
+++ b/src/diffrast/backends/_autograd.py
@@ -0,0 +1,35 @@
+"""Helpers shared by the autograd functions of the Triton backend."""
+
+from __future__ import annotations
+
+import functools
+from collections.abc import Callable
+
+import torch
+
+
+def first_order(op: str) -> Callable[[Callable], Callable]:
+ """Decorator for a ``backward`` whose kernels cannot be differentiated again.
+
+ PyTorch runs ``backward`` with gradient tracking enabled exactly when a differentiable
+ gradient was asked for (``create_graph=True``), so that is refused here with an error naming
+ ``op``. ``torch.autograd.function.once_differentiable`` is not enough: it only fails once
+ the second backward pass reaches its error node, which ``torch.autograd.grad`` skips when
+ the requested inputs are also reachable another way, and it stays silent when the incoming
+ gradient does not require grad. Both return gradients that lack the second-order terms.
+ """
+
+ def decorate(backward: Callable) -> Callable:
+ @functools.wraps(backward)
+ def guarded(ctx, *grads):
+ if torch.is_grad_enabled():
+ raise RuntimeError(
+ f"{op} on the Triton backend has no second-order gradients, but its "
+ "backward pass was run with create_graph=True. Use "
+ "diffrast.set_backend('reference') for gradients of gradients."
+ )
+ return backward(ctx, *grads)
+
+ return guarded
+
+ return decorate
diff --git a/src/diffrast/backends/_cube.py b/src/diffrast/backends/_cube.py
new file mode 100644
index 0000000..90c8c89
--- /dev/null
+++ b/src/diffrast/backends/_cube.py
@@ -0,0 +1,143 @@
+"""Cube-map geometry for ``texture``: face selection and lookups across face edges.
+
+Faces are stored in the order ``+x, -x, +y, -y, +z, -z`` and oriented as in the OpenGL
+specification. For a direction ``r`` whose largest component is along the face's major axis, the
+face coordinates are ``s = (sc / |ma| + 1) / 2`` and ``t = (tc / |ma| + 1) / 2`` with
+
+==== ==== ==== ====
+face sc tc ma
+==== ==== ==== ====
+ +x -rz -ry rx
+ -x +rz -ry rx
+ +y +rx +rz ry
+ -y +rx -rz ry
+ +z +rx -ry rz
+ -z -rx -ry rz
+==== ==== ==== ====
+
+``s`` runs along the columns of a face and ``t`` along its rows. Where components tie for the
+largest magnitude, x takes precedence over y and y over z. Everything here is plain PyTorch, so
+it runs on any device and gradients come from autograd.
+"""
+
+from __future__ import annotations
+
+from functools import lru_cache
+
+import torch
+from torch import Tensor
+
+# Per face: the major axis, and the directions in which s and t increase.
+_MAJOR = ((1, 0, 0), (-1, 0, 0), (0, 1, 0), (0, -1, 0), (0, 0, 1), (0, 0, -1))
+_S_AXIS = ((0, 0, -1), (0, 0, 1), (1, 0, 0), (1, 0, 0), (1, 0, 0), (-1, 0, 0))
+_T_AXIS = ((0, -1, 0), (0, -1, 0), (0, 0, 1), (0, 0, -1), (0, -1, 0), (0, -1, 0))
+# Derivatives of a direction saturate at this multiple of its length, like footprints in texels.
+# An infinite derivative then selects the coarsest level instead of cancelling to NaN.
+_DERIVATIVE_LIMIT = 1e18
+
+
+@lru_cache(maxsize=16)
+def _axes(device: torch.device, dtype: torch.dtype) -> tuple[Tensor, Tensor, Tensor]:
+ return tuple(torch.tensor(t, device=device, dtype=dtype) for t in (_MAJOR, _S_AXIS, _T_AXIS))
+
+
+def project(
+ dirs: Tensor, dirs_da: Tensor | None = None
+) -> tuple[Tensor, Tensor, Tensor | None, Tensor]:
+ """Project direction vectors onto the cube.
+
+ Args:
+ dirs: Directions of shape ``[..., 3]``; they need not be normalised.
+ dirs_da: Screen-space derivatives ``(d/dx, d/dy)`` of each component of ``dirs``, shape
+ ``[..., 6]``, or ``None``.
+
+ Returns:
+ ``(face, st, st_da, valid)``. ``face`` is the int64 face index of shape ``[...]``, ``st``
+ the face coordinates in ``[0, 1]`` of shape ``[..., 2]``, and ``st_da`` their screen-space
+ derivatives ``(ds/dx, ds/dy, dt/dx, dt/dy)`` of shape ``[..., 4]`` (``None`` without
+ ``dirs_da``). ``valid`` is false for directions that select no point on the cube:
+ vectors with a component that is not finite, the zero vector, and vectors so short that
+ their largest component is subnormal, which have lost the precision a direction needs.
+ Those get a placeholder that passes no gradient to ``dirs`` or ``dirs_da``.
+
+ Derivatives saturate far beyond any footprint, so huge and infinite ones stay finite.
+ Where a derivative of a valid direction is NaN, ``st_da`` is NaN and no gradient passes
+ to ``dirs`` or ``dirs_da`` through it.
+ """
+ shortest = torch.finfo(dirs.dtype).tiny
+ valid = torch.isfinite(dirs).all(-1) & (dirs.detach().abs().amax(-1) >= shortest)
+ dirs = torch.where(valid[..., None], dirs, dirs.new_tensor((0.0, 0.0, 1.0)))
+
+ ax, ay, az = dirs.detach().abs().unbind(-1)
+ x_major = (ax >= ay) & (ax >= az)
+ y_major = ~x_major & (ay >= az)
+ axis = 2 - 2 * x_major.long() - y_major.long()
+ negative = dirs.detach().gather(-1, axis[..., None]).squeeze(-1) < 0
+ face = 2 * axis + negative.long()
+
+ # The face coordinates do not depend on the length of the direction. With the major
+ # component scaled to one, neither they nor their gradients overflow or underflow on the way,
+ # however long or short the direction is.
+ length = dirs.detach().abs().amax(-1, keepdim=True)
+ dirs = dirs / length
+ major, s_axis, t_axis = (table[face] for table in _axes(dirs.device, dirs.dtype))
+ ma = (dirs * major).sum(-1, keepdim=True)
+ ratio = torch.stack([(dirs * s_axis).sum(-1), (dirs * t_axis).sum(-1)], -1) / ma
+ st = 0.5 * (ratio + 1)
+ if dirs_da is None:
+ return face, st, None, valid
+
+ # A NaN derivative is kept out of the arithmetic, where it would turn the gradient of the
+ # direction into NaN as well, and put back at the end.
+ undefined = valid & dirs_da.isnan().any(-1)
+ da = torch.where((valid & ~undefined)[..., None], dirs_da, 0) / length
+ da = da.clamp(-_DERIVATIVE_LIMIT, _DERIVATIVE_LIMIT).unflatten(-1, (3, 2))
+ d_ma = (da * major[..., None]).sum(-2)
+ d_sc = (da * s_axis[..., None]).sum(-2)
+ d_tc = (da * t_axis[..., None]).sum(-2)
+ # Quotient rule for sc / ma.
+ ds = 0.5 * (d_sc - ratio[..., :1] * d_ma) / ma
+ dt = 0.5 * (d_tc - ratio[..., 1:] * d_ma) / ma
+ st_da = torch.where(undefined[..., None], torch.nan, torch.cat([ds, dt], -1))
+ return face, st, st_da, valid
+
+
+def fold(
+ face: Tensor, row: Tensor, col: Tensor, size: Tensor
+) -> tuple[Tensor, Tensor, Tensor, Tensor]:
+ """Resolve texel coordinates that may lie one step outside their face.
+
+ Args:
+ face: Face indices, int64.
+ row: Texel rows in ``[-1, size]``, int64.
+ col: Texel columns in ``[-1, size]``, int64.
+ size: Edge length in texels of the face each coordinate is on, int64.
+
+ All four broadcast against each other.
+
+ Returns:
+ ``(face, row, col, exists)``. A texel outside one edge becomes the texel of the
+ neighbouring face that touches it in 3D; texels inside are returned unchanged. A texel
+ outside two edges lies beyond a corner of the cube, where no face continues: ``exists``
+ is false and the returned coordinates are an arbitrary texel.
+ """
+ major, s_axis, t_axis = (table[face] for table in _axes(face.device, torch.long))
+ over_col = (col < 0) | (col >= size)
+ over_row = (row < 0) | (row >= size)
+
+ # In units of half a texel the cube spans [-size, size] and texel centres are integers, so
+ # the lookup is exact. A centre sticking out past an edge at size + 1 is folded around that
+ # edge: onto the neighbouring face's plane, at size - 1 along the old major axis.
+ extent = size[..., None]
+ sc = (2 * col + 1 - size)[..., None]
+ tc = (2 * row + 1 - size)[..., None]
+ point = (extent * major + sc * s_axis + tc * t_axis).clamp(-extent, extent)
+ point = point - (over_col | over_row)[..., None] * major
+
+ axis = point.abs().argmax(-1)
+ negative = point.gather(-1, axis[..., None]).squeeze(-1) < 0
+ face = 2 * axis + negative.long()
+ _, s_axis, t_axis = (table[face] for table in _axes(face.device, torch.long))
+ col = ((point * s_axis).sum(-1) + size - 1) // 2
+ row = ((point * t_axis).sum(-1) + size - 1) // 2
+ return face, row.clamp(min=0), col.clamp(min=0), ~(over_col & over_row)
diff --git a/src/diffrast/backends/_triton_antialias.py b/src/diffrast/backends/_triton_antialias.py
index b8bed41..8441ae6 100644
--- a/src/diffrast/backends/_triton_antialias.py
+++ b/src/diffrast/backends/_triton_antialias.py
@@ -1,10 +1,19 @@
"""Triton kernels for antialias.
Silhouette edges are classified with the reference backend's PyTorch code, which is per triangle
-and cheap. The kernels then run one lane per pixel, handling the pairs it forms with its right and
-lower neighbours exactly as the reference backend does. A pixel is touched by at most four pairs,
-so blended colours and gradients are added with atomics. In the backward pass, the gradient of the
-crossing point ``t`` is chained analytically into the two vertices of the crossed edge.
+and cheap once the edge adjacency of the mesh is known. The kernels then run one lane per pixel,
+handling the pairs it forms with its right and lower neighbours exactly as the reference backend
+does. A pixel is touched by at most four pairs, so blended colours and gradients are added with
+atomics. In the backward pass, the gradient of the crossing point ``t`` is chained analytically
+into the two vertices of the crossed edge.
+
+Positions shared across the batch are read in place: the kernels take the batch item modulo the
+number of items in ``pos``, which also sums the gradients of a shared ``pos`` over the batch.
+
+The kernels are compiled without floating-point fusion, so the edge functions round as in the
+reference backend and both backends pick the same edge where two candidates tie. Agreement with
+the rasterizer that produced ``rast`` does not rely on that: a pixel centre on an edge up to
+rounding is treated as on it (``reference.EDGE_TIE``).
"""
from __future__ import annotations
@@ -14,7 +23,8 @@
import triton.language as tl
from torch import Tensor
-from diffrast.backends.reference import _silhouette_edges, pixel_centres
+from diffrast.backends._autograd import first_order
+from diffrast.backends.reference import AXIS_TIE, EDGE_TIE, _silhouette_edges, pixel_centres
BLOCK_PIXELS = 128
BLOCK_CHANNELS = 16
@@ -41,9 +51,20 @@ def _edge(xi, yi, wi, xj, yj, wj, px, py):
return (xi - px * wi) * (yj - py * wj) - (xj - px * wj) * (yi - py * wi)
+@triton.jit
+def _edge_slack(xi, yi, wi, xj, yj, wj, px, py):
+ """Rounding error of :func:`_edge` at ``(px, py)``, in epsilons; see the reference backend."""
+ ai, aj = tl.abs(xi - px * wi), tl.abs(xj - px * wj)
+ ci, cj = tl.abs(yi - py * wi), tl.abs(yj - py * wj)
+ reach_xi, reach_xj = tl.abs(xi) + tl.abs(wi), tl.abs(xj) + tl.abs(wj)
+ reach_yi, reach_yj = tl.abs(yi) + tl.abs(wi), tl.abs(yj) + tl.abs(wj)
+ return (reach_xi + ai) * cj + (reach_xj + aj) * ci + reach_yj * ai + reach_yi * aj
+
+
@triton.jit
def _crossing(pos_ptr, tri_ptr, sil_ptr, b, tri_id, src_x, src_y, dst_x, dst_y, width, height,
- num_vert, num_tri, mask, HORIZONTAL: tl.constexpr): # fmt: skip
+ num_vert, num_tri, mask, HORIZONTAL: tl.constexpr, AXIS: tl.constexpr,
+ EDGE: tl.constexpr): # fmt: skip
"""Where the triangle visible at ``src`` is exited towards ``dst``: ``(found, t, edge)``.
Mirrors ``reference._edge_crossing``; see there for when no crossing is reported.
@@ -61,24 +82,29 @@ def _crossing(pos_ptr, tri_ptr, sil_ptr, b, tri_id, src_x, src_y, dst_x, dst_y,
d1 = _edge(x2, y2, w2, x0, y0, w0, dst_x, dst_y)
d2 = _edge(x0, y0, w0, x1, y1, w1, dst_x, dst_y)
sign = tl.where(s0 + s1 + s2 < 0, -1.0, 1.0)
- out0, out1, out2 = d0 * sign < 0, d1 * sign < 0, d2 * sign < 0
+ span0, span1, span2 = s0 - d0, s1 - d1, s2 - d2
+ slack0 = _edge_slack(x1, y1, w1, x2, y2, w2, dst_x, dst_y) * EDGE
+ slack1 = _edge_slack(x2, y2, w2, x0, y0, w0, dst_x, dst_y) * EDGE
+ slack2 = _edge_slack(x0, y0, w0, x1, y1, w1, dst_x, dst_y) * EDGE
+ out0 = (d0 * sign <= slack0) & (span0 * sign > 2 * slack0)
+ out1 = (d1 * sign <= slack1) & (span1 * sign > 2 * slack1)
+ out2 = (d2 * sign <= slack2) & (span2 * sign > 2 * slack2)
inf = float("inf")
- t0 = tl.where(out0, s0 / tl.where(out0, s0 - d0, 1.0), inf)
- t1 = tl.where(out1, s1 / tl.where(out1, s1 - d1, 1.0), inf)
- t2 = tl.where(out2, s2 / tl.where(out2, s2 - d2, 1.0), inf)
+ t0 = tl.where(out0, s0 / tl.where(out0, span0, 1.0), inf)
+ t1 = tl.where(out1, s1 / tl.where(out1, span1, 1.0), inf)
+ t2 = tl.where(out2, s2 / tl.where(out2, span2, 1.0), inf)
edge = tl.where(t1 < t0, 1, 0)
t = tl.minimum(t0, t1)
edge = tl.where(t2 < t, 2, edge)
t = tl.minimum(t, t2)
- # Screen-space gradient of the chosen edge function, in pixel units.
+ # Slope of the chosen edge in pixel space, from its two vertices alone; see
+ # ``reference._along_axis``.
xi, yi, wi = _pick(edge, x1, x2, x0), _pick(edge, y1, y2, y0), _pick(edge, w1, w2, w0)
xj, yj, wj = _pick(edge, x2, x0, x1), _pick(edge, y2, y0, y1), _pick(edge, w2, w0, w1)
- ai, aj = xi - src_x * wi, xj - src_x * wj
- ci, cj = yi - src_y * wi, yj - src_y * wj
- normal_x = tl.abs(wj * ci - wi * cj) * (2.0 / width)
- normal_y = tl.abs(aj * wi - ai * wj) * (2.0 / height)
- along_axis = normal_x >= normal_y if HORIZONTAL else normal_y > normal_x
+ steep = tl.abs(wj * yi - wi * yj) * height * AXIS
+ flat = tl.abs(xj * wi - xi * wj) * width
+ along_axis = steep >= flat if HORIZONTAL else flat > steep
silhouette = tl.load(sil_ptr + (b * num_tri + tid) * 3 + edge, mask=visible, other=0) != 0
found = visible & (out0 | out1 | out2) & silhouette & along_axis
@@ -87,7 +113,8 @@ def _crossing(pos_ptr, tri_ptr, sil_ptr, b, tri_id, src_x, src_y, dst_x, dst_y,
@triton.jit
def _pair(pos_ptr, tri_ptr, sil_ptr, rast_ptr, px_ptr, py_ptr, p, b, row, col, valid, height,
- width, num_vert, num_tri, HORIZONTAL: tl.constexpr): # fmt: skip
+ width, num_vert, num_tri, HORIZONTAL: tl.constexpr, AXIS: tl.constexpr,
+ EDGE: tl.constexpr): # fmt: skip
"""Pixel ``p`` and its right (or lower) neighbour ``q``: which triangle owns the edge between
them, where it crosses, and how much each pixel blends."""
if HORIZONTAL:
@@ -100,16 +127,23 @@ def _pair(pos_ptr, tri_ptr, sil_ptr, rast_ptr, px_ptr, py_ptr, p, b, row, col, v
row_q, col_q = row + 1, col
id_p = (tl.load(rast_ptr + p * 4 + 3, mask=pair, other=0.0) + 0.5).to(tl.int64) - 1
id_q = (tl.load(rast_ptr + q * 4 + 3, mask=pair, other=0.0) + 0.5).to(tl.int64) - 1
+ # Ids past the end of tri are treated as background rather than read out of range.
+ id_p = tl.where(id_p < num_tri, id_p, -1)
+ id_q = tl.where(id_q < num_tri, id_q, -1)
pair = pair & (id_p != id_q)
x_p = tl.load(px_ptr + col, mask=pair, other=0.0)
y_p = tl.load(py_ptr + row, mask=pair, other=0.0)
x_q = tl.load(px_ptr + col_q, mask=pair, other=0.0)
y_q = tl.load(py_ptr + row_q, mask=pair, other=0.0)
- from_p, t_p, edge_p = _crossing(pos_ptr, tri_ptr, sil_ptr, b, id_p, x_p, y_p, x_q, y_q,
- width, height, num_vert, num_tri, pair, HORIZONTAL) # fmt: skip
- from_q, t_q, edge_q = _crossing(pos_ptr, tri_ptr, sil_ptr, b, id_q, x_q, y_q, x_p, y_p,
- width, height, num_vert, num_tri, pair, HORIZONTAL) # fmt: skip
+ from_p, t_p, edge_p = _crossing(
+ pos_ptr, tri_ptr, sil_ptr, b, id_p, x_p, y_p, x_q, y_q, width, height, num_vert, num_tri,
+ pair, HORIZONTAL, AXIS, EDGE,
+ ) # fmt: skip
+ from_q, t_q, edge_q = _crossing(
+ pos_ptr, tri_ptr, sil_ptr, b, id_q, x_q, y_q, x_p, y_p, width, height, num_vert, num_tri,
+ pair, HORIZONTAL, AXIS, EDGE,
+ ) # fmt: skip
depth_p = tl.load(rast_ptr + p * 4 + 2, mask=pair, other=0.0)
depth_q = tl.load(rast_ptr + q * 4 + 2, mask=pair, other=0.0)
use_p = from_p & (~from_q | (depth_p <= depth_q))
@@ -125,17 +159,18 @@ def _pair(pos_ptr, tri_ptr, sil_ptr, rast_ptr, px_ptr, py_ptr, p, b, row, col, v
@triton.jit
def _forward_kernel(color_ptr, rast_ptr, pos_ptr, tri_ptr, sil_ptr, px_ptr, py_ptr, out_ptr,
- num_pixels, height, width, num_vert, num_tri, channels,
- BLOCK_P: tl.constexpr, BLOCK_C: tl.constexpr): # fmt: skip
+ num_pixels, height, width, pos_batch, num_vert, num_tri, channels,
+ BLOCK_P: tl.constexpr, BLOCK_C: tl.constexpr, AXIS: tl.constexpr,
+ EDGE: tl.constexpr): # fmt: skip
p = tl.program_id(0).to(tl.int64) * BLOCK_P + tl.arange(0, BLOCK_P)
valid = p < num_pixels
- b = p // (height * width)
+ b = (p // (height * width)) % pos_batch
row = (p // width) % height
col = p % width
for direction in tl.static_range(2):
q, active, _, _, blend_p, blend_q, _, _, _, _, _, _ = _pair(
pos_ptr, tri_ptr, sil_ptr, rast_ptr, px_ptr, py_ptr, p, b, row, col, valid,
- height, width, num_vert, num_tri, direction == 0,
+ height, width, num_vert, num_tri, direction == 0, AXIS, EDGE,
) # fmt: skip
for c0 in range(0, channels, BLOCK_C):
c = c0 + tl.arange(0, BLOCK_C)[None, :]
@@ -192,17 +227,18 @@ def _add_edge_gradient(grad_pos_ptr, pos_ptr, tri_ptr, b, tid, edge, grad_t, src
@triton.jit
def _backward_kernel(color_ptr, rast_ptr, pos_ptr, tri_ptr, sil_ptr, px_ptr, py_ptr,
grad_out_ptr, grad_color_ptr, grad_pos_ptr, boost,
- num_pixels, height, width, num_vert, num_tri, channels,
- BLOCK_P: tl.constexpr, BLOCK_C: tl.constexpr): # fmt: skip
+ num_pixels, height, width, pos_batch, num_vert, num_tri, channels,
+ BLOCK_P: tl.constexpr, BLOCK_C: tl.constexpr, AXIS: tl.constexpr,
+ EDGE: tl.constexpr): # fmt: skip
p = tl.program_id(0).to(tl.int64) * BLOCK_P + tl.arange(0, BLOCK_P)
valid = p < num_pixels
- b = p // (height * width)
+ b = (p // (height * width)) % pos_batch
row = (p // width) % height
col = p % width
for direction in tl.static_range(2):
q, active, use_p, t, blend_p, blend_q, owner, edge, x_p, y_p, x_q, y_q = _pair(
pos_ptr, tri_ptr, sil_ptr, rast_ptr, px_ptr, py_ptr, p, b, row, col, valid,
- height, width, num_vert, num_tri, direction == 0,
+ height, width, num_vert, num_tri, direction == 0, AXIS, EDGE,
) # fmt: skip
below = active & (t < 0.5)
grad_t = tl.zeros((BLOCK_P,), dtype=t.dtype)
@@ -234,26 +270,40 @@ def _backward_kernel(color_ptr, rast_ptr, pos_ptr, tri_ptr, sil_ptr, px_ptr, py_
class Antialias(torch.autograd.Function):
@staticmethod
- def forward(ctx, color: Tensor, rast: Tensor, pos: Tensor, tri: Tensor, boost: float):
+ def forward(
+ ctx,
+ color: Tensor,
+ rast: Tensor,
+ pos: Tensor,
+ tri: Tensor,
+ boost: float,
+ neighbours: Tensor | None,
+ ):
color = color.contiguous()
rast = rast.detach().contiguous()
- pos_c = pos.detach().contiguous()
+ pos_3d = pos.detach().contiguous()
+ if pos_3d.ndim == 2:
+ pos_3d = pos_3d[None]
tri = tri.to(torch.int32).contiguous()
- with torch.no_grad():
- silhouette = _silhouette_edges(pos_c, tri.long()).to(torch.int8).contiguous()
- px, py = pixel_centres(rast.shape[1], rast.shape[2], pos_c)
+ silhouette = _silhouette_edges(pos_3d, tri.long(), neighbours).to(torch.int8).contiguous()
+ px, py = pixel_centres(rast.shape[1], rast.shape[2], pos_3d)
out = color.clone()
- args = _launch_args(rast, pos_c, tri, color)
+ args = _launch_args(rast, pos_3d, tri, color)
with torch.cuda.device(color.device):
_forward_kernel[args["grid"]](
- color, rast, pos_c, tri, silhouette, px, py, out, *args["sizes"],
- BLOCK_P=BLOCK_PIXELS, BLOCK_C=BLOCK_CHANNELS,
+ color, rast, pos_3d, tri, silhouette, px, py, out, *args["sizes"],
+ BLOCK_P=BLOCK_PIXELS, BLOCK_C=BLOCK_CHANNELS, **_ties(pos_3d),
+ enable_fp_fusion=False,
) # fmt: skip
- ctx.save_for_backward(color, rast, pos_c, tri, silhouette, px, py)
+ saved = (color, rast, pos_3d, tri, silhouette, px, py)
+ # A tensor made in inference mode cannot be saved for backward, but a copy of it can.
+ ctx.save_for_backward(*(t.clone() if t.is_inference() else t for t in saved))
ctx.boost = boost
+ ctx.pos_shape = pos.shape
return out
@staticmethod
+ @first_order("antialias")
def backward(ctx, grad_out: Tensor):
color, rast, pos, tri, silhouette, px, py = ctx.saved_tensors
grad_out = grad_out.contiguous()
@@ -263,21 +313,33 @@ def backward(ctx, grad_out: Tensor):
with torch.cuda.device(color.device):
_backward_kernel[args["grid"]](
color, rast, pos, tri, silhouette, px, py, grad_out, grad_color, grad_pos,
- ctx.boost, *args["sizes"], BLOCK_P=BLOCK_PIXELS, BLOCK_C=BLOCK_CHANNELS,
+ ctx.boost, *args["sizes"],
+ BLOCK_P=BLOCK_PIXELS, BLOCK_C=BLOCK_CHANNELS, **_ties(pos),
+ enable_fp_fusion=False,
) # fmt: skip
- return grad_color, None, grad_pos, None, None
+ return grad_color, None, grad_pos.view(ctx.pos_shape), None, None, None
-def antialias(color: Tensor, rast: Tensor, pos: Tensor, tri: Tensor, boost: float) -> Tensor:
+def antialias(
+ color: Tensor,
+ rast: Tensor,
+ pos: Tensor,
+ tri: Tensor,
+ boost: float,
+ neighbours: Tensor | None = None,
+) -> Tensor:
if tri.shape[0] == 0:
- return color
- return Antialias.apply(color, rast, pos, tri, boost)
+ return color.clone()
+ return Antialias.apply(color, rast, pos, tri, boost, neighbours)
+
+
+def _ties(pos: Tensor) -> dict:
+ """The reference backend's tie margins, as constants of the kernels."""
+ return {"AXIS": AXIS_TIE, "EDGE": EDGE_TIE * torch.finfo(pos.dtype).eps}
def _launch_args(rast: Tensor, pos: Tensor, tri: Tensor, color: Tensor) -> dict:
batch, height, width, _ = rast.shape
num_pixels = batch * height * width
- return {
- "grid": (triton.cdiv(num_pixels, BLOCK_PIXELS),),
- "sizes": (num_pixels, height, width, pos.shape[1], tri.shape[0], color.shape[-1]),
- }
+ sizes = (num_pixels, height, width, *pos.shape[:2], tri.shape[0], color.shape[-1])
+ return {"grid": (triton.cdiv(num_pixels, BLOCK_PIXELS),), "sizes": sizes}
diff --git a/src/diffrast/backends/_triton_interpolate.py b/src/diffrast/backends/_triton_interpolate.py
index 05c4bc9..bb3470b 100644
--- a/src/diffrast/backends/_triton_interpolate.py
+++ b/src/diffrast/backends/_triton_interpolate.py
@@ -3,6 +3,9 @@
Each program handles a block of pixels and loops over the attribute channels in chunks. The
backward pass accumulates the gradients of ``rast`` and ``rast_db`` per pixel in registers and
scatters the gradients of ``attr`` to the vertices with atomic adds.
+
+The kernels are compiled without floating-point fusion, so the weighted sums round as in the
+reference backend whatever the default of the installed Triton is.
"""
from __future__ import annotations
@@ -12,15 +15,18 @@
import triton.language as tl
from torch import Tensor
+from diffrast.backends._autograd import first_order
+
BLOCK_PIXELS = 64
@triton.jit
-def _load_pixel(rast_ptr, tri_ptr, p, valid, pixels_per_image, attr_batch_stride):
+def _load_pixel(rast_ptr, tri_ptr, p, valid, pixels_per_image, attr_batch_stride, num_tri):
u = tl.load(rast_ptr + p * 4, mask=valid, other=0.0)
v = tl.load(rast_ptr + p * 4 + 1, mask=valid, other=0.0)
tri_id = (tl.load(rast_ptr + p * 4 + 3, mask=valid, other=0.0) + 0.5).to(tl.int64) - 1
- covered = valid & (tri_id >= 0)
+ # Ids past the end of tri are drawn as background rather than read out of range.
+ covered = valid & (tri_id >= 0) & (tri_id < num_tri)
i0 = tl.load(tri_ptr + tri_id * 3, mask=covered, other=0).to(tl.int64)
i1 = tl.load(tri_ptr + tri_id * 3 + 1, mask=covered, other=0).to(tl.int64)
i2 = tl.load(tri_ptr + tri_id * 3 + 2, mask=covered, other=0).to(tl.int64)
@@ -40,6 +46,7 @@ def _forward_kernel(
num_pixels,
pixels_per_image,
attr_batch_stride,
+ num_tri,
channels,
num_diff,
HAS_DA: tl.constexpr,
@@ -49,7 +56,7 @@ def _forward_kernel(
p = tl.program_id(0).to(tl.int64) * BLOCK_P + tl.arange(0, BLOCK_P)
valid = p < num_pixels
u, v, covered, base, i0, i1, i2 = _load_pixel(
- rast_ptr, tri_ptr, p, valid, pixels_per_image, attr_batch_stride
+ rast_ptr, tri_ptr, p, valid, pixels_per_image, attr_batch_stride, num_tri
)
u, v = u[:, None], v[:, None]
row0 = (base + i0 * channels)[:, None]
@@ -99,16 +106,18 @@ def _backward_kernel(
num_pixels,
pixels_per_image,
attr_batch_stride,
+ num_tri,
channels,
num_diff,
HAS_DA: tl.constexpr,
+ ATTR_GRAD: tl.constexpr,
BLOCK_P: tl.constexpr,
BLOCK_C: tl.constexpr,
):
p = tl.program_id(0).to(tl.int64) * BLOCK_P + tl.arange(0, BLOCK_P)
valid = p < num_pixels
u, v, covered, base, i0, i1, i2 = _load_pixel(
- rast_ptr, tri_ptr, p, valid, pixels_per_image, attr_batch_stride
+ rast_ptr, tri_ptr, p, valid, pixels_per_image, attr_batch_stride, num_tri
)
row0 = (base + i0 * channels)[:, None]
row1 = (base + i1 * channels)[:, None]
@@ -125,9 +134,11 @@ def _backward_kernel(
a2 = tl.load(attr_ptr + row2 + c, mask=mask, other=0.0)
grad_u += tl.sum(g * (a0 - a2), axis=1)
grad_v += tl.sum(g * (a1 - a2), axis=1)
- tl.atomic_add(grad_attr_ptr + row0 + c, g * u[:, None], mask=mask)
- tl.atomic_add(grad_attr_ptr + row1 + c, g * v[:, None], mask=mask)
- tl.atomic_add(grad_attr_ptr + row2 + c, g * (1 - u - v)[:, None], mask=mask)
+ # Many pixels share a vertex, so these atomics contend; skip them when unused.
+ if ATTR_GRAD:
+ tl.atomic_add(grad_attr_ptr + row0 + c, g * u[:, None], mask=mask)
+ tl.atomic_add(grad_attr_ptr + row1 + c, g * v[:, None], mask=mask)
+ tl.atomic_add(grad_attr_ptr + row2 + c, g * (1 - u - v)[:, None], mask=mask)
tl.store(grad_rast_ptr + p * 4, grad_u, mask=valid)
tl.store(grad_rast_ptr + p * 4 + 1, grad_v, mask=valid)
@@ -158,11 +169,12 @@ def _backward_kernel(
grad_du_dy += tl.sum(gy * da_du, axis=1)
grad_dv_dx += tl.sum(gx * da_dv, axis=1)
grad_dv_dy += tl.sum(gy * da_dv, axis=1)
- g_a0 = gx * du_dx + gy * du_dy
- g_a1 = gx * dv_dx + gy * dv_dy
- tl.atomic_add(grad_attr_ptr + row0 + c, g_a0, mask=mask)
- tl.atomic_add(grad_attr_ptr + row1 + c, g_a1, mask=mask)
- tl.atomic_add(grad_attr_ptr + row2 + c, -(g_a0 + g_a1), mask=mask)
+ if ATTR_GRAD:
+ g_a0 = gx * du_dx + gy * du_dy
+ g_a1 = gx * dv_dx + gy * dv_dy
+ tl.atomic_add(grad_attr_ptr + row0 + c, g_a0, mask=mask)
+ tl.atomic_add(grad_attr_ptr + row1 + c, g_a1, mask=mask)
+ tl.atomic_add(grad_attr_ptr + row2 + c, -(g_a0 + g_a1), mask=mask)
tl.store(grad_db_ptr + p * 4, grad_du_dx, mask=valid)
tl.store(grad_db_ptr + p * 4 + 1, grad_du_dy, mask=valid)
@@ -194,16 +206,22 @@ def forward(ctx, attr: Tensor, rast: Tensor, rast_db: Tensor | None, tri: Tensor
_forward_kernel[args["grid"]](
attr_3d, rast, db, tri, diff, out, out_da,
args["num_pixels"], args["pixels_per_image"], args["batch_stride"],
- channels, num_diff,
+ tri.shape[0], channels, num_diff,
HAS_DA=has_da, BLOCK_P=BLOCK_PIXELS, BLOCK_C=args["block_c"],
+ enable_fp_fusion=False,
) # fmt: skip
- ctx.save_for_backward(attr_3d, rast, db, tri, diff)
+ saved = (attr_3d, rast, db, tri, diff)
+ # A tensor made in inference mode cannot be saved for backward, but a copy of it can.
+ ctx.save_for_backward(*(t.clone() if t.is_inference() else t for t in saved))
ctx.attr_shape = attr.shape
ctx.has_da = has_da
ctx.rast_db_given = rast_db is not None
+ if not has_da:
+ ctx.mark_non_differentiable(out_da)
return out, out_da
@staticmethod
+ @first_order("interpolate")
def backward(ctx, grad_out: Tensor | None, grad_out_da: Tensor | None):
attr_3d, rast, db, tri, diff = ctx.saved_tensors
channels = attr_3d.shape[2]
@@ -214,7 +232,8 @@ def backward(ctx, grad_out: Tensor | None, grad_out_da: Tensor | None):
grad_out = grad_out.contiguous()
grad_out_da = grad_out_da.contiguous() if has_da else grad_out
- grad_attr = torch.zeros_like(attr_3d)
+ attr_grad = ctx.needs_input_grad[0]
+ grad_attr = torch.zeros_like(attr_3d) if attr_grad else attr_3d
grad_rast = torch.empty_like(rast)
grad_db = torch.zeros_like(rast) if has_da else grad_rast
args = _launch_args(rast, attr_3d, channels, num_diff)
@@ -223,14 +242,16 @@ def backward(ctx, grad_out: Tensor | None, grad_out_da: Tensor | None):
attr_3d, rast, db, tri, diff, grad_out, grad_out_da,
grad_attr, grad_rast, grad_db,
args["num_pixels"], args["pixels_per_image"], args["batch_stride"],
- channels, num_diff,
- HAS_DA=has_da, BLOCK_P=BLOCK_PIXELS, BLOCK_C=args["block_c"],
+ tri.shape[0], channels, num_diff,
+ HAS_DA=has_da, ATTR_GRAD=attr_grad, BLOCK_P=BLOCK_PIXELS,
+ BLOCK_C=args["block_c"], enable_fp_fusion=False,
) # fmt: skip
grad_db_out = None
if ctx.rast_db_given:
grad_db_out = grad_db if has_da else torch.zeros_like(rast)
- return grad_attr.view(ctx.attr_shape), grad_rast, grad_db_out, None, None
+ grad_attr = grad_attr.view(ctx.attr_shape) if attr_grad else None
+ return grad_attr, grad_rast, grad_db_out, None, None
def _launch_args(rast: Tensor, attr_3d: Tensor, channels: int, num_diff: int) -> dict:
diff --git a/src/diffrast/backends/_triton_rasterize.py b/src/diffrast/backends/_triton_rasterize.py
index 15f4264..9868db6 100644
--- a/src/diffrast/backends/_triton_rasterize.py
+++ b/src/diffrast/backends/_triton_rasterize.py
@@ -11,7 +11,10 @@
3. ``_tile_kernel`` runs one program per chunk, keeps the nearest hit per pixel in registers, and
merges it into the buffer with one atomic per pixel.
-Coverage and depth use the same homogeneous formulation as the reference backend.
+Coverage and depth use the same homogeneous formulation as the reference backend, operation for
+operation. Both kernels are compiled without floating-point fusion: a fused multiply-add would
+break the exact antisymmetry of the edge functions of two triangles sharing an edge, and with it
+the guarantee that every pixel on that edge goes to exactly one of them.
"""
from __future__ import annotations
@@ -23,7 +26,7 @@
import triton.language as tl
from torch import Tensor
-from diffrast.backends.reference import pixel_centres
+from diffrast.backends.reference import AREA_TOLERANCE, pixel_centres
TILE = 16
# Triangles per tile program. Tiles with more triangles are split across programs.
@@ -34,6 +37,9 @@
SETUP_BLOCK = 128
EMPTY = torch.iinfo(torch.int64).max
+# Area below which a triangle is not drawn, relative to the magnitude of the terms it is computed
+# from; see the reference backend.
+TOLERANCE = tl.constexpr(AREA_TOLERANCE * torch.finfo(torch.float32).eps)
@triton.jit
@@ -47,6 +53,25 @@ def _load_vertex(pos_ptr, tri_ptr, b, t, k, num_vert, mask):
return x, y, z, w
+@triton.jit
+def _finite(x, y, z, w):
+ return tl.abs(x) + tl.abs(y) + tl.abs(z) + tl.abs(w) < float("inf")
+
+
+@triton.jit
+def _inside_edge(e, ai, ci, wi, aj, cj, wj, positive):
+ """Whether a pixel is on the inner side of the edge from vertex i to vertex j.
+
+ ``e = a_i * c_j - a_j * c_i`` is the edge function at the pixel and ``positive`` the sign of
+ the triangle's area. A pixel exactly on the edge is inside when the interior lies in the +x
+ direction, or in the +y direction for a horizontal edge; see the reference backend.
+ """
+ gx = ci * wj - cj * wi
+ gy = aj * wi - ai * wj
+ q = tl.where(e == 0, tl.where(gx == 0, gy, gx), e)
+ return (positive & (q > 0)) | (~positive & (q < 0))
+
+
@triton.jit
def _depth_key(x0, y0, z0, w0, x1, y1, z1, w1, x2, y2, z2, w2, px, py, t):
"""Packed ``(depth, t)`` key where the pixel ``(px, py)`` is covered, else the empty key."""
@@ -58,8 +83,24 @@ def _depth_key(x0, y0, z0, w0, x1, y1, z1, w1, x2, y2, z2, w2, px, py, t):
s = e0 + e1 + e2
ew = e0 * w0 + e1 * w1 + e2 * w2
depth = (e0 * z0 + e1 * z1 + e2 * z2) / ew
- inside = (s != 0) & (e0 * s >= 0) & (e1 * s >= 0) & (e2 * s >= 0) & (ew * s > 0)
- inside = inside & (depth >= -1.0) & (depth <= 1.0)
+
+ positive = s > 0
+ inside = _inside_edge(e0, a1, c1, w1, a2, c2, w2, positive)
+ inside &= _inside_edge(e1, a2, c2, w2, a0, c0, w0, positive)
+ inside &= _inside_edge(e2, a0, c0, w0, a1, c1, w1, positive)
+
+ # Rounding of the vertex coordinates and of a and c can change s by about this much, so a
+ # smaller area is indistinguishable from zero.
+ reach_x = tl.maximum(tl.maximum(tl.abs(x0) + tl.abs(w0), tl.abs(x1) + tl.abs(w1)),
+ tl.abs(x2) + tl.abs(w2)) # fmt: skip
+ reach_y = tl.maximum(tl.maximum(tl.abs(y0) + tl.abs(w0), tl.abs(y1) + tl.abs(w1)),
+ tl.abs(y2) + tl.abs(w2)) # fmt: skip
+ span_x = tl.abs(a0) + tl.abs(a1) + tl.abs(a2)
+ span_y = tl.abs(c0) + tl.abs(c1) + tl.abs(c2)
+ inside &= tl.abs(s) > (reach_x * span_y + span_x * (reach_y + span_y)) * TOLERANCE
+
+ inside &= (positive & (ew > 0)) | (~positive & (ew < 0))
+ inside &= (depth >= -1.0) & (depth <= 1.0)
# Map the float's bits to an integer with the same ordering.
bits = depth.to(tl.int32, bitcast=True)
@@ -72,9 +113,11 @@ def _depth_key(x0, y0, z0, w0, x1, y1, z1, w1, x2, y2, z2, w2, px, py, t):
@triton.jit
def _pixel_range(lo, hi, size):
"""Indices of the pixel centres within ``[lo, hi]`` in NDC, as an inclusive range."""
- # The margin keeps centres on the boundary despite rounding; extra pixels are tested exactly.
- first = tl.math.ceil(((lo + 1.0) * size - 1.0) * 0.5 - 1e-3)
- last = tl.math.floor(((hi + 1.0) * size - 1.0) * 0.5 + 1e-3)
+ # The margin keeps centres on the boundary despite rounding, which grows with the image size;
+ # extra pixels are tested exactly.
+ margin = 1e-3 + size * 1e-6
+ first = tl.math.ceil(((lo + 1.0) * size - 1.0) * 0.5 - margin)
+ last = tl.math.floor(((hi + 1.0) * size - 1.0) * 0.5 + margin)
first = tl.minimum(tl.maximum(first, 0.0), size * 1.0)
last = tl.minimum(tl.maximum(last, -1.0), size - 1.0)
return first.to(tl.int32), last.to(tl.int32)
@@ -114,8 +157,10 @@ def _setup_kernel(
x2, y2, z2, w2 = _load_vertex(pos_ptr, tri_ptr, b, t, 2, num_vert, valid)
# Every point on a triangle is a non-negative combination of its vertices, so it is invisible
- # when all vertices are behind the camera or outside the same clip plane.
- culled = (w0 <= 0) & (w1 <= 0) & (w2 <= 0)
+ # when all vertices are behind the camera or outside the same clip plane. A triangle with a
+ # NaN or infinite coordinate fails every comparison below and would be binned into all tiles.
+ culled = ~(_finite(x0, y0, z0, w0) & _finite(x1, y1, z1, w1) & _finite(x2, y2, z2, w2))
+ culled |= (w0 <= 0) & (w1 <= 0) & (w2 <= 0)
culled |= (x0 > w0) & (x1 > w1) & (x2 > w2)
culled |= (x0 < -w0) & (x1 < -w1) & (x2 < -w2)
culled |= (y0 > w0) & (y1 > w1) & (y2 > w2)
@@ -192,7 +237,8 @@ def _tile_kernel(
HAS_PREV: tl.constexpr,
):
item = tl.program_id(0)
- tile = tl.load(item_tile_ptr + item)
+ # 64 bits, since pixel offsets pass 2**31 for large batches of large images.
+ tile = tl.load(item_tile_ptr + item).to(tl.int64)
start = tl.load(item_start_ptr + item)
end = tl.load(item_end_ptr + item)
@@ -200,14 +246,16 @@ def _tile_kernel(
tile_in_image = tile % tiles_per_image
row = (tile_in_image // tiles_x) * TILE + tl.arange(0, TILE)[:, None]
col = (tile_in_image % tiles_x) * TILE + tl.arange(0, TILE)[None, :]
- px = tl.load(px_ptr + col, mask=col < width, other=0.0)
- py = tl.load(py_ptr + row, mask=row < height, other=0.0)
+ # Broadcast here, once: every triangle combines the row and column terms in several places,
+ # and expanding them inside the loop each time is slower.
+ px = tl.broadcast_to(tl.load(px_ptr + col, mask=col < width, other=0.0), (TILE, TILE))
+ py = tl.broadcast_to(tl.load(py_ptr + row, mask=row < height, other=0.0), (TILE, TILE))
offs = (image * height + row) * width + col
inside = (row < height) & (col < width)
best = tl.full((TILE, TILE), 0x7FFFFFFFFFFFFFFF, tl.int64)
for i in range(start, end):
- g = tl.load(tri_list_ptr + i).to(tl.int64)
+ g = tl.load(tri_list_ptr + i)
b, t = g // num_tri, g % num_tri
x0, y0, z0, w0 = _load_vertex(pos_ptr, tri_ptr, b, t, 0, num_vert, True)
x1, y1, z1, w1 = _load_vertex(pos_ptr, tri_ptr, b, t, 1, num_vert, True)
@@ -293,6 +341,7 @@ def setup_stage(state: Pass) -> None:
state.pos, state.tri, state.px, state.py, state.keys, _previous(state),
state.tile_box, total, state.num_tri, state.pos.shape[1], state.height, state.width,
TILE=TILE, SMALL=SMALL, BLOCK=SETUP_BLOCK, HAS_PREV=state.previous is not None,
+ enable_fp_fusion=False,
) # fmt: skip
@@ -315,6 +364,7 @@ def tile_stage(state: Pass, lists) -> None:
state.pos, state.tri, tri_list, item_tile, item_start, item_end, state.px, state.py,
state.keys, _previous(state), state.num_tri, state.pos.shape[1], state.height,
state.width, tiles_x, tiles_per_image, TILE=TILE, HAS_PREV=state.previous is not None,
+ enable_fp_fusion=False,
) # fmt: skip
@@ -324,8 +374,9 @@ def _bin_triangles(tile_box: Tensor, batch: int, height: int, width: int):
``tile_box`` holds ``(first, last)`` tile columns and rows per triangle, with ``first`` column
-1 for triangles that need no tiling. Returns ``(tri_list, item_tile, item_start, item_end,
tiles_x, tiles_per_image)``, where ``tri_list`` holds flat ``batch * num_tri + tri`` indices
- grouped by tile, and each work item covers ``tri_list[item_start:item_end]`` of tile
- ``item_tile``. Returns ``None`` when there is nothing to tile.
+ (64-bit, as a large batch of large meshes passes ``2**31``) grouped by tile, and each work
+ item covers ``tri_list[item_start:item_end]`` of tile ``item_tile``. Returns ``None`` when
+ there is nothing to tile.
"""
device = tile_box.device
num_tri = tile_box.shape[0] // batch
@@ -347,7 +398,7 @@ def _bin_triangles(tile_box: Tensor, batch: int, height: int, width: int):
tile = (g[owner] // num_tri * tiles_y + tile_y) * tiles_x + tile_x
sorted_tile, order = torch.sort(tile, stable=True)
- tri_list = g[owner][order].to(torch.int32)
+ tri_list = g[owner][order]
# Binary search on the sorted list instead of bincount, whose atomics contend heavily when
# many triangles share few tiles.
diff --git a/src/diffrast/backends/_triton_resolve.py b/src/diffrast/backends/_triton_resolve.py
index e07f129..d6f04f1 100644
--- a/src/diffrast/backends/_triton_resolve.py
+++ b/src/diffrast/backends/_triton_resolve.py
@@ -3,7 +3,9 @@
Per pixel, the visible triangle's homogeneous edge functions ``e = a x c`` (with ``a = x - px w``
and ``c = y - py w`` per vertex) give the perspective-correct barycentrics ``b = e / S``,
``S = sum(e)``, and ``z / w = (e . z) / (e . w)``. Their screen-space derivatives follow from
-``de/dpx = c x w`` and ``de/dpy = w x a``. These are the reference backend's formulas.
+``de/dpx = c x w`` and ``de/dpy = w x a``. These are the reference backend's formulas. Unlike the
+visibility kernels, these are compiled with floating-point fusion, which makes the barycentrics
+of small triangles more accurate; which triangle a pixel shows is already decided.
The backward kernel runs the same steps in reverse. For a cross product ``f = u x v`` with
upstream gradient ``G``, the gradients are ``v x G`` for ``u`` and ``G x u`` for ``v``. Vertex
@@ -18,6 +20,7 @@
import triton.language as tl
from torch import Tensor
+from diffrast.backends._autograd import first_order
from diffrast.backends.reference import pixel_centres
# Each program handles one tile of pixels, so that its pixels mostly share a few triangles.
@@ -33,6 +36,12 @@ def _cross(u0, u1, u2, v0, v1, v2):
return u1 * v2 - u2 * v1, u2 * v0 - u0 * v2, u0 * v1 - u1 * v0
+@triton.jit
+def _pixel_size(size, dtype):
+ """Size of one pixel in NDC, in the precision the kernel works in."""
+ return 2.0 / size.to(dtype)
+
+
@triton.jit
def _tile_pixels(height, width, TILE_H: tl.constexpr, TILE_W: tl.constexpr):
"""Flat indices of this program's tile of pixels, and which of them lie inside the image."""
@@ -92,7 +101,7 @@ def _forward_kernel(keys_ptr, tri_ptr, pos_ptr, px_ptr, py_ptr, rast_ptr, db_ptr
dx0, dx1, dx2 = _cross(c0, c1, c2, w0, w1, w2)
dy0, dy1, dy2 = _cross(w0, w1, w2, a0, a1, a2)
sx, sy = dx0 + dx1 + dx2, dy0 + dy1 + dy2
- scale_x, scale_y = 2.0 / width, 2.0 / height
+ scale_x, scale_y = _pixel_size(width, b0.dtype), _pixel_size(height, b0.dtype)
zero = tl.zeros_like(b0)
out = rast_ptr + p * 4
@@ -180,10 +189,11 @@ def _backward_kernel(keys_ptr, tri_ptr, pos_ptr, px_ptr, py_ptr, grad_rast_ptr,
dy0, dy1, dy2 = _cross(w0, w1, w2, a0, a1, a2)
sx, sy = dx0 + dx1 + dx2, dy0 + dy1 + dy2
g = grad_db_ptr + p * 4
- gbx0 = tl.load(g, mask=covered, other=0.0) * (2.0 / width)
- gby0 = tl.load(g + 1, mask=covered, other=0.0) * (2.0 / height)
- gbx1 = tl.load(g + 2, mask=covered, other=0.0) * (2.0 / width)
- gby1 = tl.load(g + 3, mask=covered, other=0.0) * (2.0 / height)
+ scale_x, scale_y = _pixel_size(width, b0.dtype), _pixel_size(height, b0.dtype)
+ gbx0 = tl.load(g, mask=covered, other=0.0) * scale_x
+ gby0 = tl.load(g + 1, mask=covered, other=0.0) * scale_y
+ gbx1 = tl.load(g + 2, mask=covered, other=0.0) * scale_x
+ gby1 = tl.load(g + 3, mask=covered, other=0.0) * scale_y
# db_dx_k = (de_dx_k - b_k * sum(de_dx)) / s, and the same along y.
dbx0, dbx1 = (dx0 - b0 * sx) / s, (dx1 - b1 * sx) / s
dby0, dby1 = (dy0 - b0 * sy) / s, (dy1 - b1 * sy) / s
@@ -246,7 +256,7 @@ def forward(ctx, pos: Tensor, tri: Tensor, keys: Tensor, grad_db: bool):
with torch.cuda.device(pos.device):
_forward_kernel[_grid(batch, height, width)](
keys, tri, pos_c, px, py, rast, rast_db, height, width, pos.shape[1],
- TILE_H=TILE_H, TILE_W=TILE_W,
+ TILE_H=TILE_H, TILE_W=TILE_W, enable_fp_fusion=True,
) # fmt: skip
ctx.save_for_backward(pos_c, tri, keys, px, py)
ctx.grad_db = grad_db
@@ -255,6 +265,7 @@ def forward(ctx, pos: Tensor, tri: Tensor, keys: Tensor, grad_db: bool):
return rast, rast_db
@staticmethod
+ @first_order("rasterize")
def backward(ctx, grad_rast: Tensor | None, grad_rast_db: Tensor | None):
pos, tri, keys, px, py = ctx.saved_tensors
batch, height, width = keys.shape
@@ -268,7 +279,7 @@ def backward(ctx, grad_rast: Tensor | None, grad_rast_db: Tensor | None):
_backward_kernel[_grid(batch, height, width)](
keys, tri, pos, px, py, grad_rast, grad_rast_db, grad_pos,
height, width, pos.shape[1], TILE_H=TILE_H, TILE_W=TILE_W, GRAD_DB=use_db,
- MAX_ROUNDS=MAX_ROUNDS, MIN_GROUP=MIN_GROUP,
+ MAX_ROUNDS=MAX_ROUNDS, MIN_GROUP=MIN_GROUP, enable_fp_fusion=True,
) # fmt: skip
return grad_pos, None, None, None
diff --git a/src/diffrast/backends/_triton_texture.py b/src/diffrast/backends/_triton_texture.py
index e307788..afc02eb 100644
--- a/src/diffrast/backends/_triton_texture.py
+++ b/src/diffrast/backends/_triton_texture.py
@@ -1,24 +1,34 @@
"""Triton kernels for texture.
-The mip chain is built with PyTorch ops (as in the reference backend) and packed into one buffer of
-shape ``[tex_batch, texels, channels]``, so autograd carries gradients from every level back to the
-base texture. The kernels sample that buffer: each program handles a block of pixels and loops
-over channels in chunks. The backward pass scatters texel gradients with atomic adds and sums the
-gradients of ``uv`` and the level of detail per pixel in registers.
+The mip levels are built with PyTorch ops (as in the reference backend), or given by the caller,
+and packed into one buffer of shape ``[tex_batch, texels, channels]``, so autograd carries
+gradients from every level back to the tensor it came from. The kernels sample that buffer: each
+program handles a block of pixels and loops over channels in chunks. The backward pass scatters
+texel gradients with atomic adds and sums the gradients of ``uv`` and the level of detail per
+pixel in registers.
+
+Coordinates and levels of detail that are out of range or not finite are handled as in the
+reference backend, with the same limits, so both give the same result for any input.
"""
from __future__ import annotations
+from collections.abc import Sequence
+
import torch
import triton
import triton.language as tl
from torch import Tensor
-from diffrast.backends.reference import _mip_chain
+from diffrast.backends import reference
BLOCK_PIXELS = 64
# Rounds of in-register reduction before the remaining texel gradients go out as atomics.
SCATTER_ROUNDS = 2
+# Without fused multiply-adds the kernels round like the PyTorch code of the reference backend.
+# Ties in the level of detail, and the texel a far-out coordinate lands in, are then decided the
+# same way on both backends, whatever the default of the installed Triton version.
+FP_FUSION = False
FILTER_MODES = ("nearest", "linear", "linear-mipmap-nearest", "linear-mipmap-linear")
BOUNDARY_MODES = ("wrap", "clamp", "zero")
@@ -36,44 +46,102 @@ def _texel_index(i, size, BOUNDARY: tl.constexpr):
return tl.minimum(tl.maximum(i, 0), size - 1), (i >= 0) & (i < size)
+@triton.jit
+def _texel_coordinate(coord, size, shift, BOUNDARY: tl.constexpr):
+ """Continuous texel coordinate ``coord * size - shift``, kept within reach of the texture.
+
+ Mirrors ``reference._texel_coordinate``. Returns the coordinate, whether it was not finite
+ (it is then replaced), and its derivative with respect to ``coord * size``.
+ """
+ limit = size.to(coord.dtype)
+ if BOUNDARY == 0:
+ # The fractional part of an infinite coordinate is NaN, so NaN is all that can go wrong.
+ x = (coord - tl.math.floor(coord)) * limit - shift
+ bad = x != x
+ slope = tl.where(bad, 0.0, 1.0)
+ else:
+ x = coord * limit - shift
+ # Taken before clamping, which would turn NaN into a bound.
+ bad = x != x
+ slope = tl.where((x >= -1.0) & (x <= limit), 1.0, 0.0)
+ x = tl.minimum(tl.maximum(x, -1.0), limit)
+ return tl.where(bad, 0.0, x), bad, slope
+
+
+@triton.jit
+def _nearest(u, v, height, width, BOUNDARY: tl.constexpr):
+ """Index and validity of the texel containing ``(u, v)``, and whether it was not finite."""
+ x, bad_x, _ = _texel_coordinate(u, width, 0.0, BOUNDARY)
+ y, bad_y, _ = _texel_coordinate(v, height, 0.0, BOUNDARY)
+ col, col_ok = _texel_index(tl.math.floor(x).to(tl.int32), width, BOUNDARY)
+ row, row_ok = _texel_index(tl.math.floor(y).to(tl.int32), height, BOUNDARY)
+ return row * width + col, col_ok & row_ok, bad_x | bad_y
+
+
@triton.jit
def _corners(u, v, height, width, BOUNDARY: tl.constexpr):
- """Bilinear footprint: blend factors, the four texel indices and their validity."""
- x = u * width.to(u.dtype) - 0.5
- y = v * height.to(u.dtype) - 0.5
+ """Bilinear footprint: blend factors, the four texel indices and their validity.
+
+ Also returns the derivatives of the texel coordinates with respect to ``u * width`` and
+ ``v * height``, and whether the coordinates were not finite.
+ """
+ x, bad_x, slope_x = _texel_coordinate(u, width, 0.5, BOUNDARY)
+ y, bad_y, slope_y = _texel_coordinate(v, height, 0.5, BOUNDARY)
x0 = tl.math.floor(x)
y0 = tl.math.floor(y)
fx, fy = x - x0, y - y0
- col0, col_ok0 = _texel_index(x0.to(tl.int32), width, BOUNDARY)
- col1, col_ok1 = _texel_index(x0.to(tl.int32) + 1, width, BOUNDARY)
- row0, row_ok0 = _texel_index(y0.to(tl.int32), height, BOUNDARY)
- row1, row_ok1 = _texel_index(y0.to(tl.int32) + 1, height, BOUNDARY)
+ xi, yi = x0.to(tl.int32), y0.to(tl.int32)
+ col0, col_ok0 = _texel_index(xi, width, BOUNDARY)
+ col1, col_ok1 = _texel_index(xi + 1, width, BOUNDARY)
+ row0, row_ok0 = _texel_index(yi, height, BOUNDARY)
+ row1, row_ok1 = _texel_index(yi + 1, height, BOUNDARY)
i00, i01 = row0 * width + col0, row0 * width + col1
i10, i11 = row1 * width + col0, row1 * width + col1
ok00, ok01 = row_ok0 & col_ok0, row_ok0 & col_ok1
ok10, ok11 = row_ok1 & col_ok0, row_ok1 & col_ok1
- return fx, fy, i00, i01, i10, i11, ok00, ok01, ok10, ok11
+ bad = bad_x | bad_y
+ return fx, fy, i00, i01, i10, i11, ok00, ok01, ok10, ok11, slope_x, slope_y, bad
+
+
+@triton.jit
+def _footprint(da_ptr, p, valid, size):
+ """One component of ``uv_da`` in texels, saturated as in the reference backend.
+
+ Returns it with half the derivative of its square with respect to the component, and whether
+ the component was NaN. The size is converted to floating point before it is multiplied: the
+ square of a size overflows int32 from 46341 texels on.
+ """
+ component = tl.load(da_ptr + p, mask=valid, other=0.0)
+ scale = size.to(component.dtype)
+ raw = component * scale
+ texels = tl.minimum(tl.maximum(raw, -1e18), 1e18)
+ slope = tl.where((raw >= -1e18) & (raw <= 1e18), texels * scale, 0.0)
+ return texels, slope, raw != raw
@triton.jit
def _level_of_detail(da_ptr, p, valid, height, width):
- du_dx = tl.load(da_ptr + p * 4, mask=valid, other=0.0)
- du_dy = tl.load(da_ptr + p * 4 + 1, mask=valid, other=0.0)
- dv_dx = tl.load(da_ptr + p * 4 + 2, mask=valid, other=0.0)
- dv_dy = tl.load(da_ptr + p * 4 + 3, mask=valid, other=0.0)
- w2 = (width * width).to(du_dx.dtype)
- h2 = (height * height).to(du_dx.dtype)
- len_x = du_dx * du_dx * w2 + dv_dx * dv_dx * h2
- len_y = du_dy * du_dy * w2 + dv_dy * dv_dy * h2
+ """Level of detail from ``uv_da``, with the terms its backward pass needs."""
+ ux, slope_ux, bad_ux = _footprint(da_ptr, p * 4, valid, width)
+ uy, slope_uy, bad_uy = _footprint(da_ptr, p * 4 + 1, valid, width)
+ vx, slope_vx, bad_vx = _footprint(da_ptr, p * 4 + 2, valid, height)
+ vy, slope_vy, bad_vy = _footprint(da_ptr, p * 4 + 3, valid, height)
+ len_x = ux * ux + vx * vx
+ len_y = uy * uy + vy * vy
longest = tl.maximum(tl.maximum(len_x, len_y), 1e-30)
- lod = 0.5 * tl.math.log2(longest)
- return lod, len_x, len_y, longest, du_dx, du_dy, dv_dx, dv_dy, w2, h2
+ # The saturation dropped any NaN, which has to reach the output.
+ bad = bad_ux | bad_uy | bad_vx | bad_vy
+ lod = tl.where(bad, float("nan"), 0.5 * tl.math.log2(longest))
+ return lod, len_x, len_y, longest, slope_ux, slope_uy, slope_vx, slope_vy
@triton.jit
def _levels(da_ptr, bias_ptr, offs_ptr, hs_ptr, ws_ptr, p, valid, num_levels,
MODE: tl.constexpr, HAS_DA: tl.constexpr, HAS_BIAS: tl.constexpr): # fmt: skip
- """Per pixel: the two levels to blend, the blend factor, and the unclamped level of detail."""
+ """Per pixel: the two levels to blend, the blend factor, and the unclamped level of detail.
+
+ Also returns whether the level of detail was NaN; it is then replaced by zero.
+ """
base_h = tl.load(hs_ptr)
base_w = tl.load(ws_ptr)
if MODE >= 2:
@@ -82,6 +150,8 @@ def _levels(da_ptr, bias_ptr, offs_ptr, hs_ptr, ws_ptr, p, valid, num_levels,
lod_raw += _level_of_detail(da_ptr, p, valid, base_h, base_w)[0]
if HAS_BIAS:
lod_raw += tl.load(bias_ptr + p, mask=valid, other=0.0)
+ bad = lod_raw != lod_raw
+ lod_raw = tl.where(bad, 0.0, lod_raw)
lod = tl.minimum(tl.maximum(lod_raw, 0.0), (num_levels - 1) * 1.0)
if MODE == 2:
lower = tl.math.floor(lod + 0.5)
@@ -96,7 +166,8 @@ def _levels(da_ptr, bias_ptr, offs_ptr, hs_ptr, ws_ptr, p, valid, num_levels,
frac = lod_raw
lo = tl.zeros(p.shape, dtype=tl.int32)
hi = lo
- return lo, hi, frac, lod_raw
+ bad = p != p
+ return lo, hi, frac, lod_raw, bad
@triton.jit
@@ -126,24 +197,29 @@ def _forward_kernel(
u = tl.load(uv_ptr + p * 2, mask=valid, other=0.0)
v = tl.load(uv_ptr + p * 2 + 1, mask=valid, other=0.0)
image = (p // pixels_per_image) * tex_batch_stride
- lo, hi, frac, _ = _levels(da_ptr, bias_ptr, offs_ptr, hs_ptr, ws_ptr, p, valid, num_levels,
- MODE, HAS_DA, HAS_BIAS) # fmt: skip
+ lo, hi, frac, _, bad = _levels(da_ptr, bias_ptr, offs_ptr, hs_ptr, ws_ptr, p, valid,
+ num_levels, MODE, HAS_DA, HAS_BIAS) # fmt: skip
h_lo, w_lo = tl.load(hs_ptr + lo), tl.load(ws_ptr + lo)
base_lo = image + tl.load(offs_ptr + lo)
if MODE == 0:
- col, col_ok = _texel_index(tl.math.floor(u * w_lo.to(u.dtype)).to(tl.int32), w_lo, BOUNDARY)
- row, row_ok = _texel_index(tl.math.floor(v * h_lo.to(u.dtype)).to(tl.int32), h_lo, BOUNDARY)
- texel = (base_lo + row * w_lo + col)[:, None]
- ok = (valid & col_ok & row_ok)[:, None]
+ index, ok, bad = _nearest(u, v, h_lo, w_lo, BOUNDARY)
+ texel = (base_lo + index)[:, None]
+ ok = (valid & ok)[:, None]
else:
- fx, fy, i00, i01, i10, i11, ok00, ok01, ok10, ok11 = _corners(u, v, h_lo, w_lo, BOUNDARY)
+ fx, fy, i00, i01, i10, i11, ok00, ok01, ok10, ok11, _, _, bad_lo = _corners(
+ u, v, h_lo, w_lo, BOUNDARY
+ )
fx, fy = fx[:, None], fy[:, None]
+ bad = bad | bad_lo
if MODE == 3:
h_hi, w_hi = tl.load(hs_ptr + hi), tl.load(ws_ptr + hi)
base_hi = image + tl.load(offs_ptr + hi)
- gx, gy, j00, j01, j10, j11, k00, k01, k10, k11 = _corners(u, v, h_hi, w_hi, BOUNDARY)
+ gx, gy, j00, j01, j10, j11, k00, k01, k10, k11, _, _, bad_hi = _corners(
+ u, v, h_hi, w_hi, BOUNDARY
+ )
gx, gy = gx[:, None], gy[:, None]
+ bad = bad | bad_hi
for c0 in range(0, channels, BLOCK_C):
c = c0 + tl.arange(0, BLOCK_C)[None, :]
@@ -157,6 +233,7 @@ def _forward_kernel(
upper = _bilinear(flat_ptr, base_hi, j00, j01, j10, j11, k00, k01, k10, k11,
gx, gy, c, channels, cm) # fmt: skip
value = value * (1 - frac[:, None]) + upper * frac[:, None]
+ value = tl.where(bad[:, None], float("nan"), value)
tl.store(out_ptr + p[:, None] * channels + c, value, mask=cm)
@@ -241,34 +318,44 @@ def _backward_kernel(
BOUNDARY: tl.constexpr,
HAS_DA: tl.constexpr,
HAS_BIAS: tl.constexpr,
+ COORD_GRADS: tl.constexpr,
BLOCK_P: tl.constexpr,
BLOCK_C: tl.constexpr,
ROUNDS: tl.constexpr,
):
+ """Scatter the texel gradients; with ``COORD_GRADS`` also those of ``uv`` and the level.
+
+ Only the latter read texel values, so without them ``flat_ptr`` is never dereferenced.
+ """
p = tl.program_id(0).to(tl.int64) * BLOCK_P + tl.arange(0, BLOCK_P)
valid = p < num_pixels
u = tl.load(uv_ptr + p * 2, mask=valid, other=0.0)
v = tl.load(uv_ptr + p * 2 + 1, mask=valid, other=0.0)
image = (p // pixels_per_image) * tex_batch_stride
- lo, hi, frac, lod_raw = _levels(da_ptr, bias_ptr, offs_ptr, hs_ptr, ws_ptr, p, valid,
- num_levels, MODE, HAS_DA, HAS_BIAS) # fmt: skip
+ lo, hi, frac, lod_raw, bad = _levels(da_ptr, bias_ptr, offs_ptr, hs_ptr, ws_ptr, p, valid,
+ num_levels, MODE, HAS_DA, HAS_BIAS) # fmt: skip
h_lo, w_lo = tl.load(hs_ptr + lo), tl.load(ws_ptr + lo)
base_lo = image + tl.load(offs_ptr + lo)
weight_lo = (1 - frac)[:, None]
if MODE == 0:
- col, col_ok = _texel_index(tl.math.floor(u * w_lo.to(u.dtype)).to(tl.int32), w_lo, BOUNDARY)
- row, row_ok = _texel_index(tl.math.floor(v * h_lo.to(u.dtype)).to(tl.int32), h_lo, BOUNDARY)
- texel = base_lo + row * w_lo + col
- ok = valid & col_ok & row_ok
+ index, ok, bad = _nearest(u, v, h_lo, w_lo, BOUNDARY)
+ texel = base_lo + index
+ ok = valid & ok
else:
- fx, fy, i00, i01, i10, i11, ok00, ok01, ok10, ok11 = _corners(u, v, h_lo, w_lo, BOUNDARY)
+ fx, fy, i00, i01, i10, i11, ok00, ok01, ok10, ok11, sx_lo, sy_lo, bad_lo = _corners(
+ u, v, h_lo, w_lo, BOUNDARY
+ )
fx, fy = fx[:, None], fy[:, None]
+ bad = bad | bad_lo
if MODE == 3:
h_hi, w_hi = tl.load(hs_ptr + hi), tl.load(ws_ptr + hi)
base_hi = image + tl.load(offs_ptr + hi)
- gx, gy, j00, j01, j10, j11, k00, k01, k10, k11 = _corners(u, v, h_hi, w_hi, BOUNDARY)
+ gx, gy, j00, j01, j10, j11, k00, k01, k10, k11, sx_hi, sy_hi, bad_hi = _corners(
+ u, v, h_hi, w_hi, BOUNDARY
+ )
gx, gy = gx[:, None], gy[:, None]
+ bad = bad | bad_hi
grad_u = tl.zeros((BLOCK_P,), dtype=u.dtype)
grad_v = tl.zeros((BLOCK_P,), dtype=u.dtype)
@@ -278,47 +365,52 @@ def _backward_kernel(
c = cc[None, :]
cm = valid[:, None] & (c < channels)
g = tl.load(grad_out_ptr + p[:, None] * channels + c, mask=cm, other=0.0)
+ # A pixel that is NaN in the output passes no gradient.
+ g = tl.where(bad[:, None], 0.0, g)
if MODE == 0:
_scatter(grad_flat_ptr, texel, ok, g, cc, channels, ROUNDS)
else:
- t00, t01, t10, t11 = _load_corners(
- flat_ptr, base_lo, i00, i01, i10, i11, ok00, ok01, ok10, ok11, c, channels, cm
- )
g_lo = g * weight_lo
_scatter_bilinear(grad_flat_ptr, base_lo, i00, i01, i10, i11, ok00, ok01, ok10, ok11,
fx, fy, g_lo, cc, channels, valid, ROUNDS) # fmt: skip
- d_fx = (1 - fy) * (t01 - t00) + fy * (t11 - t10)
- d_fy = (1 - fx) * (t10 - t00) + fx * (t11 - t01)
- grad_u += tl.sum(g_lo * d_fx, axis=1) * w_lo.to(u.dtype)
- grad_v += tl.sum(g_lo * d_fy, axis=1) * h_lo.to(u.dtype)
- if MODE == 3:
- s00, s01, s10, s11 = _load_corners(
- flat_ptr, base_hi, j00, j01, j10, j11, k00, k01, k10, k11, c, channels, cm
+ if COORD_GRADS:
+ t00, t01, t10, t11 = _load_corners(
+ flat_ptr, base_lo, i00, i01, i10, i11, ok00, ok01, ok10, ok11, c, channels, cm
)
+ d_fx = (1 - fy) * (t01 - t00) + fy * (t11 - t10)
+ d_fy = (1 - fx) * (t10 - t00) + fx * (t11 - t01)
+ grad_u += tl.sum(g_lo * d_fx, axis=1) * w_lo.to(u.dtype) * sx_lo
+ grad_v += tl.sum(g_lo * d_fy, axis=1) * h_lo.to(u.dtype) * sy_lo
+ if MODE == 3:
g_hi = g * frac[:, None]
_scatter_bilinear(grad_flat_ptr, base_hi, j00, j01, j10, j11, k00, k01, k10, k11,
gx, gy, g_hi, cc, channels, valid, ROUNDS) # fmt: skip
+ if (MODE == 3) and COORD_GRADS:
+ s00, s01, s10, s11 = _load_corners(
+ flat_ptr, base_hi, j00, j01, j10, j11, k00, k01, k10, k11, c, channels, cm
+ )
e_fx = (1 - gy) * (s01 - s00) + gy * (s11 - s10)
e_fy = (1 - gx) * (s10 - s00) + gx * (s11 - s01)
- grad_u += tl.sum(g_hi * e_fx, axis=1) * w_hi.to(u.dtype)
- grad_v += tl.sum(g_hi * e_fy, axis=1) * h_hi.to(u.dtype)
+ grad_u += tl.sum(g_hi * e_fx, axis=1) * w_hi.to(u.dtype) * sx_hi
+ grad_v += tl.sum(g_hi * e_fy, axis=1) * h_hi.to(u.dtype) * sy_hi
lower = (1 - fy) * ((1 - fx) * t00 + fx * t01) + fy * ((1 - fx) * t10 + fx * t11)
upper = (1 - gy) * ((1 - gx) * s00 + gx * s01) + gy * ((1 - gx) * s10 + gx * s11)
grad_frac += tl.sum(g * (upper - lower), axis=1)
- tl.store(grad_uv_ptr + p * 2, grad_u, mask=valid)
- tl.store(grad_uv_ptr + p * 2 + 1, grad_v, mask=valid)
+ if COORD_GRADS:
+ tl.store(grad_uv_ptr + p * 2, grad_u, mask=valid)
+ tl.store(grad_uv_ptr + p * 2 + 1, grad_v, mask=valid)
- if MODE == 3:
+ if (MODE == 3) and COORD_GRADS:
# The level of detail is clamped to the available levels.
in_range = (lod_raw >= 0) & (lod_raw <= (num_levels - 1) * 1.0)
grad_lod = tl.where(in_range, grad_frac, 0.0)
if HAS_BIAS:
tl.store(grad_bias_ptr + p, grad_lod, mask=valid)
- if (MODE == 3) and HAS_DA:
+ if (MODE == 3) and HAS_DA and COORD_GRADS:
base_h = tl.load(hs_ptr)
base_w = tl.load(ws_ptr)
- _, len_x, len_y, longest, du_dx, du_dy, dv_dx, dv_dy, w2, h2 = _level_of_detail(
+ _, len_x, len_y, longest, slope_ux, slope_uy, slope_vx, slope_vy = _level_of_detail(
da_ptr, p, valid, base_h, base_w
)
# lod = log2(longest) / 2, with the footprint clamped from below.
@@ -328,10 +420,10 @@ def _backward_kernel(
share_x = tl.where(len_x > len_y, 1.0, tl.where(len_x == len_y, 0.5, 0.0))
grad_x = grad_longest * share_x
grad_y = grad_longest * (1 - share_x)
- tl.store(grad_da_ptr + p * 4, grad_x * 2 * du_dx * w2, mask=valid)
- tl.store(grad_da_ptr + p * 4 + 1, grad_y * 2 * du_dy * w2, mask=valid)
- tl.store(grad_da_ptr + p * 4 + 2, grad_x * 2 * dv_dx * h2, mask=valid)
- tl.store(grad_da_ptr + p * 4 + 3, grad_y * 2 * dv_dy * h2, mask=valid)
+ tl.store(grad_da_ptr + p * 4, grad_x * 2 * slope_ux, mask=valid)
+ tl.store(grad_da_ptr + p * 4 + 1, grad_y * 2 * slope_uy, mask=valid)
+ tl.store(grad_da_ptr + p * 4 + 2, grad_x * 2 * slope_vx, mask=valid)
+ tl.store(grad_da_ptr + p * 4 + 3, grad_y * 2 * slope_vy, mask=valid)
class Texture(torch.autograd.Function):
@@ -346,42 +438,74 @@ def forward(ctx, flat, uv, uv_da, bias, offsets, heights, widths, mode, boundary
da = uv_da.contiguous() if has_da else uv
bias = bias.contiguous() if has_bias else uv
out = uv.new_empty(batch, height, width, channels)
- args = _launch_args(flat, uv, offsets)
+ args = _launch_args(flat.shape, uv)
with torch.cuda.device(uv.device):
_forward_kernel[args["grid"]](
flat, offsets, heights, widths, uv, da, bias, out,
args["num_pixels"], args["pixels_per_image"], args["batch_stride"],
channels, offsets.shape[0],
MODE=mode, BOUNDARY=boundary, HAS_DA=has_da, HAS_BIAS=has_bias,
- BLOCK_P=BLOCK_PIXELS, BLOCK_C=args["block_c"],
+ BLOCK_P=BLOCK_PIXELS, BLOCK_C=args["block_c"], enable_fp_fusion=FP_FUSION,
) # fmt: skip
- ctx.save_for_backward(flat, uv, da, bias, offsets, heights, widths)
- ctx.mode, ctx.boundary = mode, boundary
- ctx.has_da, ctx.has_bias = has_da, has_bias
+ # Texel values are needed only for the gradients of uv and the level of detail. Unless
+ # one of those is wanted they are not kept, so a texture that is sampled directly may
+ # be modified in place before the backward pass.
+ coord_grads = mode > 0 and any(ctx.needs_input_grad[1:4])
+ ctx.save_for_backward(flat if coord_grads else None, uv, da, bias, offsets, heights, widths)
+ ctx.settings = (flat.shape, mode, boundary, has_da, has_bias)
return out
@staticmethod
def backward(ctx, grad_out):
- flat, uv, da, bias, offsets, heights, widths = ctx.saved_tensors
+ grads = TextureGradients.apply(grad_out, *ctx.saved_tensors, *ctx.settings)
+ return (*grads, None, None, None, None, None)
+
+
+class TextureGradients(torch.autograd.Function):
+ """The backward pass of :class:`Texture`.
+
+ It is a function of its own so that differentiating its results raises. They depend on the
+ texture, ``uv`` and the level of detail as well as on the incoming gradient, and no kernel
+ computes those second-order terms.
+ """
+
+ @staticmethod
+ def forward(
+ ctx, grad_out, flat, uv, da, bias, offsets, heights, widths,
+ flat_shape, mode, boundary, has_da, has_bias,
+ ): # fmt: skip
+ coord_grads = flat is not None
grad_out = grad_out.contiguous()
- grad_flat = torch.zeros_like(flat)
- grad_uv = torch.empty_like(uv)
+ grad_flat = uv.new_zeros(flat_shape)
# Only trilinear filtering depends smoothly on the level of detail.
- smooth = ctx.mode == 3
- grad_da = torch.zeros_like(da) if smooth and ctx.has_da else grad_uv
- grad_bias = torch.zeros_like(bias) if smooth and ctx.has_bias else grad_uv
- args = _launch_args(flat, uv, offsets)
+ smooth = mode == 3
+ grad_uv = torch.empty_like(uv) if coord_grads else None
+ grad_da = torch.zeros_like(da) if coord_grads and smooth and has_da else None
+ grad_bias = torch.zeros_like(bias) if coord_grads and smooth and has_bias else None
+ # Pointers the kernel does not use get a placeholder, as in the forward pass.
+ unused = grad_flat
+ args = _launch_args(flat_shape, uv)
with torch.cuda.device(uv.device):
_backward_kernel[args["grid"]](
- flat, offsets, heights, widths, uv, da, bias, grad_out, grad_flat, grad_uv,
- grad_da, grad_bias, args["num_pixels"], args["pixels_per_image"],
- args["batch_stride"], flat.shape[-1], offsets.shape[0],
- MODE=ctx.mode, BOUNDARY=ctx.boundary, HAS_DA=ctx.has_da, HAS_BIAS=ctx.has_bias,
- BLOCK_P=BLOCK_PIXELS, BLOCK_C=args["block_c"], ROUNDS=SCATTER_ROUNDS,
+ flat if coord_grads else unused, offsets, heights, widths, uv, da, bias, grad_out,
+ grad_flat,
+ unused if grad_uv is None else grad_uv,
+ unused if grad_da is None else grad_da,
+ unused if grad_bias is None else grad_bias,
+ args["num_pixels"], args["pixels_per_image"], args["batch_stride"],
+ flat_shape[-1], offsets.shape[0],
+ MODE=mode, BOUNDARY=boundary, HAS_DA=has_da, HAS_BIAS=has_bias,
+ COORD_GRADS=coord_grads, BLOCK_P=BLOCK_PIXELS, BLOCK_C=args["block_c"],
+ ROUNDS=SCATTER_ROUNDS, enable_fp_fusion=FP_FUSION,
) # fmt: skip
- grad_uv_da = grad_da if smooth and ctx.has_da else None
- grad_mip_bias = grad_bias if smooth and ctx.has_bias else None
- return grad_flat, grad_uv, grad_uv_da, grad_mip_bias, None, None, None, None, None
+ return grad_flat, grad_uv, grad_da, grad_bias
+
+ @staticmethod
+ def backward(ctx, *grads):
+ raise RuntimeError(
+ "The Triton backend of texture provides first-order gradients only. Select the "
+ 'reference backend, diffrast.set_backend("reference"), for higher-order gradients.'
+ )
def texture(
@@ -392,35 +516,47 @@ def texture(
boundary_mode: str,
max_mip_level: int | None,
mip_level_bias: Tensor | None = None,
+ mip: Sequence[Tensor] | None = None,
+ packed: tuple[Tensor, Tensor, Tensor, Tensor] | None = None,
) -> Tensor:
+ if uv.numel() == 0:
+ # There is nothing to launch. The PyTorch code returns an empty result within the graph.
+ return reference.texture(
+ tex, uv, uv_da, filter_mode, boundary_mode, max_mip_level, mip_level_bias, mip, packed
+ )
mode = FILTER_MODES.index(filter_mode)
- levels = _mip_chain(tex, max_mip_level) if mode >= 2 else [tex]
- channels = tex.shape[-1]
- flat = torch.cat([level.reshape(level.shape[0], -1, channels) for level in levels], 1)
- sizes = torch.tensor([level.shape[1:3] for level in levels], dtype=torch.int32)
- counts = sizes[:, 0] * sizes[:, 1]
- offsets = (counts.cumsum(0) - counts).to(torch.int32)
- device = uv.device
+ # Inputs the output does not depend on stay out of the graph, as in the reference backend.
+ if mode == 0:
+ uv = uv.detach()
+ if mode < 3:
+ uv_da = None if uv_da is None or mode < 2 else uv_da.detach()
+ mip_level_bias = None if mip_level_bias is None or mode < 2 else mip_level_bias.detach()
+
+ if mode >= 2:
+ flat, heights, widths, offsets = reference._pack_levels(tex, mip, max_mip_level, packed)
+ else:
+ flat, heights, widths, offsets = reference._pack([tex])
return Texture.apply(
flat.contiguous(),
uv,
uv_da,
mip_level_bias,
- offsets.to(device),
- sizes[:, 0].contiguous().to(device),
- sizes[:, 1].contiguous().to(device),
+ offsets.int(),
+ heights.int(),
+ widths.int(),
mode,
BOUNDARY_MODES.index(boundary_mode),
)
-def _launch_args(flat: Tensor, uv: Tensor, offsets: Tensor) -> dict:
+def _launch_args(flat_shape: Sequence[int], uv: Tensor) -> dict:
+ """Launch parameters for a packed buffer of shape ``flat_shape`` sampled at ``uv``."""
batch, height, width, _ = uv.shape
num_pixels = batch * height * width
return {
"grid": (triton.cdiv(num_pixels, BLOCK_PIXELS),),
"num_pixels": num_pixels,
"pixels_per_image": height * width,
- "batch_stride": 0 if flat.shape[0] == 1 else flat.shape[1],
- "block_c": min(triton.next_power_of_2(flat.shape[-1]), 16),
+ "batch_stride": 0 if flat_shape[0] == 1 else flat_shape[1],
+ "block_c": min(triton.next_power_of_2(flat_shape[-1]), 16),
}
diff --git a/src/diffrast/backends/reference.py b/src/diffrast/backends/reference.py
index 622192c..d967ade 100644
--- a/src/diffrast/backends/reference.py
+++ b/src/diffrast/backends/reference.py
@@ -7,7 +7,9 @@
normalized device coordinates ``(px, py)``, the perspective-correct barycentrics ``b`` of a
triangle satisfy ``sum(b * (x - px * w)) = 0`` and ``sum(b * (y - py * w)) = 0``, so ``b`` is the
normalized cross product of those two vectors. A pixel is covered when all ``b >= 0``, the
-interpolated ``w`` is positive, and ``-1 <= z / w <= 1``. This needs no near-plane clipping.
+interpolated ``w`` is positive, and ``-1 <= z / w <= 1``. This needs no near-plane clipping. A
+pixel centre exactly on an edge belongs to one side of it only (see :func:`_inside_edge`), so
+triangles sharing the edge never both cover it and never leave it empty.
"""
from __future__ import annotations
@@ -20,6 +22,17 @@
# Upper bound on batch * triangles * pixels evaluated at once during visibility.
_CHUNK_ELEMENTS = 1 << 22
+# A triangle is not drawn at a pixel where its area is within this many epsilons of the magnitude
+# of the terms it is computed from. The Triton visibility kernels use the same constant.
+AREA_TOLERANCE = 2
+
+# Antialiasing gives an edge to the horizontal pixel pairs when it is at least as steep as 45
+# degrees in pixel space. Edges within this relative margin of 45 degrees count as steep too, so
+# that the rounding of the slope cannot decide where an edge at exactly 45 degrees goes.
+AXIS_TIE = 1 + 1e-4
+# Antialiasing counts a pixel centre as lying on an edge when the edge function there is zero
+# up to its rounding error, taken as this many epsilons of the terms it is computed from.
+EDGE_TIE = 4
def rasterize(
@@ -42,7 +55,7 @@ def rasterize_layer(
and then by triangle index, so triangles at equal depth each get their own layer.
"""
height, width = resolution
- if tri.shape[0] == 0:
+ if tri.shape[0] == 0 or pos.shape[0] == 0:
empty = pos.new_zeros(pos.shape[0], height, width, 4)
none = torch.full((pos.shape[0], height, width), -1, device=pos.device)
return empty, empty.clone(), (pos.new_full(none.shape, torch.inf), none)
@@ -103,16 +116,17 @@ def rasterize_from_ids(
def interpolate(
attr: Tensor, rast: Tensor, tri: Tensor, rast_db: Tensor | None, diff_attrs: Sequence[int]
-) -> tuple[Tensor, Tensor | None]:
+) -> tuple[Tensor, Tensor]:
batch, height, width, _ = rast.shape
channels = attr.shape[-1]
out = attr.new_zeros(batch, height, width, channels)
- out_da = attr.new_zeros(batch, height, width, 2 * len(diff_attrs)) if diff_attrs else None
+ out_da = attr.new_zeros(batch, height, width, 2 * len(diff_attrs))
if tri.shape[0] == 0:
return out, out_da
+ # Ids past the end of tri are drawn as background rather than read out of range.
tri_id = rast[..., 3].round().long() - 1
- pixel = (tri_id >= 0).nonzero(as_tuple=True)
+ pixel = ((tri_id >= 0) & (tri_id < tri.shape[0])).nonzero(as_tuple=True)
if attr.ndim == 2:
attr = attr[None]
attr = attr.expand(batch, -1, -1)
@@ -121,7 +135,7 @@ def interpolate(
u, v = rast[pixel][:, 0:1], rast[pixel][:, 1:2]
out = out.index_put(pixel, u * a0 + v * a1 + (1 - u - v) * a2)
if not diff_attrs:
- return out, None
+ return out, out_da
da_du = (a0 - a2)[:, list(diff_attrs)]
da_dv = (a1 - a2)[:, list(diff_attrs)]
@@ -140,43 +154,58 @@ def texture(
boundary_mode: str,
max_mip_level: int | None,
mip_level_bias: Tensor | None = None,
+ mip: Sequence[Tensor] | None = None,
+ packed: tuple[Tensor, Tensor, Tensor, Tensor] | None = None,
) -> Tensor:
- if filter_mode == "nearest":
- return _sample_nearest(tex, uv, boundary_mode)
- if filter_mode == "linear":
- return _sample_linear(tex, uv, boundary_mode)
-
- levels = _mip_chain(tex, max_mip_level)
- lod = uv.new_zeros(uv.shape[:3])
- if uv_da is not None:
- lod = lod + _level_of_detail(uv_da, tex.shape[1], tex.shape[2])
- if mip_level_bias is not None:
- lod = lod + mip_level_bias
- lod = lod.clamp(0, len(levels) - 1)
- if filter_mode == "linear-mipmap-nearest":
- nearest = torch.floor(lod + 0.5).detach()
- weights = [(nearest == i).to(uv.dtype) for i in range(len(levels))]
- used = [nearest == i for i in range(len(levels))]
+ """Sample ``tex``; ``mip`` holds mip levels 1 and up to use instead of a box-filtered chain.
+
+ ``packed`` is the result of :func:`_pack` for ``tex`` followed by all of ``mip``, for a
+ caller that has it already.
+
+ A cube map is reduced to a 2D lookup per face: its directions are projected to a face index
+ and face coordinates, and only fetching texels across face edges differs from there on.
+ """
+ mipmapped = "mipmap" in filter_mode
+ face = valid = None
+ if boundary_mode == "cube":
+ from diffrast.backends import _cube
+
+ face, uv, uv_da, valid = _cube.project(uv, uv_da if mipmapped else None)
+ image = torch.arange(uv.shape[0], device=uv.device)[:, None, None]
+
+ if mipmapped:
+ texels, heights, widths, offsets = _pack_levels(tex, mip, max_mip_level, packed)
+ lod = uv.new_zeros(uv.shape[:3])
+ if uv_da is not None:
+ lod = lod + _level_of_detail(uv_da, tex.shape[-3], tex.shape[-2])
+ if mip_level_bias is not None:
+ lod = lod + mip_level_bias
+ blend = filter_mode == "linear-mipmap-linear"
+ sizes = (heights, widths, offsets)
+ out, bad = _sample_mipmapped(texels, sizes, uv, lod, blend, boundary_mode, image, face)
else:
- lower = lod.floor().detach()
- frac = lod - lower
- weights = [
- torch.where(lower == i, 1 - frac, 0) + torch.where(lower + 1 == i, frac, 0)
- for i in range(len(levels))
- ]
- used = [(lower == i) | (lower + 1 == i) for i in range(len(levels))]
-
- out = uv.new_zeros(*uv.shape[:3], tex.shape[-1])
- for level, weight, mask in zip(levels, weights, used, strict=True):
- # Levels no pixel touches are skipped. A touched level is sampled even where its weight
- # is zero, so the blend factor still receives a gradient.
- if mask.any():
- out = out + weight[..., None] * _sample_linear(level, uv, boundary_mode)
- return out
+ texels, heights, widths, offsets = _pack([tex])
+ sample = _sample_nearest if filter_mode == "nearest" else _sample_linear
+ size = (heights[0], widths[0], offsets[0])
+ out, bad = sample(texels, size, uv, boundary_mode, image, face)
+ # A pixel whose coordinates or level of detail are not finite is NaN and passes no gradient.
+ out = torch.where(bad[..., None], torch.nan, out)
+ # Directions that select no point on the cube read zeros and pass no gradient.
+ return out if valid is None else torch.where(valid[..., None], out, 0)
+
+
+def texture_construct_mip(tex: Tensor, max_mip_level: int | None) -> list[Tensor]:
+ """Mip levels 1 and up of ``tex``, in the form :func:`texture` takes as ``mip``."""
+ return _mip_chain(tex, max_mip_level)[1:]
def antialias(
- color: Tensor, rast: Tensor, pos: Tensor, tri: Tensor, pos_gradient_boost: float
+ color: Tensor,
+ rast: Tensor,
+ pos: Tensor,
+ tri: Tensor,
+ pos_gradient_boost: float,
+ neighbours: Tensor | None = None,
) -> Tensor:
"""Blend colours across silhouette edges by where each edge crosses between pixel centres.
@@ -186,15 +215,23 @@ def antialias(
along that axis, the pixel whose half contains the crossing takes ``|t - 0.5|`` of the other
pixel's colour. ``t`` depends on the vertex positions, so moving an edge changes the image
continuously and gives gradients to ``pos``.
+
+ ``pos`` is ``[batch, vertices, 4]``, or ``[vertices, 4]`` to share it across the batch.
+ ``neighbours`` is the result of :func:`edge_neighbours` for ``tri``, if already known.
"""
if tri.shape[0] == 0:
- return color
- height, width = rast.shape[1:3]
+ return color.clone()
+ batch, height, width = rast.shape[:3]
tri = tri.long()
+ if pos.ndim == 2:
+ pos = pos[None]
tri_id = rast[..., 3].detach().round().long() - 1
+ # Ids past the end of tri are treated as background rather than read out of range.
+ tri_id = torch.where(tri_id < tri.shape[0], tri_id, -1)
depth = rast[..., 2].detach()
with torch.no_grad():
- silhouette = _silhouette_edges(pos.detach(), tri)
+ silhouette = _silhouette_edges(pos, tri, neighbours).expand(batch, -1, -1)
+ pos = pos.expand(batch, -1, -1)
px, py = pixel_centres(height, width, pos)
out = color
@@ -225,7 +262,7 @@ def antialias(
delta_q = torch.where(active & (t >= 0.5)[:, None], (t - 0.5)[:, None] * (c_p - c_q), 0.0)
out = out.index_put((b, row, col), delta_p, accumulate=True)
out = out.index_put((b, row_q, col_q), delta_q, accumulate=True)
- return out
+ return out.contiguous()
def pixel_centres(height: int, width: int, like: Tensor) -> tuple[Tensor, Tensor]:
@@ -253,6 +290,81 @@ def _edge_derivatives(
return de_dx, de_dy
+def _coverage(verts: Tensor, px: Tensor, py: Tensor) -> tuple[Tensor, Tensor]:
+ """Which pixels each triangle covers, and its depth ``z / w`` at every pixel.
+
+ ``verts`` holds clip-space triangles, ``[batch, triangles, 3, 1, 1, 4]``; ``px`` and ``py``
+ broadcast against ``[batch, triangles, height, width]``, the shape of both results. The Triton
+ visibility kernels evaluate the same operations in the same order, so that in float32 the two
+ backends decide every pixel alike.
+ """
+ x, y, z, w = verts.unbind(-1)
+ (x0, x1, x2), (y0, y1, y2), (z0, z1, z2), (w0, w1, w2) = (t.unbind(2) for t in (x, y, z, w))
+ a0, a1, a2 = x0 - px * w0, x1 - px * w1, x2 - px * w2
+ c0, c1, c2 = y0 - py * w0, y1 - py * w1, y2 - py * w2
+ e0 = a1 * c2 - a2 * c1
+ e1 = a2 * c0 - a0 * c2
+ e2 = a0 * c1 - a1 * c0
+ s = e0 + e1 + e2
+ ew = e0 * w0 + e1 * w1 + e2 * w2
+ depth = (e0 * z0 + e1 * z1 + e2 * z2) / ew
+
+ positive = s > 0
+ inside = _inside_edge(e0, a1, c1, w1, a2, c2, w2, positive)
+ inside &= _inside_edge(e1, a2, c2, w2, a0, c0, w0, positive)
+ inside &= _inside_edge(e2, a0, c0, w0, a1, c1, w1, positive)
+
+ # Rounding of the vertex coordinates and of a and c can change s by about this much, so a
+ # smaller area is indistinguishable from zero. Without this test, a zero-area triangle is
+ # drawn wherever the rounding residue of its edge functions happens to agree in sign. A
+ # pixel centre has |px| < 1, so |x| + |w| bounds the terms of a = x - px * w.
+ reach_x = torch.maximum(
+ torch.maximum(x0.abs() + w0.abs(), x1.abs() + w1.abs()), x2.abs() + w2.abs()
+ )
+ reach_y = torch.maximum(
+ torch.maximum(y0.abs() + w0.abs(), y1.abs() + w1.abs()), y2.abs() + w2.abs()
+ )
+ span_x = a0.abs() + a1.abs() + a2.abs()
+ span_y = c0.abs() + c1.abs() + c2.abs()
+ tolerance = AREA_TOLERANCE * torch.finfo(verts.dtype).eps
+ inside &= s.abs() > (reach_x * span_y + span_x * (reach_y + span_y)) * tolerance
+
+ inside &= torch.where(positive, ew > 0, ew < 0)
+ inside &= (depth >= -1) & (depth <= 1)
+ inside &= verts.isfinite().all(-1).all(2)
+ return inside, depth
+
+
+def _inside_edge(
+ e: Tensor,
+ ai: Tensor,
+ ci: Tensor,
+ wi: Tensor,
+ aj: Tensor,
+ cj: Tensor,
+ wj: Tensor,
+ positive: Tensor,
+) -> Tensor:
+ """Whether a pixel is on the inner side of the edge from vertex i to vertex j.
+
+ ``e = a_i * c_j - a_j * c_i`` is the edge function at the pixel, and the inner side is where
+ it has the sign of the triangle's area, given by ``positive``. A pixel centre exactly on the
+ edge is inside only when the interior lies in the +x direction of screen space, or in the +y
+ direction for a horizontal edge, like the top-left rule of hardware rasterizers.
+
+ The direction is the sign of the screen-space gradient ``(gx, gy)`` of ``e``. It is computed
+ from the coordinates relative to the pixel, which are small and often exact where ``e`` is
+ zero: at a pixel centre on a vertex, the gradients of the edges through that vertex are single
+ products, so the triangles around it agree on which of them owns the pixel. ``e`` and the
+ gradient change sign exactly when i and j are swapped, so of two triangles on opposite sides
+ of an edge exactly one owns the pixels on it, whatever their winding.
+ """
+ gx = ci * wj - cj * wi
+ gy = aj * wi - ai * wj
+ q = torch.where(e == 0, torch.where(gx == 0, gy, gx), e)
+ return torch.where(positive, q > 0, q < 0)
+
+
def _visible_triangles(
pos: Tensor, tri: Tensor, px: Tensor, py: Tensor, previous: tuple[Tensor, Tensor] | None = None
) -> tuple[Tensor, Tensor]:
@@ -270,17 +382,12 @@ def _visible_triangles(
prev_depth, prev_id = (t[:, None] for t in previous)
for start in range(0, tri.shape[0], chunk):
- verts = pos[:, tri[start : start + chunk]][:, :, None, None]
- x, y, z, w = verts.unbind(-1)
- e = _edge_functions(x, y, w, px, py)
- b = e / e.sum(-1, keepdim=True)
- w_p = (b * w).sum(-1)
- depth = (b * z).sum(-1) / w_p
- inside = (b >= 0).all(-1) & (w_p > 0) & (depth >= -1) & (depth <= 1)
+ verts = pos[:, tri[start : start + chunk]][:, :, :, None, None]
+ inside, depth = _coverage(verts, px, py)
if previous is not None:
- index = torch.arange(start, start + x.shape[1], device=pos.device)[:, None, None]
+ index = torch.arange(start, start + verts.shape[1], device=pos.device)[:, None, None]
later = (depth > prev_depth) | ((depth == prev_depth) & (index > prev_id))
- inside &= later
+ inside = inside & later
depth = torch.where(inside, depth, torch.inf)
chunk_depth, chunk_id = depth.min(dim=1)
@@ -290,65 +397,279 @@ def _visible_triangles(
return best_depth, best_id
+# Footprints saturate at this many texels. Both backends use the same value, so that they agree
+# on inputs that are out of range.
+_FOOTPRINT_LIMIT = 1e18
+
+
+def _mip_levels(
+ tex: Tensor, mip: Sequence[Tensor] | None, max_mip_level: int | None
+) -> list[Tensor]:
+ """The levels to sample, base level first: the given ones, or a chain built from ``tex``."""
+ if mip is None:
+ return _mip_chain(tex, max_mip_level)
+ levels = [tex, *mip]
+ return levels if max_mip_level is None else levels[: max_mip_level + 1]
+
+
+def _pack_levels(
+ tex: Tensor,
+ mip: Sequence[Tensor] | None,
+ max_mip_level: int | None,
+ packed: tuple[Tensor, Tensor, Tensor, Tensor] | None = None,
+) -> tuple[Tensor, Tensor, Tensor, Tensor]:
+ """The buffer and size tables, as from :func:`_pack`, of the levels a lookup may use.
+
+ With ``packed`` given, nothing is copied: the buffer keeps every level and ``max_mip_level``
+ only shortens the tables.
+ """
+ if packed is None:
+ return _pack(_mip_levels(tex, mip, max_mip_level))
+ texels, *tables = packed
+ count = None if max_mip_level is None else max_mip_level + 1
+ return (texels, *(table[:count] for table in tables))
+
+
def _mip_chain(tex: Tensor, max_mip_level: int | None) -> list[Tensor]:
- """Box-filtered mip levels, halving each dimension (rounding up) until both are 1."""
- levels = [tex]
+ """Box-filtered mip levels, halving each dimension (rounding up) until both are 1.
+
+ The faces of a cube map are filtered one by one.
+ """
+ cube = tex.ndim == 5
+ levels = [tex.flatten(0, 1) if cube else tex]
while max(levels[-1].shape[1:3]) > 1 and (
max_mip_level is None or len(levels) <= max_mip_level
):
- height, width = levels[-1].shape[1:3]
- kernel = (2 if height > 1 else 1, 2 if width > 1 else 1)
- # With ceil_mode, a window hanging over an odd edge averages only the texels it covers.
- level = F.avg_pool2d(levels[-1].permute(0, 3, 1, 2), kernel, ceil_mode=True)
- levels.append(level.permute(0, 2, 3, 1))
+ levels.append(_downsample(levels[-1]))
+ if cube:
+ levels = [tex, *(level.unflatten(0, tex.shape[:2]) for level in levels[1:])]
return levels
+def _downsample(level: Tensor) -> Tensor:
+ """The next mip level of a ``[batch, height, width, channels]`` level.
+
+ Each dimension is split into half as many equal bins (rounding up), and a coarse texel is the
+ area-weighted mean of the texels its bin overlaps. Every texel therefore has the same total
+ weight in the result, and the levels stay aligned in ``uv``. For an even size the bins are
+ whole pairs of texels.
+ """
+ height, width = level.shape[1:3]
+ image = level.permute(0, 3, 1, 2)
+ pairs = (2 if height % 2 == 0 else 1, 2 if width % 2 == 0 else 1)
+ if pairs != (1, 1):
+ image = F.avg_pool2d(image, pairs)
+ if height > 1 and height % 2 == 1:
+ image = _halve_odd(image, 2)
+ if width > 1 and width % 2 == 1:
+ image = _halve_odd(image, 3)
+ return image.permute(0, 2, 3, 1)
+
+
+def _halve_odd(image: Tensor, dim: int) -> Tensor:
+ """Resample an odd dimension of ``n`` texels into ``(n + 1) / 2`` equal bins.
+
+ A bin is less than two texels wide, so it overlaps at most three texels.
+ """
+ n = image.shape[dim]
+ m = (n + 1) // 2
+ j = torch.arange(m, device=image.device)
+ first = j * n // m
+ shape = [1] * image.ndim
+ shape[dim] = m
+ out = 0
+ for tap in range(3):
+ i = first + tap
+ # Scaled by m, bin j spans [j * n, (j + 1) * n] and texel i spans [i * m, (i + 1) * m],
+ # so the overlaps are exact integers.
+ overlap = torch.minimum((j + 1) * n, (i + 1) * m) - torch.maximum(j * n, i * m)
+ weight = (overlap.clamp(min=0).to(image.dtype) / n).view(shape)
+ out = out + weight * image.index_select(dim, i.clamp(max=n - 1))
+ return out
+
+
def _level_of_detail(uv_da: Tensor, height: int, width: int) -> Tensor:
- """Mip level from the longer of the two screen-space footprint axes, in texels."""
+ """Mip level from the longer of the two screen-space footprint axes, in texels.
+
+ The footprint saturates far beyond any texture size, so that huge or infinite derivatives
+ select the coarsest level with a zero gradient instead of overflowing.
+ """
+ limit = _FOOTPRINT_LIMIT
du_dx, du_dy, dv_dx, dv_dy = uv_da.unbind(-1)
- len_x = (du_dx * width) ** 2 + (dv_dx * height) ** 2
- len_y = (du_dy * width) ** 2 + (dv_dy * height) ** 2
+ len_x = (du_dx * width).clamp(-limit, limit) ** 2 + (dv_dx * height).clamp(-limit, limit) ** 2
+ len_y = (du_dy * width).clamp(-limit, limit) ** 2 + (dv_dy * height).clamp(-limit, limit) ** 2
return 0.5 * torch.log2(torch.maximum(len_x, len_y).clamp_min(1e-30))
-def _sample_nearest(tex: Tensor, uv: Tensor, boundary_mode: str) -> Tensor:
- height, width = tex.shape[1:3]
- col = (uv[..., 0] * width).floor().long()
- row = (uv[..., 1] * height).floor().long()
- return _fetch(tex, row, col, boundary_mode)
+def _pack(levels: Sequence[Tensor]) -> tuple[Tensor, Tensor, Tensor, Tensor]:
+ """Join mip levels into one buffer of shape ``[tex_batch, texels, channels]``.
+
+ Also returns the height, width and texel offset of each level as int64 tensors, so that a
+ lookup can address a different level per pixel. A level shared across the batch is repeated
+ when the base level is not.
+ """
+ batch, channels = levels[0].shape[0], levels[0].shape[-1]
+ sizes = [[*level.shape[-3:-1], level.shape[1:-1].numel()] for level in levels]
+ parts = [
+ level.expand(batch, *level.shape[1:]).reshape(batch, size[2], channels)
+ for level, size in zip(levels, sizes, strict=True)
+ ]
+ texels = parts[0] if len(parts) == 1 else torch.cat(parts, 1)
+ heights, widths, counts = torch.tensor(sizes, device=texels.device).unbind(1)
+ return texels, heights, widths, counts.cumsum(0) - counts
+
+
+def _sample_mipmapped(
+ texels: Tensor,
+ sizes: tuple[Tensor, Tensor, Tensor],
+ uv: Tensor,
+ lod: Tensor,
+ blend: bool,
+ boundary_mode: str,
+ image: Tensor,
+ face: Tensor | None,
+) -> tuple[Tensor, Tensor]:
+ """Bilinear lookups in the level nearest to ``lod``, or blended between the two around it.
+
+ ``sizes`` holds the height, width and offset of every level in ``texels``. Returns the
+ values and which pixels are unusable, which includes those whose level of detail is NaN.
+ """
+ top = sizes[0].shape[0] - 1
+ bad = lod.isnan()
+ lod = torch.where(bad, 0, lod).clamp(0, top)
+ lower = (lod.detach() + (0.0 if blend else 0.5)).floor().long()
+ args = (uv, boundary_mode, image, face)
+ out, bad_lower = _sample_linear(texels, [t[lower] for t in sizes], *args)
+ bad = bad | bad_lower
+ if blend:
+ # At the top level both lookups read that level, so the level of detail has no effect
+ # and no gradient there.
+ upper = (lower + 1).clamp(max=top)
+ frac = (lod - lower)[..., None]
+ above, bad_upper = _sample_linear(texels, [t[upper] for t in sizes], *args)
+ out = out * (1 - frac) + above * frac
+ bad = bad | bad_upper
+ return out, bad
+
+
+def _sample_nearest(
+ texels: Tensor,
+ size: Sequence[Tensor],
+ uv: Tensor,
+ boundary_mode: str,
+ image: Tensor,
+ face: Tensor | None = None,
+) -> tuple[Tensor, Tensor]:
+ """The texel containing ``uv``, and which pixels have coordinates that are not finite.
+ ``size`` is the height, width and offset of the level to sample.
+ """
+ height, width, _ = size
+ x, bad_x = _texel_coordinate(uv[..., 0], width, 0.0, boundary_mode)
+ y, bad_y = _texel_coordinate(uv[..., 1], height, 0.0, boundary_mode)
+ col, row = x.detach().floor().long(), y.detach().floor().long()
+ # A direction exactly on the far edge of a cube face stays on that face.
+ boundary_mode = "clamp" if boundary_mode == "cube" else boundary_mode
+ return _fetch(texels, size, image, row, col, boundary_mode, face), bad_x | bad_y
+
+
+def _sample_linear(
+ texels: Tensor,
+ size: Sequence[Tensor],
+ uv: Tensor,
+ boundary_mode: str,
+ image: Tensor,
+ face: Tensor | None = None,
+) -> tuple[Tensor, Tensor]:
+ """Blend of the four texels around ``uv``, and which pixels have non-finite coordinates.
-def _sample_linear(tex: Tensor, uv: Tensor, boundary_mode: str) -> Tensor:
- height, width = tex.shape[1:3]
- x = uv[..., 0] * width - 0.5
- y = uv[..., 1] * height - 0.5
+ ``size`` is the height, width and offset of the level to sample, per pixel or shared.
+ """
+ height, width, _ = size
+ x, bad_x = _texel_coordinate(uv[..., 0], width, 0.5, boundary_mode)
+ y, bad_y = _texel_coordinate(uv[..., 1], height, 0.5, boundary_mode)
x0, y0 = x.floor().detach(), y.floor().detach()
fx, fy = (x - x0)[..., None], (y - y0)[..., None]
col, row = x0.long(), y0.long()
- top = (1 - fx) * _fetch(tex, row, col, boundary_mode) + fx * _fetch(
- tex, row, col + 1, boundary_mode
- )
- bottom = (1 - fx) * _fetch(tex, row + 1, col, boundary_mode) + fx * _fetch(
- tex, row + 1, col + 1, boundary_mode
- )
- return (1 - fy) * top + fy * bottom
+ # The four taps are fetched in one lookup, along a new dimension before the channels.
+ rows = torch.stack([row, row, row + 1, row + 1], -1)
+ cols = torch.stack([col, col + 1, col, col + 1], -1)
+ per_tap = [t[..., None] for t in size]
+ tap_face = None if face is None else face[..., None]
+ taps = _fetch(texels, per_tap, image[..., None], rows, cols, boundary_mode, tap_face)
+ t00, t01, t10, t11 = taps.unbind(-2)
+ out = (1 - fy) * ((1 - fx) * t00 + fx * t01) + fy * ((1 - fx) * t10 + fx * t11)
+ if boundary_mode == "cube":
+ # Beyond a corner of the cube one of the four taps has no texel and was read as zero.
+ # It counts as the mean of the other three, which keeps the result continuous there.
+ left, right = (col < 0)[..., None], (col + 1 >= width)[..., None]
+ above, below = (row < 0)[..., None], (row + 1 >= height)[..., None]
+ missing = (1 - fy) * ((1 - fx) * (left & above) + fx * (right & above)) + fy * (
+ (1 - fx) * (left & below) + fx * (right & below)
+ )
+ out = out + missing * taps.sum(-2) / 3
+ return out, bad_x | bad_y
-def _fetch(tex: Tensor, row: Tensor, col: Tensor, boundary_mode: str) -> Tensor:
- """Texels at integer coordinates ``[batch, height, width]``, with out-of-range handling."""
- tex_batch, height, width, channels = tex.shape
- valid = None
+
+def _texel_coordinate(
+ coord: Tensor, size: Tensor, shift: float, boundary_mode: str
+) -> tuple[Tensor, Tensor]:
+ """Continuous texel coordinate ``coord * size - shift``, kept within reach of the texture.
+
+ Also returns where it is not finite; there it is replaced and passes no gradient.
+
+ When wrapping, ``coord`` is first reduced to its fractional part, so a coordinate far outside
+ the texture keeps the precision it has and cannot overflow an integer index. With clamping or
+ zeros outside, the result saturates one texel outside the texture, where every tap is out of
+ range already, so far-out and infinite coordinates behave like any other coordinate outside.
+ """
if boundary_mode == "wrap":
+ coord = coord - coord.detach().floor()
+ x = coord * size - shift
+ if boundary_mode in ("clamp", "zero"):
+ x = x.clamp(min=-1).clamp(max=size)
+ bad = ~torch.isfinite(x)
+ return torch.where(bad, 0, x), bad
+
+
+def _fetch(
+ texels: Tensor,
+ size: Sequence[Tensor],
+ image: Tensor,
+ row: Tensor,
+ col: Tensor,
+ boundary_mode: str,
+ face: Tensor | None = None,
+) -> Tensor:
+ """Texels at integer coordinates, with out-of-range handling.
+
+ ``texels`` has shape ``[tex_batch, texels, channels]`` and ``size`` is the height, width and
+ offset of the level each coordinate refers to. ``image`` is the batch index of each
+ coordinate, used unless the texture is shared, and ``face`` the cube face it is on. Texels
+ that do not exist are read as zero.
+ """
+ height, width, offset = size
+ valid = None
+ if boundary_mode == "cube":
+ from diffrast.backends import _cube
+
+ face, row, col, valid = _cube.fold(face, row, col, width)
+ elif boundary_mode == "wrap":
row, col = row % height, col % width
else:
if boundary_mode == "zero":
valid = (row >= 0) & (row < height) & (col >= 0) & (col < width)
- row, col = row.clamp(0, height - 1), col.clamp(0, width - 1)
+ row = row.clamp(min=0).clamp(max=height - 1)
+ col = col.clamp(min=0).clamp(max=width - 1)
- image = torch.arange(row.shape[0], device=row.device)[:, None, None] if tex_batch > 1 else 0
- texels = tex.reshape(-1, channels)[(image * height + row) * width + col]
- return texels if valid is None else texels * valid[..., None]
+ if face is not None:
+ row = row + face * height
+ index = offset + row * width + col
+ if texels.shape[0] > 1:
+ index = index + image * texels.shape[1]
+ out = texels.reshape(-1, texels.shape[-1])[index]
+ return out if valid is None else out * valid[..., None]
def _edge_crossing(
@@ -372,8 +693,12 @@ def _edge_crossing(
the other axis (it is handled by the pixel pairs along that axis). ``t`` is the crossing as a
fraction of the segment from ``src``.
"""
- visible = tri_id >= 0
- tri_id = tri_id.clamp(min=0)
+ # Only pairs with a triangle at src are evaluated. A stand-in triangle for the others would
+ # send its discarded results through the backward pass, where they can be NaN.
+ num_pairs = tri_id.shape[0]
+ covered = (tri_id >= 0).nonzero().squeeze(1)
+ b, tri_id = b[covered], tri_id[covered]
+ src_x, src_y, dst_x, dst_y = src_x[covered], src_y[covered], dst_x[covered], dst_y[covered]
x, y, _, w = pos[b[:, None], tri[tri_id]].unbind(-1)
# The edge functions are affine in screen space, so each edge's crossing is found by
@@ -381,35 +706,98 @@ def _edge_crossing(
e_src = _edge_functions(x, y, w, src_x, src_y)
e_dst = _edge_functions(x, y, w, dst_x, dst_y)
sign = torch.where(e_src.sum(-1, keepdim=True) < 0, -1.0, 1.0)
- outside = e_dst * sign < 0
- t_edge = torch.where(outside, e_src / torch.where(outside, e_src - e_dst, 1.0), torch.inf)
+ span = e_src - e_dst
+ with torch.no_grad():
+ # rast says that the triangle at src is not shown at dst, so a dst centre that lies on
+ # an edge up to rounding counts as beyond it. The crossing is then at dst, whose pixel
+ # blends half of its neighbour whichever side of the edge the rasterizer gave it to and
+ # however it rounded. An edge through both centres is not crossed between them, and
+ # dividing by its zero span would give a NaN gradient even though the quotient is
+ # discarded.
+ slack = _edge_slack(x, y, w, dst_x, dst_y)
+ crossed = (e_dst * sign <= slack) & (span * sign > 2 * slack)
+ t_edge = torch.where(crossed, e_src / torch.where(crossed, span, 1.0), torch.inf)
t, edge = t_edge.min(-1)
- de_dx, de_dy = _edge_derivatives(x, y, w, src_x, src_y)
- normal_x = de_dx.gather(-1, edge[:, None]).squeeze(-1).abs() * (2 / width)
- normal_y = de_dy.gather(-1, edge[:, None]).squeeze(-1).abs() * (2 / height)
- along_axis = normal_x >= normal_y if horizontal else normal_y > normal_x
+ with torch.no_grad():
+ along_axis = _along_axis(x, y, w, edge, horizontal, width, height)
+ found = crossed.any(-1) & silhouette[b, tri_id, edge] & along_axis
+ all_found = found.new_zeros(num_pairs).index_put((covered,), found)
+ all_t = t.new_zeros(num_pairs).index_put((covered,), torch.where(found, t, 0.0))
+ return all_found, all_t
- found = visible & outside.any(-1) & silhouette[b, tri_id, edge] & along_axis
- return found.detach(), torch.where(found, t, 0.0)
+def _edge_slack(x: Tensor, y: Tensor, w: Tensor, px: Tensor, py: Tensor) -> Tensor:
+ """Bound on the rounding error of :func:`_edge_functions` at the pixels ``(px, py)``.
-def _silhouette_edges(pos: Tensor, tri: Tensor) -> Tensor:
- """Which triangle edges are silhouettes, ``[batch, triangles, 3]``.
+ Two evaluations of an edge function that order or fuse the operations differently, such as
+ the rasterizer's and the one made here, differ by less than this.
+ """
+ a, c = x - px[..., None] * w, y - py[..., None] * w
+ # Rounding of a = x - px * w is relative to |x| + |w|, since |px| < 1, and likewise for c.
+ reach_x, reach_y = x.abs() + w.abs(), y.abs() + w.abs()
+ i, j = [1, 2, 0], [2, 0, 1]
+ terms = (
+ (reach_x[:, i] + a[:, i].abs()) * c[:, j].abs()
+ + (reach_x[:, j] + a[:, j].abs()) * c[:, i].abs()
+ + reach_y[:, j] * a[:, i].abs()
+ + reach_y[:, i] * a[:, j].abs()
+ )
+ return terms * (EDGE_TIE * torch.finfo(x.dtype).eps)
- Edge ``k`` of a triangle is the one opposite vertex ``k``. It is a silhouette when no other
- triangle shares it, when more than two do, or when the triangle sharing it projects onto the
- same side of it (the surface folds over at that edge).
+
+def _along_axis(
+ x: Tensor, y: Tensor, w: Tensor, edge: Tensor, horizontal: bool, width: int, height: int
+) -> Tensor:
+ """Whether the pixel pairs along one axis handle edge ``edge`` of each triangle.
+
+ Horizontal pairs handle an edge that is at least as steep as 45 degrees in pixel space, and
+ vertical pairs the others. The slope is taken from the two vertices of the edge alone, so
+ every pixel pair along an edge decides the same way.
"""
- num_tri = tri.shape[0]
+ i, j = ((edge + 1) % 3)[:, None], ((edge + 2) % 3)[:, None]
+ xi, yi, wi = (v.gather(-1, i).squeeze(-1) for v in (x, y, w))
+ xj, yj, wj = (v.gather(-1, j).squeeze(-1) for v in (x, y, w))
+ # Derivatives of the edge function along x and y; multiplying by the other image size
+ # compares them per pixel.
+ steep = (wj * yi - wi * yj).abs() * height * AXIS_TIE
+ flat = (xj * wi - xi * wj).abs() * width
+ return steep >= flat if horizontal else flat > steep
+
+
+def edge_neighbours(tri: Tensor) -> Tensor:
+ """For each triangle edge, the edge it is shared with, int64 of shape ``[triangles, 3]``.
+
+ Edge ``k`` of a triangle is the one opposite vertex ``k``, and edges are numbered
+ ``3 * triangle + k``. The entry is the number of the same edge in the other triangle that
+ uses it, or -1 when no other triangle does or more than one does. This depends on ``tri``
+ only, so it can be reused for as long as the index buffer stays the same.
+ """
+ tri = tri.long()
start, end = tri[:, [1, 2, 0]].flatten(), tri[:, [2, 0, 1]].flatten()
- key = torch.minimum(start, end) * (int(tri.max()) + 1) + torch.maximum(start, end)
+ # Both vertex indices fit in 32 bits, so the pair packs into one key without a multiplier
+ # that would have to be read back from the device.
+ key = (torch.minimum(start, end) << 32) | torch.maximum(start, end)
_, inverse, counts = torch.unique(key, return_inverse=True, return_counts=True)
order = torch.argsort(inverse, stable=True)
first = (counts.cumsum(0) - counts)[(counts == 2).nonzero().squeeze(1)]
neighbour = torch.full_like(key, -1)
neighbour[order[first]] = order[first + 1]
neighbour[order[first + 1]] = order[first]
+ return neighbour.view(-1, 3)
+
+
+def _silhouette_edges(pos: Tensor, tri: Tensor, neighbours: Tensor | None = None) -> Tensor:
+ """Which triangle edges are silhouettes, ``[batch, triangles, 3]``.
+
+ Edge ``k`` of a triangle is the one opposite vertex ``k``. It is a silhouette when no other
+ triangle shares it, when more than two do, or when the triangle sharing it projects onto the
+ same side of it (the surface folds over at that edge). ``neighbours`` is the result of
+ :func:`edge_neighbours` for ``tri``; it is computed here when not given.
+ """
+ num_tri = tri.shape[0]
+ neighbour = (edge_neighbours(tri) if neighbours is None else neighbours).flatten()
+ start, end = tri[:, [1, 2, 0]].flatten(), tri[:, [2, 0, 1]].flatten()
# The side of the edge's projected line a point lies on is the sign of det[a, b, p] / w_p in
# homogeneous (x, y, w) coordinates; the factor 1 / (w_a * w_b) is shared and drops out.
diff --git a/src/diffrast/backends/triton.py b/src/diffrast/backends/triton.py
index 4e26ddf..769ddd7 100644
--- a/src/diffrast/backends/triton.py
+++ b/src/diffrast/backends/triton.py
@@ -31,7 +31,7 @@ def rasterize_layer(
"""
from diffrast.backends._triton_rasterize import EMPTY, visible_keys
- if tri.shape[0] == 0:
+ if tri.shape[0] == 0 or pos.shape[0] == 0:
empty = pos.new_zeros(pos.shape[0], *resolution, 4)
keys = torch.full((pos.shape[0], *resolution), EMPTY, device=pos.device)
return empty, empty.clone(), keys
@@ -49,12 +49,11 @@ def resolve(pos: Tensor, tri: Tensor, keys: Tensor, grad_db: bool) -> tuple[Tens
def interpolate(
attr: Tensor, rast: Tensor, tri: Tensor, rast_db: Tensor | None, diff_attrs: Sequence[int]
-) -> tuple[Tensor, Tensor | None]:
+) -> tuple[Tensor, Tensor]:
from diffrast.backends._triton_interpolate import Interpolate
diff = torch.tensor(list(diff_attrs), dtype=torch.int32, device=rast.device)
- out, out_da = Interpolate.apply(attr, rast, rast_db, tri, diff)
- return out, (out_da if diff_attrs else None)
+ return Interpolate.apply(attr, rast, rast_db, tri, diff)
def texture(
@@ -65,17 +64,29 @@ def texture(
boundary_mode: str,
max_mip_level: int | None,
mip_level_bias: Tensor | None = None,
+ mip: Sequence[Tensor] | None = None,
+ packed: tuple[Tensor, Tensor, Tensor, Tensor] | None = None,
) -> Tensor:
+ args = (tex, uv, uv_da, filter_mode, boundary_mode, max_mip_level, mip_level_bias, mip, packed)
+ if boundary_mode == "cube":
+ # The kernels are 2D only. Cube maps use the PyTorch implementation, which runs on the
+ # GPU as well.
+ from diffrast.backends import reference
+
+ return reference.texture(*args)
from diffrast.backends import _triton_texture
- return _triton_texture.texture(
- tex, uv, uv_da, filter_mode, boundary_mode, max_mip_level, mip_level_bias
- )
+ return _triton_texture.texture(*args)
def antialias(
- color: Tensor, rast: Tensor, pos: Tensor, tri: Tensor, pos_gradient_boost: float
+ color: Tensor,
+ rast: Tensor,
+ pos: Tensor,
+ tri: Tensor,
+ pos_gradient_boost: float,
+ neighbours: Tensor | None = None,
) -> Tensor:
from diffrast.backends import _triton_antialias
- return _triton_antialias.antialias(color, rast, pos, tri, pos_gradient_boost)
+ return _triton_antialias.antialias(color, rast, pos, tri, pos_gradient_boost, neighbours)
diff --git a/src/diffrast/compat.py b/src/diffrast/compat.py
new file mode 100644
index 0000000..b23e71b
--- /dev/null
+++ b/src/diffrast/compat.py
@@ -0,0 +1,74 @@
+"""Run code written for nvdiffrast on diffrast without editing it."""
+
+from __future__ import annotations
+
+import importlib
+import importlib.util
+import sys
+from types import ModuleType
+
+from diffrast import log
+
+_displaced: dict[str, ModuleType] = {}
+
+
+def install_as_nvdiffrast(force: bool = False) -> None:
+ """Make ``import nvdiffrast.torch as dr`` resolve to diffrast in this process.
+
+ Registers ``diffrast`` and ``diffrast.torch`` in ``sys.modules`` under the names
+ ``nvdiffrast`` and ``nvdiffrast.torch``. Call it before importing the code that uses
+ nvdiffrast; modules that imported the real package earlier keep using it. Calling it again
+ does nothing, and :func:`uninstall_as_nvdiffrast` undoes it.
+
+ Args:
+ force: Take the place of a real nvdiffrast package that is installed or already
+ imported. Without it, that raises ``RuntimeError``.
+ """
+ ours = _modules()
+ current = {name: sys.modules.get(name) for name in ours}
+ if all(current[name] is module for name, module in ours.items()):
+ return
+ imported = [name for name, module in ours.items() if current[name] not in (None, module)]
+ if not force:
+ if imported:
+ raise RuntimeError(
+ f"{imported[0]} is already imported; pass force=True to replace it with diffrast."
+ )
+ if current["nvdiffrast"] is None and _is_installed("nvdiffrast"):
+ raise RuntimeError(
+ "An nvdiffrast package is installed; pass force=True to use diffrast in its place."
+ )
+ if imported:
+ log.warn(
+ "Replacing the imported nvdiffrast with diffrast; modules that imported it "
+ "earlier keep using it.",
+ stacklevel=2,
+ )
+ for name, module in ours.items():
+ if name in imported:
+ _displaced[name] = current[name]
+ sys.modules[name] = module
+
+
+def uninstall_as_nvdiffrast() -> None:
+ """Undo :func:`install_as_nvdiffrast`, restoring any modules it replaced."""
+ for name, module in _modules().items():
+ previous = _displaced.pop(name, None)
+ if sys.modules.get(name) is module:
+ del sys.modules[name]
+ if previous is not None:
+ sys.modules[name] = previous
+
+
+def _modules() -> dict[str, ModuleType]:
+ return {
+ "nvdiffrast": importlib.import_module("diffrast"),
+ "nvdiffrast.torch": importlib.import_module("diffrast.torch"),
+ }
+
+
+def _is_installed(name: str) -> bool:
+ try:
+ return importlib.util.find_spec(name) is not None
+ except (ImportError, ValueError):
+ return False
diff --git a/src/diffrast/context.py b/src/diffrast/context.py
index 7e88968..d756b92 100644
--- a/src/diffrast/context.py
+++ b/src/diffrast/context.py
@@ -1,5 +1,7 @@
from __future__ import annotations
+import operator
+
import torch
@@ -7,21 +9,94 @@ class RasterizeContext:
"""Device that :func:`diffrast.rasterize` runs on.
Args:
- device: Device to rasterize on. Defaults to the current CUDA/ROCm device, or the CPU
- when no GPU is available.
+ device: Device to rasterize on, as a ``torch.device``, a string such as ``"cuda:0"`` or
+ a GPU index. Defaults to the current CUDA/ROCm device, or the CPU when no GPU is
+ available.
+
+ Attributes:
+ device: The resolved ``torch.device``, with an explicit index for a GPU.
+ output_db: Whether :func:`diffrast.rasterize` returns ``rast_db``. Always true here;
+ see :class:`RasterizeGLContext`.
"""
- def __init__(self, device: torch.device | str | None = None) -> None:
- if device is None:
- device = "cuda" if torch.cuda.is_available() else "cpu"
- device = torch.device(device)
- if device.type == "cuda" and device.index is None:
- device = torch.device("cuda", torch.cuda.current_device())
- self.device = device
+ output_db = True
+
+ def __init__(self, device: torch.device | str | int | None = None) -> None:
+ self.device = _resolve_device(device)
def __repr__(self) -> str:
- return f"RasterizeContext(device={str(self.device)!r})"
+ return f"{type(self).__name__}(device={str(self.device)!r})"
# Alias so code written against the nvdiffrast API runs unchanged.
RasterizeCudaContext = RasterizeContext
+
+
+class RasterizeGLContext(RasterizeContext):
+ """Stand-in for nvdiffrast's OpenGL context, so that code which creates one runs unchanged.
+
+ diffrast has no OpenGL rasterizer: this context rasterizes exactly like
+ :class:`RasterizeContext` on the same device.
+
+ Args:
+ output_db: Whether :func:`diffrast.rasterize` returns ``rast_db``. With ``False`` it
+ returns an empty tensor of shape ``[batch, height, width, 0]`` in its place.
+ mode: Accepted for compatibility and ignored.
+ device: As for :class:`RasterizeContext`.
+ """
+
+ def __init__(
+ self,
+ output_db: bool = True,
+ mode: str = "automatic",
+ device: torch.device | str | int | None = None,
+ ) -> None:
+ super().__init__(device)
+ # A device in the first position, where the other contexts take it, would count as true.
+ if isinstance(output_db, (str, torch.device)):
+ raise TypeError(
+ f"output_db must be a bool, got {output_db!r}; pass the device as device=..."
+ )
+ self.output_db = bool(output_db)
+ self.mode = mode
+
+ def __repr__(self) -> str:
+ return f"RasterizeGLContext(output_db={self.output_db}, device={str(self.device)!r})"
+
+ def set_context(self) -> None:
+ """Do nothing; there is no OpenGL context to make current."""
+
+ def release_context(self) -> None:
+ """Do nothing; there is no OpenGL context to release."""
+
+
+def _resolve_device(device: torch.device | str | int | None) -> torch.device:
+ if device is None:
+ device = "cuda" if torch.cuda.is_available() else "cpu"
+ elif not isinstance(device, (torch.device, str)):
+ try:
+ if isinstance(device, bool):
+ raise TypeError
+ index = operator.index(device)
+ except TypeError:
+ raise TypeError(
+ f"device must be a torch.device, a string or a GPU index, got {device!r}."
+ ) from None
+ if index < 0:
+ raise ValueError(f"device must not be a negative GPU index, got {device!r}.")
+ device = torch.device("cuda", index)
+ device = torch.device(device)
+ if device.type != "cuda":
+ return device
+ if not torch.cuda.is_available():
+ raise RuntimeError(
+ f"device {str(device)!r} was requested, but no CUDA or ROCm device is available."
+ )
+ if device.index is None:
+ return torch.device("cuda", torch.cuda.current_device())
+ if device.index >= torch.cuda.device_count():
+ raise ValueError(
+ f"device {str(device)!r} does not exist; {torch.cuda.device_count()} CUDA or ROCm "
+ "devices are available."
+ )
+ return device
diff --git a/src/diffrast/log.py b/src/diffrast/log.py
new file mode 100644
index 0000000..0a61332
--- /dev/null
+++ b/src/diffrast/log.py
@@ -0,0 +1,38 @@
+"""Log level for diffrast's own messages, numbered as in nvdiffrast."""
+
+from __future__ import annotations
+
+import operator
+import warnings
+
+INFO, WARNING, ERROR, FATAL = range(4)
+
+_level = WARNING
+
+
+def get_log_level() -> int:
+ """Return the current log level: 0 is info, 1 warning (the default), 2 error and 3 fatal."""
+ return _level
+
+
+def set_log_level(level: int) -> None:
+ """Set the lowest level of message that diffrast reports.
+
+ Args:
+ level: 0 for info, 1 for warning, 2 for error or 3 for fatal. Warnings are only issued
+ at levels 0 and 1; errors are always raised as exceptions, whatever the level.
+ """
+ global _level
+ try:
+ value = operator.index(level)
+ except TypeError:
+ raise TypeError(f"level must be an int from 0 to 3, got {level!r}.") from None
+ if not INFO <= value <= FATAL:
+ raise ValueError(f"level must be an int from 0 to 3, got {level!r}.")
+ _level = value
+
+
+def warn(message: str, stacklevel: int = 1) -> None:
+ """Issue a ``UserWarning`` attributed to the caller, unless the log level silences warnings."""
+ if _level <= WARNING:
+ warnings.warn(message, stacklevel=stacklevel + 1)
diff --git a/src/diffrast/ops.py b/src/diffrast/ops.py
index cec9587..6221c2f 100644
--- a/src/diffrast/ops.py
+++ b/src/diffrast/ops.py
@@ -7,24 +7,27 @@
from __future__ import annotations
+import operator
from collections.abc import Sequence
-from typing import Literal, get_args
+from typing import Literal, SupportsFloat, get_args
import torch
from torch import Tensor
+from diffrast._cache import TensorCache
from diffrast.backends import get_backend
from diffrast.context import RasterizeContext
+from diffrast.topology import TopologyHash, neighbours_for
FilterMode = Literal["auto", "nearest", "linear", "linear-mipmap-nearest", "linear-mipmap-linear"]
-BoundaryMode = Literal["wrap", "clamp", "zero"]
+BoundaryMode = Literal["wrap", "clamp", "zero", "cube"]
FILTER_MODES = get_args(FilterMode)
BOUNDARY_MODES = get_args(BoundaryMode)
def rasterize(
- ctx: RasterizeContext,
+ glctx: RasterizeContext,
pos: Tensor,
tri: Tensor,
resolution: tuple[int, int],
@@ -33,21 +36,45 @@ def rasterize(
) -> tuple[Tensor, Tensor]:
"""Rasterize triangles into per-pixel barycentrics, depth and triangle ids.
+ The rank of ``pos`` selects the mode. In instanced mode every batch item draws all triangles
+ with its own vertex positions. In range mode all items share one vertex buffer, and item ``i``
+ draws the triangles ``tri[start_i : start_i + count_i]`` given by ``ranges``.
+
+ A pixel is covered by a triangle when its centre lies inside it. A centre exactly on an edge
+ belongs to the triangle whose interior lies in the +x direction from that edge (+y for a
+ horizontal edge), so triangles sharing an edge never both cover a pixel. Triangles with zero
+ area or with a NaN or infinite vertex are not drawn.
+
Args:
- ctx: Rasterization context.
- pos: Clip-space vertex positions, float32 of shape ``[batch, vertices, 4]``.
- tri: Vertex indices, int32 of shape ``[triangles, 3]``.
+ glctx: Rasterization context.
+ pos: Clip-space vertex positions, float32 of shape ``[batch, vertices, 4]`` (instanced
+ mode) or ``[vertices, 4]`` (range mode).
+ tri: Vertex indices, int32 of shape ``[triangles, 3]``, at most ``2**24`` triangles.
resolution: Output size as ``(height, width)``.
- ranges: Range mode is not supported yet; must be ``None``.
+ ranges: In range mode, ``(start, count)`` per batch item, int32 of shape ``[batch, 2]``,
+ normally kept on the CPU. Ignored in instanced mode.
grad_db: Propagate gradients from ``rast_db`` back to ``pos``.
Returns:
``(rast, rast_db)``, both of shape ``[batch, height, width, 4]``. Each pixel of ``rast``
- holds ``(u, v, z / w, triangle_id + 1)``, and is all zeros where no triangle covers it.
- ``rast_db`` holds the screen-space derivatives ``(du/dx, du/dy, dv/dx, dv/dy)``.
+ holds ``(u, v, z / w, triangle_id + 1)``, and is all zeros where no triangle covers it;
+ the id is the triangle's row in ``tri`` in both modes. ``rast_db`` holds the screen-space
+ derivatives ``(du/dx, du/dy, dv/dx, dv/dy)``. For a context whose ``output_db`` is false,
+ ``rast_db`` has shape ``[batch, height, width, 0]`` and ``grad_db`` is ignored.
"""
- resolution = check_rasterize_inputs(ctx, pos, tri, resolution, ranges)
- return get_backend(pos.device, "rasterize").rasterize(pos, tri, resolution, grad_db)
+ resolution = check_rasterize_inputs(glctx, pos, tri, resolution, ranges)
+ backend = get_backend(pos.device, "rasterize")
+ output_db = getattr(glctx, "output_db", True)
+ grad_db = grad_db and output_db
+ if pos.ndim == 2:
+ layers = [
+ backend.rasterize(pos[None], triangles, resolution, grad_db)
+ for triangles in split_ranges(tri, ranges)
+ ]
+ rast, rast_db = join_ranges(pos, resolution, ranges, layers)
+ else:
+ rast, rast_db = backend.rasterize(pos, tri, resolution, grad_db)
+ return rast, (rast_db if output_db else rast.new_zeros(*rast.shape[:3], 0))
def interpolate(
@@ -56,48 +83,56 @@ def interpolate(
tri: Tensor,
rast_db: Tensor | None = None,
diff_attrs: Sequence[int] | Literal["all"] | None = None,
-) -> tuple[Tensor, Tensor | None]:
+) -> tuple[Tensor, Tensor]:
"""Interpolate vertex attributes across the rasterized triangles.
Args:
attr: Vertex attributes, float32 of shape ``[batch, vertices, channels]``, or
``[vertices, channels]`` to share them across the batch.
- rast: First output of :func:`rasterize`.
- tri: Vertex indices used to produce ``rast``.
- rast_db: Second output of :func:`rasterize`. Required when ``diff_attrs`` is set.
+ rast: First output of :func:`rasterize`, float32 of shape ``[batch, height, width, 4]``.
+ Pixels whose triangle id lies past the end of ``tri`` are treated as background.
+ tri: Vertex indices into ``attr``, int32 of shape ``[triangles, 3]``, with one row per
+ triangle of the index buffer that produced ``rast``. The indices are checked against
+ the number of vertices once per tensor object, so pass the same tensor to every call
+ rather than a fresh copy or cast. Only edits PyTorch records are noticed: after
+ writing through ``tri.data`` or through memory shared with NumPy, pass a new tensor.
+ rast_db: Second output of :func:`rasterize`. Required when ``diff_attrs`` is set; an
+ empty tensor of shape ``[batch, height, width, 0]`` counts as ``None``.
diff_attrs: Attribute channels to compute screen-space derivatives for, or ``"all"``.
Returns:
``(out, out_da)``. ``out`` has shape ``[batch, height, width, channels]``. ``out_da`` has
shape ``[batch, height, width, 2 * len(diff_attrs)]`` with ``(d/dx, d/dy)`` per selected
- channel, or is ``None`` when ``diff_attrs`` is not set.
+ channel, and is empty, of shape ``[batch, height, width, 0]``, when ``diff_attrs`` is not
+ set.
"""
- if attr.ndim not in (2, 3):
- raise ValueError(f"attr must have 2 or 3 dimensions, got shape {tuple(attr.shape)}.")
- _check(attr, "attr", ndim=attr.ndim, dtype=torch.float32)
+ shared = isinstance(attr, Tensor) and attr.ndim == 2
+ layout = "[batch, vertices, channels] or [vertices, channels]"
+ _check(attr, "attr", ndim=2 if shared else 3, dtype=torch.float32, layout=layout)
_check(rast, "rast", ndim=4, last=4, dtype=torch.float32)
_check(tri, "tri", ndim=2, last=3, dtype=torch.int32)
if attr.ndim == 3 and attr.shape[0] not in (1, rast.shape[0]):
raise ValueError(
f"attr batch size {attr.shape[0]} does not match rast batch size {rast.shape[0]}."
)
+ _check_devices(attr=attr, rast=rast, tri=tri, rast_db=rast_db)
- if diff_attrs is None:
- channels: list[int] = []
- elif diff_attrs == "all":
- channels = list(range(attr.shape[-1]))
- else:
- channels = [int(c) for c in diff_attrs]
- if any(c < 0 or c >= attr.shape[-1] for c in channels):
- raise ValueError(f"diff_attrs {channels} out of range for {attr.shape[-1]} channels.")
- if channels:
- if rast_db is None:
- raise ValueError("rast_db is required when diff_attrs is set.")
+ channels = _diff_channels(diff_attrs, attr.shape[-1])
+ empty = rast_db is not None and rast_db.ndim == 4 and rast_db.shape[-1] == 0
+ if rast_db is not None and not empty:
_check(rast_db, "rast_db", ndim=4, last=4, dtype=torch.float32)
if rast_db.shape != rast.shape:
- raise ValueError("rast_db must have the same shape as rast.")
-
- _check_devices(attr=attr, rast=rast, tri=tri, rast_db=rast_db)
+ raise ValueError(
+ f"rast_db must have the same shape as rast, got {tuple(rast_db.shape)} and "
+ f"{tuple(rast.shape)}."
+ )
+ if not channels:
+ rast_db = None
+ elif rast_db is None or empty:
+ given = ", but the one given is empty" if empty else ""
+ raise ValueError(f"rast_db is required when diff_attrs is set{given}.")
+
+ _check_indices(tri, attr.shape[-2])
return get_backend(rast.device, "interpolate").interpolate(attr, rast, tri, rast_db, channels)
@@ -106,56 +141,76 @@ def texture(
uv: Tensor,
uv_da: Tensor | None = None,
mip_level_bias: Tensor | None = None,
- mip: Sequence[Tensor] | None = None,
+ mip: MipStack | Sequence[Tensor] | None = None,
filter_mode: FilterMode = "auto",
boundary_mode: BoundaryMode = "wrap",
max_mip_level: int | None = None,
) -> Tensor:
- """Sample a 2D texture at per-pixel texture coordinates.
+ """Sample a 2D texture or a cube map at per-pixel texture coordinates.
Args:
- tex: Texture, float32 of shape ``[batch, tex_height, tex_width, channels]``. A batch of
- one is shared across all views.
+ tex: Texture, float32 of shape ``[batch, tex_height, tex_width, channels]``, or a cube
+ map of shape ``[batch, 6, size, size, channels]`` with its faces in the order
+ ``+x, -x, +y, -y, +z, -z`` and oriented as in OpenGL. A batch of one is shared across
+ all views.
uv: Texture coordinates, float32 of shape ``[batch, height, width, 2]``. ``u`` runs along
the texture width and ``v`` along its height; ``(0, 0)`` is the outer corner of texel
- ``[0, 0]`` and ``(1, 1)`` the outer corner of the last texel.
+ ``[0, 0]`` and ``(1, 1)`` the outer corner of the last texel. For a cube map, direction
+ vectors of shape ``[batch, height, width, 3]``, which need not be normalised.
uv_da: Screen-space derivatives ``(du/dx, du/dy, dv/dx, dv/dy)`` of ``uv``, shape
- ``[batch, height, width, 4]``, as returned by :func:`interpolate`. The mipmapped
- filter modes need it or ``mip_level_bias``.
+ ``[batch, height, width, 4]``, as returned by :func:`interpolate`. For a cube map,
+ ``(d/dx, d/dy)`` of each of the three direction components, shape
+ ``[batch, height, width, 6]``. The mipmapped filter modes need it or
+ ``mip_level_bias``.
mip_level_bias: Per-pixel offset added to the mip level of detail, shape
``[batch, height, width]``. Without ``uv_da`` it sets the level directly.
- mip: Precomputed mip levels are not supported yet; must be ``None``.
+ mip: Mip levels to use instead of box filtering ``tex`` on every call. Either the result
+ of :func:`texture_construct_mip` for the same ``tex`` (a ``tex`` of another shape is
+ an error), or a list of tensors holding levels 1, 2 and so on. Each has the format of
+ ``tex`` with its own height and width, and a batch of one or that of ``tex``. The base
+ level stays in ``tex`` and is not part of the list, which may stop at any level.
+ Gradients reach the listed tensors and do not continue from them to ``tex``.
filter_mode: ``"auto"`` picks ``"linear-mipmap-linear"`` when ``uv_da`` or
``mip_level_bias`` is given and ``"linear"`` otherwise.
boundary_mode: Coordinates outside ``[0, 1]`` repeat the texture (``"wrap"``), repeat its
- edge texels (``"clamp"``), or read zeros (``"zero"``).
+ edge texels (``"clamp"``), or read zeros (``"zero"``). A cube map requires ``"cube"``:
+ the lookup in a mip level is filtered across face edges and corners without seams,
+ and directions that select no point on the cube (a component that is not finite,
+ or a vector shorter than the smallest normal float, such as the zero vector) read
+ zeros and receive no gradient. The level of detail is the footprint of ``uv_da`` on
+ the face the direction selects, so the level chosen from ``uv_da`` can still change
+ from one face to the next.
max_mip_level: Index of the coarsest mip level to use, or ``None`` for a full chain.
- ``0`` disables mipmapping.
+ ``0`` disables mipmapping. It also limits the levels used from ``mip``.
Returns:
- Sampled values of shape ``[batch, height, width, channels]``.
+ Sampled values of shape ``[batch, height, width, channels]``. Infinite ``uv`` counts as
+ far outside the texture, where wrapping has no texel to return. A pixel that is undefined
+ in that way, or whose ``uv``, ``uv_da`` or ``mip_level_bias`` is NaN, is NaN and passes
+ no gradient.
"""
- if mip is not None:
- raise NotImplementedError("Precomputed mip levels (mip=...) are not supported yet.")
- _check(tex, "tex", ndim=4, dtype=torch.float32)
- _check(uv, "uv", ndim=4, last=2, dtype=torch.float32)
- if tex.shape[0] not in (1, uv.shape[0]):
- raise ValueError(
- f"tex batch size {tex.shape[0]} does not match uv batch size {uv.shape[0]}."
- )
if filter_mode not in FILTER_MODES:
raise ValueError(f"Unknown filter_mode {filter_mode!r}; expected one of {FILTER_MODES}.")
if boundary_mode not in BOUNDARY_MODES:
raise ValueError(
f"Unknown boundary_mode {boundary_mode!r}; expected one of {BOUNDARY_MODES}."
)
+ cube = boundary_mode == "cube"
+ _check_texture(tex, "tex", cube, 'boundary_mode="cube"')
+ _check(uv, "uv", ndim=4, last=3 if cube else 2, dtype=torch.float32)
+ if tex.shape[0] not in (1, uv.shape[0]):
+ raise ValueError(
+ f"tex batch size {tex.shape[0]} does not match uv batch size {uv.shape[0]}."
+ )
+ if isinstance(uv_da, Tensor) and uv_da.ndim == 4 and uv_da.shape[-1] == 0:
+ uv_da = None
has_lod = uv_da is not None or mip_level_bias is not None
if filter_mode == "auto":
filter_mode = "linear-mipmap-linear" if has_lod else "linear"
if "mipmap" in filter_mode and not has_lod:
raise ValueError(f"filter_mode {filter_mode!r} requires uv_da or mip_level_bias.")
if uv_da is not None:
- _check(uv_da, "uv_da", ndim=4, last=4, dtype=torch.float32)
+ _check(uv_da, "uv_da", ndim=4, last=6 if cube else 4, dtype=torch.float32)
if uv_da.shape[:3] != uv.shape[:3]:
raise ValueError("uv_da must match uv in batch, height and width.")
if mip_level_bias is not None:
@@ -164,19 +219,155 @@ def texture(
raise ValueError("mip_level_bias must match uv in batch, height and width.")
if max_mip_level is not None and max_mip_level < 0:
raise ValueError(f"max_mip_level must be non-negative, got {max_mip_level}.")
+ levels = None if mip is None else _check_mip(mip, tex, cube)
+ stacked = isinstance(mip, MipStack) and "mipmap" in filter_mode
_check_devices(tex=tex, uv=uv, uv_da=uv_da, mip_level_bias=mip_level_bias)
return get_backend(uv.device, "texture").texture(
- tex, uv, uv_da, filter_mode, boundary_mode, max_mip_level, mip_level_bias=mip_level_bias
+ tex,
+ uv,
+ uv_da,
+ filter_mode,
+ boundary_mode,
+ max_mip_level,
+ mip_level_bias=mip_level_bias,
+ mip=levels,
+ packed=mip.pack(tex) if stacked else None,
)
+def texture_construct_mip(
+ tex: Tensor, max_mip_level: int | None = None, cube_mode: bool = False
+) -> MipStack:
+ """Build the mip levels of a texture once, for use in several :func:`texture` calls.
+
+ Passing the result as ``mip``, together with the same ``tex``, saves rebuilding the levels on
+ every call for a texture that does not change. If ``tex`` requires gradients they flow
+ through the levels back to it, so the stack has to be built again whenever ``tex`` changes.
+ For a ``tex`` that does not require gradients, the stack also keeps the buffer the backends
+ sample, a copy of ``tex`` and the levels, from one call to the next.
+
+ Args:
+ tex: Texture, float32 of shape ``[batch, tex_height, tex_width, channels]``, or a cube
+ map of shape ``[batch, 6, size, size, channels]``.
+ max_mip_level: Index of the coarsest mip level to build, or ``None`` for a full chain.
+ cube_mode: Must be true for a cube map, whose faces are filtered one by one.
+
+ Returns:
+ An opaque object holding mip levels 1 and up.
+ """
+ from diffrast.backends import reference
+
+ _check_texture(tex, "tex", cube_mode, "cube_mode=True")
+ if max_mip_level is not None and max_mip_level < 0:
+ raise ValueError(f"max_mip_level must be non-negative, got {max_mip_level}.")
+ levels = reference.texture_construct_mip(tex, max_mip_level)
+ return MipStack(levels, bool(cube_mode), tex.shape)
+
+
+class MipStack:
+ """Mip levels built by :func:`texture_construct_mip`, passed to :func:`texture` as ``mip``.
+
+ The contents are an implementation detail.
+ """
+
+ __slots__ = ("_packed", "cube_mode", "levels", "shape")
+
+ def __init__(self, levels: Sequence[Tensor], cube_mode: bool, shape: Sequence[int]) -> None:
+ self.levels = tuple(levels)
+ self.cube_mode = cube_mode
+ self.shape = tuple(shape)
+ self._packed: tuple[Tensor, int, tuple[Tensor, Tensor, Tensor, Tensor]] | None = None
+
+ def pack(self, tex: Tensor) -> tuple[Tensor, Tensor, Tensor, Tensor]:
+ """``tex`` and the levels joined into the one buffer that the backends sample.
+
+ The result is kept for later calls with the same tensor, as long as nothing in it takes
+ part in autograd. A ``tex`` modified in place since is noticed by its version counter.
+ """
+ from diffrast.backends import reference
+
+ constant = not (
+ tex.requires_grad
+ or tex.is_inference()
+ or torch.is_inference_mode_enabled()
+ or any(level.requires_grad for level in self.levels)
+ )
+ if constant and self._packed is not None:
+ base, version, packed = self._packed
+ if base is tex and version == tex._version:
+ return packed
+ packed = reference._pack([tex, *self.levels])
+ if constant:
+ self._packed = (tex, tex._version, packed)
+ return packed
+
+
+def _check_texture(t: Tensor, name: str, cube: bool, cube_option: str) -> None:
+ """Validate the format of a texture or mip level; ``cube_option`` is what selects cube maps."""
+ if isinstance(t, Tensor) and t.ndim == 5 and not cube:
+ raise ValueError(
+ f"{name} has the shape of a cube map, {tuple(t.shape)}, which needs {cube_option}."
+ )
+ if isinstance(t, Tensor) and t.ndim == 4 and cube:
+ raise ValueError(
+ f"{cube_option} needs {name} to be a cube map of shape "
+ f"[batch, 6, size, size, channels], got {tuple(t.shape)}."
+ )
+ _check(t, name, ndim=5 if cube else 4, dtype=torch.float32)
+ if cube and (t.shape[1] != 6 or t.shape[2] != t.shape[3]):
+ raise ValueError(
+ f"{name} must have six square faces, [batch, 6, size, size, channels], "
+ f"got {tuple(t.shape)}."
+ )
+ if 0 in t.shape[1:]:
+ raise ValueError(
+ f"{name} must have at least one texel and one channel, got shape {tuple(t.shape)}."
+ )
+
+
+def _check_mip(mip: MipStack | Sequence[Tensor], tex: Tensor, cube: bool) -> list[Tensor]:
+ """Validate ``mip`` against ``tex`` and return the tensors of mip levels 1 and up."""
+ if isinstance(mip, MipStack):
+ if mip.cube_mode != cube:
+ raise ValueError(
+ f"mip was constructed with cube_mode={mip.cube_mode}, which does not match "
+ f"{'a cube map' if cube else 'a 2D texture'}."
+ )
+ if mip.shape != tuple(tex.shape):
+ raise ValueError(
+ f"mip was constructed for a texture of shape {mip.shape}, but tex has shape "
+ f"{tuple(tex.shape)}."
+ )
+ levels = list(mip.levels)
+ elif isinstance(mip, Sequence):
+ levels = list(mip)
+ else:
+ raise TypeError(
+ "mip must be a list of tensors or the result of texture_construct_mip, "
+ f"got {type(mip).__name__}."
+ )
+ for index, level in enumerate(levels, start=1):
+ name = f"mip level {index}"
+ _check_texture(level, name, cube, 'boundary_mode="cube"')
+ if level.shape[-1] != tex.shape[-1]:
+ raise ValueError(f"{name} has {level.shape[-1]} channels but tex has {tex.shape[-1]}.")
+ if level.shape[0] not in (1, tex.shape[0]):
+ raise ValueError(
+ f"{name} has batch size {level.shape[0]}; expected 1 or that of tex, "
+ f"{tex.shape[0]}."
+ )
+ if level.device != tex.device:
+ raise ValueError(f"{name} is on {level.device} but tex is on {tex.device}.")
+ return levels
+
+
def antialias(
color: Tensor,
rast: Tensor,
pos: Tensor,
tri: Tensor,
- topology_hash: Tensor | None = None,
+ topology_hash: TopologyHash | None = None,
pos_gradient_boost: float = 1.0,
) -> Tensor:
"""Antialias silhouette edges so that visibility changes produce gradients in ``pos``.
@@ -184,11 +375,17 @@ def antialias(
Args:
color: Shaded image, float32 of shape ``[batch, height, width, channels]``.
rast: First output of :func:`rasterize` for the same geometry.
- pos: Clip-space vertex positions used to produce ``rast``.
- tri: Vertex indices used to produce ``rast``. Silhouettes are found from edges shared by
- index, so vertices split only for UV seams or normals turn those seams into
- silhouettes; pass position-only indices here.
- topology_hash: Accepted for API compatibility and ignored.
+ pos: Clip-space vertex positions used to produce ``rast``, float32 of shape
+ ``[batch, vertices, 4]``, or ``[vertices, 4]`` to share them across the batch.
+ tri: Vertex indices used to produce ``rast``, int32 of shape ``[triangles, 3]``.
+ Silhouettes are found from edges shared by index, so vertices split only for UV
+ seams or normals turn those seams into silhouettes; pass position-only indices here.
+ topology_hash: Result of :func:`antialias_construct_topology_hash` for ``tri``. Without
+ it, the edge adjacency of ``tri`` is found on the first call and reused for as long
+ as the same tensor object is passed and not modified in place, so pass the same
+ tensor to every call rather than a fresh copy or cast. Only edits PyTorch records
+ are noticed: after writing through ``tri.data`` or through memory shared with NumPy,
+ pass a new tensor.
pos_gradient_boost: Multiplier applied to the gradients flowing into ``pos``.
Returns:
@@ -196,65 +393,246 @@ def antialias(
"""
_check(color, "color", ndim=4, dtype=torch.float32)
_check(rast, "rast", ndim=4, last=4, dtype=torch.float32)
- _check(pos, "pos", ndim=3, last=4, dtype=torch.float32)
+ shared = isinstance(pos, Tensor) and pos.ndim == 2
+ layout = "[batch, vertices, 4] or [vertices, 4]"
+ _check(pos, "pos", ndim=2 if shared else 3, last=4, dtype=torch.float32, layout=layout)
_check(tri, "tri", ndim=2, last=3, dtype=torch.int32)
if color.shape[:3] != rast.shape[:3]:
- raise ValueError("color must match rast in batch, height and width.")
- if pos.shape[0] != rast.shape[0]:
+ raise ValueError(
+ "color must match rast in batch, height and width, got "
+ f"{tuple(color.shape)} and {tuple(rast.shape)}."
+ )
+ if not shared and pos.shape[0] != rast.shape[0]:
raise ValueError(
f"pos batch size {pos.shape[0]} does not match rast batch size {rast.shape[0]}."
)
+ if not isinstance(pos_gradient_boost, SupportsFloat):
+ raise TypeError(f"pos_gradient_boost must be a number, got {pos_gradient_boost!r}.")
_check_devices(color=color, rast=rast, pos=pos, tri=tri)
+ _check_indices(tri, pos.shape[-2])
+ # Without triangles there is no adjacency to find, but a topology_hash is still checked.
+ neighbours = None
+ if topology_hash is not None or tri.shape[0]:
+ neighbours = neighbours_for(tri, topology_hash)
return get_backend(color.device, "antialias").antialias(
- color, rast, pos, tri, float(pos_gradient_boost)
+ color, rast, pos, tri, float(pos_gradient_boost), neighbours
)
+def antialias_construct_topology_hash(tri: Tensor) -> TopologyHash:
+ """Precompute the part of :func:`antialias` that depends only on the index buffer.
+
+ :func:`antialias` already reuses this between calls that pass the same ``tri`` tensor
+ object. Building it explicitly helps when the indices arrive in a new tensor every time,
+ or to choose when the work is done.
+
+ Args:
+ tri: Vertex indices, int32 of shape ``[triangles, 3]``.
+
+ Returns:
+ An opaque object to pass as ``topology_hash`` to :func:`antialias`, together with
+ ``tri`` or any tensor of the same shape and contents on the same device.
+ """
+ _check(tri, "tri", ndim=2, last=3, dtype=torch.int32)
+ return TopologyHash(tri)
+
+
def check_rasterize_inputs(
- ctx: RasterizeContext,
+ glctx: RasterizeContext,
pos: Tensor,
tri: Tensor,
resolution: Sequence[int],
ranges: Tensor | None,
) -> tuple[int, int]:
"""Validate the arguments of :func:`rasterize` and return the resolution as two ints."""
- if ranges is not None:
- raise NotImplementedError("Range mode (ranges=...) is not supported yet.")
- _check(pos, "pos", ndim=3, last=4, dtype=torch.float32)
+ range_mode = isinstance(pos, Tensor) and pos.ndim == 2
+ _check(pos, "pos", ndim=2 if range_mode else 3, last=4, dtype=torch.float32)
_check(tri, "tri", ndim=2, last=3, dtype=torch.int32)
+ # rast stores triangle_id + 1 as float32, which holds integers exactly up to 2**24.
+ if tri.shape[0] > 1 << 24:
+ raise ValueError(
+ f"tri has {tri.shape[0]} triangles, but at most 2**24 = {1 << 24} are supported: "
+ "rast stores triangle ids as float32, which is exact only up to there."
+ )
_check_devices(pos=pos, tri=tri)
- if pos.device != ctx.device:
- raise ValueError(f"pos is on {pos.device} but the context is on {ctx.device}.")
+ _check_indices(tri, pos.shape[-2])
+ if pos.device != glctx.device:
+ raise ValueError(f"pos is on {pos.device} but the context is on {glctx.device}.")
+ if range_mode:
+ _check_ranges(ranges, tri.shape[0])
return _check_resolution(resolution)
+def _check_ranges(ranges: Tensor | None, num_tri: int) -> None:
+ """Validate the ``ranges`` argument of range mode against the number of triangles."""
+ if ranges is None:
+ raise ValueError(
+ "ranges is required when pos has shape [vertices, 4] (range mode); give pos a "
+ "leading batch dimension to draw all triangles (instanced mode)."
+ )
+ _check(ranges, "ranges", ndim=2, last=2, dtype=torch.int32)
+ for item, (start, count) in enumerate(ranges.tolist()):
+ if start < 0 or count < 0 or start + count > num_tri:
+ raise ValueError(
+ f"ranges[{item}] = (start {start}, count {count}) does not lie within the "
+ f"{num_tri} triangles of tri."
+ )
+
+
+def split_ranges(tri: Tensor, ranges: Tensor) -> list[Tensor]:
+ """The triangles each batch item draws in range mode, as slices of ``tri``.
+
+ ``ranges`` holds ``(start, count)`` per batch item, int32 of shape ``[batch, 2]``.
+ """
+ return [tri[start : start + count] for start, count in ranges.tolist()]
+
+
+def join_ranges(
+ pos: Tensor,
+ resolution: tuple[int, int],
+ ranges: Tensor,
+ layers: Sequence[tuple[Tensor, Tensor]],
+) -> tuple[Tensor, Tensor]:
+ """Stack the ``(rast, rast_db)`` of each batch item of range mode into one batch.
+
+ Every item was rasterized with a batch of one from its own slice of ``tri`` (see
+ :func:`split_ranges`). Its triangle ids are shifted to count from the start of ``tri``, so
+ that :func:`interpolate` and :func:`antialias` can be given the whole ``tri`` tensor.
+ """
+ empty = pos.new_zeros(0, *resolution, 4)
+ rasts, rast_dbs = [empty], [empty]
+ for (start, _), (rast, rast_db) in zip(ranges.tolist(), layers, strict=True):
+ ids = rast[..., 3:]
+ rasts.append(torch.cat([rast[..., :3], torch.where(ids > 0, ids + start, ids)], -1))
+ rast_dbs.append(rast_db)
+ return torch.cat(rasts), torch.cat(rast_dbs)
+
+
def _check(
t: Tensor,
name: str,
ndim: int,
last: int | None = None,
dtype: torch.dtype | None = None,
+ layout: str | None = None,
) -> None:
+ """Raise unless ``t`` is a tensor with ``ndim`` dimensions, the last of size ``last``.
+
+ ``layout`` names the dimensions in the error message, such as ``"[batch, vertices, 4]"``.
+ Without it, the usual layout of the argument called ``name`` is shown when it fits.
+ """
if not isinstance(t, Tensor):
raise TypeError(f"{name} must be a torch.Tensor, got {type(t).__name__}.")
if t.ndim != ndim or (last is not None and t.shape[-1] != last):
- expected = f"[{', '.join(['...'] * (ndim - 1) + [str(last) if last else '...'])}]"
- raise ValueError(f"{name} must have shape {expected}, got {tuple(t.shape)}.")
+ if layout is None:
+ layout = _LAYOUTS.get(name)
+ fits = layout is not None and layout.count(",") + 1 == ndim
+ if not fits or (last and not layout.endswith(f" {last}]")):
+ layout = f"[{', '.join(['...'] * (ndim - 1) + [str(last) if last else '...'])}]"
+ hint = ""
+ unbatched = t.ndim == ndim - 1 and (last is None or t.shape[-1:] == (last,))
+ if unbatched and layout.startswith("[batch") and " or " not in layout:
+ hint = f"; add a batch dimension with {name}[None]"
+ raise ValueError(f"{name} must have shape {layout}, got {tuple(t.shape)}{hint}.")
if dtype is not None and t.dtype != dtype:
- raise TypeError(f"{name} must be {dtype}, got {t.dtype}.")
+ cast = {torch.float32: "float", torch.int32: "int"}.get(dtype)
+ hint = f"; convert it with {name}.{cast}()" if cast and name.isidentifier() else ""
+ raise TypeError(f"{name} must be {dtype}, got {t.dtype}{hint}.")
+
+
+_LAYOUTS = {
+ "pos": "[batch, vertices, 4]",
+ "tri": "[triangles, 3]",
+ "rast": "[batch, height, width, 4]",
+ "rast_db": "[batch, height, width, 4]",
+ "color": "[batch, height, width, channels]",
+ "tex": "[batch, tex_height, tex_width, channels]",
+ "uv": "[batch, height, width, 2]",
+ "uv_da": "[batch, height, width, 4]",
+ "mip_level_bias": "[batch, height, width]",
+}
def _check_devices(**tensors: Tensor | None) -> None:
- devices = {name: t.device for name, t in tensors.items() if t is not None}
+ devices = {}
+ for name, t in tensors.items():
+ if t is None:
+ continue
+ if not isinstance(t, Tensor):
+ raise TypeError(f"{name} must be a torch.Tensor, got {type(t).__name__}.")
+ devices[name] = t.device
if len(set(devices.values())) > 1:
listing = ", ".join(f"{name} on {device}" for name, device in devices.items())
raise ValueError(f"All inputs must be on the same device; got {listing}.")
+def _index_range(tri: Tensor) -> tuple[int, int]:
+ low, high = torch.stack(tri.aminmax()).tolist()
+ return low, high
+
+
+_index_ranges: TensorCache[tuple[int, int]] = TensorCache(_index_range)
+
+
+def _check_indices(tri: Tensor, num_vertices: int, name: str = "tri") -> None:
+ """Raise ``ValueError`` if ``tri`` refers to a vertex outside ``[0, num_vertices)``.
+
+ Finding the smallest and largest index takes a reduction and, on a GPU, a synchronisation.
+ Both are remembered per tensor object until it is modified in place, so an index buffer
+ that is reused between calls is only scanned once, whatever it is checked against, and a new
+ tensor with the same contents is scanned again. Only edits PyTorch records are noticed:
+ writes through ``tri.data`` or through memory shared with NumPy leave the remembered range
+ in place.
+
+ Args:
+ tri: Vertex indices, an integer tensor of any shape.
+ num_vertices: Number of vertices the indices refer to.
+ name: Argument name to use in the error message.
+ """
+ if tri.numel() == 0:
+ return
+ low, high = _index_ranges.get(tri)
+ if low < 0 or high >= num_vertices:
+ index = low if low < 0 else high
+ valid = "there are no vertices"
+ if num_vertices > 0:
+ valid = f"valid indices are 0 to {num_vertices - 1} for {num_vertices} vertices"
+ raise ValueError(f"{name} refers to vertex {index}, but {valid}.")
+
+
+def _diff_channels(diff_attrs: Sequence[int] | str | None, num_channels: int) -> list[int]:
+ """Channel indices selected by the ``diff_attrs`` argument of :func:`interpolate`."""
+ if diff_attrs is None:
+ return []
+ expected = (
+ f"diff_attrs must be a sequence of channel indices, 'all' or None, got {diff_attrs!r}."
+ )
+ if isinstance(diff_attrs, str):
+ if diff_attrs != "all":
+ raise ValueError(expected)
+ return list(range(num_channels))
+ try:
+ channels = [operator.index(c) for c in diff_attrs]
+ except TypeError:
+ raise TypeError(expected) from None
+ if any(c < 0 or c >= num_channels for c in channels):
+ raise ValueError(f"diff_attrs {channels} out of range for {num_channels} channels.")
+ return channels
+
+
def _check_resolution(resolution: Sequence[int]) -> tuple[int, int]:
- if len(resolution) != 2:
- raise ValueError(f"resolution must be (height, width), got {resolution!r}.")
- height, width = (int(r) for r in resolution)
+ """Return ``resolution`` as ``(height, width)``; it may be a list, tuple, tensor or array."""
+ # Tensors and arrays become lists, which leaves sets, mappings and iterators to be refused:
+ # their order is not the caller's, or reading them uses them up.
+ values = resolution.tolist() if hasattr(resolution, "tolist") else resolution
+ try:
+ if not isinstance(values, (list, tuple)) or any(isinstance(r, bool) for r in values):
+ raise TypeError
+ height, width = (operator.index(r) for r in values)
+ except (TypeError, ValueError):
+ raise ValueError(
+ f"resolution must be (height, width) as two ints, got {resolution!r}."
+ ) from None
if height <= 0 or width <= 0:
raise ValueError(f"resolution must be positive, got {resolution!r}.")
return height, width
diff --git a/src/diffrast/peeling.py b/src/diffrast/peeling.py
index 4102399..6dde839 100644
--- a/src/diffrast/peeling.py
+++ b/src/diffrast/peeling.py
@@ -1,10 +1,12 @@
from __future__ import annotations
+from types import TracebackType
+
from torch import Tensor
from diffrast.backends import get_backend
from diffrast.context import RasterizeContext
-from diffrast.ops import check_rasterize_inputs
+from diffrast.ops import check_rasterize_inputs, join_ranges, split_ranges
class DepthPeeler:
@@ -12,42 +14,79 @@ class DepthPeeler:
The first call to :meth:`rasterize_next_layer` gives the same result as :func:`rasterize`.
Each later call gives, per pixel, the nearest triangle behind the one returned before, until
- a pixel runs out of triangles and stays empty. Triangles at exactly the same depth are
- returned in turn, in order of their index. Every layer has the same format as
- :func:`rasterize`'s output, so it works with :func:`interpolate`, :func:`texture` and
- :func:`antialias` and passes gradients back to ``pos``.
+ a pixel runs out of triangles and stays empty. Triangles are ordered by depth and then by
+ index, so triangles whose depths at a pixel are exactly equal are returned in turn, in order
+ of their index. Every layer has the same format as :func:`rasterize`'s output, so it works
+ with :func:`interpolate`, :func:`texture` and :func:`antialias` and passes gradients back to
+ ``pos``.
- Arguments are as for :func:`rasterize`. It can be used as a context manager::
+ Arguments are as for :func:`rasterize`, including range mode. The peeler keeps its own copy
+ of ``pos``, ``tri`` and ``ranges``, so every layer shows the geometry as it was when the
+ peeler was created, whatever is done to those tensors afterwards; gradients still reach the
+ ``pos`` that was passed in. It can be used as a context manager, after which no more layers
+ can be rasterized::
- with dr.DepthPeeler(ctx, pos, tri, (512, 512)) as peeler:
+ with dr.DepthPeeler(glctx, pos, tri, (512, 512)) as peeler:
for _ in range(num_layers):
rast, rast_db = peeler.rasterize_next_layer()
"""
def __init__(
self,
- ctx: RasterizeContext,
+ glctx: RasterizeContext,
pos: Tensor,
tri: Tensor,
resolution: tuple[int, int],
ranges: Tensor | None = None,
grad_db: bool = True,
) -> None:
- self._resolution = check_rasterize_inputs(ctx, pos, tri, resolution, ranges)
- self._pos, self._tri, self._grad_db = pos, tri, grad_db
+ self._resolution = check_rasterize_inputs(glctx, pos, tri, resolution, ranges)
+ self._output_db = getattr(glctx, "output_db", True)
+ self._grad_db = grad_db and self._output_db
+ # Each layer is found from the per-pixel state of the one before, which belongs to the
+ # geometry it was rasterized from. Copies keep in-place edits made between layers out.
+ self._pos, self._tri = pos.clone(), tri.clone()
+ # In range mode every batch item is peeled on its own, from its own slice of tri.
+ self._ranges = ranges.clone() if pos.ndim == 2 else None
# Each backend keeps its own per-pixel state between layers, so the backend is fixed here.
self._backend = get_backend(pos.device, "rasterize")
self._state = None
+ self._closed = False
def __enter__(self) -> DepthPeeler:
return self
- def __exit__(self, *exc_info) -> None:
+ def __exit__(
+ self,
+ exc_type: type[BaseException] | None,
+ exc_value: BaseException | None,
+ traceback: TracebackType | None,
+ ) -> None:
self._state = None
+ self._closed = True
def rasterize_next_layer(self) -> tuple[Tensor, Tensor]:
"""Return ``(rast, rast_db)`` for the next depth layer."""
- rast, rast_db, self._state = self._backend.rasterize_layer(
- self._pos, self._tri, self._resolution, self._grad_db, self._state
- )
- return rast, rast_db
+ if self._closed:
+ raise RuntimeError(
+ "This DepthPeeler was closed when its with block exited; create a new one to "
+ "rasterize more layers."
+ )
+ if self._ranges is None:
+ rast, rast_db, self._state = self._backend.rasterize_layer(
+ self._pos, self._tri, self._resolution, self._grad_db, self._state
+ )
+ else:
+ triangles = split_ranges(self._tri, self._ranges)
+ states = self._state or [None] * len(triangles)
+ layers = [
+ self._backend.rasterize_layer(
+ self._pos[None], item, self._resolution, self._grad_db, state
+ )
+ for item, state in zip(triangles, states, strict=True)
+ ]
+ self._state = [state for _, _, state in layers]
+ rast, rast_db = join_ranges(
+ self._pos, self._resolution, self._ranges, [layer[:2] for layer in layers]
+ )
+ return rast, (rast_db if self._output_db else rast.new_zeros(*rast.shape[:3], 0))
diff --git a/src/diffrast/topology.py b/src/diffrast/topology.py
new file mode 100644
index 0000000..3806fe6
--- /dev/null
+++ b/src/diffrast/topology.py
@@ -0,0 +1,72 @@
+"""Edge adjacency of a triangle mesh, the part of silhouette detection that depends only on ``tri``.
+
+:func:`diffrast.antialias` needs to know which triangle shares each edge. Finding that takes a
+sort over all edges, so it is done once per index buffer: explicitly through
+:func:`diffrast.ops.antialias_construct_topology_hash`, or automatically through a cache keyed on
+the ``tri`` tensor object.
+"""
+
+from __future__ import annotations
+
+import weakref
+
+from torch import Tensor
+
+from diffrast._cache import TensorCache, stamp
+from diffrast.backends.reference import edge_neighbours
+
+
+class TopologyHash:
+ """Edge adjacency of an index buffer, as built by ``antialias_construct_topology_hash``.
+
+ The contents are an implementation detail. Pass the object to :func:`diffrast.antialias`
+ together with the ``tri`` it was built from, or with a tensor of the same contents.
+ """
+
+ def __init__(self, tri: Tensor) -> None:
+ self._neighbours = edge_neighbours(tri)
+ self._shape = tuple(tri.shape)
+ self._device = tri.device
+ self._source: weakref.ref[Tensor] | None = weakref.ref(tri)
+ self._stamp = stamp(tri)
+
+ def __repr__(self) -> str:
+ return f"TopologyHash(triangles={self._shape[0]}, device={str(self._device)!r})"
+
+ def __getstate__(self) -> dict:
+ # A copy or an unpickled object keeps the adjacency but not the link to the tensor it
+ # was built from, which cannot be pickled and only serves to notice in-place edits.
+ return {**self.__dict__, "_source": None, "_stamp": None}
+
+ def neighbours(self, tri: Tensor) -> Tensor:
+ """Return the adjacency, int64 ``[triangles, 3]``, if it can belong to ``tri``."""
+ if tuple(tri.shape) != self._shape or tri.device != self._device:
+ raise ValueError(
+ f"topology_hash was built for a tri of shape {self._shape} on {self._device}, "
+ f"got shape {tuple(tri.shape)} on {tri.device}."
+ )
+ if self._source is not None and self._source() is tri and stamp(tri) != self._stamp:
+ raise ValueError(
+ "tri was modified in place after topology_hash was built from it; build a new "
+ "one with antialias_construct_topology_hash."
+ )
+ return self._neighbours
+
+
+# Each entry is twice the size of its index buffer, so only a few are kept.
+_neighbour_cache: TensorCache[Tensor] = TensorCache(edge_neighbours, max_entries=16)
+
+
+def neighbours_for(tri: Tensor, topology_hash: TopologyHash | None) -> Tensor:
+ """Edge adjacency of ``tri``, int64 of shape ``[triangles, 3]``.
+
+ Taken from ``topology_hash`` when one is given and from the cache otherwise.
+ """
+ if topology_hash is None:
+ return _neighbour_cache.get(tri)
+ if not isinstance(topology_hash, TopologyHash):
+ raise TypeError(
+ "topology_hash must come from antialias_construct_topology_hash, got "
+ f"{type(topology_hash).__name__}."
+ )
+ return topology_hash.neighbours(tri)
diff --git a/src/diffrast/torch.py b/src/diffrast/torch.py
new file mode 100644
index 0000000..afc8bea
--- /dev/null
+++ b/src/diffrast/torch.py
@@ -0,0 +1,19 @@
+"""The public API under the module path that nvdiffrast uses.
+
+``import diffrast.torch as dr`` gives the same names as ``import diffrast as dr``, so code written
+for nvdiffrast ports by replacing ``nvdiffrast`` with ``diffrast`` in its import line. Every name
+that ``diffrast`` exports is available here.
+
+The module shares its name with PyTorch only inside this package; ``import torch`` always means
+PyTorch, because imports are absolute.
+"""
+
+if __name__ == "torch":
+ raise ImportError(
+ "'import torch' found diffrast/torch.py instead of PyTorch, because the diffrast package "
+ "directory is the working directory or is on sys.path. Run from another directory, or "
+ "put the directory that contains the diffrast package on sys.path instead."
+ )
+
+from diffrast import * # noqa: F403
+from diffrast import __all__ as __all__
diff --git a/tests/test_antialias_fixes.py b/tests/test_antialias_fixes.py
new file mode 100644
index 0000000..22ed9da
--- /dev/null
+++ b/tests/test_antialias_fixes.py
@@ -0,0 +1,442 @@
+"""Antialias gradients on axis-aligned geometry, shared positions and edges that tie."""
+
+import math
+
+import pytest
+import torch
+
+import diffrast as dr
+from diffrast import backends
+from diffrast.backends import reference
+from diffrast.backends._autograd import first_order
+
+# Not square, so that the diagonals of the cube's faces miss the pixel centres. Which of the
+# two triangles of a face a pixel belongs to would otherwise change with the smallest step.
+RESOLUTION = (20, 24)
+
+
+@pytest.fixture
+def triton_backend():
+ pytest.importorskip("triton")
+ from diffrast.backends import triton
+
+ return triton
+
+
+def quad_grid(columns, rows, dtype=torch.float64):
+ """An axis-aligned grid of quads at ``w = 1`` with shared vertices.
+
+ The outline lies between pixel centres and pixel borders at ``RESOLUTION``, so the image is
+ differentiable in the vertex positions.
+ """
+ xs = torch.linspace(-0.57, 0.63, columns + 1, dtype=dtype)
+ ys = torch.linspace(-0.43, 0.52, rows + 1, dtype=dtype)
+ x, y = torch.meshgrid(xs, ys, indexing="xy")
+ xy = torch.stack([x, y], -1).reshape(-1, 2)
+ pos = torch.cat([xy, torch.zeros_like(xy[:, :1]), torch.ones_like(xy[:, :1])], -1)[None]
+ tri = []
+ for row in range(rows):
+ for column in range(columns):
+ a = row * (columns + 1) + column
+ b, c, d = a + 1, a + columns + 2, a + columns + 1
+ tri += [[a, b, c], [a, c, d]]
+ return pos, torch.tensor(tri, dtype=torch.int32)
+
+
+def upright_cube(angle, dtype=torch.float64):
+ """A cube turned about the vertical axis and seen in perspective.
+
+ Its vertical edges project to exactly vertical lines, and without a turn the edges of the
+ front face are exactly horizontal too.
+ """
+ signs = [[x, y, z] for x in (-1, 1) for y in (-1, 1) for z in (-1, 1)]
+ x, y, z = (torch.tensor(signs, dtype=dtype) * 0.45).unbind(-1)
+ x, z = math.cos(angle) * x + math.sin(angle) * z, math.cos(angle) * z - math.sin(angle) * x
+ pos = torch.stack([1.8 * x, 1.8 * y, z, z + 2.5], -1)[None]
+ quads = [[0, 1, 3, 2], [4, 5, 7, 6], [0, 1, 5, 4], [2, 3, 7, 6], [0, 2, 6, 4], [1, 3, 7, 5]]
+ tri = [[a, b, c] for a, b, c, _ in quads] + [[a, c, d] for a, _, c, d in quads]
+ return pos, torch.tensor(tri, dtype=torch.int32)
+
+
+SCENES = {
+ "strip": lambda: quad_grid(2, 1),
+ "grid": lambda: quad_grid(3, 2),
+ "cube": lambda: upright_cube(0.0),
+ "turned cube": lambda: upright_cube(0.4),
+}
+
+
+def random(*shape, like, seed=0):
+ values = torch.rand(*shape, generator=torch.Generator().manual_seed(seed), dtype=torch.float64)
+ return values.to(like)
+
+
+def shade(rast, tri):
+ """Smooth vertex colours, which jump at silhouettes but not at edges inside a surface."""
+ colours = random(int(tri.max()) + 1, 3, like=rast)
+ return reference.interpolate(colours, rast, tri, None, [])[0]
+
+
+def render(backend, pos, tri, resolution):
+ rast, _ = reference.rasterize(pos, tri, resolution, True)
+ return backend.antialias(shade(rast, tri), rast, pos, tri, 1.0)
+
+
+def position_gradient(backend, pos, tri, resolution):
+ pos = pos.clone().requires_grad_(True)
+ out = render(backend, pos, tri, resolution)
+ (out * random(*out.shape, like=out, seed=1)).sum().backward()
+ return out.detach(), pos.grad
+
+
+@pytest.mark.parametrize("scene", SCENES)
+def test_axis_aligned_edges_give_finite_gradients(ctx, scene):
+ pos, tri = SCENES[scene]()
+ pos = pos.float().requires_grad_(True)
+ rast, _ = dr.rasterize(ctx, pos, tri, RESOLUTION)
+ out = dr.antialias(shade(rast, tri), rast, pos, tri)
+ out.square().sum().backward()
+
+ assert out.isfinite().all()
+ assert pos.grad.isfinite().all()
+ assert pos.grad.abs().sum() > 0
+
+
+@pytest.mark.parametrize("scene", SCENES)
+def test_axis_aligned_gradients_match_finite_differences(scene):
+ pos, tri = SCENES[scene]()
+ w = random(1, *RESOLUTION, 3, like=pos, seed=1)
+
+ def loss(p):
+ return (render(reference, p, tri, RESOLUTION) * w).sum()
+
+ _, grad = position_gradient(reference, pos, tri, RESOLUTION)
+ eps = 1e-6
+ numeric = torch.zeros_like(pos)
+ for vertex in range(pos.shape[1]):
+ for axis in (0, 1, 3):
+ step = torch.zeros_like(pos)
+ step[0, vertex, axis] = eps
+ numeric[0, vertex, axis] = (loss(pos + step) - loss(pos - step)) / (2 * eps)
+
+ assert numeric.abs().sum() > 0
+ torch.testing.assert_close(grad[..., [0, 1, 3]], numeric[..., [0, 1, 3]], rtol=1e-4, atol=1e-6)
+
+
+@pytest.mark.parametrize("scene", ["strip", "cube"])
+def test_axis_aligned_gradcheck(scene):
+ pos, tri = SCENES[scene]()
+ rast, _ = reference.rasterize(pos, tri, RESOLUTION, True)
+ color = shade(rast, tri)[..., :2].contiguous()
+ pos.requires_grad_(True)
+ assert torch.autograd.gradcheck(lambda p: reference.antialias(color, rast, p, tri, 1.0), (pos,))
+
+
+@pytest.mark.gpu
+@pytest.mark.parametrize("scene", SCENES)
+def test_axis_aligned_gradients_match_triton(triton_backend, scene):
+ pos, tri = (t.cuda() for t in SCENES[scene]())
+ ref_out, ref_grad = position_gradient(reference, pos, tri, RESOLUTION)
+ out, grad = position_gradient(triton_backend, pos, tri, RESOLUTION)
+ torch.testing.assert_close(out, ref_out, atol=1e-9, rtol=1e-9)
+ torch.testing.assert_close(grad, ref_grad, atol=1e-9, rtol=1e-9)
+
+ out32, grad32 = position_gradient(triton_backend, pos.float(), tri, RESOLUTION)
+ assert grad32.isfinite().all()
+ torch.testing.assert_close(out32.double(), ref_out, atol=1e-5, rtol=1e-5)
+ torch.testing.assert_close(grad32.double(), ref_grad, atol=1e-3, rtol=1e-3)
+
+
+class TestSharedPositions:
+ """A 2D ``pos`` is shared by all batch items, as in nvdiffrast's range mode."""
+
+ def scene(self, dtype=torch.float64, device="cpu"):
+ pos, tri = upright_cube(0.4, dtype)
+ pos, tri = pos.to(device), tri.to(device)
+ rast, _ = reference.rasterize(pos.expand(3, -1, -1), tri, (16, 20), True)
+ return pos[0], tri, rast, random(3, 16, 20, 2, like=rast)
+
+ def check(self, antialias, pos, tri, rast, color):
+ w = random(*color.shape, like=color, seed=2)
+ shared = pos.clone().requires_grad_(True)
+ out_shared = antialias(color, rast, shared, tri)
+ (out_shared * w).sum().backward()
+ batched = pos.expand(3, -1, -1).clone().requires_grad_(True)
+ out_batched = antialias(color, rast, batched, tri)
+ (out_batched * w).sum().backward()
+
+ assert (out_shared != color).any()
+ tolerance = {"atol": 1e-12, "rtol": 1e-12} if pos.dtype == torch.float64 else {}
+ torch.testing.assert_close(out_shared, out_batched, **tolerance)
+ assert shared.grad.shape == pos.shape
+ torch.testing.assert_close(shared.grad, batched.grad.sum(0), **tolerance)
+ return out_shared.detach(), shared.grad
+
+ def test_matches_expanded_positions(self):
+ pos, tri, rast, color = self.scene(torch.float32)
+ self.check(dr.antialias, pos, tri, rast, color)
+
+ def test_gradcheck(self):
+ pos, tri, rast, color = self.scene()
+ pos.requires_grad_(True)
+ assert torch.autograd.gradcheck(
+ lambda p, c: reference.antialias(c, rast, p, tri, 1.0), (pos, color.requires_grad_())
+ )
+
+ def test_rejects_other_ranks(self):
+ pos, tri, rast, color = self.scene(torch.float32)
+ with pytest.raises(ValueError, match=r"pos must have shape \[batch, vertices, 4\] or"):
+ dr.antialias(color, rast, pos[0], tri)
+ with pytest.raises(ValueError, match="pos batch size 2"):
+ dr.antialias(color, rast, pos.expand(2, -1, -1), tri)
+
+ @pytest.mark.gpu
+ def test_triton_matches_reference(self, triton_backend):
+ pos, tri, rast, color = self.scene(device="cuda")
+ ref = self.check(lambda *args: reference.antialias(*args, 1.0), pos, tri, rast, color)
+ out = self.check(lambda *args: triton_backend.antialias(*args, 1.0), pos, tri, rast, color)
+ for ours, theirs in zip(out, ref, strict=True):
+ torch.testing.assert_close(ours, theirs, atol=1e-9, rtol=1e-9)
+
+ @pytest.mark.gpu
+ def test_triton_gradcheck(self, triton_backend):
+ pos, tri, rast, color = self.scene(device="cuda")
+ pos.requires_grad_(True)
+ assert torch.autograd.gradcheck(
+ lambda p, c: triton_backend.antialias(c, rast, p, tri, 1.0),
+ (pos, color.requires_grad_()),
+ )
+
+
+def quad(corners, scale, device="cpu"):
+ """Two triangles through four ``(x, y)`` corners, with all clip coordinates scaled."""
+ pos = torch.tensor([[[x, y, 0.1, 1.0] for x, y in corners]], device=device) * scale
+ tri = torch.tensor([[0, 1, 2], [0, 2, 3]], dtype=torch.int32, device=device)
+ return pos, tri
+
+
+def diamond(scale, device="cpu", radius=0.7):
+ """A square standing on a corner, whose four edges run at 45 degrees on a square image."""
+ corners = [[0.0, -radius], [radius, 0.0], [0.0, radius], [-radius, 0.0]]
+ return quad(corners, scale, device)
+
+
+def antialiased_coverage(backend, pos, tri, resolution):
+ rast, _ = reference.rasterize(pos, tri, resolution, True)
+ return backend.antialias((rast[..., 3:] > 0).float(), rast, pos, tri, 1.0)
+
+
+@pytest.mark.parametrize("scale", [2.3, 0.37, 7.1])
+def test_diagonal_edges_do_not_depend_on_clip_space_scale(scale):
+ # Scaling all four clip coordinates leaves the geometry unchanged, and with a scale of one
+ # the arithmetic is exact. Rounding at other scales must not move an edge between the
+ # horizontal and the vertical pixel pairs from one pixel to the next.
+ resolution = (256, 256)
+ exact = antialiased_coverage(reference, *diamond(1.0), resolution)
+ scaled = antialiased_coverage(reference, *diamond(scale), resolution)
+ torch.testing.assert_close(scaled, exact, atol=1e-4, rtol=0)
+ area = 2 * 0.7**2 * resolution[0] * resolution[1] / 4
+ torch.testing.assert_close(scaled.sum(), torch.tensor(area), rtol=1e-4, atol=0)
+
+
+@pytest.mark.gpu
+@pytest.mark.parametrize("resolution", [(256, 256), (100, 100), (64, 96)])
+@pytest.mark.parametrize("scale", [1.0, 2.3, 0.37, 7.1])
+def test_diagonal_edges_match_between_backends(triton_backend, resolution, scale):
+ # At 100 x 100 the edges also pass exactly through pixel centres.
+ pos, tri = diamond(scale, "cuda")
+ grads, images = [], []
+ for backend in (reference, triton_backend):
+ p = pos.clone().requires_grad_(True)
+ out = antialiased_coverage(backend, p, tri, resolution)
+ out.sum().backward()
+ images.append(out.detach())
+ grads.append(p.grad)
+ torch.testing.assert_close(images[1], images[0], atol=1e-6, rtol=0)
+ assert (grads[1] - grads[0]).abs().max() < 1e-4 * grads[0].abs().max()
+
+
+# Outlines whose edges all pass through pixel centres, while the diagonal shared by their two
+# triangles passes through none inside the outline: corners, resolution and area in pixels.
+CENTRED_SHAPES = {
+ "diamond": ([[0.0, -0.7], [0.7, 0.0], [0.0, 0.7], [-0.7, 0.0]], (100, 100), 2450.0),
+ "small diamond": ([[0.0, -0.5], [0.5, 0.0], [0.0, 0.5], [-0.5, 0.0]], (64, 64), 512.0),
+ "rectangle": ([[-0.51, -0.31], [0.51, -0.31], [0.51, 0.31], [-0.51, 0.31]], (100, 100), 1581.0),
+}
+CLIP_SPACE_SCALES = (1.0, 2.3, 0.37)
+
+
+class TestEdgesThroughPixelCentres:
+ """A pixel whose centre lies on a silhouette is half covered, whichever side of the edge the
+ rasterizer gives it to and however the rasterizer rounds."""
+
+ @pytest.fixture(
+ params=[
+ ("cpu", "reference"),
+ pytest.param(("cuda", "reference"), marks=pytest.mark.gpu),
+ pytest.param(("cuda", "triton"), marks=pytest.mark.gpu),
+ ],
+ ids=["reference", "reference on gpu", "triton"],
+ )
+ def device(self, request):
+ """A device, with one backend selected for all ops."""
+ name, backend = request.param
+ if backend == "triton":
+ pytest.importorskip("triton")
+ previous = backends._selected
+ dr.set_backend(backend)
+ yield torch.device(name)
+ backends._selected = previous
+
+ def expected(self, corners, resolution, device):
+ """The coverage of each pixel, a half on the outline, and the pixels to compare: all but
+ those at a vertex, where two silhouette edges meet and the blend is only approximate."""
+ height, width = resolution
+ x = ((torch.arange(width, dtype=torch.float64) * 2 + 1) / width - 1)[None, :]
+ y = ((torch.arange(height, dtype=torch.float64) * 2 + 1) / height - 1)[:, None]
+ corners = torch.tensor(corners, dtype=torch.float64)
+ # Counter-clockwise outlines: the interior is on the left of every edge.
+ sides = torch.stack(
+ [
+ (x1 - x0) * (y - y0) - (y1 - y0) * (x - x0)
+ for (x0, y0), (x1, y1) in zip(corners, corners.roll(-1, 0), strict=True)
+ ]
+ )
+ inside = (sides > 1e-9).all(0)
+ outline = (sides > -1e-9).all(0) & ~inside
+ coverage = torch.where(outline, 0.5, inside.double())
+ pixels = torch.stack(
+ [
+ torch.maximum((x - cx).abs() * width / 2, (y - cy).abs() * height / 2)
+ for cx, cy in corners
+ ]
+ )
+ away = pixels.min(0).values > 1.5
+ assert (outline & away).sum() > 20
+ return coverage.float().to(device), away.to(device)
+
+ def check(self, image, corners, resolution, area):
+ coverage, away = self.expected(corners, resolution, image.device)
+ torch.testing.assert_close(image[away], coverage[away], atol=1e-3, rtol=0)
+ assert abs(float(image.sum()) - area) <= 2.5
+
+ @pytest.mark.parametrize("scale", CLIP_SPACE_SCALES)
+ @pytest.mark.parametrize("shape", CENTRED_SHAPES)
+ def test_rasterize_then_antialias(self, device, shape, scale):
+ corners, resolution, area = CENTRED_SHAPES[shape]
+ pos, tri = quad(corners, scale, device)
+ pos.requires_grad_(True)
+ rast, _ = dr.rasterize(dr.RasterizeContext(device), pos, tri, resolution)
+ image = dr.antialias((rast[..., 3:] > 0).float(), rast, pos, tri)
+ image.sum().backward()
+ self.check(image[0, ..., 0].detach(), corners, resolution, area)
+ assert pos.grad.isfinite().all() and (pos.grad != 0).any()
+
+ @pytest.mark.parametrize("scale", CLIP_SPACE_SCALES)
+ @pytest.mark.parametrize("shape", CENTRED_SHAPES)
+ def test_rast_from_a_rasterizer_that_rounds_differently(self, device, shape, scale):
+ # In float64 the edge functions round differently, so pixels on an edge are given to
+ # the triangle or to the background in another pattern than float32 would.
+ corners, resolution, area = CENTRED_SHAPES[shape]
+ pos, tri = quad(corners, scale, device)
+ rast, _ = reference.rasterize(pos.double(), tri, resolution, True)
+ rast = rast.float()
+ image = dr.antialias((rast[..., 3:] > 0).float(), rast, pos, tri)
+ self.check(image[0, ..., 0], corners, resolution, area)
+
+
+class TestFirstOrderGuard:
+ """``first_order`` refuses a backward pass that is asked for a differentiable result."""
+
+ class Double(torch.autograd.Function):
+ @staticmethod
+ def forward(ctx, x):
+ return x * 2
+
+ @staticmethod
+ @first_order("double")
+ def backward(ctx, grad):
+ return grad * 2
+
+ def test_first_order_gradients_pass(self):
+ x = torch.ones(3, requires_grad=True)
+ self.Double.apply(x).sum().backward(retain_graph=True)
+ with torch.enable_grad():
+ (grad,) = torch.autograd.grad(self.Double.apply(x).square().sum(), x)
+ assert torch.equal(x.grad, torch.full((3,), 2.0))
+ assert torch.equal(grad, torch.full((3,), 8.0)) and not grad.requires_grad
+
+ def test_differentiable_gradient_is_refused(self):
+ x = torch.ones(3, requires_grad=True)
+ with pytest.raises(RuntimeError, match="double on the Triton backend has no second-order"):
+ torch.autograd.grad(self.Double.apply(x).sum(), x, create_graph=True)
+
+
+def squared(out, leaf):
+ return out.square().sum()
+
+
+def mixed(out, leaf):
+ return out.square().sum() + leaf.pow(3).sum()
+
+
+def linear(out, leaf):
+ return out.sum()
+
+
+@pytest.mark.gpu
+class TestDoubleBackward:
+ """The Triton backward passes are kernels, which autograd cannot differentiate again.
+
+ Every way of asking for a gradient of a gradient has to raise, also the ones where the
+ second pass could reach its inputs without going through the op again and would return a
+ gradient that lacks the op's share.
+ """
+
+ def scene(self):
+ pos, tri = (t.cuda() for t in upright_cube(0.4, torch.float32))
+ rast, rast_db = reference.rasterize(pos, tri, (16, 16), True)
+ return pos, tri, rast, rast_db
+
+ def antialias(self, backend):
+ pos, tri, rast, _ = self.scene()
+ pos.requires_grad_(True)
+ color = shade(rast, tri).requires_grad_(True)
+ return backend.antialias(color, rast, pos, tri, 1.0), pos
+
+ def interpolate(self, backend):
+ _, tri, rast, rast_db = self.scene()
+ attr = random(8, 3, like=rast).requires_grad_(True)
+ out, out_da = backend.interpolate(attr, rast, tri, rast_db, [0, 1])
+ return torch.cat([out, out_da], -1), attr
+
+ @pytest.mark.parametrize("op", ["antialias", "interpolate"])
+ @pytest.mark.parametrize("loss", [squared, mixed, linear], ids=lambda loss: loss.__name__)
+ def test_differentiable_gradient_is_refused(self, triton_backend, op, loss):
+ out, leaf = getattr(self, op)(triton_backend)
+ with pytest.raises(RuntimeError, match=f"{op} on the Triton backend has no second-order"):
+ torch.autograd.grad(loss(out, leaf), leaf, create_graph=True)
+
+ @pytest.mark.filterwarnings("ignore:Using backward.. with create_graph=True")
+ @pytest.mark.parametrize("op", ["antialias", "interpolate"])
+ def test_backward_with_create_graph_is_refused(self, triton_backend, op):
+ out, leaf = getattr(self, op)(triton_backend)
+ with pytest.raises(RuntimeError, match="set_backend\\('reference'\\)"):
+ squared(out, leaf).backward(create_graph=True)
+
+ @pytest.mark.parametrize("op", ["antialias", "interpolate"])
+ def test_first_order_gradients_are_unaffected(self, triton_backend, op):
+ out, leaf = getattr(self, op)(triton_backend)
+ with torch.enable_grad():
+ (grad,) = torch.autograd.grad(mixed(out, leaf), leaf, retain_graph=True)
+ ref_out, ref_leaf = getattr(self, op)(reference)
+ (expected,) = torch.autograd.grad(mixed(ref_out, ref_leaf), ref_leaf)
+ assert not grad.requires_grad
+ torch.testing.assert_close(grad, expected, atol=1e-4, rtol=1e-4)
+
+ @pytest.mark.parametrize("op", ["antialias", "interpolate"])
+ def test_reference_backend_gives_second_order_gradients(self, op):
+ out, leaf = getattr(self, op)(reference)
+ (grad,) = torch.autograd.grad(mixed(out, leaf), leaf, create_graph=True)
+ (second,) = torch.autograd.grad(grad.square().sum(), leaf)
+ assert second.isfinite().all() and (second != 0).any()
diff --git a/tests/test_compat.py b/tests/test_compat.py
new file mode 100644
index 0000000..4956b69
--- /dev/null
+++ b/tests/test_compat.py
@@ -0,0 +1,614 @@
+"""Compatibility with code written for nvdiffrast.
+
+Contexts, the ``diffrast.torch`` module path, the log level and the ``nvdiffrast`` import alias,
+followed by the ways in which real pipelines call the ops.
+"""
+
+import importlib
+import os
+import pathlib
+import pkgutil
+import subprocess
+import sys
+import types
+import warnings
+
+import pytest
+import torch
+
+import diffrast as dr
+import diffrast.torch as dr_torch
+from diffrast import backends, compat, log
+from diffrast.context import RasterizeContext, RasterizeCudaContext, RasterizeGLContext
+
+CONTEXTS = [RasterizeContext, RasterizeCudaContext, RasterizeGLContext]
+NEW_NAMES = [
+ "RasterizeGLContext",
+ "antialias_construct_topology_hash",
+ "get_log_level",
+ "set_log_level",
+ "install_as_nvdiffrast",
+ "uninstall_as_nvdiffrast",
+]
+
+RENDERER = '''
+from typing import Union
+
+import nvdiffrast.torch as dr
+
+
+class Renderer:
+ """A renderer in the style of the wrappers found in image-to-3D pipelines."""
+
+ ctx: {annotation}
+
+ def __init__(self, device, context: {annotation} = None):
+ self.ctx = context if context is not None else dr.{default}(device=device)
+
+ def render(self, pos, tri, colour, resolution):
+ rast, _ = dr.rasterize(self.ctx, pos, tri, resolution)
+ image, _ = dr.interpolate(colour, rast, tri)
+ return dr.antialias(image, rast, pos, tri)
+'''
+
+
+@pytest.fixture(
+ params=[("cpu", "reference"), pytest.param(("cuda", "triton"), marks=pytest.mark.gpu)],
+ ids=["reference", "triton"],
+)
+def device(request):
+ """Run a test on the reference backend on the CPU and on the Triton backend on the GPU."""
+ name, backend = request.param
+ if backend == "triton":
+ pytest.importorskip("triton")
+ previous = backends._selected
+ dr.set_backend(backend)
+ yield torch.device(name)
+ backends._selected = previous
+
+
+class TestContexts:
+ def test_class_relations(self):
+ assert RasterizeCudaContext is RasterizeContext
+ assert issubclass(RasterizeGLContext, RasterizeContext)
+
+ @pytest.mark.parametrize("context", CONTEXTS)
+ def test_default_device(self, context):
+ expected = "cuda" if torch.cuda.is_available() else "cpu"
+ assert context().device.type == expected
+ assert context(device=None).device.type == expected
+
+ @pytest.mark.parametrize("context", CONTEXTS)
+ @pytest.mark.parametrize("device", ["cpu", torch.device("cpu")])
+ def test_cpu(self, context, device):
+ assert context(device=device).device == torch.device("cpu")
+
+ @pytest.mark.gpu
+ @pytest.mark.parametrize("context", CONTEXTS)
+ @pytest.mark.parametrize("device", ["cuda", "cuda:0", torch.device("cuda:0"), 0])
+ def test_gpu(self, context, device):
+ ctx = context(device=device)
+ index = torch.cuda.current_device() if device == "cuda" else 0
+ assert ctx.device == torch.device("cuda", index)
+
+ def test_plain_contexts_output_db(self):
+ assert RasterizeContext("cpu").output_db is True
+
+ def test_gl_context_arguments(self):
+ ctx = RasterizeGLContext(device="cpu")
+ assert ctx.output_db is True and ctx.mode == "automatic"
+ ctx = RasterizeGLContext(False, "manual", "cpu")
+ assert ctx.output_db is False and ctx.mode == "manual"
+ assert RasterizeGLContext(output_db=False, device="cpu").output_db is False
+
+ @pytest.mark.gpu
+ def test_gl_context_without_output_db_on_gpu(self):
+ ctx = RasterizeGLContext(output_db=False, device="cuda")
+ assert ctx.output_db is False and ctx.device.type == "cuda"
+
+ @pytest.mark.parametrize("output_db", ["cuda", "no", torch.device("cpu")])
+ def test_gl_context_refuses_a_device_as_output_db(self, output_db):
+ with pytest.raises(
+ TypeError, match=r"output_db must be a bool, got .*; pass the device as"
+ ):
+ RasterizeGLContext(output_db)
+
+ @pytest.mark.parametrize("context", CONTEXTS)
+ def test_device_of_a_wrong_type(self, context):
+ for device in (True, False, 0.0, [0], b"cuda"):
+ message = "device must be a torch.device, a string or a GPU index, got"
+ with pytest.raises(TypeError, match=message):
+ context(device=device)
+ with pytest.raises(ValueError, match="device must not be a negative GPU index, got -1"):
+ context(device=-1)
+
+ @pytest.mark.gpu
+ def test_numpy_gpu_index(self):
+ np = pytest.importorskip("numpy")
+ assert RasterizeContext(device=np.int64(0)).device == torch.device("cuda", 0)
+
+ def test_gl_context_without_output_db_rasterizes(self, device, triangle):
+ pos, tri = (t.to(device) for t in triangle)
+ rast, rast_db = dr.rasterize(RasterizeGLContext(False, device=device), pos, tri, (8, 8))
+ expected, _ = dr.rasterize(RasterizeGLContext(device=device), pos, tri, (8, 8))
+ assert torch.equal(rast, expected)
+ assert rast_db.shape == (1, 8, 8, 0)
+ out, out_da = dr.interpolate(pos, rast, tri, rast_db=rast_db)
+ assert out.shape == (1, 8, 8, 4) and out_da.shape == (1, 8, 8, 0)
+
+ def test_gl_context_methods_do_nothing(self):
+ ctx = RasterizeGLContext(device="cpu")
+ assert ctx.set_context() is None
+ assert ctx.release_context() is None
+
+ def test_gl_context_rasterizes(self, triangle):
+ pos, tri = triangle
+ rast, _ = dr.rasterize(RasterizeGLContext(device="cpu"), pos, tri, (8, 8))
+ expected, _ = dr.rasterize(RasterizeContext("cpu"), pos, tri, (8, 8))
+ assert torch.equal(rast, expected)
+
+ def test_repr(self):
+ assert repr(RasterizeContext("cpu")) == "RasterizeContext(device='cpu')"
+ assert repr(RasterizeGLContext(output_db=False, device="cpu")) == (
+ "RasterizeGLContext(output_db=False, device='cpu')"
+ )
+
+ def test_gpu_requested_without_one(self, monkeypatch):
+ monkeypatch.setattr(torch.cuda, "is_available", lambda: False)
+ for device in ("cuda", "cuda:0", 0, torch.device("cuda")):
+ with pytest.raises(RuntimeError, match="no CUDA or ROCm device is available"):
+ RasterizeGLContext(device=device)
+ assert RasterizeContext().device == torch.device("cpu")
+
+ def test_gpu_index_that_does_not_exist(self, monkeypatch):
+ monkeypatch.setattr(torch.cuda, "is_available", lambda: True)
+ monkeypatch.setattr(torch.cuda, "device_count", lambda: 2)
+ assert RasterizeContext("cuda:1").device == torch.device("cuda", 1)
+ with pytest.raises(ValueError, match="device 'cuda:7' does not exist; 2 CUDA or ROCm"):
+ RasterizeContext("cuda:7")
+ with pytest.raises(ValueError, match="device 'cuda:2' does not exist"):
+ RasterizeCudaContext(device=2)
+
+
+class TestLogLevel:
+ @pytest.fixture(autouse=True)
+ def restore(self):
+ previous = log.get_log_level()
+ yield
+ log.set_log_level(previous)
+
+ def test_default_is_warning(self):
+ assert log.get_log_level() == 1
+
+ @pytest.mark.parametrize("level", [0, 1, 2, 3])
+ def test_round_trip(self, level):
+ log.set_log_level(level)
+ assert log.get_log_level() == level
+
+ @pytest.mark.parametrize("level", [-1, 4, 100])
+ def test_rejects_unknown_levels(self, level):
+ with pytest.raises(ValueError, match="level must be an int from 0 to 3"):
+ log.set_log_level(level)
+ assert log.get_log_level() == 1
+
+ @pytest.mark.parametrize("level", [1.0, "1", None])
+ def test_rejects_other_types(self, level):
+ with pytest.raises(TypeError, match="level must be an int from 0 to 3"):
+ log.set_log_level(level)
+
+ @pytest.mark.parametrize("level", [0, 1])
+ def test_warnings_are_issued(self, level):
+ log.set_log_level(level)
+ with pytest.warns(UserWarning, match="something odd") as record:
+ log.warn("something odd")
+ assert record[0].filename == __file__
+
+ @pytest.mark.parametrize("level", [2, 3])
+ def test_warnings_are_silenced(self, level):
+ log.set_log_level(level)
+ with warnings.catch_warnings():
+ warnings.simplefilter("error")
+ log.warn("something odd")
+
+
+class TestTorchModule:
+ def test_exports_everything_diffrast_exports(self):
+ assert dr_torch.__all__ == dr.__all__
+ for name in dr.__all__:
+ assert getattr(dr_torch, name) is getattr(dr, name)
+
+ def test_from_import(self):
+ from diffrast.torch import RasterizeCudaContext, rasterize
+
+ assert rasterize is dr.rasterize
+ assert RasterizeCudaContext is dr.RasterizeCudaContext
+
+ def test_new_exports_are_picked_up(self, monkeypatch):
+ marker = object()
+ monkeypatch.setattr(dr, "an_op_added_later", marker, raising=False)
+ monkeypatch.setattr(dr, "__all__", [*dr.__all__, "an_op_added_later"])
+ try:
+ assert importlib.reload(dr_torch).an_op_added_later is marker
+ finally:
+ monkeypatch.undo()
+ vars(dr_torch).pop("an_op_added_later", None)
+ importlib.reload(dr_torch)
+ assert not hasattr(dr_torch, "an_op_added_later")
+
+ def test_does_not_shadow_pytorch(self):
+ pytorch = sys.modules["torch"]
+ assert pytorch.__name__ == "torch" and hasattr(pytorch, "Tensor")
+ assert dr_torch.__name__ == "diffrast.torch" and dr_torch is not pytorch
+ checked = 0
+ for info in pkgutil.walk_packages(dr.__path__, "diffrast."):
+ try:
+ module = importlib.import_module(info.name)
+ except ImportError:
+ continue # The Triton kernels, where Triton is not installed.
+ if info.name != "diffrast.torch" and hasattr(module, "torch"):
+ assert module.torch is pytorch, info.name
+ checked += 1
+ assert checked >= 4
+
+ @pytest.mark.parametrize("statement", ["import diffrast", "import torch"])
+ def test_package_directory_on_the_path_is_reported(self, statement):
+ # From inside the package directory, "import torch" finds diffrast/torch.py.
+ package = pathlib.Path(dr.__file__).parent
+ env = {**os.environ, "PYTHONPATH": str(package.parent)}
+ result = subprocess.run(
+ [sys.executable, "-c", statement], cwd=package, env=env, capture_output=True, text=True
+ )
+ assert result.returncode != 0
+ assert "found diffrast/torch.py instead of PyTorch" in result.stderr
+
+ @pytest.mark.parametrize("name", NEW_NAMES)
+ def test_compatibility_names_are_exported(self, name):
+ assert name in dr.__all__
+ assert getattr(dr_torch, name) is getattr(dr, name)
+
+
+class TestInstallAsNvdiffrast:
+ NAMES = ("nvdiffrast", "nvdiffrast.torch")
+
+ @pytest.fixture(autouse=True)
+ def isolated(self, monkeypatch):
+ """Start without nvdiffrast, real or aliased, and put everything back afterwards."""
+ saved = {name: sys.modules.pop(name) for name in self.NAMES if name in sys.modules}
+ monkeypatch.setattr(compat, "_is_installed", lambda name: False)
+ yield
+ compat.uninstall_as_nvdiffrast()
+ compat._displaced.clear()
+ for name in self.NAMES:
+ sys.modules.pop(name, None)
+ sys.modules.update(saved)
+
+ def test_nothing_is_registered_until_asked(self):
+ assert not any(name in sys.modules for name in self.NAMES)
+
+ def test_import_resolves_to_diffrast(self):
+ compat.install_as_nvdiffrast()
+ import nvdiffrast
+ import nvdiffrast.torch as nvdr
+ from nvdiffrast.torch import interpolate
+
+ assert nvdiffrast is dr
+ assert nvdr is dr_torch
+ assert nvdiffrast.torch is dr_torch
+ assert nvdr.rasterize is dr.rasterize and interpolate is dr.interpolate
+ assert importlib.import_module("nvdiffrast.torch") is dr_torch
+
+ def test_can_be_called_twice(self):
+ compat.install_as_nvdiffrast()
+ compat.install_as_nvdiffrast()
+ assert sys.modules["nvdiffrast.torch"] is dr_torch
+ assert not compat._displaced
+
+ def test_uninstall(self):
+ compat.install_as_nvdiffrast()
+ compat.uninstall_as_nvdiffrast()
+ assert not any(name in sys.modules for name in self.NAMES)
+ compat.uninstall_as_nvdiffrast()
+
+ def test_refuses_when_nvdiffrast_is_installed(self, monkeypatch):
+ monkeypatch.setattr(compat, "_is_installed", lambda name: name == "nvdiffrast")
+ with pytest.raises(RuntimeError, match="An nvdiffrast package is installed"):
+ compat.install_as_nvdiffrast()
+ assert not any(name in sys.modules for name in self.NAMES)
+ compat.install_as_nvdiffrast(force=True)
+ assert sys.modules["nvdiffrast.torch"] is dr_torch
+
+ def test_refuses_when_nvdiffrast_is_imported(self):
+ real = types.ModuleType("nvdiffrast")
+ real_torch = types.ModuleType("nvdiffrast.torch")
+ sys.modules.update({"nvdiffrast": real, "nvdiffrast.torch": real_torch})
+ with pytest.raises(RuntimeError, match="nvdiffrast is already imported"):
+ compat.install_as_nvdiffrast()
+ assert sys.modules["nvdiffrast"] is real
+
+ with pytest.warns(UserWarning, match="Replacing the imported nvdiffrast") as record:
+ compat.install_as_nvdiffrast(force=True)
+ assert record[0].filename == __file__
+ assert sys.modules["nvdiffrast"] is dr and sys.modules["nvdiffrast.torch"] is dr_torch
+
+ compat.uninstall_as_nvdiffrast()
+ assert sys.modules["nvdiffrast"] is real
+ assert sys.modules["nvdiffrast.torch"] is real_torch
+
+ def test_uninstall_leaves_other_modules_alone(self):
+ compat.install_as_nvdiffrast()
+ other = types.ModuleType("nvdiffrast")
+ sys.modules["nvdiffrast"] = other
+ compat.uninstall_as_nvdiffrast()
+ assert sys.modules["nvdiffrast"] is other
+ assert "nvdiffrast.torch" not in sys.modules
+
+ def import_renderer(self, tmp_path, monkeypatch, annotation, default):
+ source = RENDERER.format(annotation=annotation, default=default)
+ (tmp_path / "third_party_renderer.py").write_text(source, encoding="utf-8")
+ monkeypatch.syspath_prepend(str(tmp_path))
+ monkeypatch.delitem(sys.modules, "third_party_renderer", raising=False)
+ module = importlib.import_module("third_party_renderer")
+ monkeypatch.delitem(sys.modules, "third_party_renderer")
+ return module
+
+ def render(self, module, triangle):
+ pos, tri = triangle
+ colour = torch.eye(3)
+ image = module.Renderer("cpu").render(pos, tri, colour, [16, 16])
+ rast, _ = dr.rasterize(dr.RasterizeContext("cpu"), pos, tri, (16, 16))
+ expected = dr.antialias(dr.interpolate(colour, rast, tri)[0], rast, pos, tri)
+ torch.testing.assert_close(image, expected)
+ assert image.sum() > 0
+
+ def test_unmodified_code_runs(self, tmp_path, monkeypatch, triangle):
+ compat.install_as_nvdiffrast()
+ module = self.import_renderer(
+ tmp_path, monkeypatch, "dr.RasterizeCudaContext", "RasterizeCudaContext"
+ )
+ assert module.dr is dr_torch
+ self.render(module, triangle)
+
+ def test_unmodified_code_with_opengl_context_runs(self, tmp_path, monkeypatch, triangle):
+ # The annotations are evaluated when the module is imported.
+ dr.install_as_nvdiffrast()
+ annotation = "Union[dr.RasterizeGLContext, dr.RasterizeCudaContext]"
+ module = self.import_renderer(tmp_path, monkeypatch, annotation, "RasterizeGLContext")
+ assert isinstance(module.Renderer("cpu").ctx, dr.RasterizeGLContext)
+ self.render(module, triangle)
+
+
+def sheet(device, size=6):
+ """A curved sheet of quads with shared vertices, seen in perspective from two sides.
+
+ Returns ``pos`` ``[2, vertices, 4]``, ``tri`` ``[triangles, 3]`` and ``uv`` ``[vertices, 2]``.
+ No two triangles overlap on screen.
+ """
+ line = torch.linspace(-0.83, 0.86, size + 1)
+ x, y = (t.flatten() for t in torch.meshgrid(line, line, indexing="xy"))
+ w = 1.3 + 0.25 * x - 0.1 * y
+ pos = torch.stack([x * w, y * w, 0.4 * x * y * w, w], -1)
+ pos = torch.stack([pos, pos * torch.tensor([-1.0, 1.0, 1.0, 1.0])])
+ tri = []
+ for row in range(size):
+ for column in range(size):
+ a = row * (size + 1) + column
+ b, c, d = a + 1, a + size + 2, a + size + 1
+ tri += [[a, b, c], [a, c, d]]
+ uv = torch.stack([x, y], -1) * 0.5 + 0.5
+ return pos.to(device), torch.tensor(tri, dtype=torch.int32, device=device), uv.to(device)
+
+
+def strided(tensor):
+ """The same values in memory that is not contiguous."""
+ view = tensor.repeat_interleave(2, dim=-1)[..., ::2]
+ assert not view.is_contiguous()
+ return view
+
+
+def random(*shape, device, seed=0):
+ return torch.rand(*shape, generator=torch.Generator().manual_seed(seed)).to(device)
+
+
+class TestCallPatterns:
+ RESOLUTION = (24, 32)
+
+ @pytest.fixture
+ def scene(self, device):
+ pos, tri, uv = sheet(device)
+ ctx = dr.RasterizeContext(device)
+ rast, rast_db = dr.rasterize(ctx, pos, tri, self.RESOLUTION)
+ assert (rast[..., 3] > 0).float().mean() > 0.5
+ return types.SimpleNamespace(
+ ctx=ctx, pos=pos, tri=tri, uv=uv, rast=rast, rast_db=rast_db, device=device
+ )
+
+ def test_list_and_tuple_resolutions(self, scene):
+ for resolution in ([24, 32], (24, 32), torch.tensor([24, 32])):
+ rast, rast_db = dr.rasterize(scene.ctx, scene.pos, scene.tri, resolution)
+ assert torch.equal(rast, scene.rast) and torch.equal(rast_db, scene.rast_db)
+
+ def test_numpy_resolutions(self, scene):
+ np = pytest.importorskip("numpy")
+ shape = np.zeros((24, 32)).shape
+ forms = (np.array([24, 32]), (np.int64(24), np.int32(32)), [np.intp(24), 32], shape)
+ for resolution in forms:
+ rast, _ = dr.rasterize(scene.ctx, scene.pos, scene.tri, resolution)
+ assert torch.equal(rast, scene.rast)
+
+ def test_positional_rasterize(self, scene):
+ rast, rast_db = dr.rasterize(scene.ctx, scene.pos, scene.tri, [24, 32], None, True)
+ assert torch.equal(rast, scene.rast) and torch.equal(rast_db, scene.rast_db)
+
+ def test_positional_texture(self, scene):
+ tex = random(1, 16, 16, 3, device=scene.device)
+ uv, uv_da = dr.interpolate(scene.uv, scene.rast, scene.tri, scene.rast_db, "all")
+ out = dr.texture(tex, uv, uv_da, None, None, "linear", "wrap", None)
+ expected = dr.texture(tex, uv, filter_mode="linear", boundary_mode="wrap")
+ assert torch.equal(out, expected)
+
+ def test_shared_attributes_with_batched_rast(self, scene):
+ attr = random(scene.pos.shape[1], 5, device=scene.device)
+ shared, _ = dr.interpolate(attr, scene.rast, scene.tri)
+ batched, _ = dr.interpolate(attr[None].expand(2, -1, -1), scene.rast, scene.tri)
+ single, _ = dr.interpolate(attr[None], scene.rast, scene.tri)
+ assert shared.shape == (2, *self.RESOLUTION, 5)
+ torch.testing.assert_close(shared, batched)
+ torch.testing.assert_close(shared, single)
+
+ def test_per_face_attributes(self, scene):
+ faces = scene.tri.shape[0]
+ face_tri = torch.arange(faces, dtype=torch.int32, device=scene.device)
+ face_tri = face_tri[:, None].repeat(1, 3)
+ attr = random(faces, 3, device=scene.device)
+ out, _ = dr.interpolate(attr, scene.rast, face_tri)
+
+ ids = scene.rast[..., 3].long()
+ expected = attr[(ids - 1).clamp(min=0)] * (ids > 0)[..., None]
+ torch.testing.assert_close(out, expected, atol=1e-6, rtol=1e-5)
+
+ def test_separate_uv_index_buffer(self, scene):
+ # One uv per triangle corner, as in a mesh whose uv map has seams.
+ corner_uv = scene.uv[scene.tri.long()].reshape(-1, 2)
+ uv_tri = torch.arange(corner_uv.shape[0], dtype=torch.int32, device=scene.device)
+ uv_tri = uv_tri.view(-1, 3)
+ out, out_da = dr.interpolate(corner_uv, scene.rast, uv_tri, scene.rast_db, "all")
+ expected = dr.interpolate(scene.uv, scene.rast, scene.tri, scene.rast_db, "all")
+ torch.testing.assert_close(out, expected[0])
+ torch.testing.assert_close(out_da, expected[1])
+
+ def test_rast_db_without_diff_attrs(self, scene):
+ out, out_da = dr.interpolate(scene.uv, scene.rast, scene.tri, rast_db=scene.rast_db)
+ expected, _ = dr.interpolate(scene.uv, scene.rast, scene.tri)
+ assert torch.equal(out, expected)
+ assert out_da.shape == (2, *self.RESOLUTION, 0)
+ out, out_da = dr.interpolate(scene.uv, scene.rast, scene.tri, scene.rast_db, None)
+ assert torch.equal(out, expected) and out_da.numel() == 0
+
+ def test_rast_edited_in_place(self, scene):
+ expected, _ = dr.interpolate(scene.uv, scene.rast, scene.tri)
+ rast = scene.rast.clone()
+ rast[..., :2].clamp_(0, 1)
+ rast[..., :2] = torch.clamp(rast[..., :2], 0, 1)
+ out, _ = dr.interpolate(scene.uv, rast, scene.tri)
+ torch.testing.assert_close(out, expected)
+
+ def test_rast_edited_in_place_with_gradients(self, scene):
+ # The edits are made on the tensor that rasterize returned, which is part of the graph.
+ weights = random(2, *self.RESOLUTION, 2, device=scene.device, seed=3)
+
+ def render(edit):
+ pos = scene.pos.clone().requires_grad_(True)
+ rast, rast_db = dr.rasterize(scene.ctx, pos, scene.tri, self.RESOLUTION)
+ rast = edit(rast)
+ uv, uv_da = dr.interpolate(scene.uv, rast, scene.tri, rast_db, "all")
+ out = dr.antialias(uv, rast, pos, scene.tri)
+ ((out * weights).sum() + uv_da.square().sum()).backward()
+ return out.detach(), pos.grad
+
+ def in_place(rast):
+ rast[..., 3:4] += 0
+ rast[..., :2].clamp_(0, 1)
+ return rast
+
+ def copied(rast):
+ return torch.cat([rast[..., :2].clamp(0, 1), rast[..., 2:]], -1)
+
+ out, grad = render(in_place)
+ expected_out, expected_grad = render(copied)
+ assert grad.isfinite().all() and (grad != 0).any()
+ torch.testing.assert_close(out, expected_out)
+ scale = float(expected_grad.abs().max())
+ torch.testing.assert_close(grad, expected_grad, atol=1e-5 * scale, rtol=1e-4)
+
+ def test_chunked_triangles(self, scene):
+ # Rasterize a few triangles at a time, shift the ids of each chunk to their place in
+ # the whole index buffer, and keep the first chunk to cover a pixel.
+ rast = torch.zeros_like(scene.rast)
+ for start in range(0, scene.tri.shape[0], 20):
+ chunk, _ = dr.rasterize(
+ scene.ctx, scene.pos, scene.tri[start : start + 20], self.RESOLUTION
+ )
+ covered = chunk[..., 3:4] > 0
+ chunk[..., 3:4] += start
+ rast = torch.where(covered & (rast[..., 3:4] == 0), chunk, rast)
+
+ assert torch.equal(rast[..., 3] > 0, scene.rast[..., 3] > 0)
+ assert rast[..., 3].max() > 60
+ out, _ = dr.interpolate(scene.uv, rast, scene.tri)
+ expected, _ = dr.interpolate(scene.uv, scene.rast, scene.tri)
+ torch.testing.assert_close(out, expected, atol=1e-5, rtol=1e-5)
+
+ @pytest.mark.parametrize("filter_mode", ["auto", "linear", "nearest"])
+ def test_empty_derivatives_passed_on_to_texture(self, scene, filter_mode):
+ # Without diff_attrs, interpolate returns an empty tensor in place of the derivatives.
+ tex = random(1, 8, 8, 3, device=scene.device)
+ uv, uv_da = dr.interpolate(scene.uv, scene.rast, scene.tri)
+ assert uv_da.shape[-1] == 0
+ out = dr.texture(tex, uv, uv_da, filter_mode=filter_mode)
+ assert torch.equal(out, dr.texture(tex, uv, filter_mode=filter_mode))
+ assert torch.equal(dr.texture(tex, uv, uv_da=uv_da), dr.texture(tex, uv))
+
+ def test_nearest_filter_with_uv_da(self, scene):
+ tex = random(1, 8, 8, 3, device=scene.device)
+ uv, uv_da = dr.interpolate(scene.uv, scene.rast, scene.tri, scene.rast_db, "all")
+ out = dr.texture(tex, uv, uv_da, filter_mode="nearest")
+ assert torch.equal(out, dr.texture(tex, uv, filter_mode="nearest"))
+
+ def test_point_lookups(self, device):
+ tex = random(1, 4, 4, 3, device=device)
+ centres = (torch.arange(4, device=device) + 0.5) / 4
+ v, u = torch.meshgrid(centres, centres, indexing="ij")
+ uv = torch.stack([u, v], -1).reshape(1, 16, 1, 2)
+ out = dr.texture(tex, uv, filter_mode="linear")
+ assert out.shape == (1, 16, 1, 3)
+ torch.testing.assert_close(out.reshape(4, 4, 3), tex[0])
+
+ def test_constant_texture_with_mipmaps(self, scene):
+ tex = torch.tensor([0.2, 0.5, 0.9], device=scene.device).view(1, 1, 1, 3)
+ tex.requires_grad_(True)
+ uv, uv_da = dr.interpolate(scene.uv, scene.rast, scene.tri, scene.rast_db, "all")
+ out = dr.texture(tex, uv, uv_da, filter_mode="linear-mipmap-linear")
+ out.sum().backward()
+ torch.testing.assert_close(out, tex.detach().expand_as(out))
+ pixels = float(out[..., 0].numel())
+ torch.testing.assert_close(tex.grad.flatten(), torch.full((3,), pixels).to(tex))
+
+ def test_antialias_of_a_mask(self, scene):
+ pos = scene.pos.clone().requires_grad_(True)
+ mask = (scene.rast[..., 3:] > 0).float()
+ out = dr.antialias(mask, scene.rast, pos, scene.tri)
+ out.sum().backward()
+
+ assert out.shape == mask.shape
+ assert ((out > 0) & (out < 1)).any()
+ assert pos.grad.isfinite().all()
+ assert (pos.grad != 0).any()
+
+ def test_without_grad_db(self, scene):
+ pos = scene.pos.clone().requires_grad_(True)
+ rast, _ = dr.rasterize(scene.ctx, pos, scene.tri, self.RESOLUTION, grad_db=False)
+ out, _ = dr.interpolate(scene.uv, rast, scene.tri)
+ out.sum().backward()
+ assert torch.equal(rast, scene.rast)
+ assert pos.grad.isfinite().all() and (pos.grad != 0).any()
+
+ def test_non_contiguous_inputs(self, scene):
+ tex = random(1, 16, 16, 3, device=scene.device, seed=1)
+ weights = random(2, *self.RESOLUTION, 3, device=scene.device, seed=2)
+
+ def render(convert):
+ pos = scene.pos.clone().requires_grad_(True)
+ texture = tex.clone().requires_grad_(True)
+ tri = convert(scene.tri)
+ rast, rast_db = dr.rasterize(scene.ctx, convert(pos), tri, self.RESOLUTION)
+ uv, uv_da = dr.interpolate(convert(scene.uv), rast, tri, rast_db, "all")
+ color = dr.texture(convert(texture), convert(uv), convert(uv_da))
+ out = dr.antialias(convert(color), rast, convert(pos), tri)
+ (out * weights).sum().backward()
+ return out.detach(), pos.grad, texture.grad
+
+ expected = render(lambda t: t)
+ for ours, theirs in zip(render(strided), expected, strict=True):
+ scale = theirs.abs().max()
+ assert scale > 0
+ torch.testing.assert_close(ours, theirs, atol=1e-5 * float(scale), rtol=1e-4)
diff --git a/tests/test_coverage.py b/tests/test_coverage.py
new file mode 100644
index 0000000..1f50409
--- /dev/null
+++ b/tests/test_coverage.py
@@ -0,0 +1,818 @@
+"""Which pixels a triangle covers: the fill rule on edges, cracks, degenerate and non-finite
+triangles, and size limits. Every rule is checked on both backends, and the Triton backend is
+compared with the reference backend pixel by pixel."""
+
+import importlib
+
+import pytest
+import torch
+
+import diffrast as dr
+from diffrast.backends import reference
+from diffrast.ops import check_rasterize_inputs
+from helpers import screen_space_rasterize
+
+QUAD = torch.tensor([[0, 1, 2], [0, 2, 3]], dtype=torch.int32)
+RESOLUTIONS = [(100, 100), (255, 255), (1000, 1000), (600, 800)]
+# Directions of the two infinitesimal steps in exact_owner; the first is the fill rule.
+STEPS = [(1, 1), (1, -1), (-1, 1), (-1, -1)]
+SHEETS = {
+ "facing": ((6, 5), (6, 0), (0, 6)),
+ "rotated 45 degrees": ((32, 4), (4, 4), (-4, 4)),
+ "generic angle": ((20, 3), (6, 2), (-2, 6)),
+}
+
+
+def load_triton():
+ pytest.importorskip("triton")
+ return importlib.import_module("diffrast.backends.triton")
+
+
+@pytest.fixture(params=["reference", pytest.param("triton", marks=pytest.mark.gpu)])
+def backend(request):
+ """A backend module and the device it is run on."""
+ if request.param == "triton":
+ return load_triton(), "cuda"
+ return reference, "cpu"
+
+
+def peel(backend, pos, tri, resolution, count=1):
+ """Triangle index per pixel (-1 for background) of the first ``count`` depth layers."""
+ module, device = backend
+ pos, tri = pos.to(device), tri.to(device)
+ state, layers = None, []
+ for _ in range(count):
+ rast, _, state = module.rasterize_layer(pos, tri, resolution, True, state)
+ layers.append(rast[..., 3].long().cpu() - 1)
+ return layers
+
+
+def owner(backend, pos, tri, resolution):
+ return peel(backend, pos, tri, resolution)[0]
+
+
+def lattice(cols, rows, resolution, w=1.0, z=0.0, device="cpu", dtype=torch.float32):
+ """Clip-space vertices that project onto the centres of the pixels ``(rows, cols)``.
+
+ The centres are computed like the rasterizer's own and on the same device, where a division
+ by a scalar may round differently, so that the edge functions through a vertex are exactly
+ zero at its pixel. Indices outside the image give lattice points off screen.
+ """
+ height, width = resolution
+ x = (cols.to(device, dtype) * 2 + 1) / width - 1
+ y = (rows.to(device, dtype) * 2 + 1) / height - 1
+ w = torch.as_tensor(w, dtype=dtype, device=device).expand(x.shape)
+ return torch.stack([x * w, y * w, z * w, w], -1)[None]
+
+
+def exact_owner(cols, rows, tri, resolution, step=(1, 1)):
+ """Coverage in integer arithmetic of triangles with vertices on pixel centres.
+
+ Each pixel is sampled at its centre moved by an infinitesimal step along x and a much smaller
+ one along y, in the directions given by ``step``; ``(1, 1)`` is the fill rule. Returns the
+ index of a covering triangle per pixel (-1 for none) and the number of covering triangles.
+ """
+ height, width = resolution
+ v = torch.stack([cols, rows], -1).long()[tri.long()][:, :, :, None, None]
+ px, py = torch.arange(width).view(1, 1, width), torch.arange(height).view(1, height, 1)
+ # Coordinates are far below 2**13, so with this scale neither step can outweigh a nonzero
+ # value of the term before it.
+ scale = 1 << 13
+ area, shifted = 0, []
+ for k in range(3):
+ (ax, ay), (bx, by) = v[:, (k + 1) % 3].unbind(1), v[:, (k + 2) % 3].unbind(1)
+ e = (ax - px) * (by - py) - (bx - px) * (ay - py)
+ area = area + e
+ shifted.append((e * scale + step[0] * (ay - by)) * scale + step[1] * (bx - ax))
+ inside = torch.stack([value * area.sign() > 0 for value in shifted]).all(0)
+ count = inside.sum(0)
+ return torch.where(count > 0, inside.long().argmax(0), -1), count
+
+
+def shuffle_vertices(tri, gen):
+ """List the vertices of each triangle in a random order, which also randomizes winding."""
+ order = torch.stack([torch.randperm(3, generator=gen) for _ in range(tri.shape[0])])
+ return tri.gather(1, order)
+
+
+def grid_triangles(nx, ny, gen=None):
+ """Triangles of a grid of ``nx`` by ``ny`` quads over ``(ny + 1) * (nx + 1)`` vertices.
+
+ With ``gen``, each quad is split along a random diagonal and the vertices of each triangle
+ are shuffled, so neighbours differ in winding.
+ """
+ idx = torch.arange((nx + 1) * (ny + 1)).view(ny + 1, nx + 1)
+ a, b, c, d = (t.flatten() for t in (idx[:-1, :-1], idx[:-1, 1:], idx[1:, 1:], idx[1:, :-1]))
+ first, second = torch.stack([a, b, c], -1), torch.stack([a, c, d], -1)
+ if gen is None:
+ return torch.cat([first, second]).int()
+ other = (torch.rand(nx * ny, generator=gen) < 0.5)[:, None]
+ first = torch.where(other, torch.stack([a, b, d], -1), first)
+ second = torch.where(other, torch.stack([b, c, d], -1), second)
+ return shuffle_vertices(torch.cat([first, second]), gen).int()
+
+
+def sheet(origin, u, v, n, gen):
+ """Lattice coordinates and triangles of an ``n`` by ``n`` grid of quads with sides u and v."""
+ j, i = torch.meshgrid(torch.arange(n + 1), torch.arange(n + 1), indexing="ij")
+ cols = (origin[0] + i * u[0] + j * v[0]).flatten()
+ rows = (origin[1] + i * u[1] + j * v[1]).flatten()
+ return cols, rows, grid_triangles(n, n, gen)
+
+
+def screen_quad(scale=1.0, w=1.0):
+ corners = [[-1.0, -1.0], [1.0, -1.0], [1.0, 1.0], [-1.0, 1.0]]
+ return torch.tensor([[[x * scale * w, y * scale * w, 0.0, w] for x, y in corners]])
+
+
+def corner_grid(nx, ny, w=1.0):
+ """A grid of quads filling the screen exactly, so its diagonals pass through pixel centres."""
+ y, x = torch.meshgrid(
+ torch.linspace(-1, 1, ny + 1), torch.linspace(-1, 1, nx + 1), indexing="ij"
+ )
+ xy = torch.stack([x, y], -1).reshape(-1, 2)
+ return torch.cat([xy * w, torch.zeros(len(xy), 1), torch.full((len(xy), 1), w)], -1)[None]
+
+
+def covering_lattice(resolution, cell, gen, device, w=None):
+ """A lattice mesh of ``cell``-pixel quads that extends past every side of the image."""
+ height, width = resolution
+ nx, ny = (width + 1) // cell + 1, (height + 1) // cell + 1
+ rows, cols = torch.meshgrid(
+ torch.arange(ny + 1) * cell - 1, torch.arange(nx + 1) * cell - 1, indexing="ij"
+ )
+ if w is None:
+ w = torch.rand(rows.numel(), generator=gen) + 0.5
+ pos = lattice(cols.flatten(), rows.flatten(), resolution, w=w, device=device)
+ return pos, grid_triangles(nx, ny, gen)
+
+
+def full_screen_scenes(resolution, gen, cell, device):
+ """Meshes that cover every pixel exactly once, with many edges through pixel centres."""
+ nx, ny = resolution[1] // cell, resolution[0] // cell
+ return {
+ "quad": (screen_quad(), QUAD),
+ "oversized quad": (screen_quad(1.3, w=0.37), QUAD),
+ "corner grid": (corner_grid(nx, ny), grid_triangles(nx, ny, gen)),
+ "corner grid, w = 2.5": (corner_grid(4, 3, w=2.5), grid_triangles(4, 3, gen)),
+ "lattice": covering_lattice(resolution, cell, gen, device, w=1.0),
+ "lattice, w per vertex": covering_lattice(resolution, cell, gen, device),
+ }
+
+
+def small_triangles(count, size, gen, perspective=True):
+ """Triangles about ``size`` NDC units across, scattered over and just past the screen."""
+ centre = torch.rand(count, 1, 2, generator=gen) * 2.2 - 1.1
+ xy = (centre + (torch.rand(count, 3, 2, generator=gen) * 2 - 1) * size).reshape(1, -1, 2)
+ z = torch.rand(1, 3 * count, 1, generator=gen) * 1.8 - 0.9
+ w = torch.rand(1, 3 * count, 1, generator=gen) + 1.0 if perspective else torch.ones_like(z)
+ return torch.cat([xy * w, z * w, w], -1), torch.arange(3 * count).view(count, 3).int()
+
+
+def collinear_triangles(count, gen, perspective):
+ """Triangles ``(a, b, midpoint of a and b)`` with ``a`` and ``b`` on a lattice of 1 / 10."""
+ ends = torch.randint(-9, 10, (count, 2, 2), generator=gen).float() / 10
+ xy = torch.cat([ends, ends.mean(1, keepdim=True)], 1).reshape(1, -1, 2)
+ w = torch.ones(1, 3 * count, 1)
+ if perspective:
+ w = w + torch.rand(1, 3 * count, 1, generator=gen)
+ pos = torch.cat([xy * w, torch.zeros_like(w), w], -1)
+ return pos, torch.arange(3 * count, dtype=torch.int32).view(count, 3)
+
+
+def integer_homography_grid(gen):
+ """A planar grid seen through a random integer homography, as integer ``(x, y, w)`` per vertex.
+
+ Many of these grids cross the camera plane, and many pixel centres lie exactly on their edges.
+ """
+ while True:
+ h = torch.randint(-4, 5, (3, 3), generator=gen)
+ minors = h[1, [1, 2, 0]] * h[2, [2, 0, 1]] - h[1, [2, 0, 1]] * h[2, [1, 2, 0]]
+ if (h[0] * minors).sum() != 0:
+ break
+ n = int(torch.randint(2, 6, (1,), generator=gen))
+ line = torch.arange(n + 1) - int(torch.randint(1, 4, (1,), generator=gen))
+ v, u = torch.meshgrid(line, line, indexing="ij")
+ grid = torch.stack([u.flatten(), v.flatten(), torch.ones(u.numel(), dtype=torch.long)], -1)
+ return grid @ h.T, grid_triangles(n, n, gen)
+
+
+def exact_homogeneous_owner(clip, tri, size):
+ """Coverage in integer arithmetic of triangles with integer clip coordinates ``(x, y, w)``.
+
+ Each pixel of a ``size`` by ``size`` image is sampled at its centre moved by an infinitesimal
+ step along +x and a much smaller one along +y: where an edge function is zero, the sign of
+ its derivative along x decides, and that along y where this is zero as well. Returns the
+ covering triangle per pixel (-1 for none), the number of covering triangles, the pixels
+ whose owner has such a zero, those of them whose owner crosses the camera plane, and the
+ pixels left undecided because a triangle's area there is zero or close to the tolerance.
+ """
+ x, y, w = (clip[tri.long()][:, :, k, None, None] for k in range(3))
+ centre = torch.arange(size) * 2 + 1 - size
+ a = x * size - centre.view(1, 1, 1, size) * w
+ c = y * size - centre.view(1, 1, size, 1) * w
+ area, ew, zero, shifted = 0, 0, False, []
+ for k in range(3):
+ i, j = (k + 1) % 3, (k + 2) % 3
+ e = a[:, i] * c[:, j] - a[:, j] * c[:, i]
+ along_x = y[:, i] * w[:, j] - y[:, j] * w[:, i]
+ along_y = x[:, j] * w[:, i] - x[:, i] * w[:, j]
+ area, ew, zero = area + e, ew + e * w[:, k], zero | (e == 0)
+ shifted.append(torch.where(e != 0, e, torch.where(along_x != 0, along_x, along_y)))
+ inside = torch.stack([value * area.sign() > 0 for value in shifted]).all(0) & (ew * area > 0)
+ count = inside.sum(0)
+
+ reach_x, reach_y = ((t.abs() + w.abs()).amax(1).double() for t in (x, y))
+ span_x, span_y = (t.abs().sum(1).double() / size for t in (a, c))
+ noise = (reach_x * span_y + span_x * (reach_y + span_y)) * torch.finfo(torch.float32).eps
+ undecided = (area.abs().double() / size**2 < 4 * noise).any(0)
+ tie = (inside & zero).any(0)
+ crossing = (inside & zero & (w.amin(1) <= 0)).any(0)
+ return torch.where(count > 0, inside.long().argmax(0), -1), count, tie, crossing, undecided
+
+
+def sliver(half_width, steps):
+ """A triangle around the centre of pixel ``(8, 8)`` of a 16 by 16 image.
+
+ It is ``2 * half_width`` wide and ``2 * steps`` float32 steps of its y coordinates high. Its
+ coordinates, and everything the coverage test computes from them at that pixel, are exact.
+ """
+ centre, step = 0.0625, 2.0**-27
+ xy = [[-half_width, -steps * step], [half_width, -steps * step], [0.0, steps * step]]
+ return torch.tensor([[[centre + x, centre + y, 0.0, 1.0] for x, y in xy]])
+
+
+# Fill rule
+
+
+@pytest.mark.parametrize("resolution", [(8, 8), (100, 100), (255, 255), (1000, 1000)])
+@pytest.mark.parametrize("scale", [1.0, 0.9])
+def test_quad_diagonal_goes_to_the_triangle_on_its_right(backend, resolution, scale):
+ # The diagonal passes through the centres of the pixels on it, where its edge function is
+ # exactly zero in both triangles: triangle 0 lies in the +x direction and takes them all.
+ size = resolution[0]
+ ids = owner(backend, screen_quad(scale), QUAD, resolution)[0]
+ centre = (torch.arange(size, dtype=torch.float64) * 2 + 1) / size - 1
+ inside = (centre.abs() < scale)[:, None] & (centre.abs() < scale)[None, :]
+ row, col = torch.meshgrid(torch.arange(size), torch.arange(size), indexing="ij")
+ assert torch.equal(ids, torch.where(inside, torch.where(col >= row, 0, 1), -1))
+
+
+@pytest.mark.parametrize("order", [[0, 1, 2, 3], [3, 2, 1, 0], [1, 2, 3, 0]])
+@pytest.mark.parametrize("w", [1.0, 2.5])
+def test_rectangle_owns_its_left_and_top_edges_only(backend, order, w):
+ # All four sides pass through pixel centres. Row 0 is at y = -1, so the side whose interior
+ # lies in the +y direction is the one with the lowest row.
+ resolution = (20, 24)
+ cols, rows = torch.tensor([5, 17, 17, 5])[order], torch.tensor([3, 3, 14, 14])[order]
+ pos = lattice(cols, rows, resolution, w=w, device=backend[1])
+ ids = owner(backend, pos, QUAD, resolution)[0]
+ expected = torch.zeros(resolution, dtype=torch.bool)
+ expected[3:14, 5:17] = True
+ assert torch.equal(ids >= 0, expected)
+
+
+def test_fill_rule_matches_shifted_sampling(backend):
+ # Right triangles with two axis-aligned sides, whose edge functions are exactly zero on the
+ # pixel centres they pass, and legs of coprime length, so the third side passes none. Every
+ # pixel then has to match the integer computation.
+ resolution = (40, 48)
+ gen = torch.Generator().manual_seed(0)
+ for _ in range(40):
+ col, row = torch.randint(18, 24, (2,), generator=gen).tolist()
+ dx = (3, 5, 7, 9, 11)[int(torch.randint(5, (1,), generator=gen))]
+ dy = (2, 4, 8, 16)[int(torch.randint(4, (1,), generator=gen))]
+ sx, sy = (torch.randint(0, 2, (2,), generator=gen) * 2 - 1).tolist()
+ cols = torch.tensor([col, col + sx * dx, col])
+ rows = torch.tensor([row, row, row + sy * dy])
+ tri = shuffle_vertices(torch.tensor([[0, 1, 2]]), gen).int()
+ w = torch.rand(3, generator=gen) + 0.5
+ pos = lattice(cols, rows, resolution, w=w, device=backend[1])
+ expected, _ = exact_owner(cols, rows, tri, resolution)
+ assert torch.equal(owner(backend, pos, tri, resolution)[0], expected)
+
+
+def assert_partition(layers, cols, rows, tri, resolution):
+ """The first layer covers the mesh without holes or overlaps and the second is empty.
+
+ A pixel whose centre lies on an edge may go to any triangle touching it there, since an edge
+ function that is zero in exact arithmetic can round to either side; every other pixel has to
+ match the integer computation.
+ """
+ first, second = (layer[0] for layer in layers)
+ owners = [exact_owner(cols, rows, tri, resolution, step) for step in STEPS]
+ assert all(int(count.max()) == 1 for _, count in owners), "the mesh overlaps itself"
+ candidates = torch.stack([ids for ids, _ in owners])
+ clear = (candidates == candidates[0]).all(0)
+ interior = (candidates >= 0).all(0)
+ assert (clear & interior).sum() > 100 and (interior & ~clear).sum() > 10
+ assert torch.equal(first[clear], candidates[0][clear])
+ assert (first[interior][None] == candidates[:, interior]).any(0).all()
+ assert (second == -1).all()
+
+
+@pytest.mark.parametrize("name", SHEETS)
+@pytest.mark.parametrize("w", ["one", "uniform", "per vertex"])
+def test_flat_sheet_has_a_single_layer(backend, name, w):
+ origin, u, v = SHEETS[name]
+ resolution = (60, 64)
+ gen = torch.Generator().manual_seed(1)
+ cols, rows, tri = sheet(origin, u, v, 6, gen)
+ w = {"one": 1.0, "uniform": 2.5, "per vertex": torch.rand(49, generator=gen) + 0.5}[w]
+ pos = lattice(cols, rows, resolution, w=w, z=0.25, device=backend[1])
+ assert_partition(peel(backend, pos, tri, resolution, 2), cols, rows, tri, resolution)
+
+
+@pytest.mark.parametrize(("u", "v"), [((3, 0), (0, 3)), ((2, 2), (-2, 2)), ((3, 1), (-1, 3))])
+def test_sheet_of_triangles_a_few_pixels_across(backend, u, v):
+ # Small enough for the Triton backend to rasterize them directly, without binning into tiles.
+ resolution = (40, 44)
+ gen = torch.Generator().manual_seed(4)
+ cols, rows, tri = sheet((16, 4), u, v, 8, gen)
+ w = torch.rand(81, generator=gen) + 0.5
+ pos = lattice(cols, rows, resolution, w=w, z=-0.5, device=backend[1])
+ assert_partition(peel(backend, pos, tri, resolution, 2), cols, rows, tri, resolution)
+
+
+def test_depth_peeler_finds_no_second_layer_in_a_flat_sheet(ctx):
+ resolution = (60, 64)
+ cols, rows, tri = sheet(*SHEETS["facing"], 6, torch.Generator().manual_seed(1))
+ with dr.DepthPeeler(ctx, lattice(cols, rows, resolution), tri, resolution) as peeler:
+ first, _ = peeler.rasterize_next_layer()
+ second, second_db = peeler.rasterize_next_layer()
+ assert (first[..., 3] > 0).sum() == 36 * 36
+ assert (second == 0).all() and (second_db == 0).all()
+
+
+@pytest.mark.parametrize("resolution", RESOLUTIONS)
+def test_meshes_through_pixel_centres_cover_every_pixel_once(backend, resolution):
+ gen = torch.Generator().manual_seed(2)
+ cell = 20 if backend[1] == "cuda" else resolution[1] // 4
+ for name, (pos, tri) in full_screen_scenes(resolution, gen, cell, backend[1]).items():
+ first, second = peel(backend, pos, tri, resolution, 2)
+ assert (first >= 0).all(), f"{name}: holes"
+ assert (second == -1).all(), f"{name}: pixels covered twice"
+
+
+@pytest.mark.parametrize("seed", range(4))
+def test_triangles_sharing_an_edge_cover_their_union_once(backend, seed):
+ # The shared edge runs between lattice points, so it passes through pixel centres. The second
+ # triangle lies on the other side of it and is listed with either winding.
+ resolution = (36, 40)
+ gen = torch.Generator().manual_seed(seed)
+ for _ in range(10):
+ a, b = torch.randint(8, 28, (2, 2), generator=gen) // 4 * 4 + 2
+ along = b - a
+ if not along.any():
+ continue
+ normal = torch.stack([-along[1], along[0]])
+ c = a + normal + torch.randint(-3, 4, (2,), generator=gen)
+ d = b - normal + torch.randint(-3, 4, (2,), generator=gen)
+ cols, rows = torch.stack([a, b, c, d]).unbind(-1)
+ second = [[1, 0, 3], [0, 1, 3], [3, 0, 1]][int(torch.randint(3, (1,), generator=gen))]
+ tri = torch.tensor([[0, 1, 2], second], dtype=torch.int32)
+ w = torch.rand(4, generator=gen) + 0.5
+ pos = lattice(cols, rows, resolution, w=w, device=backend[1])
+
+ alone = [owner(backend, pos, tri[k : k + 1], resolution)[0] >= 0 for k in (0, 1)]
+ assert not (alone[0] & alone[1]).any()
+ assert torch.equal(alone[0] | alone[1], owner(backend, pos, tri, resolution)[0] >= 0)
+ steps = int(torch.gcd(along[0], along[1]))
+ on_edge = a + along // steps * torch.arange(1, steps)[:, None]
+ assert (alone[0] | alone[1])[on_edge[:, 1], on_edge[:, 0]].all()
+
+
+@pytest.mark.parametrize("second", [[1, 0, 3], [0, 1, 3]])
+def test_shared_edge_of_a_triangle_crossing_the_camera_plane(backend, second):
+ # Vertex 3 projects onto the same side of the shared edge as vertex 2, but lies behind the
+ # camera, so the visible part of its triangle is on the opposite side of the edge.
+ resolution = (32, 32)
+ cols, rows = torch.tensor([6, 26, 20, 14]), torch.tensor([6, 26, 8, 4])
+ w = torch.tensor([1.0, 1.5, 0.75, 1.0])
+ pos = lattice(cols, rows, resolution, w=w, z=0.1, device=backend[1])
+ pos[0, 3] = -pos[0, 3]
+ tri = torch.tensor([[0, 1, 2], second], dtype=torch.int32)
+
+ alone = [owner(backend, pos, tri[k : k + 1], resolution)[0] >= 0 for k in (0, 1)]
+ assert alone[0].sum() > 20 and alone[1].sum() > 20
+ assert not (alone[0] & alone[1]).any()
+ assert torch.equal(alone[0] | alone[1], owner(backend, pos, tri, resolution)[0] >= 0)
+ assert (alone[0] | alone[1]).diagonal()[7:26].all()
+
+
+@pytest.mark.parametrize("count", [3, 4, 7])
+@pytest.mark.parametrize("on_lattice", [True, False])
+def test_vertex_of_a_closed_fan_is_covered_once(backend, count, on_lattice):
+ # The hub lies on a pixel centre, where two edge functions of every triangle in the fan are
+ # exactly zero.
+ resolution = (24, 24)
+ gen = torch.Generator().manual_seed(count)
+ for _ in range(6):
+ angle = (torch.arange(count) + torch.rand(count, generator=gen) * 0.4) / count
+ angle = (angle + torch.rand(1, generator=gen)) * 6.2832
+ rim = torch.stack([angle.cos(), angle.sin()], -1) * 9
+ hub = torch.tensor([[12.0, 11.0]])
+ cols, rows = torch.cat([hub, hub + (rim.round() if on_lattice else rim)]).unbind(-1)
+ w = torch.cat([torch.ones(1), torch.rand(count, generator=gen) + 0.5])
+ pos = lattice(cols, rows, resolution, w=w, device=backend[1])
+ spokes = torch.arange(count)
+ tri = torch.stack([torch.zeros_like(spokes), spokes + 1, (spokes + 1) % count + 1], -1)
+ tri = shuffle_vertices(tri, gen).int()
+
+ alone = [owner(backend, pos, tri[k : k + 1], resolution)[0, 11, 12] >= 0 for k in spokes]
+ assert sum(int(covers) for covers in alone) == 1
+ first, second = peel(backend, pos, tri, resolution, 2)
+ assert first[0, 11, 12] >= 0 and (second == -1).all()
+
+
+@pytest.mark.parametrize("seed", range(6))
+def test_fan_with_nearly_horizontal_spokes_covers_its_hub_once(backend, seed):
+ # Several spokes leave the hub a few float32 steps off its row, at different lengths, with
+ # slivers between them. In order of angle from the +x axis towards +y: a vertex on the -y
+ # side of the hub, spokes along +x tilted slightly towards +y, a vertex on the +y side, and
+ # spokes along -x tilted slightly towards -y. The first triangle contains the direction just
+ # past +x and owns the hub. All coordinates are exact.
+ resolution = (16, 16)
+ gen = torch.Generator().manual_seed(seed)
+ step = 2.0**-24
+ for _ in range(8):
+ slopes = {}
+ while len(slopes) < 6:
+ steps, length = (int(torch.randint(1, high, (1,), generator=gen)) for high in (9, 600))
+ slopes[steps / length] = (length / 1024, steps * step)
+ spokes = [slopes[slope] for slope in sorted(slopes)]
+ rim = [(0.125, -0.375), *spokes[::2], (-0.0625, 0.375)]
+ rim += [(-length, -rise) for length, rise in spokes[1::2]]
+ xy = torch.tensor([(0.0, 0.0), *rim], dtype=torch.float64) + torch.tensor([0.0625, 0.5625])
+ pos = torch.cat([xy, torch.zeros(len(xy), 1), torch.ones(len(xy), 1)], -1).float()[None]
+ assert torch.equal(pos[0, :, :2].double(), xy)
+ index = torch.arange(len(rim))
+ tri = torch.stack([torch.zeros_like(index), index + 1, (index + 1) % len(rim) + 1], -1)
+ tri = shuffle_vertices(tri, gen).int()
+
+ alone = [int(owner(backend, pos, tri[k : k + 1], resolution)[0, 12, 8] >= 0) for k in index]
+ assert alone == [1] + [0] * (len(rim) - 1)
+ first, second = peel(backend, pos, tri, resolution, 2)
+ assert first[0, 12, 8] == 0 and (second == -1).all()
+
+
+def test_owner_of_pixels_on_edges_matches_exact_arithmetic(backend):
+ # With small integer clip coordinates and a power-of-two resolution every edge function is
+ # exact in float32, so the triangle each pixel goes to is known, also on the edges of
+ # triangles that cross the camera plane.
+ size = 16
+ gen = torch.Generator().manual_seed(10)
+ ties = crossing_ties = decided = 0
+ for _ in range(150):
+ clip, tri = integer_homography_grid(gen)
+ expected, count, tie, crossing, undecided = exact_homogeneous_owner(clip, tri, size)
+ assert count.max() <= 1
+ x, y, w = clip.float().unbind(-1)
+ pos = torch.stack([x, y, torch.zeros_like(x), w], -1)[None]
+ ids = owner(backend, pos, tri, (size, size))[0]
+ assert torch.equal(ids[~undecided], expected[~undecided])
+ ties += int((tie & ~undecided).sum())
+ crossing_ties += int((crossing & ~undecided).sum())
+ decided += int((~undecided).sum())
+ assert decided > 0.95 * 150 * size * size
+ assert ties > 300 and crossing_ties > 100
+
+
+@pytest.mark.gpu
+@pytest.mark.parametrize("resolution", RESOLUTIONS)
+def test_triton_picks_the_reference_triangle_on_shared_edges(resolution):
+ triton_backend = load_triton()
+ gen = torch.Generator().manual_seed(3)
+ scenes = full_screen_scenes(resolution, gen, max(20, resolution[1] // 16), "cuda")
+ scenes["quad, 0.9"] = (screen_quad(0.9), QUAD)
+ for name, (origin, u, v) in SHEETS.items():
+ cols, rows, tri = sheet(origin, u, v, 6, gen)
+ scenes[name] = (lattice(cols, rows, resolution, w=1.5, device="cuda"), tri)
+ for name, (pos, tri) in scenes.items():
+ pos, tri = pos.cuda(), tri.cuda()
+ ref, _ = reference.rasterize(pos, tri, resolution, True)
+ out, _ = triton_backend.rasterize(pos, tri, resolution, True)
+ assert torch.equal(ref[..., 3], out[..., 3]), name
+
+
+def test_gradients_on_a_shared_vertex_are_those_of_its_owner():
+ # The fill rule only selects the triangle. With the selection held fixed, the outputs are
+ # smooth in the vertex positions, also at a pixel centre that is a vertex of the mesh.
+ resolution = (6, 6)
+ cols, rows = torch.tensor([3.0, 0.4, 5.3, 4.6, 0.7]), torch.tensor([2.0, 0.6, 0.2, 5.4, 4.9])
+ w = torch.tensor([1.0, 1.3, 0.8, 1.1, 1.6], dtype=torch.float64)
+ pos = lattice(cols, rows, resolution, w=w, z=0.2, dtype=torch.float64).requires_grad_(True)
+ tri = torch.tensor([[0, 1, 2], [0, 2, 3], [0, 3, 4], [0, 4, 1]], dtype=torch.int32)
+ rast, _ = reference.rasterize(pos, tri, resolution, True)
+ tri_id = rast[..., 3].long() - 1
+ assert tri_id[0, 2, 3] >= 0 and (tri_id >= 0).sum() > 12
+ torch.testing.assert_close(rast[0, 2, 3, :3], pos.new_tensor([1.0, 0.0, 0.2]))
+ assert torch.autograd.gradcheck(
+ lambda p: reference.rasterize_from_ids(p, tri, tri_id, True), (pos,)
+ )
+
+
+# Degenerate triangles
+
+
+@pytest.mark.parametrize("perspective", [False, True])
+def test_collinear_triangles_are_not_drawn(backend, perspective):
+ # The lattice lines pass through pixel centres, where the edge functions of these triangles
+ # are rounding residue whose signs would otherwise agree on thousands of pixels.
+ pos, tri = collinear_triangles(20000, torch.Generator().manual_seed(0), perspective)
+ assert (owner(backend, pos, tri, (100, 100)) == -1).all()
+
+
+def test_repeated_index_triangles_are_not_drawn(backend):
+ gen = torch.Generator().manual_seed(1)
+ xy = torch.randint(-14, 15, (1, 500, 2), generator=gen).float() / 16
+ pos = torch.cat([xy, torch.zeros(1, 500, 1), torch.ones(1, 500, 1)], -1)
+ i, j = torch.randint(0, 500, (2, 5000), generator=gen)
+ tri = torch.cat([torch.stack([i, i, j], -1), torch.stack([i, j, i], -1)]).int()
+ assert (owner(backend, pos, tri, (100, 100)) == -1).all()
+
+
+def test_zero_area_triangles_do_not_hide_the_mesh_behind_them(backend):
+ quad = screen_quad()
+ quad[..., 2] = 0.5
+ line = torch.tensor([[[-0.9, -0.9, 0.0, 1.0], [0.3, 0.3, 0.0, 1.0], [0.9, 0.9, 0.0, 1.0]]])
+ tri = torch.cat([torch.tensor([[0, 1, 2], [0, 0, 1]], dtype=torch.int32), QUAD + 3])
+ for resolution in ((100, 100), (255, 255)):
+ assert (owner(backend, torch.cat([line, quad], 1), tri, resolution) >= 2).all()
+
+
+@pytest.mark.parametrize("thickness", [1e-2, 1e-3, 1e-4])
+def test_thin_triangles_are_drawn(backend, thickness):
+ # Slivers up to 20000 times longer than wide.
+ resolution = (128, 128)
+ gen = torch.Generator().manual_seed(2)
+ start = torch.rand(300, 2, generator=gen) * 1.6 - 0.8
+ angle = torch.rand(300, generator=gen) * 6.2832
+ along = torch.stack([angle.cos(), angle.sin()], -1)
+ across = torch.stack([-angle.sin(), angle.cos()], -1) * thickness
+ xy = torch.stack([start - along, start + along, start + along + across], 1).reshape(1, -1, 2)
+ z = (torch.arange(300.0) / 300 - 0.5).repeat_interleave(3).view(1, -1, 1) * 1.6
+ pos = torch.cat([xy, z, torch.ones(1, 900, 1)], -1)
+ tri = torch.arange(900, dtype=torch.int32).view(300, 3)
+
+ ids = owner(backend, pos, tri, resolution)
+ # The thinner the triangle, the larger the float32 error of its barycentrics.
+ expected, _, ambiguous = screen_space_rasterize(pos, tri, *resolution, margin=2e-7 / thickness)
+ assert (expected[~ambiguous] >= 0).sum() > 3e5 * thickness
+ assert torch.equal(ids[~ambiguous], expected[~ambiguous])
+
+
+@pytest.mark.parametrize(("size", "count"), [(0.3, 100), (0.03, 1000), (0.01, 2000)])
+def test_small_valid_triangles_match_screen_space_rasterizer(backend, size, count):
+ resolution = (64, 56)
+ pos, tri = small_triangles(count, size, torch.Generator().manual_seed(3))
+ ids = owner(backend, pos, tri, resolution)
+ expected, _, ambiguous = screen_space_rasterize(pos, tri, *resolution)
+ assert (~ambiguous).float().mean() > 0.9 and (expected[~ambiguous] >= 0).sum() > 20
+ assert torch.equal(ids[~ambiguous], expected[~ambiguous])
+
+
+def test_triangles_below_float_resolution_are_not_drawn(backend):
+ # Triangles a few float32 steps across have no meaningful edge functions anywhere on screen.
+ pos, tri = small_triangles(5000, 3e-7, torch.Generator().manual_seed(4), perspective=False)
+ assert (owner(backend, pos, tri, (64, 64)) == -1).all()
+
+
+@pytest.mark.parametrize("half_width", [2.0**-5, 0.5])
+@pytest.mark.parametrize(("steps", "drawn"), [(4, False), (16, False), (18, True), (64, True)])
+def test_area_tolerance_is_two_epsilons(backend, half_width, steps, drawn):
+ # The centre of pixel (8, 8) lies strictly inside the triangle, whose area there is
+ # 2 * steps / 17 epsilons of the magnitude of the terms it is computed from. Below two
+ # epsilons the triangle counts as degenerate, although its exact area is positive.
+ ids = owner(backend, sliver(half_width, steps), torch.tensor([[0, 1, 2]]).int(), (16, 16))
+ assert (ids[0, 8, 8] == 0) == drawn
+ assert drawn or (ids == -1).all()
+
+
+@pytest.mark.gpu
+def test_triton_matches_reference_near_the_area_tolerance():
+ # One sliver per image, around a pixel centre, with an area there between half an epsilon
+ # and five epsilons of the magnitude of its terms: the backends have to draw the same ones.
+ triton_backend = load_triton()
+ gen = torch.Generator().manual_seed(12)
+ count, eps = 3000, torch.finfo(torch.float32).eps
+ centre = (torch.randint(0, 16, (count, 1, 2), generator=gen).double() * 2 + 1) / 16 - 1
+ half_width = 2.0 ** -torch.randint(1, 6, (count,), generator=gen).double()
+ ratio = torch.rand(count, generator=gen, dtype=torch.float64) * 4.5 + 0.5
+ height = ratio * eps * (1 + centre[:, 0, 1].abs()) / 2
+ zero = torch.zeros(count, dtype=torch.float64)
+ offset = torch.stack([-half_width, -height, half_width, -height, zero, height], -1)
+ xy = (centre + offset.view(count, 3, 2)).float()
+ pos = torch.cat([xy, torch.zeros(count, 3, 1), torch.ones(count, 3, 1)], -1).cuda()
+ tri = torch.tensor([[0, 1, 2]], dtype=torch.int32).cuda()
+
+ ref, _ = reference.rasterize(pos, tri, (16, 16), True)
+ out, _ = triton_backend.rasterize(pos, tri, (16, 16), True)
+ assert torch.equal(ref[..., 3], out[..., 3])
+ drawn = (ref[..., 3] > 0).flatten(1).any(1).float().mean()
+ assert 0.3 < drawn < 0.85
+
+
+@pytest.mark.parametrize("exponent", [-40, -20, -10, 10, 20, 40])
+def test_coverage_does_not_depend_on_clip_space_scale(backend, exponent):
+ # A power of two scales every intermediate value exactly, so nothing may change at all while
+ # the products of three coordinates fit in float32: twelve orders of magnitude either way.
+ gen = torch.Generator().manual_seed(5)
+ resolution = (48, 48)
+ cols, rows, sheet_tri = sheet(*SHEETS["facing"], 6, gen)
+ scenes = [
+ small_triangles(60, 0.5, gen),
+ (lattice(cols, rows, resolution, device=backend[1]), sheet_tri),
+ collinear_triangles(500, gen, True),
+ ]
+ for pos, tri in scenes:
+ scaled = owner(backend, pos * 2.0**exponent, tri, resolution)
+ assert torch.equal(scaled, owner(backend, pos, tri, resolution))
+ # The last scene has no area at any scale.
+ assert (scaled == -1).all()
+
+
+@pytest.mark.gpu
+def test_triton_matches_reference_on_degenerate_and_tiny_triangles():
+ triton_backend = load_triton()
+ gen = torch.Generator().manual_seed(6)
+ scenes = [collinear_triangles(5000, gen, perspective) for perspective in (False, True)]
+ scenes += [small_triangles(20000, size, gen) for size in (3e-2, 3e-4, 3e-6)]
+ for pos, tri in scenes:
+ pos, tri = pos.cuda(), tri.cuda()
+ for resolution in ((100, 100), (37, 61)):
+ ref, _ = reference.rasterize(pos, tri, resolution, True)
+ out, _ = triton_backend.rasterize(pos, tri, resolution, True)
+ assert torch.equal(ref[..., 3], out[..., 3])
+
+
+@pytest.mark.gpu
+@pytest.mark.parametrize("w_range", [(1.0, 2.0), (-1.0, 2.0)])
+def test_triton_matches_reference_on_every_pixel_of_every_layer(w_range):
+ # Meshes in general position, also across the camera plane and the depth range: no pixel is
+ # left to rounding, because the visibility kernels perform the reference's operations.
+ triton_backend = load_triton()
+ gen = torch.Generator().manual_seed(9)
+ xy = torch.rand(2, 900, 2, generator=gen) * 3 - 1.5
+ z = torch.rand(2, 900, 1, generator=gen) * 2.4 - 1.2
+ w = torch.rand(2, 900, 1, generator=gen) * (w_range[1] - w_range[0]) + w_range[0]
+ pos = torch.cat([xy * w, z * w, w], -1)
+ tri = torch.arange(900, dtype=torch.int32).view(300, 3)
+ for resolution in ((64, 64), (37, 61), (255, 257)):
+ ref = peel((reference, "cuda"), pos, tri, resolution, 4)
+ out = peel((triton_backend, "cuda"), pos, tri, resolution, 4)
+ assert (ref[3] >= 0).any()
+ for expected, layer in zip(ref, out, strict=True):
+ assert torch.equal(layer, expected)
+
+
+def test_gradcheck_ignores_a_zero_area_triangle():
+ pos = torch.tensor(
+ [
+ [
+ [-0.8, -0.7, 0.2, 1.0],
+ [0.9, -0.6, 0.5, 1.4],
+ [0.1, 0.8, -0.3, 1.2],
+ [-0.7, -0.33, -0.5, 1.0],
+ [0.1, 0.07, -0.5, 1.0],
+ [0.5, 0.27, -0.5, 1.0],
+ ]
+ ],
+ dtype=torch.float64,
+ requires_grad=True,
+ )
+ tri = torch.tensor([[0, 1, 2], [3, 4, 5], [3, 3, 5]], dtype=torch.int32)
+ rast, _ = reference.rasterize(pos, tri, (8, 8), True)
+ assert set(rast[..., 3].unique().tolist()) == {0.0, 1.0}
+ assert torch.autograd.gradcheck(lambda p: reference.rasterize(p, tri, (8, 8), True), (pos,))
+
+
+# Non-finite vertices
+
+
+@pytest.mark.parametrize("value", [torch.nan, torch.inf, -torch.inf])
+@pytest.mark.parametrize("coordinate", range(4))
+def test_triangles_with_non_finite_vertices_are_culled(backend, value, coordinate):
+ module, device = backend
+ resolution = (24, 24)
+ pos = torch.cat([screen_quad(0.8), screen_quad(0.5)], 1)
+ pos[0, 4:, 2] = -0.5
+ tri = torch.cat([QUAD, QUAD + 4])
+ behind = owner(backend, pos, tri[:2], resolution)
+ for vertex in (4, 5, 6):
+ broken = pos.clone()
+ broken[0, vertex, coordinate] = value
+ rast, rast_db = module.rasterize(broken.to(device), tri.to(device), resolution, True)
+ assert torch.isfinite(rast).all() and torch.isfinite(rast_db).all()
+ ids = rast[..., 3].long().cpu() - 1
+ # Vertex 5 is part of triangle 2 only, so triangle 3 stays; the others are in both.
+ intact = ids == 3
+ assert intact.any() == (vertex == 5)
+ assert torch.equal(ids[~intact], behind[~intact])
+
+
+@pytest.mark.gpu
+def test_non_finite_triangles_are_not_binned():
+ load_triton()
+ from diffrast.backends import _triton_rasterize
+
+ gen = torch.Generator().manual_seed(7)
+ pos = (torch.rand(1, 600, 4, generator=gen) * 2 - 1).cuda()
+ tri = torch.arange(600, dtype=torch.int32).view(200, 3).cuda()
+ for value in (torch.nan, torch.inf):
+ broken = pos.clone()
+ broken[0, ::3, 3] = value
+ state = _triton_rasterize.prepare(broken, tri, (128, 128))
+ _triton_rasterize.setup_stage(state)
+ assert _triton_rasterize.bin_stage(state) is None
+ assert (state.keys == _triton_rasterize.EMPTY).all()
+
+
+# Limits
+#
+# The 64-bit pixel offsets and triangle lists of the Triton tile kernel have no test: they only
+# matter from 2**31 pixels or triangle instances per call, whose buffers alone exceed 16 GiB.
+
+
+def test_batch_of_zero_gives_empty_outputs(backend):
+ module, device = backend
+ pos = torch.zeros(0, 3, 4, device=device)
+ tri = torch.tensor([[0, 1, 2]], dtype=torch.int32, device=device)
+ rast, rast_db, state = module.rasterize_layer(pos, tri, (6, 8), True, None)
+ assert rast.shape == rast_db.shape == (0, 6, 8, 4)
+ second, _, _ = module.rasterize_layer(pos, tri, (6, 8), True, state)
+ assert second.shape == (0, 6, 8, 4)
+
+
+def test_batch_of_zero_through_the_public_api(ctx):
+ pos = torch.zeros(0, 3, 4)
+ tri = torch.tensor([[0, 1, 2]], dtype=torch.int32)
+ rast, rast_db = dr.rasterize(ctx, pos, tri, (6, 8))
+ assert rast.shape == rast_db.shape == (0, 6, 8, 4)
+ with dr.DepthPeeler(ctx, pos, tri, (6, 8)) as peeler:
+ assert peeler.rasterize_next_layer()[0].shape == (0, 6, 8, 4)
+
+
+def test_more_triangles_than_float32_can_index_are_rejected(ctx, triangle):
+ pos, tri = triangle
+ limit = 1 << 24
+ assert check_rasterize_inputs(ctx, pos, tri.expand(limit, 3), (4, 4), None) == (4, 4)
+ with pytest.raises(ValueError, match=r"at most 2\*\*24"):
+ dr.rasterize(ctx, pos, tri.expand(limit + 1, 3), (4, 4))
+ with pytest.raises(ValueError, match=r"at most 2\*\*24"):
+ dr.DepthPeeler(ctx, pos, tri.expand(limit + 1, 3), (4, 4))
+
+
+@pytest.mark.gpu
+@pytest.mark.parametrize("size", [80001, 200003])
+@pytest.mark.parametrize("tall", [False, True])
+def test_very_wide_and_very_tall_images(size, tall):
+ # Two opposite sides of every quad lie exactly on pixel-centre columns, or rows of a tall
+ # image. The bounding box of a triangle has to keep them despite float32 rounding, which
+ # grows with the image size.
+ triton_backend = load_triton()
+ gen = torch.Generator().manual_seed(8)
+ first = torch.randint(0, size - 8, (3000,), generator=gen)
+ last = first + torch.randint(1, 4, (3000,), generator=gen)
+ along = torch.stack([first, last, last, first], -1).flatten()
+ across = torch.tensor([-2, -2, 4, 4]).repeat(3000)
+ resolution = (size, 2) if tall else (2, size)
+ cols, rows = (across, along) if tall else (along, across)
+ pos = lattice(cols, rows, resolution, device="cuda")
+ tri = (QUAD[None] + torch.arange(3000)[:, None, None] * 4).view(-1, 3).int().cuda()
+
+ edges = torch.zeros(size + 1)
+ edges.index_add_(0, first, torch.ones(3000)).index_add_(0, last, -torch.ones(3000))
+ expected = (edges.cumsum(0)[:size] > 0).expand(2, size)
+ rast, _ = triton_backend.rasterize(pos, tri, resolution, True)
+ covered = (rast[0, ..., 3] > 0).cpu()
+ assert torch.equal(covered.T if tall else covered, expected)
+
+
+@pytest.mark.gpu
+@pytest.mark.parametrize("resolution", [(64, 96), (100, 100)])
+def test_float64_resolve_is_accurate_to_float64(resolution, perspective_triangle):
+ # Sizes that are not powers of two, whose pixel size 2 / size is inexact in float32.
+ triton_backend = load_triton()
+ pos, tri = (t.cuda() for t in perspective_triangle)
+ ref_pos, our_pos = (pos.double().requires_grad_(True) for _ in range(2))
+ ref, ref_db = reference.rasterize(ref_pos, tri, resolution, True)
+ ours, our_db = triton_backend.rasterize(our_pos, tri, resolution, True)
+ # Visibility runs in float32 on Triton, so a pixel on the outline may differ.
+ same = ref[..., 3] == ours[..., 3]
+ assert same.float().mean() > 0.999
+ ref_db[same].square().sum().backward()
+ our_db[same].square().sum().backward()
+ for value, expected in ((ours, ref), (our_db, ref_db)):
+ torch.testing.assert_close(value[same], expected[same], rtol=1e-12, atol=1e-13)
+ torch.testing.assert_close(our_pos.grad, ref_pos.grad, rtol=1e-12, atol=1e-13)
+
+
+@pytest.mark.gpu
+def test_triton_double_backward_raises(perspective_triangle):
+ triton_backend = load_triton()
+ pos, tri = (t.cuda() for t in perspective_triangle)
+ pos.requires_grad_(True)
+ rast, _ = triton_backend.rasterize(pos, tri, (16, 16), True)
+ with pytest.raises(RuntimeError, match="no second-order gradients"):
+ torch.autograd.grad(rast[..., :3].square().sum(), pos, create_graph=True)
diff --git a/tests/test_cube.py b/tests/test_cube.py
new file mode 100644
index 0000000..dc7d405
--- /dev/null
+++ b/tests/test_cube.py
@@ -0,0 +1,819 @@
+"""Cube-map lookups, checked against a brute-force sampler written from the OpenGL face table."""
+
+import itertools
+import math
+
+import pytest
+import torch
+
+import diffrast as dr
+from diffrast import backends
+from diffrast.backends import reference
+from diffrast.ops import texture_construct_mip
+
+FILTERS = ("nearest", "linear", "linear-mipmap-nearest", "linear-mipmap-linear")
+MIP_FILTERS = FILTERS[2:]
+CORNERS = list(itertools.product((-1.0, 1.0), repeat=3))
+
+
+def face_coords(direction, face=None):
+ """``(face, s, t)`` of a direction: the major-axis table of the OpenGL specification.
+
+ With ``face`` given, the direction is projected onto the plane of that face instead.
+ """
+ x, y, z = direction
+ ax, ay, az = abs(x), abs(y), abs(z)
+ if face is None:
+ if ax >= ay and ax >= az:
+ face = 0 if x > 0 else 1
+ elif ay >= az:
+ face = 2 if y > 0 else 3
+ else:
+ face = 4 if z > 0 else 5
+ sc, tc, ma = [(-z, -y, ax), (z, -y, ax), (x, z, ay), (x, -z, ay), (x, -y, az), (-x, -y, az)][
+ face
+ ]
+ return face, (sc / ma + 1) / 2, (tc / ma + 1) / 2
+
+
+def face_direction(face, s, t):
+ """A direction that projects to ``(s, t)`` on ``face``; the inverse of the table."""
+ sc, tc = 2 * s - 1, 2 * t - 1
+ return [
+ (1.0, -tc, -sc),
+ (-1.0, -tc, sc),
+ (sc, 1.0, tc),
+ (sc, -1.0, -tc),
+ (sc, -tc, 1.0),
+ (-sc, -tc, -1.0),
+ ][face]
+
+
+def texel(tex, face, row, col):
+ """Texel of a ``[6, size, size, channels]`` map, continued across one edge.
+
+ A texel one step outside a face is looked up by projecting its centre back onto the cube.
+ Returns ``None`` beyond a corner, where no face continues.
+ """
+ size = tex.shape[1]
+ inside_row, inside_col = 0 <= row < size, 0 <= col < size
+ if not inside_row and not inside_col:
+ return None
+ if not (inside_row and inside_col):
+ centre = face_direction(face, (col + 0.5) / size, (row + 0.5) / size)
+ face, s, t = face_coords(centre)
+ row, col = min(int(t * size), size - 1), min(int(s * size), size - 1)
+ return tex[face, row, col]
+
+
+def brute_nearest(tex, direction):
+ size = tex.shape[1]
+ face, s, t = face_coords(direction)
+ return tex[face, min(int(t * size), size - 1), min(int(s * size), size - 1)]
+
+
+def brute_linear(tex, direction):
+ """Seamless bilinear lookup; a tap missing beyond a corner is the mean of the other three."""
+ size = tex.shape[1]
+ face, s, t = face_coords(direction)
+ x, y = s * size - 0.5, t * size - 0.5
+ x0, y0 = math.floor(x), math.floor(y)
+ fx, fy = x - x0, y - y0
+ taps = [
+ (texel(tex, face, y0 + j, x0 + i), (fx if i else 1 - fx) * (fy if j else 1 - fy))
+ for j in (0, 1)
+ for i in (0, 1)
+ ]
+ present = [value for value, _ in taps if value is not None]
+ fill = sum(present) / len(present)
+ return sum((fill if value is None else value) * weight for value, weight in taps)
+
+
+def brute_level_of_detail(direction, derivs, size, step=1e-5):
+ """Level of detail from finite differences of the face coordinates along screen x and y."""
+ face = face_coords(direction)[0]
+ longest = 0.0
+ for axis in (0, 1):
+ ahead = [d + step * da[axis] for d, da in zip(direction, derivs, strict=True)]
+ behind = [d - step * da[axis] for d, da in zip(direction, derivs, strict=True)]
+ _, s1, t1 = face_coords(ahead, face)
+ _, s0, t0 = face_coords(behind, face)
+ longest = max(longest, math.hypot(s1 - s0, t1 - t0) * size / (2 * step))
+ return math.log2(longest)
+
+
+def brute_lods(dirs, uv_da, size):
+ return torch.tensor(
+ [
+ brute_level_of_detail(d, da, size)
+ for d, da in zip(
+ dirs.detach().view(-1, 3).tolist(),
+ uv_da.detach().view(-1, 3, 2).tolist(),
+ strict=True,
+ )
+ ],
+ dtype=torch.float64,
+ )
+
+
+def box_levels(tex):
+ """Mip levels of a ``[6, size, size, channels]`` map with a power-of-two size."""
+ levels = [tex]
+ while levels[-1].shape[1] > 1:
+ half = levels[-1].shape[1] // 2
+ levels.append(levels[-1].view(6, half, 2, half, 2, -1).mean((2, 4)))
+ return levels
+
+
+def brute_mipmapped(levels, direction, lod, blend):
+ lod = min(max(lod, 0.0), len(levels) - 1.0)
+ if not blend:
+ return brute_linear(levels[math.floor(lod + 0.5)], direction)
+ lower = min(math.floor(lod), len(levels) - 2) if len(levels) > 1 else 0
+ upper = min(lower + 1, len(levels) - 1)
+ frac = lod - lower
+ return (1 - frac) * brute_linear(levels[lower], direction) + frac * brute_linear(
+ levels[upper], direction
+ )
+
+
+def random_cube(size, channels=2, batch=1, seed=0, dtype=torch.float64):
+ gen = torch.Generator().manual_seed(seed)
+ return torch.randn(batch, 6, size, size, channels, generator=gen, dtype=dtype)
+
+
+def random_directions(count, seed=0, dtype=torch.float64):
+ """Unnormalised directions: half anywhere, half close to the edges and corners of the cube."""
+ gen = torch.Generator().manual_seed(seed)
+ anywhere = torch.randn(count // 2, 3, generator=gen, dtype=dtype)
+ anywhere = anywhere * (torch.rand(count // 2, 1, generator=gen, dtype=dtype) * 5 + 0.1)
+ near = torch.randint(0, 2, (count - count // 2, 3), generator=gen).to(dtype) * 2 - 1
+ near = near + 0.2 * torch.randn(near.shape, generator=gen, dtype=dtype)
+ near[::2, 0] *= torch.rand(near[::2].shape[0], generator=gen, dtype=dtype)
+ return torch.cat([anywhere, near]).view(1, 1, count, 3)
+
+
+def sample(tex, dirs, filter_mode="linear", uv_da=None, **kwargs):
+ """The reference backend, which also accepts float64."""
+ kwargs.setdefault("max_mip_level", None)
+ return reference.texture(
+ tex, dirs, uv_da, filter_mode, "cube", kwargs.pop("max_mip_level"), **kwargs
+ )
+
+
+def edge_points(steps=(-0.97, -0.5, 0.0, 0.3, 0.8, 0.999)):
+ """Points on the twelve edges of the cube, each with the axis whose face it leaves."""
+ points = []
+ for a, b in ((0, 1), (0, 2), (1, 2)):
+ free = 3 - a - b
+ for sign_a, sign_b, along in itertools.product((-1.0, 1.0), (-1.0, 1.0), steps):
+ point = [0.0, 0.0, 0.0]
+ point[a], point[b], point[free] = sign_a, sign_b, along
+ points.append((point, a))
+ return points
+
+
+@pytest.mark.parametrize("filter_mode", FILTERS)
+def test_constant_map_returns_the_constant(filter_mode):
+ tex = torch.full((1, 6, 8, 8, 3), 0.375)
+ dirs = random_directions(200, dtype=torch.float32)
+ uv_da = torch.randn(1, 1, 200, 6, generator=torch.Generator().manual_seed(1))
+ out = dr.texture(
+ tex,
+ dirs,
+ uv_da if "mipmap" in filter_mode else None,
+ filter_mode=filter_mode,
+ boundary_mode="cube",
+ )
+ torch.testing.assert_close(out, torch.full_like(out, 0.375), atol=1e-6, rtol=1e-6)
+
+
+@pytest.mark.parametrize("filter_mode", ["nearest", "linear"])
+def test_axis_directions_return_face_centres(filter_mode):
+ tex = random_cube(5, dtype=torch.float32)
+ axes = [(1, 0, 0), (-1, 0, 0), (0, 1, 0), (0, -1, 0), (0, 0, 1), (0, 0, -1)]
+ dirs = torch.tensor(axes, dtype=torch.float32).view(1, 1, 6, 3) * 2.5
+ out = dr.texture(tex, dirs, filter_mode=filter_mode, boundary_mode="cube")
+ torch.testing.assert_close(out[0, 0], tex[0, :, 2, 2])
+
+
+@pytest.mark.parametrize("filter_mode", ["nearest", "linear"])
+@pytest.mark.parametrize("size", [1, 4, 7])
+def test_face_orientation_texel_by_texel(filter_mode, size):
+ tex = random_cube(size, dtype=torch.float32)
+ centres = [
+ face_direction(face, (col + 0.5) / size, (row + 0.5) / size)
+ for face, row, col in itertools.product(range(6), range(size), range(size))
+ ]
+ dirs = torch.tensor(centres, dtype=torch.float32).view(1, 6, size * size, 3) * 0.3
+ out = dr.texture(tex, dirs, filter_mode=filter_mode, boundary_mode="cube")
+ torch.testing.assert_close(out.view(tex.shape), tex, atol=1e-5, rtol=1e-5)
+
+
+def test_faces_are_ordered_and_oriented_as_in_opengl():
+ # Spot checks written out by hand: on +x, s runs towards -z and t towards -y.
+ tex = torch.arange(6 * 4 * 4, dtype=torch.float32).view(1, 6, 4, 4, 1)
+ dirs = torch.tensor(
+ [[1.0, 0.75, 0.75], [1.0, -0.75, -0.75], [-0.25, 1.0, 0.75], [0.25, 0.75, -1.0]]
+ ).view(1, 1, 4, 3)
+ out = dr.texture(tex, dirs, filter_mode="nearest", boundary_mode="cube")
+ expected = [tex[0, 0, 0, 0], tex[0, 0, 3, 3], tex[0, 2, 3, 1], tex[0, 5, 0, 1]]
+ assert out.flatten().tolist() == [value.item() for value in expected]
+
+
+@pytest.mark.parametrize("filter_mode", ["nearest", "linear"])
+@pytest.mark.parametrize("size", [1, 2, 5, 8])
+def test_matches_brute_force(filter_mode, size):
+ tex = random_cube(size)
+ dirs = random_directions(600)
+ out = sample(tex, dirs, filter_mode)
+ brute = brute_nearest if filter_mode == "nearest" else brute_linear
+ expected = torch.stack([brute(tex[0], d) for d in dirs[0, 0].tolist()])
+ torch.testing.assert_close(out[0, 0], expected, atol=1e-12, rtol=1e-12)
+
+
+@pytest.mark.parametrize("size", [1, 3, 8])
+def test_continuous_across_every_edge(size):
+ # Any map is continuous under bilinear filtering, not only a smooth one, so a random map
+ # and a tiny step make the test strict.
+ tex = random_cube(size, seed=2)
+ step = 1e-9
+ inside, outside = [], []
+ for point, axis in edge_points():
+ nudged = list(point)
+ nudged[axis] *= 1 + step
+ inside.append(nudged)
+ nudged = list(point)
+ nudged[axis] *= 1 - step
+ outside.append(nudged)
+ dirs = torch.tensor([inside, outside], dtype=torch.float64).view(1, 2, -1, 3)
+ faces = [face_coords(d)[0] for d in dirs.view(-1, 3).tolist()]
+ half = len(faces) // 2
+ assert all(a != b for a, b in zip(faces[:half], faces[half:], strict=True))
+ out = sample(tex, dirs)
+ torch.testing.assert_close(out[0, 0], out[0, 1], atol=1e-6, rtol=0)
+
+
+@pytest.mark.parametrize("filter_mode", MIP_FILTERS)
+@pytest.mark.parametrize("level", [0.0, 1.3, 2.0])
+def test_mip_levels_are_continuous_across_every_edge(filter_mode, level):
+ # With the level set by a bias it is the same on both sides of an edge, and every level is
+ # filtered across the edge like the base level. A level derived from uv_da is the footprint
+ # on one face, which is not the same on the next.
+ tex = random_cube(8, seed=49)
+ step = 1e-9
+ sides = []
+ for scale in (1 + step, 1 - step):
+ nudged = [list(point) for point, _ in edge_points()]
+ for direction, (_, axis) in zip(nudged, edge_points(), strict=True):
+ direction[axis] *= scale
+ sides.append(nudged)
+ dirs = torch.tensor(sides, dtype=torch.float64).view(1, 2, -1, 3)
+ bias = torch.full(dirs.shape[:3], level, dtype=torch.float64)
+ out = sample(tex, dirs, filter_mode, mip_level_bias=bias)
+ torch.testing.assert_close(out[0, 0], out[0, 1], atol=1e-6, rtol=0)
+
+
+@pytest.mark.parametrize("size", [1, 3, 8])
+def test_continuous_around_every_corner(size):
+ tex = random_cube(size, seed=3)
+ step = 1e-9
+ dirs = []
+ for corner in CORNERS:
+ for axis in range(3):
+ nudged = [c * (1 - step) for c in corner]
+ nudged[axis] = corner[axis]
+ dirs.append(nudged)
+ dirs = torch.tensor(dirs, dtype=torch.float64).view(1, 8, 3, 3)
+ faces = [face_coords(d)[0] for d in dirs.view(-1, 3).tolist()]
+ assert all(len(set(faces[i : i + 3])) == 3 for i in range(0, 24, 3))
+ out = sample(tex, dirs)
+ torch.testing.assert_close(out[0, :, 0], out[0, :, 1], atol=1e-6, rtol=0)
+ torch.testing.assert_close(out[0, :, 0], out[0, :, 2], atol=1e-6, rtol=0)
+
+
+def test_corner_direction_is_the_mean_of_the_three_corner_texels():
+ size = 4
+ tex = random_cube(size, seed=4)
+ dirs = torch.tensor(CORNERS, dtype=torch.float64).view(1, 1, 8, 3)
+ out = sample(tex, dirs)
+ for index, corner in enumerate(CORNERS):
+ texels = []
+ for axis in range(3):
+ # Step just inside each of the three faces that meet at the corner.
+ inner = [c * 0.999 for c in corner]
+ inner[axis] = corner[axis]
+ texels.append(brute_nearest(tex[0], inner))
+ torch.testing.assert_close(out[0, 0, index], sum(texels) / 3)
+
+
+@pytest.mark.parametrize("filter_mode", MIP_FILTERS)
+@pytest.mark.parametrize("with_bias", [False, True])
+def test_mipmapped_matches_brute_force(filter_mode, with_bias):
+ size, count = 8, 300
+ tex = random_cube(size, seed=5)
+ dirs = random_directions(count, seed=6)
+ gen = torch.Generator().manual_seed(7)
+ scale = 10 ** (torch.rand(1, 1, count, 1, generator=gen, dtype=torch.float64) * 2 - 1.5)
+ uv_da = torch.randn(1, 1, count, 6, generator=gen, dtype=torch.float64) * scale
+ uv_da = uv_da * dirs.abs().amax(-1, keepdim=True)
+ bias = torch.rand(1, 1, count, generator=gen, dtype=torch.float64) * 3 - 1.5
+ out = sample(tex, dirs, filter_mode, uv_da, mip_level_bias=bias if with_bias else None)
+
+ levels = box_levels(tex[0])
+ expected, lods = [], []
+ for i, direction in enumerate(dirs[0, 0].tolist()):
+ lod = brute_level_of_detail(direction, uv_da[0, 0, i].view(3, 2).tolist(), size)
+ lod += bias[0, 0, i].item() if with_bias else 0.0
+ # Where the level is rounded, a lookup at the rounding point may go either way.
+ close_call = filter_mode == "linear-mipmap-nearest" and abs(lod % 1 - 0.5) < 1e-6
+ lods.append(lod)
+ blend = filter_mode == "linear-mipmap-linear"
+ expected.append(
+ out[0, 0, i] if close_call else brute_mipmapped(levels, direction, lod, blend)
+ )
+ assert min(lods) < 0 and max(lods) > 3 and sum(0 < lod < 3 for lod in lods) > count // 3
+ torch.testing.assert_close(out[0, 0], torch.stack(expected), atol=1e-7, rtol=1e-7)
+
+
+@pytest.mark.parametrize("scale", [1.0, 0.01, 300.0])
+def test_footprint_of_four_texels_uses_level_two(scale):
+ # At the centre of +z, s = (x / z + 1) / 2, so a footprint of four of the sixteen texels
+ # along a face takes a step of 8 / 16 in x / z per pixel.
+ size = 16
+ tex = random_cube(size, seed=8)
+ dirs = torch.tensor([0.0, 0.0, 1.0], dtype=torch.float64).view(1, 1, 1, 3) * scale
+ uv_da = torch.tensor([0.5, 0.0, 0.0, 0.5, 0.0, 0.0], dtype=torch.float64).view(1, 1, 1, 6)
+ out = sample(tex, dirs, "linear-mipmap-linear", uv_da * scale)
+ # The centre of level two is the mean of its four middle texels: the middle 8 x 8 texels.
+ torch.testing.assert_close(out[0, 0, 0], tex[0, 4, 4:12, 4:12].mean((0, 1)))
+ by_bias = sample(tex, dirs, "linear-mipmap-linear", mip_level_bias=torch.full((1, 1, 1), 2.0))
+ torch.testing.assert_close(out, by_bias.to(out.dtype))
+
+
+def test_max_mip_level_and_bias():
+ tex = random_cube(8, seed=9, dtype=torch.float32)
+ dirs = random_directions(60, dtype=torch.float32)
+ far = torch.full((1, 1, 60), 9.0)
+ kwargs = {"boundary_mode": "cube"}
+ coarsest = dr.texture(tex, dirs, mip_level_bias=far, **kwargs)
+ one_texel_faces = box_levels(tex[0])[-1]
+ expected = torch.stack([brute_linear(one_texel_faces, d) for d in dirs[0, 0].tolist()])
+ torch.testing.assert_close(coarsest[0, 0], expected)
+ limited = dr.texture(tex, dirs, mip_level_bias=far, max_mip_level=1, **kwargs)
+ level_one = dr.texture(tex, dirs, mip_level_bias=torch.full((1, 1, 60), 1.0), **kwargs)
+ assert torch.equal(limited, level_one)
+ disabled = dr.texture(tex, dirs, mip_level_bias=far, max_mip_level=0, **kwargs)
+ assert torch.equal(disabled, dr.texture(tex, dirs, **kwargs))
+
+
+class TestMipStacks:
+ def lookup(self, tex, **kwargs):
+ dirs = random_directions(80, seed=10, dtype=torch.float32)
+ gen = torch.Generator().manual_seed(11)
+ uv_da = torch.randn(1, 1, 80, 6, generator=gen) * 0.3
+ return dr.texture(tex, dirs, uv_da, boundary_mode="cube", **kwargs)
+
+ @pytest.mark.parametrize("size", [8, 6, 5])
+ def test_constructed_stack_matches_building_internally(self, size):
+ tex = random_cube(size, batch=1, seed=12, dtype=torch.float32)
+ mip = texture_construct_mip(tex, cube_mode=True)
+ assert [level.shape[2] for level in mip.levels][:2] == [(size + 1) // 2, (size + 3) // 4]
+ assert all(level.shape[:2] == (1, 6) for level in mip.levels)
+ assert torch.equal(self.lookup(tex, mip=mip), self.lookup(tex))
+ short = texture_construct_mip(tex, max_mip_level=1, cube_mode=True)
+ assert torch.equal(self.lookup(tex, mip=short), self.lookup(tex, max_mip_level=1))
+
+ def test_faces_are_filtered_one_by_one(self):
+ tex = random_cube(8, seed=13, dtype=torch.float32)
+ levels = texture_construct_mip(tex, cube_mode=True).levels
+ for level, expected in zip(levels, box_levels(tex[0])[1:], strict=True):
+ torch.testing.assert_close(level[0], expected)
+
+ def test_custom_list_of_the_same_levels(self):
+ tex = random_cube(8, seed=14, dtype=torch.float32)
+ levels = [level[None] for level in box_levels(tex[0])[1:]]
+ torch.testing.assert_close(self.lookup(tex, mip=levels), self.lookup(tex))
+ torch.testing.assert_close(
+ self.lookup(tex, mip=levels[:1]), self.lookup(tex, max_mip_level=1)
+ )
+
+ def test_prefiltered_specular_lookup_as_in_pipelines(self):
+ # A list of independently trained cube maps, one per roughness, selected by a bias.
+ gen = torch.Generator().manual_seed(15)
+ spec = [
+ torch.rand(16 >> i, 16 >> i, 6, 3, generator=gen).permute(2, 0, 1, 3) for i in range(4)
+ ]
+ spec = [level.contiguous().requires_grad_() for level in spec]
+ dirs = random_directions(2 * 5 * 7, seed=16, dtype=torch.float32).view(2, 5, 7, 3)
+ bias = torch.rand(2, 5, 7, generator=gen) * 3
+ out = dr.texture(
+ spec[0][None],
+ dirs,
+ mip=[level[None] for level in spec[1:]],
+ mip_level_bias=bias,
+ filter_mode="linear-mipmap-linear",
+ boundary_mode="cube",
+ )
+ assert out.shape == (2, 5, 7, 3)
+ out.sum().backward()
+ assert all(level.grad.abs().sum() > 0 for level in spec)
+ expected = [
+ brute_mipmapped([lv.detach().double() for lv in spec], d, b, True)
+ for d, b in zip(dirs.view(-1, 3).tolist(), bias.flatten().tolist(), strict=True)
+ ]
+ expected = torch.stack(expected).view(2, 5, 7, 3).float()
+ torch.testing.assert_close(out.detach(), expected, atol=1e-5, rtol=1e-5)
+
+ def test_environment_lookup_as_in_pipelines(self):
+ cubemap = random_cube(8, channels=3, seed=17, dtype=torch.float32)[0]
+ dirs = random_directions(64, seed=18, dtype=torch.float32).view(8, 8, 3)
+ plain = dr.texture(cubemap[None], dirs[None], boundary_mode="cube")
+ linear = dr.texture(
+ cubemap[None] * 0.25,
+ dirs[None].contiguous(),
+ filter_mode="linear",
+ boundary_mode="cube",
+ )
+ assert plain.shape == (1, 8, 8, 3)
+ torch.testing.assert_close(linear, plain * 0.25)
+
+
+class TestGradients:
+ def inputs(self, seed, size=4, level_offset=(0.25, 0.75)):
+ """Inputs whose level of detail is a whole level in 0 to 2 plus ``level_offset``.
+
+ That keeps it away from the levels where the lookup has a kink or a jump.
+ """
+ gen = torch.Generator().manual_seed(seed)
+ tex = torch.randn(1, 6, size, size, 2, generator=gen, dtype=torch.float64)
+ dirs = random_directions(12, seed=seed).view(1, 3, 4, 3)
+ length = dirs.abs().amax(-1, keepdim=True)
+ uv_da = (torch.rand(1, 3, 4, 6, generator=gen, dtype=torch.float64) * 0.4 + 0.2) * length
+ low, high = level_offset
+ offset = torch.rand(1, 3, 4, generator=gen, dtype=torch.float64) * (high - low) + low
+ level = torch.randint(0, 3, (1, 3, 4), generator=gen) + offset
+ bias = level - brute_lods(dirs, uv_da, size).view(1, 3, 4)
+ return [t.requires_grad_() for t in (tex, dirs, uv_da, bias)]
+
+ def test_linear(self):
+ tex, dirs, _, _ = self.inputs(19)
+ assert torch.autograd.gradcheck(lambda t, d: sample(t, d), (tex, dirs))
+
+ def test_nearest_texture_gradient(self):
+ tex, dirs, _, _ = self.inputs(20)
+ assert torch.autograd.gradcheck(lambda t: sample(t, dirs.detach(), "nearest"), (tex,))
+
+ @pytest.mark.parametrize("seed", [21, 22])
+ def test_trilinear(self, seed):
+ tex, dirs, uv_da, bias = self.inputs(seed, size=8)
+ assert torch.autograd.gradcheck(
+ lambda t, d, a, b: sample(t, d, "linear-mipmap-linear", a, mip_level_bias=b),
+ (tex, dirs, uv_da, bias),
+ )
+
+ def test_mipmap_nearest(self):
+ tex, dirs, uv_da, bias = self.inputs(23, size=8, level_offset=(0.6, 1.4))
+ uv_da, bias = uv_da.detach(), bias.detach()
+ assert torch.autograd.gradcheck(
+ lambda t, d: sample(t, d, "linear-mipmap-nearest", uv_da, mip_level_bias=bias),
+ (tex, dirs),
+ )
+
+ def test_custom_mip_levels(self):
+ tex, dirs, _, _ = self.inputs(24)
+ level = random_cube(2, seed=25).requires_grad_()
+ gen = torch.Generator().manual_seed(46)
+ bias = (
+ torch.rand(1, 3, 4, generator=gen, dtype=torch.float64) * 0.5 + 0.25
+ ).requires_grad_()
+ assert torch.autograd.gradcheck(
+ lambda t, m, d, b: sample(t, d, "linear-mipmap-linear", mip_level_bias=b, mip=[m]),
+ (tex, level, dirs, bias),
+ )
+
+ def test_constructed_stack_carries_gradients_to_the_texture(self):
+ tex = random_cube(8, seed=26, dtype=torch.float32).requires_grad_()
+ dirs = random_directions(40, seed=27, dtype=torch.float32)
+ bias = torch.rand(1, 1, 40, generator=torch.Generator().manual_seed(28)) * 3
+ kwargs = {"mip_level_bias": bias, "boundary_mode": "cube"}
+ (expected,) = torch.autograd.grad(dr.texture(tex, dirs, **kwargs).sum(), tex)
+ mip = texture_construct_mip(tex, cube_mode=True)
+ (grad,) = torch.autograd.grad(dr.texture(tex, dirs, mip=mip, **kwargs).sum(), tex)
+ torch.testing.assert_close(grad, expected)
+
+
+class TestInvalidDirections:
+ BAD = (
+ (0.0, 0.0, 0.0),
+ (float("nan"), 1.0, 0.0),
+ (float("inf"), 0.0, 1.0),
+ (1.0, -float("inf"), 2.0),
+ )
+
+ @pytest.mark.parametrize("filter_mode", FILTERS)
+ def test_zeros_and_no_gradient(self, filter_mode):
+ tex = random_cube(4, seed=29, dtype=torch.float32).abs() + 1
+ good = random_directions(4, seed=30, dtype=torch.float32).view(4, 3)
+ dirs = torch.cat([torch.tensor(self.BAD), good]).view(1, 2, 4, 3)
+ uv_da = torch.randn(1, 2, 4, 6, generator=torch.Generator().manual_seed(31)) * 0.2
+ for leaf in (tex, dirs, uv_da):
+ leaf.requires_grad_()
+ mip = "mipmap" in filter_mode
+ out = dr.texture(
+ tex, dirs, uv_da if mip else None, filter_mode=filter_mode, boundary_mode="cube"
+ )
+ assert (out[0, 0] == 0).all()
+ assert (out[0, 1] > 0.99).all()
+
+ out[0, 0].sum().backward(retain_graph=True)
+ assert (tex.grad == 0).all()
+ assert dirs.grad is None or (dirs.grad == 0).all()
+ assert uv_da.grad is None or (uv_da.grad == 0).all()
+ out.sum().backward()
+ assert tex.grad.abs().sum() > 0
+ for grad in (tex.grad, dirs.grad, uv_da.grad):
+ assert grad is None or torch.isfinite(grad).all()
+ assert dirs.grad is None or (dirs.grad[0, 0] == 0).all()
+
+ def lookup_with_derivatives(self, first, filter_mode="linear-mipmap-linear", bias=None):
+ """Four valid directions; the first has the derivatives ``first``, the others 0.05."""
+ tex = random_cube(8, seed=32, dtype=torch.float32)
+ dirs = torch.tensor(
+ [[0.2, 0.3, 1.0], [1.0, 0.1, -0.4], [-0.3, 1.0, 0.2], [0.1, -0.2, -1.0]]
+ ).view(1, 1, 4, 3)
+ uv_da = torch.full((1, 1, 4, 6), 0.05)
+ uv_da[0, 0, 0] = torch.tensor(first)
+ leaves = [t.requires_grad_() for t in (tex, dirs, uv_da)]
+ out = dr.texture(
+ *leaves, mip_level_bias=bias, filter_mode=filter_mode, boundary_mode="cube"
+ )
+ weights = torch.randn(out.shape, generator=torch.Generator().manual_seed(47))
+ grads = torch.autograd.grad((out * weights).nansum(), leaves, allow_unused=True)
+ return out, [
+ torch.zeros_like(t) if g is None else g for g, t in zip(grads, leaves, strict=True)
+ ]
+
+ @pytest.mark.parametrize("filter_mode", MIP_FILTERS)
+ @pytest.mark.parametrize("component", range(6))
+ def test_nan_derivatives_of_a_valid_direction_give_nan_and_no_gradient(
+ self, filter_mode, component
+ ):
+ first = [0.05] * 6
+ first[component] = float("nan")
+ out, (grad_tex, grad_dirs, grad_da) = self.lookup_with_derivatives(first, filter_mode)
+ assert out[0, 0, 0].isnan().all() and not out[0, 0, 1:].isnan().any()
+ for grad in (grad_tex, grad_dirs, grad_da):
+ assert torch.isfinite(grad).all()
+ assert (grad_dirs[0, 0, 0] == 0).all() and (grad_da[0, 0, 0] == 0).all()
+ assert grad_dirs[0, 0, 1:].abs().sum() > 0 and grad_tex.abs().sum() > 0
+
+ def test_nan_bias_gives_nan_and_no_gradient(self):
+ bias = torch.tensor([float("nan"), 0.5, 0.5, 0.5]).view(1, 1, 4)
+ out, grads = self.lookup_with_derivatives([0.05] * 6, bias=bias)
+ assert out[0, 0, 0].isnan().all() and not out[0, 0, 1:].isnan().any()
+ assert all(torch.isfinite(grad).all() for grad in grads)
+ assert (grads[1][0, 0, 0] == 0).all()
+
+ @pytest.mark.parametrize(
+ "first",
+ [
+ [float("inf"), 0.0, 0.0, 0.0, 0.0, 0.0],
+ [0.0, 0.0, 0.0, -float("inf"), 0.0, 0.0],
+ [float("inf")] * 6,
+ [float("inf"), -float("inf")] * 3,
+ [3e38, 3e38, -3e38, 3e38, 3e38, 3e38],
+ [1e30, 0.0, 0.0, 0.0, 0.0, 0.0],
+ ],
+ )
+ def test_huge_derivatives_select_the_coarsest_level(self, first):
+ out, (grad_tex, grad_dirs, grad_da) = self.lookup_with_derivatives(first)
+ far = torch.full((1, 1, 4), 50.0)
+ coarsest, (_, coarsest_grad_dirs, _) = self.lookup_with_derivatives([0.05] * 6, bias=far)
+ torch.testing.assert_close(out[0, 0, 0], coarsest[0, 0, 0])
+ for grad in (grad_tex, grad_dirs, grad_da):
+ assert torch.isfinite(grad).all()
+ assert (grad_da[0, 0, 0] == 0).all()
+ torch.testing.assert_close(grad_dirs[0, 0, 0], coarsest_grad_dirs[0, 0, 0])
+ assert grad_dirs[0, 0, 0].abs().sum() > 0
+
+
+class TestDirectionLength:
+ """Only the direction of ``uv`` matters, whatever its length."""
+
+ DIRECTION = (0.375, -1.0, 0.625)
+
+ def lookup(self, length, filter_mode="linear"):
+ tex = random_cube(4, seed=48, dtype=torch.float32)
+ dirs = (torch.tensor(self.DIRECTION) * length).view(1, 1, 1, 3).requires_grad_()
+ uv_da = torch.tensor([0.9, 0.3, -0.6, 0.75, 0.45, -0.3]).view(1, 1, 1, 6) * length
+ mip = "mipmap" in filter_mode
+ out = dr.texture(
+ tex, dirs, uv_da if mip else None, filter_mode=filter_mode, boundary_mode="cube"
+ )
+ (grad,) = torch.autograd.grad(out.sum(), dirs)
+ return out, grad
+
+ @pytest.mark.parametrize("filter_mode", ["linear", "linear-mipmap-linear"])
+ @pytest.mark.parametrize("length", [2.0**-120, 1e-30, 1e-20, 1e-6, 1e6, 1e20, 1e30])
+ def test_value_and_gradient_at_any_length(self, filter_mode, length):
+ expected, expected_grad = self.lookup(1.0, filter_mode)
+ out, grad = self.lookup(length, filter_mode)
+ torch.testing.assert_close(out, expected, atol=1e-6, rtol=1e-5)
+ assert expected_grad.abs().sum() > 0
+ torch.testing.assert_close(grad * length, expected_grad, atol=1e-5, rtol=1e-4)
+
+ @pytest.mark.parametrize("filter_mode", ["linear", "linear-mipmap-linear"])
+ @pytest.mark.parametrize("length", [2.0**-127, 2.0**-130, 2.0**-146])
+ def test_subnormal_length_counts_as_the_zero_vector(self, filter_mode, length):
+ # A subnormal vector has lost the bits that give it a direction, and the gradient of a
+ # lookup, which grows with the reciprocal of the length, would overflow.
+ out, grad = self.lookup(length, filter_mode)
+ assert (out == 0).all() and (grad == 0).all()
+ out, grad = self.lookup(2.0**-126, filter_mode)
+ torch.testing.assert_close(out, self.lookup(1.0, filter_mode)[0], atol=1e-6, rtol=1e-5)
+ assert not grad.isnan().any() and grad.abs().sum() > 0
+
+
+class TestBatches:
+ def test_shared_map_matches_per_view_maps(self):
+ tex = random_cube(4, seed=33, dtype=torch.float32)
+ dirs = random_directions(36, seed=34, dtype=torch.float32).view(3, 3, 4, 3)
+ shared = dr.texture(tex, dirs, boundary_mode="cube")
+ per_view = dr.texture(
+ tex.expand(3, -1, -1, -1, -1).contiguous(), dirs, boundary_mode="cube"
+ )
+ assert torch.equal(shared, per_view)
+
+ @pytest.mark.parametrize("filter_mode", FILTERS)
+ def test_per_view_maps_are_independent(self, filter_mode):
+ tex = random_cube(4, batch=3, seed=35, dtype=torch.float32)
+ dirs = random_directions(36, seed=36, dtype=torch.float32).view(3, 3, 4, 3)
+ bias = torch.rand(3, 3, 4, generator=torch.Generator().manual_seed(37)) * 2
+ kwargs = {"filter_mode": filter_mode, "boundary_mode": "cube"}
+ if "mipmap" in filter_mode:
+ kwargs["mip_level_bias"] = bias
+ out = dr.texture(tex, dirs, **kwargs)
+ for view in range(3):
+ if "mipmap" in filter_mode:
+ kwargs["mip_level_bias"] = bias[view : view + 1]
+ single = dr.texture(tex[view : view + 1], dirs[view : view + 1], **kwargs)
+ torch.testing.assert_close(out[view : view + 1], single)
+
+ def test_custom_level_shared_across_a_batch_of_maps(self):
+ tex = random_cube(4, batch=2, seed=38, dtype=torch.float32)
+ level = random_cube(2, seed=39, dtype=torch.float32)
+ dirs = random_directions(24, seed=40, dtype=torch.float32).view(2, 3, 4, 3)
+ kwargs = {"mip_level_bias": torch.full((2, 3, 4), 0.6), "boundary_mode": "cube"}
+ shared = dr.texture(tex, dirs, mip=[level], **kwargs)
+ repeated = dr.texture(tex, dirs, mip=[level.expand(2, -1, -1, -1, -1)], **kwargs)
+ assert torch.equal(shared, repeated)
+
+
+class TestValidation:
+ def test_cube_map_needs_the_cube_boundary_mode(self):
+ tex, dirs = torch.zeros(1, 6, 4, 4, 3), torch.zeros(1, 2, 2, 3)
+ with pytest.raises(ValueError, match=r'shape of a cube map.*boundary_mode="cube"'):
+ dr.texture(tex, dirs)
+ with pytest.raises(ValueError, match=r"shape of a cube map.*cube_mode=True"):
+ texture_construct_mip(tex)
+
+ def test_cube_boundary_mode_needs_a_cube_map(self):
+ with pytest.raises(ValueError, match="needs tex to be a cube map"):
+ dr.texture(torch.zeros(1, 4, 4, 3), torch.zeros(1, 2, 2, 3), boundary_mode="cube")
+ with pytest.raises(ValueError, match="needs tex to be a cube map"):
+ texture_construct_mip(torch.zeros(1, 4, 4, 3), cube_mode=True)
+
+ @pytest.mark.parametrize("shape", [(1, 5, 4, 4, 3), (1, 6, 4, 5, 3)])
+ def test_six_square_faces(self, shape):
+ with pytest.raises(ValueError, match="six square faces"):
+ dr.texture(torch.zeros(shape), torch.zeros(1, 2, 2, 3), boundary_mode="cube")
+
+ def test_coordinates_are_directions(self):
+ tex = torch.zeros(1, 6, 4, 4, 3)
+ with pytest.raises(ValueError, match="uv must have shape"):
+ dr.texture(tex, torch.zeros(1, 2, 2, 2), boundary_mode="cube")
+ with pytest.raises(ValueError, match="uv_da must have shape"):
+ dr.texture(tex, torch.zeros(1, 2, 2, 3), torch.zeros(1, 2, 2, 4), boundary_mode="cube")
+ with pytest.raises(ValueError, match="uv must have shape"):
+ dr.texture(torch.zeros(1, 4, 4, 3), torch.zeros(1, 2, 2, 3))
+
+ @pytest.mark.parametrize(
+ "level, match",
+ [
+ (torch.zeros(1, 2, 2, 3), "needs mip level 1 to be a cube map"),
+ (torch.zeros(1, 6, 2, 3, 3), "mip level 1 must have six square faces"),
+ (torch.zeros(1, 6, 2, 2, 1), "mip level 1 has 1 channels"),
+ (torch.zeros(2, 6, 2, 2, 3), "mip level 1 has batch size 2"),
+ ],
+ )
+ def test_mip_levels_are_cube_maps(self, level, match):
+ tex, dirs = torch.zeros(1, 6, 4, 4, 3), torch.zeros(1, 2, 2, 3)
+ with pytest.raises(ValueError, match=match):
+ dr.texture(tex, dirs, mip=[level], boundary_mode="cube")
+
+ def test_stack_of_another_kind(self):
+ tex, dirs = torch.zeros(1, 6, 4, 4, 3), torch.zeros(1, 2, 2, 3)
+ stack = texture_construct_mip(torch.zeros(1, 4, 4, 3))
+ with pytest.raises(ValueError, match="cube_mode=False"):
+ dr.texture(tex, dirs, mip=stack, boundary_mode="cube")
+
+ def test_stack_of_another_map(self):
+ dirs = torch.zeros(1, 2, 2, 3)
+ stack = texture_construct_mip(torch.zeros(1, 6, 8, 8, 3), cube_mode=True)
+ with pytest.raises(ValueError, match="constructed for a texture of shape"):
+ dr.texture(torch.zeros(1, 6, 4, 4, 3), dirs, mip=stack, boundary_mode="cube")
+
+
+@pytest.mark.gpu
+class TestDevices:
+ """Cube maps run the same PyTorch code on every device and backend."""
+
+ def scene(self):
+ tex = random_cube(8, channels=3, batch=2, seed=41, dtype=torch.float32)
+ dirs = random_directions(2 * 6 * 20, seed=42, dtype=torch.float32).view(2, 6, 20, 3)
+ dirs[0, 0, 0] = 0.0
+ gen = torch.Generator().manual_seed(43)
+ uv_da = torch.randn(2, 6, 20, 6, generator=gen) * 0.3
+ bias = torch.rand(2, 6, 20, generator=gen) * 2 - 0.5
+ return tex, dirs, uv_da, bias
+
+ def run(self, inputs, filter_mode):
+ tex, dirs, uv_da, bias = (t.clone().requires_grad_() for t in inputs)
+ mip = "mipmap" in filter_mode
+ out = dr.texture(
+ tex,
+ dirs,
+ uv_da if mip else None,
+ bias if mip else None,
+ filter_mode=filter_mode,
+ boundary_mode="cube",
+ )
+ weights = torch.randn(out.shape, generator=torch.Generator().manual_seed(44))
+ (out * weights.to(out.device)).sum().backward()
+ grads = [
+ torch.zeros_like(t) if t.grad is None else t.grad for t in (tex, dirs, uv_da, bias)
+ ]
+ return [out.detach().cpu(), *(grad.cpu() for grad in grads)]
+
+ @pytest.mark.parametrize("filter_mode", FILTERS)
+ @pytest.mark.parametrize("backend", ["auto", "triton", "reference"])
+ def test_same_on_cpu_and_gpu(self, filter_mode, backend, monkeypatch):
+ pytest.importorskip("triton")
+ inputs = self.scene()
+ monkeypatch.setattr(backends, "_selected", "reference")
+ on_cpu = self.run(inputs, filter_mode)
+ monkeypatch.setattr(backends, "_selected", backend)
+ assert dr.get_backend_name("cuda", "texture") == (
+ "reference" if backend == "reference" else "triton"
+ )
+ on_gpu = self.run([t.cuda() for t in inputs], filter_mode)
+ torch.testing.assert_close(on_gpu[0], on_cpu[0], atol=1e-5, rtol=1e-5)
+ for gpu_grad, cpu_grad in zip(on_gpu[1:], on_cpu[1:], strict=True):
+ torch.testing.assert_close(gpu_grad, cpu_grad, atol=1e-4, rtol=1e-3)
+
+ def test_set_backend_triton(self):
+ pytest.importorskip("triton")
+ tex, dirs, uv_da, _ = (t.cuda() for t in self.scene())
+ selected = backends._selected
+ try:
+ dr.set_backend("reference")
+ expected = dr.texture(tex, dirs, uv_da, boundary_mode="cube")
+ dr.set_backend("triton")
+ out = dr.texture(tex, dirs, uv_da, boundary_mode="cube")
+ mip = texture_construct_mip(tex, cube_mode=True)
+ with_stack = dr.texture(tex, dirs, uv_da, mip=mip, boundary_mode="cube")
+ finally:
+ dr.set_backend(selected)
+ assert out.device.type == "cuda"
+ assert torch.equal(out, expected)
+ assert torch.equal(with_stack, expected)
+
+ @pytest.mark.parametrize("bad", [float("nan"), float("inf"), -3e38])
+ def test_derivatives_that_are_not_finite(self, bad, monkeypatch):
+ pytest.importorskip("triton")
+ inputs = self.scene()
+ inputs[1][0, 0, 0] = 1.0
+ inputs[2][0, 0, :4, :3] = bad
+ inputs[2][0, 1, :4, 3:] = -bad
+ monkeypatch.setattr(backends, "_selected", "reference")
+ on_cpu = self.run(inputs, "linear-mipmap-linear")
+ monkeypatch.setattr(backends, "_selected", "triton")
+ on_gpu = self.run([t.cuda() for t in inputs], "linear-mipmap-linear")
+ undefined = on_cpu[0].isnan().all(-1)
+ assert undefined[0, :2, :4].all() if math.isnan(bad) else not undefined.any()
+ assert not undefined[0, 2:].any() and not undefined[1].any()
+ torch.testing.assert_close(on_gpu[0], on_cpu[0], atol=1e-5, rtol=1e-5, equal_nan=True)
+ for gpu_grad, cpu_grad in zip(on_gpu[1:], on_cpu[1:], strict=True):
+ assert torch.isfinite(cpu_grad).all()
+ torch.testing.assert_close(gpu_grad, cpu_grad, atol=1e-4, rtol=1e-3)
+
+ def test_large_lookup(self):
+ # A 512 x 512 lookup into 256 x 256 faces, all in one vectorised pass.
+ gen = torch.Generator().manual_seed(45)
+ tex = torch.rand(1, 6, 256, 256, 3, generator=gen).cuda()
+ dirs = torch.randn(1, 512, 512, 3, generator=gen).cuda()
+ uv_da = (torch.randn(1, 512, 512, 6, generator=gen) * 0.02).cuda()
+ out = dr.texture(tex, dirs, uv_da, boundary_mode="cube")
+ assert out.shape == (1, 512, 512, 3)
+ assert torch.isfinite(out).all() and 0.3 < out.mean() < 0.7
diff --git a/tests/test_input_checks.py b/tests/test_input_checks.py
new file mode 100644
index 0000000..a313cec
--- /dev/null
+++ b/tests/test_input_checks.py
@@ -0,0 +1,401 @@
+"""Vertex index validation, error messages for common mistakes and interpolate's outputs."""
+
+import pytest
+import torch
+
+import diffrast as dr
+from diffrast import backends, ops
+from diffrast._cache import TensorCache
+from diffrast.backends import reference
+
+
+@pytest.fixture(
+ params=[("cpu", "reference"), pytest.param(("cuda", "triton"), marks=pytest.mark.gpu)],
+ ids=["reference", "triton"],
+)
+def device(request):
+ """Run a test on the reference backend on the CPU and on the Triton backend on the GPU."""
+ name, backend = request.param
+ if backend == "triton":
+ pytest.importorskip("triton")
+ previous = backends._selected
+ dr.set_backend(backend)
+ yield torch.device(name)
+ backends._selected = previous
+
+
+@pytest.fixture
+def scans(monkeypatch):
+ """Count how often an index buffer is scanned for its range, starting from an empty cache."""
+ calls = []
+
+ def compute(tri):
+ calls.append(tri.shape[0])
+ return ops._index_range(tri)
+
+ monkeypatch.setattr(ops, "_index_ranges", TensorCache(compute))
+ return calls
+
+
+def scene(device="cpu", resolution=(12, 16)):
+ """Two views of two overlapping triangles, with their rasterization."""
+ pos = torch.tensor(
+ [[-0.8, -0.7, 0.3, 1.0], [0.9, -0.5, 0.2, 1.2], [-0.2, 0.8, 0.4, 1.1],
+ [-0.5, 0.6, -0.2, 1.0], [0.1, -0.9, -0.1, 1.3], [0.8, 0.7, -0.3, 0.9]],
+ device=device,
+ ) # fmt: skip
+ pos = torch.stack([pos, pos * torch.tensor([-1.0, 0.9, 1.0, 1.0], device=device)])
+ tri = torch.tensor([[0, 1, 2], [3, 4, 5]], dtype=torch.int32, device=device)
+ rast, rast_db = dr.rasterize(dr.RasterizeContext(device), pos, tri, resolution)
+ return pos, tri, rast, rast_db
+
+
+class TestVertexIndices:
+ @pytest.mark.parametrize("index", [6, 7, 1000, -1, -6])
+ def test_out_of_range_index_is_rejected(self, device, index):
+ pos, tri, rast, _ = scene(device)
+ bad = tri.clone()
+ bad[1, 2] = index
+ color = torch.zeros(2, 12, 16, 3, device=device)
+ message = rf"tri refers to vertex {index}, but valid indices are 0 to 5 for 6 vertices"
+ with pytest.raises(ValueError, match=message):
+ dr.interpolate(pos, rast, bad)
+ with pytest.raises(ValueError, match=message):
+ dr.antialias(color, rast, pos, bad)
+
+ def test_checked_against_the_attributes(self, device):
+ _, tri, rast, _ = scene(device)
+ with pytest.raises(
+ ValueError, match="tri refers to vertex 5, but valid indices are 0 to 3"
+ ):
+ dr.interpolate(torch.zeros(4, 2, device=device), rast, tri)
+ with pytest.raises(
+ ValueError, match="tri refers to vertex 5, but valid indices are 0 to 4"
+ ):
+ dr.interpolate(torch.zeros(2, 5, 2, device=device), rast, tri)
+ dr.interpolate(torch.zeros(9, 2, device=device), rast, tri)
+
+ def test_checked_against_shared_positions(self, device):
+ pos, tri, rast, _ = scene(device)
+ color = torch.zeros(2, 12, 16, 3, device=device)
+ with pytest.raises(ValueError, match="tri refers to vertex 5"):
+ dr.antialias(color, rast, pos[0, :5], tri)
+
+ def test_helper_names_the_argument(self):
+ tri = torch.tensor([[0, 1, 2], [2, 1, 3]], dtype=torch.int32)
+ ops._check_indices(tri, 4)
+ ops._check_indices(tri[:0], 0)
+ with pytest.raises(ValueError, match="uv_idx refers to vertex 3, but valid indices are 0"):
+ ops._check_indices(tri, 3, name="uv_idx")
+ with pytest.raises(
+ ValueError, match=r"tri refers to vertex 3, but there are no vertices\.$"
+ ):
+ ops._check_indices(tri, 0)
+
+ def test_range_is_found_once_per_tensor(self, scans):
+ pos, tri, rast, _ = scene()
+ color = torch.zeros(2, 12, 16, 3)
+ for _ in range(3):
+ dr.interpolate(pos, rast, tri)
+ dr.antialias(color, rast, pos, tri)
+ # The stored range serves any vertex count.
+ dr.interpolate(torch.zeros(40, 2), rast, tri)
+ with pytest.raises(ValueError, match="tri refers to vertex 5"):
+ dr.interpolate(torch.zeros(3, 2), rast, tri)
+ assert len(scans) == 1
+
+ def test_in_place_edit_is_checked_again(self, scans):
+ pos, tri, rast, _ = scene()
+ dr.interpolate(pos, rast, tri)
+ tri[0, 0] = 6
+ with pytest.raises(ValueError, match="tri refers to vertex 6"):
+ dr.interpolate(pos, rast, tri)
+ tri[:1][0, 0] = 0
+ dr.interpolate(pos, rast, tri)
+ assert len(scans) == 3
+
+ def test_equal_tensor_is_checked_separately(self, scans):
+ pos, tri, rast, _ = scene()
+ dr.interpolate(pos, rast, tri)
+ dr.interpolate(pos, rast, tri.clone())
+ assert len(scans) == 2
+
+
+class TestTriangleIdsInRast:
+ """Ids past the end of ``tri`` are treated as background instead of read out of range."""
+
+ def test_interpolate(self, device):
+ _, tri, rast, rast_db = scene(device)
+ attr = torch.rand(6, 3, generator=torch.Generator().manual_seed(0)).to(device)
+ attr.requires_grad_(True)
+ covered = rast[..., 3] > 0
+ beyond = rast.clone()
+ beyond[..., 3] += 2 * covered
+ out, out_da = dr.interpolate(attr, beyond, tri, rast_db=rast_db, diff_attrs="all")
+ (out.sum() + out_da.sum()).backward()
+
+ assert covered.any()
+ assert (out == 0).all() and (out_da == 0).all()
+ assert (attr.grad == 0).all()
+
+ def test_interpolate_keeps_ids_in_range(self, device):
+ pos, tri, rast, _ = scene(device)
+ second = rast[..., 3] == 2
+ beyond = rast.clone()
+ beyond[..., 3] += 5 * second
+ expected, _ = dr.interpolate(pos, rast, tri)
+ out, _ = dr.interpolate(pos, beyond, tri)
+ assert second.any() and (~second & (rast[..., 3] > 0)).any()
+ torch.testing.assert_close(out, expected * ~second[..., None])
+
+ def test_antialias(self, device):
+ pos, tri, rast, _ = scene(device)
+ color = torch.rand(2, 12, 16, 3, generator=torch.Generator().manual_seed(1)).to(device)
+ second = rast[..., 3] == 2
+ beyond = rast.clone()
+ beyond[..., 3] += 5 * second
+ background = rast.clone()
+ background[..., 3] *= ~second
+ p = pos.clone().requires_grad_(True)
+ out = dr.antialias(color, beyond, p, tri)
+ out.sum().backward()
+ torch.testing.assert_close(out, dr.antialias(color, background, pos, tri))
+ assert p.grad.isfinite().all()
+
+
+class TestInterpolateOutputs:
+ def test_second_output_is_empty_without_derivatives(self, device):
+ _, tri, rast, rast_db = scene(device)
+ attr = torch.rand(6, 3, device=device, requires_grad=True)
+ for kwargs in ({}, {"rast_db": rast_db}, {"rast_db": rast_db, "diff_attrs": []}):
+ out, out_da = dr.interpolate(attr, rast, tri, **kwargs)
+ assert out_da.shape == (2, 12, 16, 0)
+ assert out_da.dtype == torch.float32 and out_da.device == rast.device
+ assert not out_da.requires_grad
+ assert torch.cat([out, out_da], -1).shape == out.shape
+ out.sum().backward()
+
+ def test_second_output_is_empty_without_triangles(self, device):
+ _, tri, rast, _ = scene(device)
+ out, out_da = dr.interpolate(torch.zeros(6, 3, device=device), rast, tri[:0])
+ assert out.shape == (2, 12, 16, 3) and out_da.shape == (2, 12, 16, 0)
+
+ def test_empty_rast_db_counts_as_none(self, device):
+ pos, tri, rast, _ = scene(device)
+ empty = rast.new_zeros(2, 12, 16, 0)
+ expected, _ = dr.interpolate(pos, rast, tri)
+ out, out_da = dr.interpolate(pos, rast, tri, rast_db=empty)
+ assert torch.equal(out, expected)
+ assert out_da.shape == (2, 12, 16, 0)
+ with pytest.raises(ValueError, match="rast_db is required when diff_attrs is set, but"):
+ dr.interpolate(pos, rast, tri, rast_db=empty, diff_attrs="all")
+
+ def test_rast_db_is_checked_without_diff_attrs(self, device):
+ pos, tri, rast, rast_db = scene(device)
+ with pytest.raises(
+ ValueError, match=r"rast_db must have shape \[batch, height, width, 4\]"
+ ):
+ dr.interpolate(pos, rast, tri, rast_db=torch.zeros(3, device=device))
+ with pytest.raises(ValueError, match="rast_db must have the same shape as rast"):
+ dr.interpolate(pos, rast, tri, rast_db=rast_db[:, :6])
+ with pytest.raises(TypeError, match=r"rast_db must be torch\.float32"):
+ dr.interpolate(pos, rast, tri, rast_db=rast_db.double())
+
+ def test_unused_rast_db_is_not_differentiated(self, device):
+ _, tri, rast, rast_db = scene(device)
+ attr = torch.rand(6, 3, device=device, requires_grad=True)
+ rast_db = rast_db.clone().requires_grad_(True)
+ out, _ = dr.interpolate(attr, rast, tri, rast_db=rast_db)
+ out.sum().backward()
+ assert rast_db.grad is None and attr.grad is not None
+
+
+class TestInferenceTensors:
+ """Inputs made under ``torch.inference_mode`` work in a pass that tracks gradients."""
+
+ def inputs(self, device):
+ with torch.inference_mode():
+ pos, tri, rast, rast_db = scene(device)
+ return pos, tri, rast, rast_db
+
+ def test_interpolate(self, device):
+ _, tri, rast, rast_db = self.inputs(device)
+ normal = [t.clone() for t in (tri, rast, rast_db)]
+ grads = []
+ for tri_, rast_, rast_db_ in ((tri, rast, rast_db), normal):
+ attr = torch.ones(6, 2, device=device, requires_grad=True)
+ out, out_da = dr.interpolate(attr, rast_, tri_, rast_db=rast_db_, diff_attrs=[1])
+ (out.square().sum() + out_da.sum()).backward()
+ grads.append(attr.grad)
+ torch.testing.assert_close(grads[0], grads[1])
+ assert grads[0].abs().sum() > 0
+
+ def test_antialias(self, device):
+ pos, tri, rast, _ = self.inputs(device)
+ color = torch.rand(2, 12, 16, 3, generator=torch.Generator().manual_seed(2)).to(device)
+ grads = []
+ for tri_, rast_ in ((tri, rast), (tri.clone(), rast.clone())):
+ p = pos.clone().requires_grad_(True)
+ dr.antialias(color, rast_, p, tri_).square().sum().backward()
+ grads.append(p.grad)
+ torch.testing.assert_close(grads[0], grads[1])
+ assert grads[0].abs().sum() > 0
+
+
+class TestMessages:
+ @pytest.mark.parametrize(
+ "resolution", [8, None, 8.0, (8.0, 8.0), (8.5, 8), "88", (8, 8, 8), [[8, 8]], (8, None)]
+ )
+ def test_resolution_must_be_two_ints(self, resolution):
+ with pytest.raises(ValueError, match=r"resolution must be \(height, width\) as two ints"):
+ ops._check_resolution(resolution)
+
+ @pytest.mark.parametrize(
+ "resolution",
+ [
+ {8, 16},
+ {8: "height", 16: "width"},
+ iter([8, 16]),
+ range(8, 10),
+ (True, 8),
+ [8, False],
+ torch.tensor([True, True]),
+ torch.tensor([8.0, 16.0]),
+ torch.tensor([[8, 16]]),
+ torch.tensor(8),
+ ],
+ ids=lambda r: type(r).__name__,
+ )
+ def test_resolution_must_be_an_ordered_pair_of_ints(self, resolution):
+ with pytest.raises(ValueError, match=r"resolution must be \(height, width\) as two ints"):
+ ops._check_resolution(resolution)
+
+ def test_resolution_containers(self):
+ np = pytest.importorskip("numpy")
+ forms = ([8, 16], (8, 16), torch.Size([8, 16]), torch.tensor([8, 16]), np.array([8, 16]))
+ for resolution in (*forms, (np.int64(8), torch.tensor(16))):
+ size = ops._check_resolution(resolution)
+ assert size == (8, 16) and all(type(s) is int for s in size)
+ with pytest.raises(ValueError, match="as two ints"):
+ ops._check_resolution(np.array([8.0, 16.0]))
+
+ @pytest.mark.parametrize("resolution", [(0, 8), (8, -1), [0, 0]])
+ def test_resolution_must_be_positive(self, resolution):
+ with pytest.raises(ValueError, match="resolution must be positive"):
+ ops._check_resolution(resolution)
+
+ def test_resolution_is_checked_by_rasterize(self, ctx, triangle):
+ pos, tri = triangle
+ with pytest.raises(ValueError, match=r"resolution must be .* got 8\."):
+ dr.rasterize(ctx, pos, tri, 8)
+
+ def test_missing_batch_dimension(self, triangle):
+ pos, tri = triangle
+ with pytest.raises(
+ ValueError, match=r"rast must have shape \[batch, height, width, 4\].*rast\[None\]"
+ ):
+ dr.interpolate(pos, torch.zeros(8, 8, 4), tri)
+ expected = r"pos must have shape \[batch, vertices, 4\], got \(3, 4\); add a batch"
+ with pytest.raises(ValueError, match=expected):
+ ops._check(pos[0], "pos", ndim=3, last=4)
+ with pytest.raises(
+ ValueError, match=r"tex must have shape \[batch, tex_height.*tex\[None\]"
+ ):
+ ops._check(torch.zeros(4, 4, 3), "tex", ndim=4)
+
+ def test_layout_is_named(self, triangle):
+ pos, tri = triangle
+ rast = torch.zeros(1, 8, 8, 4)
+ with pytest.raises(ValueError, match=r"tri must have shape \[triangles, 3\], got \(1, 4\)"):
+ dr.interpolate(pos, rast, torch.zeros(1, 4, dtype=torch.int32))
+ with pytest.raises(
+ ValueError, match=r"attr must have shape \[batch, vertices, channels\] or"
+ ):
+ dr.interpolate(pos[0, 0], rast, tri)
+ with pytest.raises(
+ ValueError, match=r"rast_db must have shape \[batch, height, width, 4\]"
+ ):
+ dr.interpolate(pos, rast, tri, rast_db=rast[..., :2], diff_attrs="all")
+ with pytest.raises(ValueError, match=r"same shape as rast, got \(1, 4, 8, 4\) and"):
+ dr.interpolate(pos, rast, tri, rast_db=rast[:, :4], diff_attrs="all")
+ with pytest.raises(ValueError, match=r"color must match rast.*\(1, 4, 4, 3\) and"):
+ dr.antialias(torch.zeros(1, 4, 4, 3), rast, pos, tri)
+
+ def test_helper_falls_back_to_placeholders(self):
+ with pytest.raises(ValueError, match=r"weights must have shape \[\.\.\., \.\.\., 5\], got"):
+ ops._check(torch.zeros(2), "weights", ndim=3, last=5)
+ with pytest.raises(ValueError, match=r"uv must have shape \[\.\.\., \.\.\., \.\.\., 3\]"):
+ ops._check(torch.zeros(1, 2, 2, 2), "uv", ndim=4, last=3)
+ with pytest.raises(
+ ValueError, match=r"tex must have shape \[\.\.\., \.\.\., \.\.\., \.\.\., \.\.\.\]"
+ ):
+ ops._check(torch.zeros(1, 2, 2, 2), "tex", ndim=5)
+ with pytest.raises(ValueError, match=r"pos must have shape \[vertices, 4\], got \(3,\)\."):
+ ops._check(torch.zeros(3), "pos", ndim=2, last=4, layout="[vertices, 4]")
+
+ def test_wrong_dtype_says_how_to_convert(self, triangle):
+ pos, tri = triangle
+ rast = torch.zeros(1, 8, 8, 4)
+ with pytest.raises(
+ TypeError, match=r"tri must be torch\.int32, got torch\.int64; .*tri\.int\(\)"
+ ):
+ dr.interpolate(pos, rast, tri.long())
+ with pytest.raises(
+ TypeError, match=r"attr must be torch\.float32, got torch\.float64; .*attr\.float\(\)"
+ ):
+ dr.interpolate(pos.double(), rast, tri)
+ with pytest.raises(TypeError, match=r"pos must be torch\.float32, got torch\.int64"):
+ dr.antialias(rast, rast, pos.long(), tri)
+ with pytest.raises(TypeError, match=r"tri must be torch\.int32, got torch\.float32"):
+ dr.antialias(rast, rast, pos, tri.float())
+ # A description that is not an argument name gets no code to paste.
+ with pytest.raises(TypeError, match=r"level 1 must be torch\.float32, got torch\.int32\.$"):
+ ops._check(tri, "level 1", ndim=2, dtype=torch.float32)
+
+ def test_non_tensors(self, triangle):
+ pos, tri = triangle
+ rast = torch.zeros(1, 8, 8, 4)
+ with pytest.raises(TypeError, match=r"attr must be a torch\.Tensor, got list"):
+ dr.interpolate(pos.tolist(), rast, tri)
+ with pytest.raises(TypeError, match=r"rast_db must be a torch\.Tensor, got bool"):
+ dr.interpolate(pos, rast, tri, rast_db=True)
+ with pytest.raises(TypeError, match=r"pos must be a torch\.Tensor, got NoneType"):
+ dr.antialias(rast, rast, None, tri)
+
+ @pytest.mark.parametrize("diff_attrs", [1, 1.5, [0.5], [None]])
+ def test_diff_attrs_of_a_wrong_type(self, triangle, diff_attrs):
+ pos, tri = triangle
+ rast = torch.zeros(1, 8, 8, 4)
+ with pytest.raises(TypeError, match="diff_attrs must be a sequence of channel indices"):
+ dr.interpolate(pos, rast, tri, rast_db=rast, diff_attrs=diff_attrs)
+
+ def test_diff_attrs_misspelt(self, triangle):
+ pos, tri = triangle
+ rast = torch.zeros(1, 8, 8, 4)
+ with pytest.raises(ValueError, match="'all' or None, got 'ALL'"):
+ dr.interpolate(pos, rast, tri, rast_db=rast, diff_attrs="ALL")
+
+ def test_diff_attrs_accepts_any_integer_sequence(self, ctx, perspective_triangle):
+ pos, tri = perspective_triangle
+ rast, rast_db = dr.rasterize(ctx, pos, tri, (8, 8))
+ _, expected = dr.interpolate(pos, rast, tri, rast_db=rast_db, diff_attrs=[2, 0])
+ for diff_attrs in ((2, 0), torch.tensor([2, 0]), range(2, -1, -2)):
+ _, out_da = dr.interpolate(pos, rast, tri, rast_db=rast_db, diff_attrs=diff_attrs)
+ assert torch.equal(out_da, expected)
+
+ @pytest.mark.parametrize("boost", ["2", None, [1.0]])
+ def test_pos_gradient_boost_must_be_a_number(self, triangle, boost):
+ pos, tri = triangle
+ rast = torch.zeros(1, 8, 8, 4)
+ with pytest.raises(TypeError, match="pos_gradient_boost must be a number"):
+ dr.antialias(rast, rast, pos, tri, pos_gradient_boost=boost)
+
+
+def test_reference_antialias_returns_a_contiguous_copy(ctx, perspective_triangle):
+ pos, tri = perspective_triangle
+ rast, _ = dr.rasterize(ctx, pos, tri, (8, 8))
+ color = torch.rand(1, 8, 3, 8).permute(0, 1, 3, 2)
+ out = reference.antialias(color, rast, pos, tri, 1.0)
+ assert out.is_contiguous()
+ empty = reference.antialias(color, rast, pos, tri[:0], 1.0)
+ assert empty is not color and torch.equal(empty, color)
diff --git a/tests/test_interpolate.py b/tests/test_interpolate.py
index 76af1d2..621632f 100644
--- a/tests/test_interpolate.py
+++ b/tests/test_interpolate.py
@@ -57,4 +57,4 @@ def test_no_derivatives_requested(ctx, triangle):
pos, tri = triangle
rast, rast_db = dr.rasterize(ctx, pos, tri, (8, 8))
_, out_da = dr.interpolate(torch.ones(3, 2), rast, tri, rast_db=rast_db)
- assert out_da is None
+ assert out_da.shape == (1, 8, 8, 0)
diff --git a/tests/test_mip.py b/tests/test_mip.py
new file mode 100644
index 0000000..ed5960c
--- /dev/null
+++ b/tests/test_mip.py
@@ -0,0 +1,776 @@
+"""Mip chains, custom mip stacks, and the corner cases of mipmapped lookups."""
+
+import itertools
+from fractions import Fraction
+
+import pytest
+import torch
+import torch.nn.functional as F
+
+import diffrast as dr
+from diffrast import backends
+from diffrast.backends import reference
+from diffrast.ops import MipStack, texture_construct_mip
+
+FILTERS = ("nearest", "linear", "linear-mipmap-nearest", "linear-mipmap-linear")
+MIP_FILTERS = FILTERS[2:]
+BOUNDARIES = ("wrap", "clamp", "zero")
+INF, NAN = float("inf"), float("nan")
+
+
+def area_weights(n):
+ """Exact weights, ``[ceil(n / 2), n]``, that resample ``n`` texels into equal bins by area."""
+ m = (n + 1) // 2
+ weights = torch.zeros(m, n, dtype=torch.float64)
+ for j, i in itertools.product(range(m), range(n)):
+ overlap = min(Fraction((j + 1) * n, m), i + 1) - max(Fraction(j * n, m), i)
+ weights[j, i] = float(max(overlap, 0) / Fraction(n, m))
+ return weights
+
+
+def footprint(shape, texels, size):
+ """``uv_da`` for a footprint of ``texels`` texels along both screen axes."""
+ da = torch.zeros(*shape, 4)
+ da[..., 0] = texels / size
+ da[..., 3] = texels / size
+ return da
+
+
+def scene(size=(8, 12), tex_batch=1, batch=2, channels=3, seed=0, dtype=torch.float32):
+ gen = torch.Generator().manual_seed(seed)
+ tex = torch.randn(tex_batch, *size, channels, generator=gen, dtype=dtype)
+ uv = torch.rand(batch, 5, 6, 2, generator=gen, dtype=dtype) * 1.6 - 0.3
+ uv_da = torch.rand(batch, 5, 6, 4, generator=gen, dtype=dtype) * 0.6 - 0.3
+ return tex, uv, uv_da
+
+
+def gradients(out, inputs, weights=None):
+ """Gradients of a weighted sum of ``out``, with zeros for inputs it does not depend on."""
+ loss = out.nansum() if weights is None else (out * weights).nansum()
+ grads = torch.autograd.grad(loss, inputs, allow_unused=True)
+ return [torch.zeros_like(t) if g is None else g for g, t in zip(grads, inputs, strict=True)]
+
+
+class TestMipChain:
+ @pytest.mark.parametrize("size", [(1, 1025), (3, 3), (513, 513), (5, 7)])
+ def test_every_texel_has_the_same_weight_in_every_level(self, size):
+ tex = torch.rand(1, *size, 1, dtype=torch.float64, requires_grad=True)
+ levels = reference._mip_chain(tex, None)
+ for level in levels[1:]:
+ (weight,) = torch.autograd.grad(level.sum(), tex, retain_graph=True)
+ share = level.shape[1] * level.shape[2] / (size[0] * size[1])
+ torch.testing.assert_close(weight, torch.full_like(weight, share), rtol=1e-9, atol=0)
+ assert levels[-1].shape == (1, 1, 1, 1)
+ torch.testing.assert_close(levels[-1].flatten(), tex.detach().mean().view(1))
+
+ def test_sizes_halve_rounding_up(self):
+ levels = reference._mip_chain(torch.zeros(2, 5, 12, 3), None)
+ sizes = [tuple(level.shape) for level in levels]
+ assert sizes == [(2, 5, 12, 3), (2, 3, 6, 3), (2, 2, 3, 3), (2, 1, 2, 3), (2, 1, 1, 3)]
+ assert len(reference._mip_chain(torch.zeros(2, 5, 12, 3), 2)) == 3
+
+ @pytest.mark.parametrize("size", [(16, 8), (2, 6), (1, 8), (6, 1), (64, 64)])
+ def test_even_sizes_are_the_two_by_two_box_filter(self, size):
+ tex = torch.randn(2, *size, 3, generator=torch.Generator().manual_seed(0))
+ kernel = (min(size[0], 2), min(size[1], 2))
+ box = F.avg_pool2d(tex.permute(0, 3, 1, 2), kernel).permute(0, 2, 3, 1)
+ assert torch.equal(reference._mip_chain(tex, 1)[1], box)
+
+ @pytest.mark.parametrize("size", [(5, 7), (6, 9), (1, 13), (10, 3), (3, 3), (4, 4), (15, 2)])
+ def test_matches_independent_area_weighting(self, size):
+ gen = torch.Generator().manual_seed(1)
+ tex = torch.randn(2, *size, 2, generator=gen, dtype=torch.float64)
+ expected = tex
+ for level in reference._mip_chain(tex, None)[1:]:
+ rows, cols = area_weights(expected.shape[1]), area_weights(expected.shape[2])
+ expected = torch.einsum("ri,bijc,sj->brsc", rows, expected, cols)
+ torch.testing.assert_close(level, expected, rtol=1e-12, atol=1e-12)
+
+ @pytest.mark.parametrize("width", [5, 9, 13, 513, 1025, 1500])
+ def test_levels_stay_aligned(self, width):
+ # A texture holding u at each texel centre holds nearly u at each coarser texel centre.
+ # Averaging a window that hangs over an odd edge would shift levels by up to a texel.
+ tex = ((torch.arange(width, dtype=torch.float64) + 0.5) / width).view(1, 1, width, 1)
+ for level in reference._mip_chain(tex, None)[1:]:
+ size = level.shape[2]
+ centres = (torch.arange(size, dtype=torch.float64) + 0.5) / size
+ assert (level.flatten() - centres).abs().max() * size < 0.1
+
+ def test_gradcheck(self):
+ gen = torch.Generator().manual_seed(2)
+ tex = torch.randn(1, 5, 7, 2, generator=gen, dtype=torch.float64, requires_grad=True)
+ assert torch.autograd.gradcheck(
+ lambda t: torch.cat([lv.flatten() for lv in reference._mip_chain(t, None)[1:]]), (tex,)
+ )
+
+ @pytest.mark.parametrize("size", [(5, 7), (1, 1025), (33, 17)])
+ def test_far_minified_lookup_returns_the_mean(self, size):
+ gen = torch.Generator().manual_seed(3)
+ tex = torch.randn(1, *size, 2, generator=gen)
+ uv = torch.rand(1, 3, 3, 2, generator=gen)
+ out = dr.texture(tex, uv, footprint((1, 3, 3), 4096.0, 1))
+ expected = tex.mean((1, 2), keepdim=True).expand_as(out)
+ torch.testing.assert_close(out, expected, atol=1e-5, rtol=1e-5)
+
+
+class TestTopLevelGradient:
+ """At the coarsest level the level of detail is clamped, so it has no gradient."""
+
+ def lookup(self, bias, max_mip_level=None, size=(8, 8), uv_da=None):
+ gen = torch.Generator().manual_seed(4)
+ tex = torch.randn(1, *size, 2, generator=gen, dtype=torch.float64)
+ uv = torch.rand(1, 4, 4, 2, generator=gen, dtype=torch.float64)
+ return reference.texture(
+ tex, uv, uv_da, "linear-mipmap-linear", "wrap", max_mip_level, mip_level_bias=bias
+ )
+
+ @pytest.mark.parametrize(
+ "max_mip_level, size, top",
+ [(None, (8, 8), 3), (0, (8, 8), 0), (1, (8, 8), 1), (None, (1, 1), 0)],
+ )
+ def test_bias_at_the_top_level(self, max_mip_level, size, top):
+ bias = torch.full((1, 4, 4), float(top), dtype=torch.float64, requires_grad=True)
+ out = self.lookup(bias, max_mip_level, size)
+ (grad,) = torch.autograd.grad(out.sum(), bias)
+ assert (grad == 0).all()
+ # Zero is the derivative towards coarser levels: the output does not change that way.
+ torch.testing.assert_close(self.lookup(bias + 1e-3, max_mip_level, size), out)
+
+ @pytest.mark.parametrize("max_mip_level, texels", [(None, 8.0), (0, 1.0), (None, 20.0)])
+ def test_footprint_at_or_past_the_top_level(self, max_mip_level, texels):
+ uv_da = footprint((1, 4, 4), texels, 8).double().requires_grad_()
+ out = self.lookup(None, max_mip_level, uv_da=uv_da)
+ (grad,) = torch.autograd.grad(out.sum(), uv_da)
+ assert (grad == 0).all()
+
+ def test_interior_level_uses_the_derivative_towards_coarser(self):
+ bias = torch.full((1, 4, 4), 1.0, dtype=torch.float64, requires_grad=True)
+ out = self.lookup(bias)
+ (grad,) = torch.autograd.grad(out.sum(), bias)
+ step = 1e-6
+ slope = (self.lookup(bias + step) - out).sum((0, 3)) / step
+ assert grad.abs().min() > 1e-3
+ torch.testing.assert_close(grad[0], slope.detach(), rtol=1e-5, atol=1e-7)
+
+
+class TestOutOfRange:
+ """Coordinates far outside the texture and values that are not finite."""
+
+ def ramp(self):
+ return torch.arange(2048.0).view(1, 1, 2048, 1)
+
+ def sample(self, u, filter_mode, boundary_mode, tex=None):
+ uv = torch.tensor([[[[u, 0.5]]]])
+ tex = self.ramp() if tex is None else tex
+ return dr.texture(tex, uv, filter_mode=filter_mode, boundary_mode=boundary_mode).item()
+
+ @pytest.mark.parametrize(
+ "u, filter_mode, expected",
+ [
+ (1048575.25, "nearest", 512.0),
+ (1048576.25, "nearest", 512.0),
+ (-2000000.25, "nearest", 1536.0),
+ (2000000.25, "linear", 511.5),
+ (3e8, "linear", 1023.5),
+ (-1e30, "nearest", 0.0),
+ ],
+ )
+ def test_wrap_keeps_the_fractional_part(self, u, filter_mode, expected):
+ assert self.sample(u, filter_mode, "wrap") == expected
+
+ @pytest.mark.parametrize("filter_mode", ["nearest", "linear"])
+ @pytest.mark.parametrize(
+ "u, expected", [(1e30, 2047.0), (-1e30, 0.0), (INF, 2047.0), (-INF, 0.0)]
+ )
+ def test_clamp_returns_the_nearest_edge(self, filter_mode, u, expected):
+ assert self.sample(u, filter_mode, "clamp") == expected
+
+ @pytest.mark.parametrize("filter_mode", ["nearest", "linear"])
+ @pytest.mark.parametrize("u", [1e30, -1e30, INF, -INF])
+ def test_zero_returns_zero_far_outside(self, filter_mode, u):
+ assert self.sample(u, filter_mode, "zero", self.ramp() + 1) == 0.0
+
+ @pytest.mark.parametrize("filter_mode", ["nearest", "linear"])
+ @pytest.mark.parametrize(
+ "u, boundary_mode", [(NAN, "wrap"), (NAN, "clamp"), (NAN, "zero"), (INF, "wrap")]
+ )
+ def test_undefined_coordinates_give_nan(self, filter_mode, u, boundary_mode):
+ assert self.sample(u, filter_mode, boundary_mode) != self.sample(
+ u, filter_mode, boundary_mode
+ )
+
+ @pytest.mark.parametrize("filter_mode", FILTERS)
+ @pytest.mark.parametrize("boundary_mode", BOUNDARIES)
+ def test_bad_pixels_pass_no_gradient(self, filter_mode, boundary_mode):
+ tex, uv, uv_da = scene(batch=1)
+ uv[0, 0, 0, 0], uv[0, 1, 1, 1], uv[0, 2, 2, 0] = NAN, INF, -1e30
+ uv_da[0, 3, 3, 2] = NAN
+ mip = "mipmap" in filter_mode
+ inputs = [t.requires_grad_() for t in (tex, uv, uv_da)]
+ out = dr.texture(
+ tex, uv, uv_da if mip else None, filter_mode=filter_mode, boundary_mode=boundary_mode
+ )
+ expected = torch.zeros(5, 6, dtype=torch.bool)
+ expected[0, 0] = True
+ expected[1, 1] = boundary_mode == "wrap"
+ expected[3, 3] = mip
+ assert torch.equal(out.isnan().any(-1)[0], expected)
+ assert torch.equal(out.isnan().all(-1)[0], expected)
+ for grad in gradients(out, inputs):
+ assert torch.isfinite(grad).all()
+
+ @pytest.mark.parametrize("value", [3e38, -3e38, INF, -INF])
+ def test_huge_footprint_selects_the_coarsest_level(self, value):
+ tex, uv, uv_da = scene(size=(8, 8), batch=1)
+ uv_da[..., 0] = value
+ uv_da.requires_grad_()
+ out = dr.texture(tex, uv, uv_da)
+ torch.testing.assert_close(out, tex.mean((1, 2), keepdim=True).expand_as(out))
+ (grad,) = torch.autograd.grad(out.sum(), uv_da)
+ assert (grad == 0).all()
+
+ @pytest.mark.parametrize("value, max_mip_level", [(INF, None), (-INF, 0), (50.0, None)])
+ def test_infinite_bias_is_clamped(self, value, max_mip_level):
+ tex, uv, _ = scene(size=(8, 8), batch=1)
+ bias = torch.full((1, 5, 6), value, requires_grad=True)
+ out = dr.texture(tex, uv, mip_level_bias=bias)
+ level = 0 if value < 0 else 3
+ expected = dr.texture(tex, uv, mip_level_bias=torch.full((1, 5, 6), float(level)))
+ torch.testing.assert_close(out, expected)
+ (grad,) = torch.autograd.grad(out.sum(), bias)
+ assert (grad == 0).all()
+
+ @pytest.mark.parametrize("filter_mode", FILTERS)
+ @pytest.mark.parametrize("shape", [(0, 4, 4, 2), (2, 0, 4, 2), (2, 4, 0, 2)])
+ def test_no_pixels(self, filter_mode, shape):
+ tex = torch.rand(2 if shape[0] else 0, 4, 4, 3, requires_grad=True)
+ uv = torch.zeros(shape)
+ uv_da = torch.zeros(*shape[:3], 4) if "mipmap" in filter_mode else None
+ out = dr.texture(tex, uv, uv_da, filter_mode=filter_mode)
+ assert out.shape == (*shape[:3], 3)
+ out.sum().backward()
+ assert (tex.grad == 0).all()
+
+
+class TestValidation:
+ @pytest.mark.parametrize("shape", [(1, 0, 4, 3), (1, 4, 0, 3), (1, 4, 4, 0)])
+ def test_zero_sized_texture(self, shape):
+ with pytest.raises(ValueError, match="at least one texel and one channel"):
+ dr.texture(torch.zeros(shape), torch.zeros(1, 4, 4, 2))
+ with pytest.raises(ValueError, match="at least one texel and one channel"):
+ texture_construct_mip(torch.zeros(shape))
+
+ @pytest.mark.parametrize(
+ "level, error, match",
+ [
+ (torch.zeros(4, 4, 3), ValueError, "mip level 1 must have shape"),
+ (torch.zeros(1, 4, 4, 2), ValueError, "mip level 1 has 2 channels but tex has 3"),
+ (torch.zeros(3, 4, 4, 3), ValueError, "mip level 1 has batch size 3"),
+ (torch.zeros(1, 4, 0, 3), ValueError, "mip level 1 must have at least one texel"),
+ (torch.zeros(1, 4, 4, 3, dtype=torch.float64), TypeError, "mip level 1 must be"),
+ (torch.zeros(1, 6, 4, 4, 3), ValueError, "mip level 1 has the shape of a cube map"),
+ ([[0.0]], TypeError, "mip level 1 must be a torch.Tensor"),
+ ],
+ )
+ def test_bad_mip_level(self, level, error, match):
+ tex = torch.zeros(2, 8, 8, 3)
+ with pytest.raises(error, match=match):
+ dr.texture(tex, torch.zeros(2, 4, 4, 2), mip=[level])
+
+ def test_later_levels_are_checked_too(self):
+ tex = torch.zeros(1, 8, 8, 3)
+ with pytest.raises(ValueError, match="mip level 2 has 1 channels"):
+ dr.texture(
+ tex, torch.zeros(1, 4, 4, 2), mip=[tex[:, ::2, ::2], torch.zeros(1, 2, 2, 1)]
+ )
+
+ def test_stack_of_another_kind(self):
+ stack = texture_construct_mip(torch.zeros(1, 6, 4, 4, 3), cube_mode=True)
+ with pytest.raises(ValueError, match="cube_mode=True"):
+ dr.texture(torch.zeros(1, 4, 4, 3), torch.zeros(1, 4, 4, 2), mip=stack)
+
+ @pytest.mark.parametrize("shape", [(1, 16, 8, 3), (1, 8, 16, 3), (2, 8, 8, 3)])
+ def test_stack_of_another_texture(self, shape):
+ stack = texture_construct_mip(torch.zeros(1, 8, 8, 3))
+ uv = torch.zeros(2, 4, 4, 2)
+ with pytest.raises(ValueError, match="constructed for a texture of shape"):
+ dr.texture(torch.zeros(shape), uv, mip_level_bias=torch.zeros(2, 4, 4), mip=stack)
+ with pytest.raises(ValueError, match="constructed for a texture of shape"):
+ dr.texture(torch.zeros(shape), uv, mip=stack, filter_mode="linear")
+
+ def test_construct_mip_arguments(self):
+ with pytest.raises(ValueError, match="max_mip_level must be non-negative"):
+ texture_construct_mip(torch.zeros(1, 4, 4, 3), max_mip_level=-1)
+ with pytest.raises(TypeError, match=r"tex must be torch\.float32"):
+ texture_construct_mip(torch.zeros(1, 4, 4, 3, dtype=torch.float64))
+ with pytest.raises(ValueError, match="tex must have shape"):
+ texture_construct_mip(torch.zeros(4, 4, 3))
+
+
+class TestCustomMips:
+ @pytest.mark.parametrize("filter_mode", MIP_FILTERS)
+ @pytest.mark.parametrize("max_mip_level", [None, 1, 0])
+ def test_list_of_the_same_levels_reproduces_the_automatic_chain(
+ self, filter_mode, max_mip_level
+ ):
+ tex, uv, uv_da = scene(size=(8, 16))
+ levels = [tex]
+ while max(levels[-1].shape[1:3]) > 1:
+ height, width = levels[-1].shape[1:3]
+ pairs = levels[-1].view(1, max(height // 2, 1), -1, max(width // 2, 1), 2, 3)
+ levels.append(pairs.mean((2, 4)))
+ kwargs = {"filter_mode": filter_mode, "max_mip_level": max_mip_level}
+ auto = dr.texture(tex, uv, uv_da, **kwargs)
+ custom = dr.texture(tex, uv, uv_da, mip=levels[1:], **kwargs)
+ torch.testing.assert_close(custom, auto, rtol=1e-6, atol=1e-6)
+
+ def test_list_may_stop_at_any_level(self):
+ tex, uv, uv_da = scene()
+ levels = reference._mip_chain(tex, None)
+ short = dr.texture(tex, uv, uv_da * 8, mip=levels[1:3])
+ assert torch.equal(short, dr.texture(tex, uv, uv_da * 8, max_mip_level=2))
+ assert torch.equal(dr.texture(tex, uv, uv_da, mip=[]), dr.texture(tex, uv))
+
+ def test_levels_keep_their_own_size(self):
+ tex, uv, _ = scene(size=(8, 8))
+ level = torch.randn(1, 3, 5, 3, generator=torch.Generator().manual_seed(5))
+ bias = torch.full(uv.shape[:3], 1.0)
+ out = dr.texture(tex, uv, mip_level_bias=bias, mip=[level])
+ assert torch.equal(out, dr.texture(level, uv, filter_mode="linear"))
+
+ @pytest.mark.parametrize("filter_mode", MIP_FILTERS)
+ def test_level_shared_across_a_batch_of_textures(self, filter_mode):
+ tex, uv, uv_da = scene(tex_batch=2)
+ level = torch.randn(1, 4, 6, 3, generator=torch.Generator().manual_seed(6))
+ shared = dr.texture(tex, uv, uv_da, mip=[level], filter_mode=filter_mode)
+ repeated = dr.texture(
+ tex, uv, uv_da, mip=[level.expand(2, -1, -1, -1)], filter_mode=filter_mode
+ )
+ assert torch.equal(shared, repeated)
+
+ def test_gradients_stop_at_the_listed_tensors(self):
+ tex, uv, _ = scene(size=(8, 8))
+ tex.requires_grad_()
+ levels = [lv.detach().requires_grad_() for lv in reference._mip_chain(tex, None)[1:]]
+ # A bias of exactly one reads level one only.
+ out = dr.texture(tex, uv, mip_level_bias=torch.full(uv.shape[:3], 1.0), mip=levels)
+ out.sum().backward()
+ assert (tex.grad == 0).all()
+ assert levels[0].grad.abs().sum() > 0
+
+ def test_list_gradients_are_those_of_the_automatic_chain(self):
+ # The gradient the base texture gets from the automatic chain is what it gets directly
+ # plus what each level of a custom list gets, carried through the box filters.
+ tex, uv, _ = scene(size=(8, 12), dtype=torch.float64)
+ tex.requires_grad_()
+ chain = reference._mip_chain(tex, None)
+ levels = [level.detach().requires_grad_() for level in chain[1:]]
+ gen = torch.Generator().manual_seed(7)
+ weights = torch.randn(2, 5, 6, 3, generator=gen, dtype=torch.float64)
+ bias = torch.rand(2, 5, 6, generator=gen, dtype=torch.float64) * 4
+
+ def lookup(mip):
+ return reference.texture(
+ tex, uv, None, "linear-mipmap-linear", "wrap", None, mip_level_bias=bias, mip=mip
+ )
+
+ (total,) = gradients(lookup(None), [tex], weights)
+ direct, *level_grads = gradients(lookup(levels), [tex, *levels], weights)
+ carried = torch.autograd.grad(chain[1:], tex, level_grads)[0]
+ assert all(grad.abs().sum() > 0 for grad in level_grads)
+ torch.testing.assert_close(direct + carried, total)
+
+ @pytest.mark.parametrize("filter_mode", MIP_FILTERS)
+ def test_gradcheck(self, filter_mode):
+ tex, uv, _ = scene(size=(4, 6), batch=1, channels=2, dtype=torch.float64)
+ gen = torch.Generator().manual_seed(8)
+ levels = [
+ torch.randn(1, *size, 2, generator=gen, dtype=torch.float64, requires_grad=True)
+ for size in ((2, 3), (3, 1))
+ ]
+ # Footprints of 1.2 to 3.2 texels keep the level of detail away from integers and clamps.
+ scale = (torch.rand(1, 5, 6, 1, generator=gen, dtype=torch.float64) * 2 + 1.2) / 6
+ uv_da = (scale * torch.tensor([1.0, 0.1, -0.2, 0.9], dtype=torch.float64)).requires_grad_()
+ tex.requires_grad_()
+ uv.requires_grad_()
+ assert torch.autograd.gradcheck(
+ lambda t, a, b, c, d: reference.texture(t, c, d, filter_mode, "wrap", None, mip=[a, b]),
+ (tex, *levels, uv, uv_da),
+ )
+
+ def test_trainable_mip_list_as_in_pipelines(self):
+ # Pipelines keep a texture as a list of trainable levels and pass all but the first.
+ _, uv, uv_da = scene()
+ gen = torch.Generator().manual_seed(9)
+ levels = [
+ torch.rand(1, 16 >> i, 16 >> i, 3, generator=gen, requires_grad=True) for i in range(5)
+ ]
+ optimizer = torch.optim.SGD(levels, lr=0.1)
+ before = [level.detach().clone() for level in levels]
+ out = dr.texture(levels[0], uv, uv_da, mip=levels[1:], filter_mode="linear-mipmap-linear")
+ out.square().mean().backward()
+ optimizer.step()
+ assert out.shape == (2, 5, 6, 3)
+ assert sum(not torch.equal(a, b) for a, b in zip(levels, before, strict=True)) >= 3
+
+
+class TestConstructMip:
+ @pytest.mark.parametrize("filter_mode", MIP_FILTERS)
+ @pytest.mark.parametrize("size", [(8, 12), (5, 7)])
+ def test_same_result_as_building_internally(self, filter_mode, size):
+ tex, uv, uv_da = scene(size=size, tex_batch=2)
+ mip = texture_construct_mip(tex)
+ out = dr.texture(tex, uv, uv_da, mip=mip, filter_mode=filter_mode)
+ assert torch.equal(out, dr.texture(tex, uv, uv_da, filter_mode=filter_mode))
+
+ def test_holds_levels_one_and_up(self):
+ tex = torch.rand(1, 8, 12, 3)
+ chain = reference._mip_chain(tex, None)
+ mip = texture_construct_mip(tex)
+ assert isinstance(mip, MipStack)
+ assert len(mip.levels) == len(chain) - 1 == 4
+ assert all(torch.equal(a, b) for a, b in zip(mip.levels, chain[1:], strict=True))
+ assert len(texture_construct_mip(tex, max_mip_level=2).levels) == 2
+ assert len(texture_construct_mip(tex, max_mip_level=0).levels) == 0
+
+ def test_max_mip_level_limits_the_levels_used(self):
+ tex, uv, uv_da = scene()
+ mip = texture_construct_mip(tex)
+ limited = dr.texture(tex, uv, uv_da * 8, mip=mip, max_mip_level=1)
+ assert torch.equal(limited, dr.texture(tex, uv, uv_da * 8, max_mip_level=1))
+ short = texture_construct_mip(tex, max_mip_level=1)
+ assert torch.equal(dr.texture(tex, uv, uv_da * 8, mip=short), limited)
+
+ def test_gradients_flow_through_the_stack_to_the_texture(self):
+ tex, uv, uv_da = scene()
+ tex.requires_grad_()
+ (expected,) = gradients(dr.texture(tex, uv, uv_da * 4), [tex])
+ mip = texture_construct_mip(tex)
+ (grad,) = gradients(dr.texture(tex, uv, uv_da * 4, mip=mip), [tex])
+ torch.testing.assert_close(grad, expected)
+
+ def test_reused_across_calls(self):
+ tex, uv, uv_da = scene()
+ mip = texture_construct_mip(tex)
+ for scale in (1.0, 3.0, 9.0):
+ out = dr.texture(tex, uv, uv_da * scale, mip=mip)
+ assert torch.equal(out, dr.texture(tex, uv, uv_da * scale))
+
+ @pytest.mark.parametrize("filter_mode", MIP_FILTERS)
+ def test_packed_levels_are_kept_between_calls(self, filter_mode):
+ tex, uv, uv_da = scene(tex_batch=2)
+ mip = texture_construct_mip(tex)
+ packed = mip.pack(tex)
+ assert all(a is b for a, b in zip(mip.pack(tex), packed, strict=True))
+ for max_mip_level in (None, 2, 1, 0, 7):
+ kwargs = {"filter_mode": filter_mode, "max_mip_level": max_mip_level}
+ out = dr.texture(tex, uv, uv_da * 4, mip=mip, **kwargs)
+ assert torch.equal(out, dr.texture(tex, uv, uv_da * 4, **kwargs))
+ assert mip.pack(tex)[0] is packed[0]
+
+ def test_kept_levels_follow_the_texture_passed(self):
+ # The stack was built for one texture. Whatever is passed as tex is still the base level
+ # that is sampled, also after the levels have been packed for another one.
+ tex, uv, uv_da = scene()
+ mip = texture_construct_mip(tex)
+ levels = list(mip.levels)
+ dr.texture(tex, uv, uv_da, mip=mip)
+
+ other = torch.rand_like(tex)
+ assert torch.equal(
+ dr.texture(other, uv, uv_da, mip=mip), dr.texture(other, uv, uv_da, mip=levels)
+ )
+ dr.texture(tex, uv, uv_da, mip=mip)
+ tex.mul_(2.0)
+ assert torch.equal(
+ dr.texture(tex, uv, uv_da, mip=mip), dr.texture(tex, uv, uv_da, mip=levels)
+ )
+
+ def test_kept_levels_do_not_hide_a_texture_that_starts_to_require_gradients(self):
+ tex, uv, uv_da = scene()
+ mip = texture_construct_mip(tex)
+ dr.texture(tex, uv, uv_da, mip=mip)
+ tex.requires_grad_()
+ (grad,) = gradients(dr.texture(tex, uv, uv_da, mip=mip), [tex])
+ (expected,) = gradients(dr.texture(tex, uv, uv_da, mip=list(mip.levels)), [tex])
+ assert expected.abs().sum() > 0
+ torch.testing.assert_close(grad, expected)
+
+ def test_inference_mode(self):
+ tex, uv, uv_da = scene()
+ mip = texture_construct_mip(tex)
+ expected = dr.texture(tex, uv, uv_da * 4)
+ with torch.inference_mode():
+ assert torch.equal(dr.texture(tex, uv, uv_da * 4, mip=mip), expected)
+ uv.requires_grad_()
+ out = dr.texture(tex, uv, uv_da * 4, mip=mip)
+ assert torch.equal(out, expected)
+ (grad,) = gradients(out, [uv])
+ assert grad.abs().sum() > 0
+
+
+@pytest.fixture
+def triton_backend():
+ pytest.importorskip("triton")
+ from diffrast.backends import triton
+
+ return triton
+
+
+@pytest.mark.gpu
+class TestTriton:
+ """The Triton backend against the reference backend on the same device."""
+
+ def compare(self, triton_backend, inputs, call):
+ """Run ``call(backend, *inputs)`` on both backends and compare outputs and gradients.
+
+ Returns the reference output followed by its gradient for each input.
+ """
+ results = []
+ for backend in (reference, triton_backend):
+ leaves = [t.detach().clone().requires_grad_() for t in inputs]
+ out = call(backend, *leaves)
+ weights = torch.randn(out.shape, generator=torch.Generator().manual_seed(10)).cuda()
+ results.append([out.detach(), *gradients(out, leaves, weights)])
+ ref, ours = results
+ # The kernels round like the PyTorch code, so the same pixels are NaN and the rest agree
+ # to the last bits.
+ torch.testing.assert_close(ours[0], ref[0], atol=1e-6, rtol=1e-6, equal_nan=True)
+ for grad, ref_grad in zip(ours[1:], ref[1:], strict=True):
+ assert torch.isfinite(ref_grad).all()
+ torch.testing.assert_close(grad, ref_grad, atol=1e-5, rtol=1e-4)
+ return ref
+
+ @pytest.mark.parametrize("max_mip_level, bias", [(None, 3.0), (0, 0.0), (1, 1.0), (None, 7.5)])
+ def test_bias_at_or_past_the_top_level(self, triton_backend, max_mip_level, bias):
+ tex, uv, _ = (t.cuda() for t in scene(size=(8, 8)))
+ bias = torch.full(uv.shape[:3], bias).cuda()
+ ref = self.compare(
+ triton_backend,
+ (tex, uv, bias),
+ lambda backend, t, c, b: backend.texture(
+ t, c, None, "linear-mipmap-linear", "wrap", max_mip_level, mip_level_bias=b
+ ),
+ )
+ assert (ref[3] == 0).all()
+
+ @pytest.mark.parametrize(
+ "max_mip_level, texels", [(None, 8.0), (0, 1.0), (2, 4.0), (None, 64.0)]
+ )
+ def test_footprint_at_or_past_the_top_level(self, triton_backend, max_mip_level, texels):
+ tex, uv, _ = (t.cuda() for t in scene(size=(8, 8)))
+ uv_da = footprint(uv.shape[:3], texels, 8).cuda()
+ ref = self.compare(
+ triton_backend,
+ (tex, uv, uv_da),
+ lambda backend, t, c, d: backend.texture(
+ t, c, d, "linear-mipmap-linear", "wrap", max_mip_level
+ ),
+ )
+ assert (ref[3] == 0).all()
+
+ @pytest.mark.parametrize("size", [(5, 1), (1, 7), (6, 10), (37, 50)])
+ def test_isotropic_footprint_on_a_non_square_texture(self, triton_backend, size):
+ # Both footprint axes are equally long here, and the two backends have to split the
+ # gradient between them in the same way.
+ tex, uv, _ = (t.cuda() for t in scene(size=size))
+ uv_da = torch.zeros(*uv.shape[:3], 4)
+ uv_da[..., 0], uv_da[..., 3] = 2.0 / size[1], 2.0 / size[0]
+ ref = self.compare(
+ triton_backend,
+ (tex, uv, uv_da.cuda()),
+ lambda backend, t, c, d: backend.texture(t, c, d, "linear-mipmap-linear", "wrap", None),
+ )
+ assert ref[3].abs().sum() > 0
+
+ @pytest.mark.parametrize("size", [(1, 46342), (1, 65536), (65536, 1)])
+ def test_level_of_detail_of_very_long_textures(self, triton_backend, size):
+ # Stripes of zeros and ones average to one half from the first mip level on.
+ length = max(size)
+ tex = (torch.arange(length) % 2).float().view(1, *size, 1).cuda()
+ centre = (torch.arange(16.0) * 1000 + 0.5) / length
+ along_u = size[1] > 1
+ uv = torch.full((1, 1, 16, 2), 0.5)
+ uv[..., 0 if along_u else 1] = centre
+ uv_da = torch.zeros(1, 1, 16, 4)
+ uv_da[..., 0 if along_u else 3] = 8.0 / length
+ out = triton_backend.texture(
+ tex, uv.cuda(), uv_da.cuda(), "linear-mipmap-linear", "wrap", None
+ )
+ torch.testing.assert_close(out, torch.full_like(out, 0.5))
+
+ @pytest.mark.parametrize("filter_mode", FILTERS)
+ @pytest.mark.parametrize("boundary", BOUNDARIES)
+ def test_far_out_and_undefined_coordinates(self, triton_backend, filter_mode, boundary):
+ values = [0.3, -0.2, 1.4, 3e8, -2000000.25, 1048576.25, 1e30, -1e30, 3e38, INF, -INF, NAN]
+ pairs = torch.tensor(list(itertools.product(values, values))).view(1, 12, 12, 2)
+ tex, _, _ = scene(size=(6, 9), tex_batch=2)
+ uv = pairs.expand(2, -1, -1, -1).contiguous()
+ gen = torch.Generator().manual_seed(11)
+ uv_da = torch.rand(2, 12, 12, 4, generator=gen) * 0.4 - 0.2
+ mip = "mipmap" in filter_mode
+ ref = self.compare(
+ triton_backend,
+ (tex.cuda(), uv.cuda(), uv_da.cuda()),
+ lambda backend, t, c, d: backend.texture(
+ t, c, d if mip else None, filter_mode, boundary, None
+ ),
+ )
+ finite = torch.isfinite(pairs).all(-1)[0]
+ assert not ref[0][0][finite].isnan().any()
+
+ @pytest.mark.parametrize("filter_mode", MIP_FILTERS)
+ @pytest.mark.parametrize("with_bias", [False, True])
+ def test_extreme_levels_of_detail(self, triton_backend, filter_mode, with_bias):
+ values = [0.05, 0.0, 3e38, -3e38, INF, -INF, NAN, 1e-30, 1e10]
+ pairs = torch.tensor(list(itertools.product(values, values))).view(1, 9, 9, 2)
+ uv_da = torch.cat([pairs[..., :1], torch.zeros(1, 9, 9, 2), pairs[..., 1:]], -1)
+ bias = torch.tensor([0.0, 1.5, -3.0, INF, -INF, NAN, 50.0, -55.0, 2.0])
+ bias = bias.view(1, 9, 1).expand(1, 9, 9).contiguous()
+ tex = scene(size=(6, 9))[0]
+ uv = torch.rand(1, 9, 9, 2, generator=torch.Generator().manual_seed(12))
+ self.compare(
+ triton_backend,
+ (tex.cuda(), uv.cuda(), uv_da.cuda(), bias.cuda()),
+ lambda backend, t, c, d, b: backend.texture(
+ t, c, d, filter_mode, "wrap", None, mip_level_bias=b if with_bias else None
+ ),
+ )
+
+ @pytest.mark.parametrize("filter_mode", MIP_FILTERS)
+ @pytest.mark.parametrize("level_batch", [1, 2])
+ @pytest.mark.parametrize("max_mip_level", [None, 1])
+ def test_custom_mip_list(self, triton_backend, filter_mode, level_batch, max_mip_level):
+ tex, uv, _ = (t.cuda() for t in scene(size=(8, 12), tex_batch=2))
+ gen = torch.Generator().manual_seed(13)
+ levels = [
+ torch.randn(level_batch, *size, 3, generator=gen).cuda()
+ for size in ((4, 6), (3, 2), (1, 1))
+ ]
+ bias = (torch.rand(uv.shape[:3], generator=gen) * 3.5 - 0.25).cuda()
+ ref = self.compare(
+ triton_backend,
+ (tex, uv, bias, *levels),
+ lambda backend, t, c, b, *lv: backend.texture(
+ t, c, None, filter_mode, "clamp", max_mip_level, mip_level_bias=b, mip=lv
+ ),
+ )
+ used = 1 if max_mip_level == 1 else 3
+ assert all(grad.abs().sum() > 0 for grad in ref[4 : 4 + used])
+
+ @pytest.mark.parametrize("filter_mode, lone", [("nearest", 1), ("linear-mipmap-nearest", 2)])
+ def test_output_requires_grad_as_on_the_reference_backend(
+ self, triton_backend, filter_mode, lone
+ ):
+ # Inputs a filter mode does not depend on smoothly do not make the output differentiable.
+ inputs = [t.cuda() for t in scene()]
+ inputs[lone].requires_grad_()
+ for backend in (reference, triton_backend):
+ out = backend.texture(*inputs, filter_mode, "wrap", None)
+ assert not out.requires_grad
+
+ @pytest.mark.parametrize("filter_mode", ["linear", "linear-mipmap-linear"])
+ @pytest.mark.parametrize(
+ "loss", [lambda out: out.sum(), lambda out: out.mean(), lambda out: out.square().sum()]
+ )
+ def test_double_backward_raises(self, triton_backend, filter_mode, loss):
+ # With a loss that is linear in the lookup, the incoming gradient is a constant and the
+ # second-order terms come from the texture and the coordinates alone.
+ tex, uv, uv_da = (t.cuda().requires_grad_() for t in scene())
+ mip = "mipmap" in filter_mode
+ out = triton_backend.texture(tex, uv, uv_da if mip else None, filter_mode, "wrap", None)
+ (grad,) = torch.autograd.grad(loss(out), uv, create_graph=True)
+ with pytest.raises(RuntimeError, match="first-order gradients only"):
+ grad.square().sum().backward()
+
+ def test_double_backward_of_a_nearest_lookup_raises(self, triton_backend):
+ tex, uv, _ = (t.cuda() for t in scene())
+ tex.requires_grad_()
+ out = triton_backend.texture(tex, uv, None, "nearest", "wrap", None)
+ (grad,) = torch.autograd.grad(out.square().sum(), tex, create_graph=True)
+ with pytest.raises(RuntimeError, match="first-order gradients only"):
+ grad.square().sum().backward()
+
+ def test_first_order_gradients_with_create_graph(self, triton_backend):
+ inputs = [t.cuda().requires_grad_() for t in scene()]
+ out = triton_backend.texture(*inputs, "linear-mipmap-linear", "wrap", None)
+ expected = torch.autograd.grad(out.square().sum(), inputs, retain_graph=True)
+ grads = torch.autograd.grad(out.square().sum(), inputs, create_graph=True)
+ for grad, expected_grad in zip(grads, expected, strict=True):
+ assert expected_grad.abs().sum() > 0
+ torch.testing.assert_close(grad, expected_grad, atol=1e-6, rtol=1e-5)
+
+ @pytest.mark.parametrize("filter_mode", FILTERS)
+ @pytest.mark.parametrize("boundary", BOUNDARIES)
+ def test_texture_gradient_alone(self, triton_backend, filter_mode, boundary):
+ # Without gradients for the coordinates the backward pass does not read the texture.
+ tex, uv, uv_da = (t.cuda() for t in scene(size=(6, 9), tex_batch=2))
+ bias = torch.rand(uv.shape[:3], generator=torch.Generator().manual_seed(14)).cuda() * 2
+ mip = "mipmap" in filter_mode
+ ref = self.compare(
+ triton_backend,
+ (tex,),
+ lambda backend, t: backend.texture(
+ t, uv, uv_da if mip else None, filter_mode, boundary, None, bias if mip else None
+ ),
+ )
+ assert ref[1].abs().sum() > 0
+
+ @pytest.mark.parametrize("filter_mode", ["nearest", "linear"])
+ def test_texture_modified_in_place_before_backward(self, triton_backend, filter_mode):
+ results = []
+ for backend in (reference, triton_backend):
+ base, uv, _ = (t.cuda() for t in scene())
+ base.requires_grad_()
+ tex = base * 1.0
+ out = backend.texture(tex, uv, None, filter_mode, "wrap", None)
+ with torch.no_grad():
+ tex.mul_(2.0)
+ results.append(gradients(out, [base])[0])
+ assert results[0].abs().sum() > 0
+ torch.testing.assert_close(results[1], results[0], atol=1e-5, rtol=1e-4)
+
+ @pytest.mark.parametrize("filter_mode", MIP_FILTERS)
+ def test_constructed_stack_is_packed_once(self, triton_backend, filter_mode, monkeypatch):
+ monkeypatch.setattr(backends, "_selected", "triton")
+ tex, uv, uv_da = (t.cuda() for t in scene(size=(5, 7), tex_batch=2))
+ mip = texture_construct_mip(tex)
+ uv.requires_grad_()
+ for max_mip_level in (None, 1, 0):
+ kwargs = {"filter_mode": filter_mode, "max_mip_level": max_mip_level}
+ expected = dr.texture(tex, uv, uv_da * 4, **kwargs)
+ with torch.inference_mode():
+ assert torch.equal(dr.texture(tex, uv, uv_da * 4, mip=mip, **kwargs), expected)
+ out = dr.texture(tex, uv, uv_da * 4, mip=mip, **kwargs)
+ assert torch.equal(out, expected)
+ assert torch.equal(gradients(out, [uv])[0], gradients(expected, [uv])[0])
+ assert mip.pack(tex)[0] is mip.pack(tex)[0]
+
+ @pytest.mark.parametrize("filter_mode", FILTERS)
+ @pytest.mark.parametrize("shape", [(0, 4, 4, 2), (2, 0, 4, 2)])
+ def test_no_pixels(self, triton_backend, filter_mode, shape):
+ tex = torch.rand(2 if shape[0] else 0, 4, 4, 3).cuda().requires_grad_()
+ uv = torch.zeros(shape).cuda()
+ uv_da = torch.zeros(*shape[:3], 4).cuda() if "mipmap" in filter_mode else None
+ out = triton_backend.texture(tex, uv, uv_da, filter_mode, "wrap", None)
+ assert out.shape == (*shape[:3], 3)
+ out.sum().backward()
+ assert (tex.grad == 0).all()
+
+ def test_public_api_on_the_gpu(self, triton_backend, monkeypatch):
+ monkeypatch.setattr(backends, "_selected", "triton")
+ tex, uv, uv_da = (t.cuda() for t in scene(size=(5, 7), tex_batch=2))
+ tex.requires_grad_()
+ auto = dr.texture(tex, uv, uv_da * 4)
+ (expected,) = gradients(auto, [tex])
+ mip = texture_construct_mip(tex)
+ out = dr.texture(tex, uv, uv_da * 4, mip=mip)
+ assert torch.equal(out, auto)
+ torch.testing.assert_close(gradients(out, [tex])[0], expected, atol=1e-5, rtol=1e-4)
+ levels = [level.detach() for level in mip.levels]
+ assert torch.equal(dr.texture(tex, uv, uv_da * 4, mip=levels), auto)
+
+ with pytest.raises(ValueError, match="at least one texel and one channel"):
+ dr.texture(torch.zeros(1, 0, 4, 3).cuda(), uv)
+ with pytest.raises(ValueError, match="mip level 1 is on cpu but tex is on cuda"):
+ dr.texture(tex, uv, uv_da, mip=[levels[0].cpu()])
diff --git a/tests/test_peeling.py b/tests/test_peeling.py
index ba82dfd..73aebd4 100644
--- a/tests/test_peeling.py
+++ b/tests/test_peeling.py
@@ -80,5 +80,5 @@ def test_peeler_validates_inputs(ctx, triangle):
pos, tri = triangle
with pytest.raises(ValueError, match="pos must have shape"):
dr.DepthPeeler(ctx, pos[..., :3], tri, (8, 8))
- with pytest.raises(NotImplementedError, match="Range mode"):
- dr.DepthPeeler(ctx, pos, tri, (8, 8), ranges=torch.zeros(1, 2, dtype=torch.int32))
+ with pytest.raises(ValueError, match="ranges is required"):
+ dr.DepthPeeler(ctx, pos[0], tri, (8, 8))
diff --git a/tests/test_ranges.py b/tests/test_ranges.py
new file mode 100644
index 0000000..a97b57a
--- /dev/null
+++ b/tests/test_ranges.py
@@ -0,0 +1,307 @@
+"""Range mode of rasterize and DepthPeeler, and how both treat their context and their state."""
+
+import pytest
+import torch
+
+import diffrast as dr
+from diffrast.backends import reference
+from diffrast.ops import join_ranges, split_ranges
+
+RES = (24, 32)
+
+
+@pytest.fixture(params=["cpu", pytest.param("cuda", marks=pytest.mark.gpu)])
+def glctx(request):
+ """A context per device; on the GPU the ops run on the Triton backend."""
+ if request.param == "cuda":
+ pytest.importorskip("triton")
+ if dr.get_backend_name("cuda", "rasterize") != "triton":
+ pytest.skip("the Triton backend is not selected")
+ return dr.RasterizeContext(request.param)
+
+
+def scene(device="cpu", seed=0, num_tri=24):
+ """A shared vertex buffer with overlapping triangles, and ranges that overlap as well."""
+ gen = torch.Generator().manual_seed(seed)
+ xy = torch.rand(3 * num_tri, 2, generator=gen) * 2.4 - 1.2
+ z = torch.rand(3 * num_tri, 1, generator=gen) * 1.8 - 0.9
+ w = torch.rand(3 * num_tri, 1, generator=gen) + 1.0
+ pos = torch.cat([xy * w, z * w, w], -1).to(device)
+ tri = torch.arange(3 * num_tri, dtype=torch.int32).view(num_tri, 3).to(device)
+ ranges = torch.tensor([[0, 9], [10, 13], [4, 5], [23, 1], [7, 0]], dtype=torch.int32)
+ return pos, tri, ranges
+
+
+def instanced(glctx, pos, tri, ranges, **kwargs):
+ """Every range rendered by its own instanced call, with ids shifted to index ``tri``."""
+ rasts, rast_dbs = [], []
+ for start, count in ranges.tolist():
+ rast, rast_db = dr.rasterize(glctx, pos[None], tri[start : start + count], RES, **kwargs)
+ ids = torch.where(rast[..., 3:] > 0, rast[..., 3:] + start, 0)
+ rasts.append(torch.cat([rast[..., :3], ids], -1))
+ rast_dbs.append(rast_db)
+ return torch.cat(rasts), torch.cat(rast_dbs)
+
+
+def peel(glctx, pos, tri, layers, **kwargs):
+ with dr.DepthPeeler(glctx, pos, tri, RES, **kwargs) as peeler:
+ return [peeler.rasterize_next_layer() for _ in range(layers)]
+
+
+# Range mode
+
+
+def test_range_mode_matches_instanced_calls(glctx):
+ pos, tri, ranges = scene(glctx.device)
+ rast, rast_db = dr.rasterize(glctx, pos, tri, RES, ranges=ranges)
+ expected, expected_db = instanced(glctx, pos, tri, ranges)
+
+ assert rast.shape == rast_db.shape == (5, *RES, 4)
+ assert torch.equal(rast, expected) and torch.equal(rast_db, expected_db)
+ covered = rast[..., 3] > 0
+ assert covered[:4].flatten(1).any(1).all() and not covered[4].any()
+ for item, (start, count) in enumerate(ranges.tolist()):
+ ids = rast[item, ..., 3][covered[item]] - 1
+ assert ((ids >= start) & (ids < start + count)).all()
+
+
+def test_ids_index_the_whole_triangle_buffer(glctx):
+ pos, tri, ranges = scene(glctx.device)
+ attr = torch.arange(pos.shape[0], dtype=torch.float32, device=pos.device)[:, None]
+ rast, rast_db = dr.rasterize(glctx, pos, tri, RES, ranges=ranges)
+ out, out_da = dr.interpolate(attr, rast, tri, rast_db=rast_db, diff_attrs="all")
+
+ for item, (start, count) in enumerate(ranges.tolist()):
+ single = dr.rasterize(glctx, pos[None], tri[start : start + count], RES)
+ expected, expected_da = dr.interpolate(
+ attr, single[0], tri[start : start + count], rast_db=single[1], diff_attrs="all"
+ )
+ torch.testing.assert_close(out[item : item + 1], expected)
+ torch.testing.assert_close(out_da[item : item + 1], expected_da)
+
+
+@pytest.mark.parametrize("grad_db", [True, False])
+def test_gradients_reach_the_shared_vertices(glctx, grad_db):
+ pos, tri, ranges = scene(glctx.device, seed=1)
+ gen = torch.Generator().manual_seed(2)
+ weights = torch.randn(5, *RES, 4, generator=gen).to(glctx.device)
+
+ grads = []
+ for range_mode in (True, False):
+ p = pos.clone().requires_grad_(True)
+ if range_mode:
+ rast, rast_db = dr.rasterize(glctx, p, tri, RES, ranges=ranges, grad_db=grad_db)
+ else:
+ rast, rast_db = instanced(glctx, p, tri, ranges, grad_db=grad_db)
+ assert rast_db.requires_grad == grad_db
+ loss = (rast[..., :3] * weights[..., :3]).sum()
+ (loss + (rast_db * weights).sum() if grad_db else loss).backward()
+ grads.append(p.grad)
+ assert grads[0].abs().sum() > 0
+ # Triangle 9 is in no range, so its vertices get no gradient.
+ assert (grads[0][27:30] == 0).all()
+ scale = float(grads[1].abs().max())
+ torch.testing.assert_close(grads[0], grads[1], rtol=1e-4, atol=1e-4 * scale)
+
+
+def test_range_mode_gradcheck():
+ pos, tri, ranges = scene(seed=3, num_tri=6)
+ ranges = torch.tensor([[0, 4], [2, 4], [5, 0]], dtype=torch.int32)
+ pos = pos.double().requires_grad_(True)
+
+ def render(p):
+ layers = [reference.rasterize(p[None], t, (8, 8), True) for t in split_ranges(tri, ranges)]
+ return join_ranges(p, (8, 8), ranges, layers)
+
+ assert (render(pos)[0][:2, ..., 3] > 0).flatten(1).sum(1).min() > 10
+ assert torch.autograd.gradcheck(render, (pos,))
+
+
+def test_depth_peeler_in_range_mode(glctx):
+ pos, tri, ranges = scene(glctx.device, seed=4)
+ layers = peel(glctx, pos, tri, 4, ranges=ranges)
+ assert (layers[2][0][..., 3] > 0).any(), "the scene should have several layers"
+ for item, (start, count) in enumerate(ranges.tolist()):
+ single = peel(glctx, pos[None], tri[start : start + count], 4)
+ for (rast, rast_db), (expected, expected_db) in zip(layers, single, strict=True):
+ ids = torch.where(expected[..., 3:] > 0, expected[..., 3:] + start, 0)
+ assert torch.equal(rast[item : item + 1, ..., :3], expected[..., :3])
+ assert torch.equal(rast[item : item + 1, ..., 3:], ids)
+ assert torch.equal(rast_db[item : item + 1], expected_db)
+
+
+def test_depth_peeler_gradients_in_range_mode(glctx):
+ pos, tri, ranges = scene(glctx.device, seed=5)
+ grads = []
+ for mode in ("ranges", "instanced"):
+ p = pos.clone().requires_grad_(True)
+ if mode == "ranges":
+ second = peel(glctx, p, tri, 2, ranges=ranges)[1][0]
+ else:
+ second = torch.cat(
+ [peel(glctx, p[None], tri[s : s + c], 2)[1][0] for s, c in ranges.tolist()]
+ )
+ second[..., :3].sum().backward()
+ grads.append(p.grad)
+ assert grads[0].abs().sum() > 0
+ scale = float(grads[1].abs().max())
+ torch.testing.assert_close(grads[0], grads[1], rtol=1e-4, atol=1e-4 * scale)
+
+
+def test_ranges_may_live_on_either_device(glctx):
+ pos, tri, ranges = scene(glctx.device)
+ expected, _ = dr.rasterize(glctx, pos, tri, RES, ranges=ranges)
+ rast, _ = dr.rasterize(glctx, pos, tri, RES, ranges=ranges.to(glctx.device))
+ assert torch.equal(rast, expected)
+
+
+def test_empty_ranges(ctx):
+ pos, tri, _ = scene()
+ none = torch.zeros(0, 2, dtype=torch.int32)
+ rast, rast_db = dr.rasterize(ctx, pos, tri, RES, ranges=none)
+ assert rast.shape == rast_db.shape == (0, *RES, 4)
+ assert peel(ctx, pos, tri, 2, ranges=none)[1][0].shape == (0, *RES, 4)
+
+ empty = torch.tensor([[3, 0], [24, 0]], dtype=torch.int32)
+ rast, rast_db = dr.rasterize(ctx, pos, tri, RES, ranges=empty)
+ assert rast.shape == (2, *RES, 4) and (rast == 0).all() and (rast_db == 0).all()
+
+
+def test_ranges_are_ignored_in_instanced_mode(ctx):
+ pos, tri, _ = scene()
+ expected = dr.rasterize(ctx, pos[None], tri, RES)
+ for ranges in (
+ torch.tensor([[0, 3]], dtype=torch.int32),
+ torch.tensor([[100, 100]], dtype=torch.int32),
+ torch.zeros(7, dtype=torch.int64),
+ ):
+ rast = dr.rasterize(ctx, pos[None], tri, RES, ranges=ranges)
+ assert torch.equal(rast[0], expected[0]) and torch.equal(rast[1], expected[1])
+ layers = peel(ctx, pos[None], tri, 1, ranges=ranges)
+ assert torch.equal(layers[0][0], expected[0])
+
+
+@pytest.mark.parametrize("make", [dr.rasterize, dr.DepthPeeler])
+def test_range_mode_validates_ranges(ctx, make):
+ pos, tri, ranges = scene()
+ with pytest.raises(ValueError, match="ranges is required"):
+ make(ctx, pos, tri, RES)
+ with pytest.raises(TypeError, match=r"ranges must be a torch\.Tensor"):
+ make(ctx, pos, tri, RES, ranges=[[0, 3]])
+ with pytest.raises(ValueError, match="ranges must have shape"):
+ make(ctx, pos, tri, RES, ranges=ranges[0])
+ with pytest.raises(ValueError, match="ranges must have shape"):
+ make(ctx, pos, tri, RES, ranges=torch.zeros(2, 3, dtype=torch.int32))
+ with pytest.raises(TypeError, match=r"ranges must be torch\.int32"):
+ make(ctx, pos, tri, RES, ranges=ranges.long())
+ for bad in ([20, 5], [-1, 3], [3, -1], [25, 0]):
+ with pytest.raises(ValueError, match=r"ranges\[1\]"):
+ make(ctx, pos, tri, RES, ranges=torch.tensor([[0, 24], bad], dtype=torch.int32))
+ with pytest.raises(ValueError, match="pos must have shape"):
+ make(ctx, pos[:, :3], tri, RES, ranges=ranges)
+
+
+def test_depth_peeler_keeps_its_ranges(ctx):
+ pos, tri, ranges = scene()
+ kept = ranges.clone()
+ with dr.DepthPeeler(ctx, pos, tri, RES, ranges=kept) as peeler:
+ first, _ = peeler.rasterize_next_layer()
+ kept.zero_()
+ second, _ = peeler.rasterize_next_layer()
+ expected = peel(ctx, pos, tri, 2, ranges=ranges)
+ assert torch.equal(first, expected[0][0]) and torch.equal(second, expected[1][0])
+
+
+# Context
+
+
+class ContextWithoutDerivatives:
+ """Stands in for a context that produces no ``rast_db``, like nvdiffrast's OpenGL context."""
+
+ output_db = False
+
+ def __init__(self, device):
+ self.device = torch.device(device)
+
+
+def test_context_is_named_glctx(ctx, triangle):
+ pos, tri = triangle
+ expected, _ = dr.rasterize(ctx, pos, tri, (8, 8))
+ rast, _ = dr.rasterize(glctx=ctx, pos=pos, tri=tri, resolution=(8, 8))
+ assert torch.equal(rast, expected)
+ with dr.DepthPeeler(glctx=ctx, pos=pos, tri=tri, resolution=(8, 8)) as peeler:
+ assert torch.equal(peeler.rasterize_next_layer()[0], expected)
+
+
+@pytest.mark.parametrize("grad_db", [True, False])
+def test_context_without_derivative_output(glctx, grad_db):
+ plain = ContextWithoutDerivatives(glctx.device)
+ pos, tri, ranges = scene(glctx.device)
+ for p, kwargs in ((pos[None].clone(), {}), (pos.clone(), {"ranges": ranges})):
+ expected, _ = dr.rasterize(glctx, p, tri, RES, **kwargs)
+ p.requires_grad_(True)
+ rast, rast_db = dr.rasterize(plain, p, tri, RES, grad_db=grad_db, **kwargs)
+ assert rast_db.shape == (*rast.shape[:3], 0) and not rast_db.requires_grad
+ assert torch.equal(rast, expected)
+ rast[..., :3].sum().backward()
+ assert p.grad.abs().sum() > 0
+
+ for rast, rast_db in peel(plain, p, tri, 2, grad_db=grad_db, **kwargs):
+ assert rast.shape == expected.shape and rast_db.shape == (*rast.shape[:3], 0)
+
+
+# DepthPeeler state
+
+
+def test_depth_peeler_cannot_be_used_after_its_with_block(glctx):
+ pos, tri, _ = scene(glctx.device)
+ with dr.DepthPeeler(glctx, pos[None], tri, RES) as peeler:
+ peeler.rasterize_next_layer()
+ with pytest.raises(RuntimeError, match="closed"):
+ peeler.rasterize_next_layer()
+
+
+def test_depth_peeler_without_with_block_keeps_peeling(ctx):
+ pos, tri, _ = scene()
+ peeler = dr.DepthPeeler(ctx, pos[None], tri, RES)
+ layers = [peeler.rasterize_next_layer() for _ in range(3)]
+ for (rast, _), (expected, _) in zip(layers, peel(ctx, pos[None], tri, 3), strict=True):
+ assert torch.equal(rast, expected)
+
+
+def test_depth_peeler_keeps_the_geometry_it_was_given(glctx):
+ # The buffers are edited in place between layers; pos is a view of a larger one.
+ pos, tri, _ = scene(glctx.device)
+ buffer, tri = pos[None].repeat(2, 1, 1), tri.clone()
+ expected = peel(glctx, pos[None], tri.clone(), 3)
+ with dr.DepthPeeler(glctx, buffer[:1], tri, RES) as peeler:
+ layers = [peeler.rasterize_next_layer()]
+ buffer[1] += 1.0
+ layers.append(peeler.rasterize_next_layer())
+ buffer[0, :, 2] -= 0.1
+ tri[:] = tri.flip(0)
+ layers.append(peeler.rasterize_next_layer())
+ for (rast, rast_db), (wanted, wanted_db) in zip(layers, expected, strict=True):
+ assert torch.equal(rast, wanted) and torch.equal(rast_db, wanted_db)
+ assert (layers[2][0][..., 3] > 0).any()
+
+
+def test_depth_peeler_gradients_reach_the_pos_it_was_given(glctx):
+ pos, tri, _ = scene(glctx.device)
+ pos = pos[None].clone().requires_grad_(True)
+ with dr.DepthPeeler(glctx, pos, tri, RES) as peeler:
+ peeler.rasterize_next_layer()
+ with torch.no_grad():
+ pos[..., :2] *= 0.5
+ rast, rast_db = peeler.rasterize_next_layer()
+ assert (rast[..., 3] > 0).any()
+ (rast[..., :3].sum() + rast_db.sum()).backward()
+ assert pos.grad.abs().sum() > 0
+
+
+def test_depth_peeler_in_inference_mode(ctx):
+ pos, tri, _ = scene()
+ with torch.inference_mode():
+ layers = peel(ctx, pos[None].clone(), tri, 2)
+ expected = peel(ctx, pos[None], tri, 2)
+ assert torch.equal(layers[1][0], expected[1][0])
diff --git a/tests/test_topology.py b/tests/test_topology.py
new file mode 100644
index 0000000..e6b4e1c
--- /dev/null
+++ b/tests/test_topology.py
@@ -0,0 +1,414 @@
+"""Edge adjacency for antialias: the topology hash and the per-tensor cache behind it."""
+
+import copy
+import gc
+import io
+import pickle
+import threading
+
+import pytest
+import torch
+
+import diffrast as dr
+from diffrast import backends, topology
+from diffrast._cache import TensorCache
+from diffrast.backends import reference
+from diffrast.ops import antialias_construct_topology_hash
+from diffrast.topology import TopologyHash
+
+QUAD = torch.tensor([[0, 1, 2], [0, 2, 3]], dtype=torch.int32)
+
+
+@pytest.fixture(
+ params=[("cpu", "reference"), pytest.param(("cuda", "triton"), marks=pytest.mark.gpu)],
+ ids=["reference", "triton"],
+)
+def device(request):
+ """Run a test on the reference backend on the CPU and on the Triton backend on the GPU."""
+ name, backend = request.param
+ if backend == "triton":
+ pytest.importorskip("triton")
+ previous = backends._selected
+ dr.set_backend(backend)
+ yield torch.device(name)
+ backends._selected = previous
+
+
+@pytest.fixture
+def counted(monkeypatch):
+ """Count how often the adjacency is rebuilt, starting from an empty cache."""
+ calls = []
+
+ def compute(tri):
+ calls.append(tri.shape[0])
+ return reference.edge_neighbours(tri)
+
+ cache = TensorCache(compute, max_entries=16)
+ monkeypatch.setattr(topology, "_neighbour_cache", cache)
+ return calls
+
+
+def folded_strip(device="cpu", columns=6):
+ """A strip of quads with shared vertices, folded back over itself along its middle."""
+ xs = torch.linspace(-0.8, 0.8, columns + 1)
+ xs = torch.where(xs > 0, 0.4 - xs, xs)
+ bottom = torch.stack([xs, torch.full_like(xs, -0.6)], -1)
+ top = torch.stack([xs + 0.05, torch.full_like(xs, 0.7)], -1)
+ xy = torch.cat([bottom, top])
+ depth = torch.linspace(-0.5, 0.5, columns + 1).repeat(2)[:, None]
+ w = torch.linspace(1.0, 1.6, 2 * columns + 2)[:, None]
+ pos = torch.cat([xy * w, depth * w, w], -1)[None]
+ tri = []
+ for column in range(columns):
+ a, b = column, column + 1
+ c, d = b + columns + 1, a + columns + 1
+ tri += [[a, b, c], [a, c, d]]
+ return pos.to(device), torch.tensor(tri, dtype=torch.int32, device=device)
+
+
+def scene(device, resolution=(24, 32)):
+ pos, tri = folded_strip(device)
+ pos = torch.cat([pos, pos * torch.tensor([0.8, -0.9, 1.0, 1.0], device=device)])
+ ctx = dr.RasterizeContext(device)
+ rast, _ = dr.rasterize(ctx, pos, tri, resolution)
+ gen = torch.Generator().manual_seed(0)
+ color = torch.rand(2, *resolution, 3, generator=gen).to(device)
+ return color, rast, pos, tri
+
+
+def run(color, rast, pos, tri, **kwargs):
+ pos = pos.clone().requires_grad_(True)
+ out = dr.antialias(color, rast, pos, tri, **kwargs)
+ out.square().sum().backward()
+ return out.detach(), pos.grad
+
+
+class TestEdgeNeighbours:
+ def test_quad(self):
+ # Edge k is opposite vertex k, so the diagonal (0, 2) is edge 1 of [0, 1, 2], numbered
+ # 1, and edge 2 of [0, 2, 3], numbered 5.
+ neighbours = reference.edge_neighbours(QUAD)
+ assert neighbours.dtype == torch.int64
+ assert neighbours.tolist() == [[-1, 5, -1], [-1, -1, 1]]
+
+ def test_edge_shared_by_three_triangles_has_no_neighbour(self):
+ tri = torch.tensor([[0, 1, 2], [0, 2, 3], [0, 2, 4]], dtype=torch.int32)
+ assert (reference.edge_neighbours(tri) == -1).all()
+
+ def test_does_not_depend_on_winding_or_index_size(self):
+ tri = torch.tensor([[70000, 5, 900000], [900000, 70000, 12]], dtype=torch.int32)
+ assert reference.edge_neighbours(tri).tolist() == [[-1, 5, -1], [-1, -1, 1]]
+
+ def test_silhouettes_are_the_same_with_precomputed_neighbours(self):
+ pos, tri = folded_strip()
+ tri = tri.long()
+ direct = reference._silhouette_edges(pos, tri)
+ reused = reference._silhouette_edges(pos, tri, reference.edge_neighbours(tri))
+ assert torch.equal(direct, reused)
+ # Both the outline and the fold are silhouettes; the other shared edges are not.
+ assert direct.any() and not direct.all()
+
+
+class TestTopologyHash:
+ def test_results_are_identical_with_and_without(self, device):
+ color, rast, pos, tri = scene(device)
+ topology_hash = antialias_construct_topology_hash(tri)
+ assert isinstance(topology_hash, TopologyHash)
+
+ plain = run(color, rast, pos, tri)
+ cached = run(color, rast, pos, tri)
+ hashed = run(color, rast, pos, tri, topology_hash=topology_hash)
+ assert (plain[0] != color).any()
+ for other in (cached, hashed):
+ torch.testing.assert_close(other[0], plain[0], atol=1e-6, rtol=0)
+ torch.testing.assert_close(other[1], plain[1], atol=1e-3, rtol=1e-4)
+
+ def test_backend_gets_the_same_adjacency_either_way(self, device, monkeypatch):
+ color, rast, pos, tri = scene(device)
+ backend = backends.get_backend(device, "antialias")
+ seen = []
+ original = backend.antialias
+
+ def spy(*args):
+ seen.append(args[5])
+ return original(*args)
+
+ monkeypatch.setattr(backend, "antialias", spy)
+ dr.antialias(color, rast, pos, tri)
+ dr.antialias(color, rast, pos, tri, antialias_construct_topology_hash(tri))
+ assert torch.equal(seen[0], seen[1])
+ assert torch.equal(seen[0], reference.edge_neighbours(tri))
+
+ def test_is_not_rebuilt_per_call(self, counted):
+ color, rast, pos, tri = scene("cpu")
+ topology_hash = antialias_construct_topology_hash(tri)
+ for _ in range(3):
+ dr.antialias(color, rast, pos, tri, topology_hash=topology_hash)
+ assert not counted
+
+ def test_works_with_an_equal_tensor(self):
+ color, rast, pos, tri = scene("cpu")
+ topology_hash = antialias_construct_topology_hash(tri)
+ expected = dr.antialias(color, rast, pos, tri)
+ assert torch.equal(dr.antialias(color, rast, pos, tri.clone(), topology_hash), expected)
+
+ def test_rejects_another_shape(self):
+ color, rast, pos, tri = scene("cpu")
+ topology_hash = antialias_construct_topology_hash(tri)
+ with pytest.raises(ValueError, match=r"built for a tri of shape \(12, 3\) on cpu"):
+ dr.antialias(color, rast, pos, tri[:4], topology_hash=topology_hash)
+
+ @pytest.mark.gpu
+ def test_rejects_another_device(self):
+ color, rast, pos, tri = scene("cuda")
+ topology_hash = antialias_construct_topology_hash(tri.cpu())
+ with pytest.raises(ValueError, match=r"on cpu, got shape .* on cuda:0"):
+ dr.antialias(color, rast, pos, tri, topology_hash=topology_hash)
+
+ def test_rejects_a_tensor_modified_since(self):
+ color, rast, pos, tri = scene("cpu")
+ topology_hash = antialias_construct_topology_hash(tri)
+ tri[0] = tri[0].flip(0)
+ with pytest.raises(ValueError, match="modified in place"):
+ dr.antialias(color, rast, pos, tri, topology_hash=topology_hash)
+
+ def test_rejects_other_objects(self):
+ color, rast, pos, tri = scene("cpu")
+ with pytest.raises(TypeError, match="topology_hash must come from"):
+ dr.antialias(color, rast, pos, tri, topology_hash=torch.zeros(3))
+
+ def test_constructor_checks_tri(self):
+ with pytest.raises(TypeError, match=r"tri must be torch\.int32"):
+ antialias_construct_topology_hash(QUAD.long())
+ with pytest.raises(ValueError, match=r"tri must have shape \[triangles, 3\]"):
+ antialias_construct_topology_hash(QUAD.flatten())
+
+ def test_repr(self):
+ assert repr(antialias_construct_topology_hash(QUAD)) == (
+ "TopologyHash(triangles=2, device='cpu')"
+ )
+
+ def test_is_checked_without_triangles(self):
+ color, rast, pos, tri = scene("cpu")
+ with pytest.raises(TypeError, match="topology_hash must come from"):
+ dr.antialias(color, rast, pos, tri[:0], topology_hash="junk")
+ with pytest.raises(ValueError, match=r"built for a tri of shape \(12, 3\)"):
+ dr.antialias(color, rast, pos, tri[:0], antialias_construct_topology_hash(tri))
+ empty = antialias_construct_topology_hash(tri[:0])
+ assert torch.equal(dr.antialias(color, rast, pos, tri[:0], empty), color)
+
+ @pytest.mark.parametrize(
+ "duplicate",
+ [lambda h: pickle.loads(pickle.dumps(h)), copy.deepcopy, copy.copy],
+ ids=["pickle", "deepcopy", "copy"],
+ )
+ def test_can_be_pickled_and_copied(self, device, duplicate):
+ color, rast, pos, tri = scene(device)
+ original = antialias_construct_topology_hash(tri)
+ topology_hash = duplicate(original)
+ assert isinstance(topology_hash, TopologyHash)
+ assert repr(topology_hash) == repr(original)
+ assert torch.equal(topology_hash.neighbours(tri), original.neighbours(tri))
+ # The Triton kernels add the blends in no fixed order, so two runs differ by rounding.
+ out = dr.antialias(color, rast, pos, tri, topology_hash)
+ torch.testing.assert_close(out, dr.antialias(color, rast, pos, tri), atol=1e-6, rtol=0)
+ with pytest.raises(ValueError, match="built for a tri of shape"):
+ dr.antialias(color, rast, pos, tri[:4], topology_hash)
+
+ def test_can_be_saved_with_torch(self):
+ color, rast, pos, tri = scene("cpu")
+ buffer = io.BytesIO()
+ torch.save({"topology": antialias_construct_topology_hash(tri)}, buffer)
+ buffer.seek(0)
+ topology_hash = torch.load(buffer, weights_only=False)["topology"]
+ expected = dr.antialias(color, rast, pos, tri)
+ assert torch.equal(dr.antialias(color, rast, pos, tri, topology_hash), expected)
+
+
+class TestAutomaticReuse:
+ def test_same_tensor_is_analysed_once(self, counted):
+ color, rast, pos, tri = scene("cpu")
+ first = dr.antialias(color, rast, pos, tri)
+ second = dr.antialias(color, rast, pos, tri)
+ assert len(counted) == 1
+ assert torch.equal(first, second)
+
+ def test_in_place_edit_rebuilds(self, counted):
+ color, rast, pos, tri = scene("cpu")
+ before = dr.antialias(color, rast, pos, tri)
+ # Pointing a corner of the first triangle at another vertex in the same place turns the
+ # edges it shared into silhouettes, so a stale adjacency would give a different image.
+ pos = torch.cat([pos, pos[:, 8:9]], 1)
+ tri[0, 2] = 14
+ edited = dr.antialias(color, rast, pos, tri)
+ assert len(counted) == 2
+ fresh = dr.antialias(color, rast, pos, tri.clone())
+ assert torch.equal(edited, fresh)
+ assert not torch.equal(edited, before)
+
+ def test_edit_through_a_view_rebuilds(self, counted):
+ color, rast, pos, tri = scene("cpu")
+ dr.antialias(color, rast, pos, tri)
+ tri[:1][0, 2] = 13
+ dr.antialias(color, rast, pos, tri)
+ assert len(counted) == 2
+
+ def test_equal_tensor_gets_its_own_entry(self, counted):
+ color, rast, pos, tri = scene("cpu")
+ expected = dr.antialias(color, rast, pos, tri)
+ copy = tri.clone()
+ assert torch.equal(dr.antialias(color, rast, pos, copy), expected)
+ assert len(counted) == 2
+ assert len(topology._neighbour_cache) == 2
+
+ def test_no_growth_after_tensors_are_freed(self, counted):
+ color, rast, pos, tri = scene("cpu")
+ for _ in range(40):
+ dr.antialias(color, rast, pos, tri.clone())
+ gc.collect()
+ assert len(topology._neighbour_cache) == 0
+ assert len(counted) == 40
+
+ def test_live_tensors_are_bounded(self, counted):
+ color, rast, pos, tri = scene("cpu")
+ alive = [tri.clone() for _ in range(40)]
+ for t in alive:
+ dr.antialias(color, rast, pos, t)
+ assert len(topology._neighbour_cache) == 16
+
+ def test_zero_triangles_are_not_cached(self, counted):
+ color, rast, pos, tri = scene("cpu")
+ out = dr.antialias(color, rast, pos, tri[:0])
+ assert torch.equal(out, color)
+ assert out is not color
+ assert not counted
+
+ def test_concurrent_calls_give_the_same_image(self, counted):
+ color, rast, pos, tri = scene("cpu")
+ expected = dr.antialias(color, rast, pos, tri.clone())
+ own = [tri.clone() for _ in range(4)]
+ failures = []
+
+ def work(index):
+ try:
+ for step in range(25):
+ # Alternate between a tensor all threads share, one that only this thread
+ # uses, and a new one, so that entries are added and dropped concurrently.
+ t = (tri, own[index], tri.clone())[step % 3]
+ if not torch.equal(dr.antialias(color, rast, pos, t), expected):
+ failures.append((index, step))
+ except Exception as error:
+ failures.append(error)
+
+ threads = [threading.Thread(target=work, args=(index,)) for index in range(4)]
+ for thread in threads:
+ thread.start()
+ for thread in threads:
+ thread.join()
+ assert not failures
+
+
+class TestTensorCache:
+ def make(self, max_entries=4):
+ calls = []
+
+ def compute(tensor):
+ calls.append(1)
+ return tensor.sum().item()
+
+ return TensorCache(compute, max_entries), calls
+
+ def test_hit_and_miss(self):
+ cache, calls = self.make()
+ a, b = torch.arange(3), torch.arange(4)
+ assert [cache.get(a), cache.get(a), cache.get(b), cache.get(a)] == [3, 3, 6, 3]
+ assert len(calls) == 2
+ assert len(cache) == 2
+
+ def test_in_place_edit_is_seen(self):
+ cache, calls = self.make()
+ a = torch.arange(3)
+ assert cache.get(a) == 3
+ a[0] = 10
+ assert cache.get(a) == 13
+ a.add_(1)
+ assert cache.get(a) == 16
+ a[1:].mul_(2)
+ assert cache.get(a) == 21
+ assert len(calls) == 4
+ assert len(cache) == 1
+
+ def test_new_storage_is_seen(self):
+ # Assigning to .data leaves the version counter alone.
+ cache, _ = self.make()
+ a = torch.arange(3)
+ assert cache.get(a) == 3
+ a.data = torch.arange(5)
+ assert cache.get(a) == 10
+ a.resize_(2)
+ assert cache.get(a) == 1
+
+ def test_entry_dies_with_its_tensor(self):
+ cache, _ = self.make()
+ a = torch.arange(3)
+ cache.get(a)
+ del a
+ gc.collect()
+ assert len(cache) == 0
+
+ def test_new_tensor_at_a_recycled_address_is_not_confused(self):
+ cache, _ = self.make()
+ for size in range(1, 200):
+ # Each tensor is freed before the next is made, so addresses repeat.
+ assert cache.get(torch.ones(size)) == size
+
+ def test_oldest_entry_is_dropped(self):
+ cache, calls = self.make(max_entries=2)
+ a, b, c = torch.arange(2), torch.arange(3), torch.arange(4)
+ for tensor in (a, b, c):
+ cache.get(tensor)
+ assert len(cache) == 2
+ cache.get(b)
+ cache.get(c)
+ assert len(calls) == 3
+ cache.get(a)
+ assert len(calls) == 4
+
+ def test_inference_tensors_are_not_cached(self):
+ cache, calls = self.make()
+ with torch.inference_mode():
+ a = torch.arange(3)
+ assert cache.get(a) == 3
+ assert cache.get(a) == 3
+ assert len(calls) == 2
+ assert len(cache) == 0
+
+ def test_clear(self):
+ cache, calls = self.make()
+ a = torch.arange(3)
+ cache.get(a)
+ cache.clear()
+ cache.get(a)
+ assert len(calls) == 2
+
+ def test_concurrent_use(self):
+ cache, _ = self.make(max_entries=3)
+ shared = [torch.full((5,), value) for value in range(6)]
+ failures = []
+
+ def work():
+ try:
+ for step in range(300):
+ tensor = shared[step % 6] if step % 2 else torch.full((5,), step)
+ if cache.get(tensor) != 5 * int(tensor[0]):
+ failures.append(step)
+ except Exception as error:
+ failures.append(error)
+
+ threads = [threading.Thread(target=work) for _ in range(6)]
+ for thread in threads:
+ thread.start()
+ for thread in threads:
+ thread.join()
+ assert not failures
+ assert len(cache) <= 3
diff --git a/tests/test_triton.py b/tests/test_triton.py
index dfcee52..5294c9a 100644
--- a/tests/test_triton.py
+++ b/tests/test_triton.py
@@ -186,10 +186,8 @@ def test_forward_matches_reference(self, channels, attr_layout):
ref = reference.interpolate(attr, rast, tri, rast_db, diff)
out = triton_backend.interpolate(attr, rast, tri, rast_db, diff)
torch.testing.assert_close(out[0], ref[0])
- if diff:
- torch.testing.assert_close(out[1], ref[1])
- else:
- assert out[1] is None
+ assert out[1].shape == (*rast.shape[:3], 2 * len(diff))
+ torch.testing.assert_close(out[1], ref[1])
@pytest.mark.parametrize("attr_layout", ["shared", "per_view"])
@pytest.mark.parametrize("diff", [[], [0, 2, 3]])
@@ -209,6 +207,20 @@ def test_gradients_match_reference(self, attr_layout, diff):
for ours, ref in zip(grads[1], grads[0], strict=True):
torch.testing.assert_close(ours, ref, atol=1e-4, rtol=1e-4)
+ @pytest.mark.parametrize("diff", [[], [0, 2, 3]])
+ def test_constant_attributes_still_pass_gradients_to_rast(self, diff):
+ attr, rast, rast_db, tri = self.scene(5, "shared", seed=5)
+ grads = []
+ for backend in (reference, triton_backend):
+ r, d = (t.clone().requires_grad_(True) for t in (rast, rast_db))
+ out, out_da = backend.interpolate(attr, r, tri, d, diff)
+ (out.sum() + out_da.square().sum()).backward()
+ grads.append((r.grad, d.grad if diff else None))
+ torch.testing.assert_close(grads[1][0], grads[0][0], atol=1e-4, rtol=1e-4)
+ if diff:
+ torch.testing.assert_close(grads[1][1], grads[0][1], atol=1e-4, rtol=1e-4)
+ assert attr.grad is None
+
def test_gradient_through_derivatives_only(self):
attr, rast, rast_db, tri = self.scene(4, "shared", seed=3)
grads = []
@@ -330,6 +342,7 @@ def test_gradients_where_pixels_share_texels(self, filter_mode, pattern):
@pytest.mark.parametrize("filter_mode", ["nearest", "linear", "linear-mipmap-nearest"])
def test_unused_uv_da_gets_no_gradient(self, filter_mode):
tex, uv, uv_da = self.scene()
+ tex.requires_grad_(True)
uv_da.requires_grad_(True)
triton_backend.texture(tex, uv, uv_da, filter_mode, "wrap", None).sum().backward()
assert uv_da.grad is None or (uv_da.grad == 0).all()
diff --git a/tests/test_validation.py b/tests/test_validation.py
index 97912e4..e89f9dc 100644
--- a/tests/test_validation.py
+++ b/tests/test_validation.py
@@ -23,10 +23,11 @@ def test_rasterize_rejects_bad_resolution(ctx, triangle, resolution):
dr.rasterize(ctx, pos, tri, resolution)
-def test_rasterize_rejects_range_mode(ctx, triangle):
+def test_rasterize_ignores_ranges_in_instanced_mode(ctx, triangle):
pos, tri = triangle
- with pytest.raises(NotImplementedError, match="Range mode"):
- dr.rasterize(ctx, pos, tri, (8, 8), ranges=torch.zeros(1, 2, dtype=torch.int32))
+ expected = dr.rasterize(ctx, pos, tri, (8, 8))
+ rast = dr.rasterize(ctx, pos, tri, (8, 8), ranges=torch.zeros(1, 2, dtype=torch.int32))
+ assert torch.equal(rast[0], expected[0])
def test_interpolate_requires_rast_db_for_derivatives(triangle):
@@ -69,11 +70,11 @@ def test_texture_rejects_unknown_modes():
dr.texture(tex, uv, boundary_mode="mirror")
-def test_texture_rejects_precomputed_mips():
+def test_texture_rejects_mip_that_is_not_a_list():
tex = torch.zeros(1, 16, 16, 3)
uv = torch.zeros(1, 8, 8, 2)
- with pytest.raises(NotImplementedError, match="mip="):
- dr.texture(tex, uv, mip=[tex])
+ with pytest.raises(TypeError, match="mip must be a list"):
+ dr.texture(tex, uv, mip=torch.zeros(1, 8, 8, 3))
def test_texture_checks_mip_level_bias_shape():
From d2f7ce82a79dba79ef80ef4463a5b70455785a7c Mon Sep 17 00:00:00 2001
From: Senne Cools <113857183+sennecools@users.noreply.github.com>
Date: Mon, 16 Nov 2026 22:13:37 +0100
Subject: [PATCH 2/4] Add examples for shape, pose, environment-map fitting and
depth peeling
The examples share meshes, cameras and image helpers in examples/common.py, and each runs as a smoke test on the CPU. texture_fitting.py now fits a texture on a torus knot.
---
examples/antialias_gradients.py | 313 +++++++++++++++
examples/common.py | 691 ++++++++++++++++++++++++++++++++
examples/depth_peeling.py | 356 ++++++++++++++++
examples/env_lighting.py | 461 +++++++++++++++++++++
examples/gbuffer.py | 228 +++++++++++
examples/pose_fitting.py | 532 ++++++++++++++++++++++++
examples/shape_fitting.py | 417 +++++++++++++++++++
examples/texture_fitting.py | 462 ++++++++++++---------
tests/test_examples.py | 54 ++-
9 files changed, 3320 insertions(+), 194 deletions(-)
create mode 100644 examples/antialias_gradients.py
create mode 100644 examples/common.py
create mode 100644 examples/depth_peeling.py
create mode 100644 examples/env_lighting.py
create mode 100644 examples/gbuffer.py
create mode 100644 examples/pose_fitting.py
create mode 100644 examples/shape_fitting.py
diff --git a/examples/antialias_gradients.py b/examples/antialias_gradients.py
new file mode 100644
index 0000000..faf0bca
--- /dev/null
+++ b/examples/antialias_gradients.py
@@ -0,0 +1,313 @@
+"""Show why a silhouette needs ``antialias`` before it can be optimised.
+
+A coarse sphere is rendered as a flat silhouette and compared with the silhouette of the same
+sphere moved a little to the side. Whether a pixel is covered is a yes-or-no decision, so without
+``antialias`` the image does not change when a vertex moves by a small amount, and the gradient of
+the loss with respect to the vertex positions is exactly zero. ``antialias`` blends the pixels
+along the outline by how far the edge reaches into them. That makes the image a continuous function
+of the vertices: the gradient appears, and only on the outline.
+
+The mesh is coarse on purpose. ``antialias`` looks for the silhouette edge among the edges of the
+triangle that a pixel shows, so it needs triangles that are larger than a pixel where they meet
+the outline. Try ``--subdivisions 3`` to see how much of the outline a finer mesh loses at the same
+resolution.
+
+ python examples/antialias_gradients.py --out antialias_gradients.png
+
+Requires Pillow (``pip install -e . --group examples``).
+"""
+
+from __future__ import annotations
+
+import argparse
+import math
+
+import torch
+import torch.nn.functional as F
+from PIL import Image, ImageDraw
+from torch import Tensor
+
+import diffrast as dr
+from common import (
+ ACCENT,
+ BACKGROUND,
+ CLAY,
+ MUTED,
+ PANEL,
+ TEXT,
+ Mesh,
+ downsample,
+ icosphere,
+ look_at,
+ orbit,
+ perspective,
+ rgb,
+ titled_panels,
+ to_clip,
+ to_image,
+ to_srgb,
+)
+
+TARGET_OFFSET = (0.16, 0.10, 0.0)
+
+
+def render_silhouette(
+ ctx: dr.RasterizeContext, mesh: Mesh, mvp: Tensor, resolution: int, antialias: bool
+) -> Tensor:
+ """Coverage image ``[1, height, width, 1]``: one inside the silhouette, zero outside."""
+ pos = to_clip(mesh.positions, mvp)
+ rast, _ = dr.rasterize(ctx, pos, mesh.tri, (resolution, resolution))
+ white = torch.ones_like(mesh.positions[:, :1])
+ coverage, _ = dr.interpolate(white, rast, mesh.tri)
+ if antialias:
+ coverage = dr.antialias(coverage, rast, pos, mesh.tri)
+ return coverage
+
+
+def vertex_gradient(
+ ctx: dr.RasterizeContext, mesh: Mesh, mvp: Tensor, target: Tensor, antialias: bool
+) -> tuple[Tensor, Tensor]:
+ """The silhouette and the gradient of its squared error with respect to the vertices."""
+ positions = mesh.positions.detach().requires_grad_()
+ image = render_silhouette(
+ ctx, mesh._replace(positions=positions), mvp, target.shape[1], antialias
+ )
+ loss = F.mse_loss(image, target)
+ loss.backward()
+ return image.detach(), positions.grad
+
+
+def blended_share(aliased: Tensor, smooth: Tensor) -> float:
+ """Share of the pixel pairs lying across the outline in which ``antialias`` changed a pixel."""
+ inside = aliased > 0.5
+ changed = smooth != aliased
+ last = inside.shape[0] - 1
+ pairs = blended = 0
+ for axis in (0, 1):
+ across = inside.narrow(axis, 0, last) != inside.narrow(axis, 1, last)
+ touched = changed.narrow(axis, 0, last) | changed.narrow(axis, 1, last)
+ pairs += int(across.sum())
+ blended += int((across & touched).sum())
+ return blended / max(pairs, 1)
+
+
+def draw_flat(
+ ctx: dr.RasterizeContext, pos: Tensor, tri: Tensor, colour: tuple[float, ...], under: Tensor
+) -> Tensor:
+ """Triangles in one colour over the image ``under``, with antialiased edges."""
+ rast, _ = dr.rasterize(ctx, pos, tri, under.shape[1:3])
+ image = torch.where(rast[..., 3:] > 0, under.new_tensor(colour), under)
+ return dr.antialias(image, rast, pos, tri)
+
+
+def draw_mesh(ctx: dr.RasterizeContext, mesh: Mesh, mvp: Tensor, under: Tensor) -> Tensor:
+ """Flat-shaded clay mesh with its triangle edges drawn in, over the image ``under``."""
+ pos = to_clip(mesh.positions, mvp)
+ rast, rast_db = dr.rasterize(ctx, pos, mesh.tri, under.shape[1:3])
+
+ # The triangle id in rast picks the normal of the face behind each pixel.
+ a, b, c = mesh.positions[mesh.tri.long()].unbind(1)
+ face_normals = F.normalize(torch.linalg.cross(b - a, c - a), dim=-1)
+ normal = face_normals[(rast[..., 3].long() - 1).clamp(min=0)]
+ light = F.normalize(normal.new_tensor([0.45, 0.85, 0.55]), dim=0)
+ diffuse = (normal @ light).clamp(min=0)[..., None]
+ colour = to_srgb(normal.new_tensor(CLAY) * (0.2 + 0.3 * diffuse))
+
+ # A barycentric is zero on one edge of its triangle and rast_db says how fast it grows per
+ # pixel, so their ratio is the distance to that edge in pixels.
+ u, v = rast[..., 0], rast[..., 1]
+ du_dx, du_dy, dv_dx, dv_dy = rast_db.unbind(-1)
+ weights = torch.stack([u, v, 1 - u - v], -1)
+ slopes = torch.stack(
+ [
+ torch.hypot(du_dx, du_dy),
+ torch.hypot(dv_dx, dv_dy),
+ torch.hypot(du_dx + dv_dx, du_dy + dv_dy),
+ ],
+ -1,
+ )
+ distance = (weights / slopes.clamp(min=1e-8)).amin(-1, keepdim=True)
+ colour = colour * (0.6 + 0.4 * (distance - 0.5).clamp(0, 1))
+
+ image = torch.where(rast[..., 3:] > 0, colour, under)
+ return dr.antialias(image, rast, pos, mesh.tri)
+
+
+def arrow_mesh(
+ start: Tensor, end: Tensor, width: float, margin: float = 0.0
+) -> tuple[Tensor, Tensor]:
+ """Flat arrows from ``start`` to ``end`` (``[count, 2]``, in clip space) as triangles.
+
+ ``margin`` moves every edge of the arrows outwards by that distance.
+ """
+ along = end - start
+ length = along.norm(dim=-1, keepdim=True).clamp(min=1e-8)
+ along = along / length
+ side = torch.stack([-along[:, 1], along[:, 0]], -1)
+ head = torch.minimum(0.6 * length, torch.full_like(length, 3.5 * width))
+ slope = 0.45
+ reach = margin * math.hypot(1, slope) / slope
+
+ tail = start - margin * along
+ neck = end - (head + margin) * along
+ tip = end + reach * along
+ half = (0.5 * width + margin) * side
+ barb = slope * (head + margin + reach) * side
+ corners = torch.stack(
+ [tail - half, tail + half, neck + half, neck - half, neck - barb, neck + barb, tip], 1
+ )
+ pos = F.pad(F.pad(corners.reshape(1, -1, 2), (0, 1)), (0, 1), value=1.0)
+ faces = torch.tensor([[0, 1, 2], [0, 2, 3], [4, 5, 6]], device=start.device)
+ first = 7 * torch.arange(start.shape[0], device=start.device)
+ tri = (faces + first[:, None, None]).reshape(-1, 3).int()
+ return pos.contiguous(), tri
+
+
+def gradient_picture(
+ ctx: dr.RasterizeContext, mesh: Mesh, target: Mesh, mvp: Tensor, grad: Tensor, size: int
+) -> Tensor:
+ """The mesh in front of the target silhouette, with an arrow down the gradient per vertex."""
+ image = grad.new_tensor(PANEL).expand(1, size, size, 3)
+ image = draw_flat(ctx, to_clip(target.positions, mvp), target.tri, ACCENT, image)
+ image = draw_mesh(ctx, mesh, mvp, image)
+
+ moved = grad.norm(dim=-1) > 0
+ if moved.any():
+ # The longest arrow stands for a step of 0.45 units; the others are in proportion.
+ step = 0.45 / grad.norm(dim=-1).max()
+ start = to_clip(mesh.positions[moved], mvp)[0]
+ end = to_clip(mesh.positions[moved] - step * grad[moved], mvp)[0]
+ start, end = start[:, :2] / start[:, 3:], end[:, :2] / end[:, 3:]
+ # A dark rim under each arrow keeps it readable on the clay and on the target.
+ for colour, margin in ((BACKGROUND, 0.01), (TEXT, 0.0)):
+ pos, tri = arrow_mesh(start, end, 0.026, margin)
+ image = draw_flat(ctx, pos, tri, colour, image)
+ return image
+
+
+def edge_window(changed: Tensor, size: int) -> tuple[int, int]:
+ """Lower-left corner of a ``size`` pixel window centred on the upper left of the outline."""
+ rows, cols = changed.nonzero(as_tuple=True)
+ pick = (rows - cols).argmax()
+ limit = changed.shape[0] - size
+ row = int((rows[pick] - size // 2).clamp(0, limit))
+ col = int((cols[pick] - size // 2).clamp(0, limit))
+ return row, col
+
+
+def coverage_colours(coverage: Tensor) -> Tensor:
+ """Clay on the panel colour, mixed by coverage so that in-between values show as they are."""
+ clay = to_srgb(coverage.new_tensor(CLAY) * 0.6)
+ return torch.lerp(coverage.new_tensor(PANEL), clay, coverage)
+
+
+def enlarge(image: Tensor, size: int) -> Image.Image:
+ """Nearest-neighbour magnification, so every pixel stays a flat square."""
+ return to_image(image).resize((size, size), Image.Resampling.NEAREST)
+
+
+def figure(
+ ctx: dr.RasterizeContext,
+ mesh: Mesh,
+ target: Mesh,
+ mvp: Tensor,
+ images: tuple[Tensor, Tensor],
+ grads: tuple[Tensor, Tensor],
+ scale: int,
+ zoom: int,
+) -> Image.Image:
+ """Close-ups of one edge, the pixels ``antialias`` changed, and both gradients on the mesh."""
+ aliased, smooth = (image[0] for image in images)
+ resolution = aliased.shape[0]
+ size = resolution * scale
+ difference = (smooth - aliased).abs()
+ changed = difference[..., 0] > 0
+
+ window = max(2, size // zoom)
+ row, col = edge_window(changed, window)
+ close_ups = [
+ enlarge(coverage_colours(image[row : row + window, col : col + window]), size)
+ for image in (aliased, smooth)
+ ]
+
+ # Every changed pixel is drawn at least half bright, so that faint changes stay visible.
+ strength = torch.where(changed[..., None], 0.5 + difference, difference)
+ change_map = enlarge(
+ torch.lerp(strength.new_tensor(PANEL), strength.new_tensor(TEXT), strength), size
+ )
+ left, top = col * scale, (resolution - row - window) * scale
+ box = (left - 2, top - 2, left + window * scale + 1, top + window * scale + 1)
+ ImageDraw.Draw(change_map).rectangle(box, outline=rgb(MUTED), width=2)
+
+ # Rendered at twice the size and averaged down.
+ with torch.no_grad():
+ pictures = [
+ to_image(downsample(gradient_picture(ctx, mesh, target, mvp, grad, 2 * size), 2)[0])
+ for grad in grads
+ ]
+ vertices = mesh.positions.shape[0]
+ reached = [int((grad.norm(dim=-1) > 0).sum()) for grad in grads]
+ cells = [
+ ("without antialias", f"edge pixels, {zoom}x", close_ups[0]),
+ ("with antialias", f"edge pixels, {zoom}x", close_ups[1]),
+ ("changed pixels", f"{int(changed.sum())} of {changed.numel()} pixels", change_map),
+ ("gradient, no antialias", f"{reached[0]} of {vertices} vertices", pictures[0]),
+ ("gradient, with antialias", f"{reached[1]} of {vertices} vertices", pictures[1]),
+ ]
+ titles, details, images = zip(*cells, strict=True)
+ return titled_panels(images, titles, details, columns=len(cells))
+
+
+def main() -> None:
+ parser = argparse.ArgumentParser(description=__doc__.split("\n\n")[0])
+ parser.add_argument("--resolution", type=int, default=154, help="size of the rendered image")
+ parser.add_argument("--subdivisions", type=int, default=1, help="icosphere subdivisions")
+ parser.add_argument("--scale", type=int, default=2, help="figure pixels per image pixel")
+ parser.add_argument("--zoom", type=int, default=14, help="magnification of the close-ups")
+ parser.add_argument("--out", help="write the figure to this PNG")
+ parser.add_argument(
+ "--device", default="cuda" if torch.cuda.is_available() else "cpu", help="cuda or cpu"
+ )
+ args = parser.parse_args()
+
+ device = torch.device(args.device)
+ ctx = dr.RasterizeContext(device)
+ mesh = icosphere(args.subdivisions, device)
+ target = mesh._replace(positions=mesh.positions + mesh.positions.new_tensor(TARGET_OFFSET))
+ eye = orbit(torch.tensor([0.9], device=device), torch.tensor([0.6], device=device), 6.0)
+ mvp = perspective(30, 1.0, device=device) @ look_at(eye)
+
+ with torch.no_grad():
+ goal = render_silhouette(ctx, target, mvp, args.resolution, antialias=True)
+ aliased, grad_aliased = vertex_gradient(ctx, mesh, mvp, goal, antialias=False)
+ smooth, grad_smooth = vertex_gradient(ctx, mesh, mvp, goal, antialias=True)
+
+ vertices = mesh.positions.shape[0]
+ for name, grad in (("without antialias", grad_aliased), ("with antialias", grad_smooth)):
+ reached = int((grad.norm(dim=-1) > 0).sum())
+ print(
+ f"{name:18s} gradient norm {grad.norm().item():.3e}, "
+ f"{reached} of {vertices} vertices receive gradient"
+ )
+ changed = int((smooth != aliased).sum())
+ share = blended_share(aliased[0, ..., 0], smooth[0, ..., 0])
+ print(f"antialias changed {changed} of {smooth.numel()} pixels")
+ print(f"it blended {share:.0%} of the pixel pairs that lie across the outline")
+
+ if args.out:
+ picture = figure(
+ ctx,
+ mesh,
+ target,
+ mvp,
+ (aliased, smooth),
+ (grad_aliased, grad_smooth),
+ args.scale,
+ args.zoom,
+ )
+ picture.save(args.out)
+ print(f"wrote {args.out}")
+
+
+if __name__ == "__main__":
+ main()
diff --git a/examples/common.py b/examples/common.py
new file mode 100644
index 0000000..4427f49
--- /dev/null
+++ b/examples/common.py
@@ -0,0 +1,691 @@
+"""Meshes, cameras, colours and figure layout shared by the examples.
+
+Only boilerplate lives here. Each example spells out its own chain of diffrast ops.
+"""
+
+from __future__ import annotations
+
+import math
+import shutil
+import subprocess
+from collections.abc import Mapping, Sequence
+from pathlib import Path
+from typing import NamedTuple
+
+import numpy as np
+import torch
+import torch.nn.functional as F
+from PIL import Image, ImageDraw, ImageFont
+from torch import Tensor
+
+BACKGROUND = (0.071, 0.067, 0.063)
+PANEL = (0.102, 0.094, 0.090)
+TEXT = (0.941, 0.918, 0.875)
+MUTED = (0.62, 0.60, 0.57)
+ACCENT = (1.0, 0.31, 0.12)
+
+# The colours above are display values. These two are linear albedos: the warm clay of whatever
+# an example optimises, and the near black of what is printed on it.
+CLAY = (0.85, 0.82, 0.78)
+INK = (0.03, 0.028, 0.026)
+
+
+class Mesh(NamedTuple):
+ """Triangle mesh with separate index buffers for positions and texture coordinates.
+
+ Positions are shared across texture seams, so ``tri`` describes the surface itself and is the
+ index buffer to rasterize and antialias with. ``tri_uv`` indexes ``uvs``, which are cut along
+ the seams. Meshes without texture coordinates leave both as ``None``.
+ """
+
+ positions: Tensor
+ tri: Tensor
+ uvs: Tensor | None = None
+ tri_uv: Tensor | None = None
+
+
+def uv_sphere(rings: int = 48, segments: int = 96, device: torch.device | str = "cpu") -> Mesh:
+ """Unit sphere with an equirectangular texture layout; the poles are single vertices."""
+ theta = torch.linspace(0, math.pi, rings + 1)
+ return lathe(torch.sin(theta), torch.cos(theta), segments, device)
+
+
+def lathe(
+ radius: Tensor, height: Tensor, segments: int = 96, device: torch.device | str = "cpu"
+) -> Mesh:
+ """Surface of revolution around the y axis.
+
+ ``radius`` and ``height`` give the profile from top to bottom. It must start and end on the
+ axis, where the surface closes in a single vertex. ``u`` runs around the axis and ``v`` along
+ the profile, from 1 at the top to 0 at the bottom.
+ """
+ radius = radius.to(device, torch.float32)
+ height = height.to(device, torch.float32)
+ rings = radius.shape[0] - 1
+ phi = torch.linspace(0, 2 * math.pi, segments + 1, device=device)
+
+ inner_r, inner_h = radius[1:-1, None], height[1:-1, None]
+ ring_xyz = torch.stack(
+ [
+ inner_r * torch.cos(phi[None, :-1]),
+ inner_h.expand(-1, segments),
+ -inner_r * torch.sin(phi[None, :-1]),
+ ],
+ -1,
+ ).reshape(-1, 3)
+ poles = torch.zeros(2, 3, device=device)
+ poles[:, 1] = height[[0, -1]]
+ positions = torch.cat([poles[:1], ring_xyz, poles[1:]])
+
+ steps = torch.hypot(radius.diff(), height.diff())
+ along = F.pad(steps.cumsum(0), (1, 0)) / steps.sum()
+ u, v = torch.meshgrid(phi / (2 * math.pi), 1 - along, indexing="xy")
+ uvs = torch.stack([u, v], -1).reshape(-1, 2)
+
+ def pos_index(r, s):
+ if r == 0:
+ return 0
+ if r == rings:
+ return positions.shape[0] - 1
+ return 1 + (r - 1) * segments + s % segments
+
+ def uv_index(r, s):
+ return r * (segments + 1) + s
+
+ tri, tri_uv = [], []
+ for r in range(rings):
+ for s in range(segments):
+ a, b, c, d = (r, s), (r + 1, s), (r + 1, s + 1), (r, s + 1)
+ if r == 0:
+ cell = [(a, b, c)] # a and d are the north pole
+ elif r == rings - 1:
+ cell = [(a, b, d)] # b and c are the south pole
+ else:
+ cell = [(a, b, c), (a, c, d)]
+ for corners in cell:
+ tri.append([pos_index(*corner) for corner in corners])
+ tri_uv.append([uv_index(*corner) for corner in corners])
+ tri = torch.tensor(tri, dtype=torch.int32, device=device)
+ tri_uv = torch.tensor(tri_uv, dtype=torch.int32, device=device)
+ return Mesh(positions, tri, uvs, tri_uv)
+
+
+def torus_knot(
+ p: int = 2,
+ q: int = 3,
+ segments: int = 384,
+ sides: int = 48,
+ tube: float = 0.2,
+ device: torch.device | str = "cpu",
+ flat: bool = False,
+ flip_v: bool = False,
+) -> Mesh:
+ """Tube around a ``(p, q)`` torus knot that fits in the unit sphere.
+
+ The knot winds around the z axis. ``flat`` lays it down instead, with the y axis through its
+ middle, so that a camera above it sees the lobes apart and a turn about y is a turntable.
+
+ ``u`` runs along the knot and ``v`` around the tube. Seen from outside the tube that frame is
+ left-handed, so a texture appears as its mirror image. Stripes do not mind, lettering does:
+ ``flip_v`` reverses ``v`` so that text reads the right way round.
+ """
+
+ def curve(t):
+ r = 2 + torch.cos(q * t)
+ return torch.stack([r * torch.cos(p * t), r * torch.sin(p * t), -torch.sin(q * t)], -1)
+
+ # Frenet frame from finite differences, in float64 so the second difference is accurate.
+ t = torch.arange(segments, dtype=torch.float64) / segments * 2 * math.pi
+ step = 1e-4
+ centre, ahead, behind = curve(t), curve(t + step), curve(t - step)
+ tangent = F.normalize(ahead - behind, dim=-1)
+ bend = ahead - 2 * centre + behind
+ normal = F.normalize(bend - (bend * tangent).sum(-1, keepdim=True) * tangent, dim=-1)
+ binormal = torch.linalg.cross(tangent, normal)
+
+ scale = 1 / (3 + 3 * tube)
+ angle = torch.arange(sides, dtype=torch.float64) / sides * 2 * math.pi
+ around = (
+ torch.cos(angle)[:, None] * normal[:, None] + torch.sin(angle)[:, None] * binormal[:, None]
+ )
+ positions = ((centre[:, None] + 3 * tube * around) * scale).reshape(-1, 3).float().to(device)
+ if flat:
+ # A quarter turn about the x axis.
+ positions = positions[:, [0, 2, 1]] * positions.new_tensor([1.0, 1.0, -1.0])
+
+ i, j = torch.meshgrid(torch.arange(segments), torch.arange(sides), indexing="ij")
+ i, j = i.flatten(), j.flatten()
+
+ def pos_index(a, b):
+ return (a % segments) * sides + b % sides
+
+ def uv_index(a, b):
+ return a * (sides + 1) + b
+
+ def quads(index):
+ a, b, c, d = index(i, j), index(i + 1, j), index(i + 1, j + 1), index(i, j + 1)
+ return torch.cat([torch.stack([a, c, b], -1), torch.stack([a, d, c], -1)])
+
+ u, v = torch.meshgrid(
+ torch.linspace(0, 1, segments + 1), torch.linspace(0, 1, sides + 1), indexing="ij"
+ )
+ uvs = torch.stack([u, 1 - v if flip_v else v], -1).reshape(-1, 2).to(device)
+ tri = quads(pos_index).to(torch.int32).to(device)
+ tri_uv = quads(uv_index).to(torch.int32).to(device)
+ return Mesh(positions, tri, uvs, tri_uv)
+
+
+def icosphere(subdivisions: int = 4, device: torch.device | str = "cpu") -> Mesh:
+ """Unit sphere made of near-equal triangles, without texture coordinates."""
+ g = (1 + math.sqrt(5)) / 2
+ positions = torch.tensor(
+ [
+ [-1, g, 0], [1, g, 0], [-1, -g, 0], [1, -g, 0],
+ [0, -1, g], [0, 1, g], [0, -1, -g], [0, 1, -g],
+ [g, 0, -1], [g, 0, 1], [-g, 0, -1], [-g, 0, 1],
+ ],
+ dtype=torch.float64,
+ ) # fmt: skip
+ tri = torch.tensor(
+ [
+ [0, 11, 5], [0, 5, 1], [0, 1, 7], [0, 7, 10], [0, 10, 11],
+ [1, 5, 9], [5, 11, 4], [11, 10, 2], [10, 7, 6], [7, 1, 8],
+ [3, 9, 4], [3, 4, 2], [3, 2, 6], [3, 6, 8], [3, 8, 9],
+ [4, 9, 5], [2, 4, 11], [6, 2, 10], [8, 6, 7], [9, 8, 1],
+ ]
+ ) # fmt: skip
+ positions = F.normalize(positions, dim=-1)
+ for _ in range(subdivisions):
+ positions, tri = _subdivide(positions, tri)
+ positions = F.normalize(positions, dim=-1)
+ return Mesh(positions.float().to(device), tri.to(torch.int32).to(device))
+
+
+def _subdivide(positions: Tensor, tri: Tensor) -> tuple[Tensor, Tensor]:
+ """Split every triangle in four, sharing the new vertex on each edge."""
+ edges = torch.cat([tri[:, [0, 1]], tri[:, [1, 2]], tri[:, [2, 0]]]).sort(-1).values
+ unique, inverse = torch.unique(edges, dim=0, return_inverse=True)
+ midpoints = positions[unique].mean(1)
+ mid = inverse.view(3, -1) + positions.shape[0]
+ a, b, c = tri.unbind(-1)
+ ab, bc, ca = mid
+ tri = torch.cat(
+ [
+ torch.stack([a, ab, ca], -1),
+ torch.stack([b, bc, ab], -1),
+ torch.stack([c, ca, bc], -1),
+ torch.stack([ab, bc, ca], -1),
+ ]
+ )
+ return torch.cat([positions, midpoints]), tri
+
+
+def load_obj(path: str, device: torch.device | str = "cpu") -> Mesh:
+ """Read positions, texture coordinates and faces from a Wavefront OBJ file.
+
+ Polygons are split into triangle fans. The mesh is centred and scaled to the unit sphere.
+ """
+ positions, uvs, tri, tri_uv = [], [], [], []
+ with open(path) as file:
+ for line in file:
+ parts = line.split()
+ if not parts:
+ continue
+ if parts[0] == "v":
+ positions.append([float(x) for x in parts[1:4]])
+ elif parts[0] == "vt":
+ uvs.append([float(x) for x in parts[1:3]])
+ elif parts[0] == "f":
+ corners = [corner.split("/") for corner in parts[1:]]
+ pos_ids = [_obj_index(c[0], len(positions)) for c in corners]
+ has_uv = all(len(c) > 1 and c[1] for c in corners)
+ uv_ids = [_obj_index(c[1], len(uvs)) for c in corners] if has_uv else None
+ for k in range(1, len(corners) - 1):
+ tri.append([pos_ids[0], pos_ids[k], pos_ids[k + 1]])
+ if uv_ids:
+ tri_uv.append([uv_ids[0], uv_ids[k], uv_ids[k + 1]])
+
+ positions = torch.tensor(positions, dtype=torch.float32, device=device)
+ positions = positions - (positions.amax(0) + positions.amin(0)) / 2
+ positions = positions / positions.norm(dim=-1).max()
+ tri = torch.tensor(tri, dtype=torch.int32, device=device)
+ if len(tri_uv) != len(tri):
+ return Mesh(positions, tri)
+ return Mesh(
+ positions,
+ tri,
+ torch.tensor(uvs, dtype=torch.float32, device=device),
+ torch.tensor(tri_uv, dtype=torch.int32, device=device),
+ )
+
+
+def _obj_index(token: str, count: int) -> int:
+ index = int(token)
+ return index - 1 if index > 0 else count + index
+
+
+def vertex_normals(positions: Tensor, tri: Tensor) -> Tensor:
+ """Area-weighted vertex normals for positions of shape ``[..., vertices, 3]``."""
+ tri = tri.long()
+ v0, v1, v2 = positions[..., tri, :].unbind(-2)
+ face = torch.linalg.cross(v1 - v0, v2 - v0, dim=-1)
+ normals = torch.zeros_like(positions).index_add(
+ -2, tri.flatten(), face.repeat_interleave(3, dim=-2)
+ )
+ return F.normalize(normals, dim=-1)
+
+
+def perspective(
+ fov_y: float,
+ aspect: float,
+ near: float = 0.1,
+ far: float = 20.0,
+ device: torch.device | str = "cpu",
+) -> Tensor:
+ """OpenGL-style projection matrix for a vertical field of view in degrees."""
+ f = 1 / math.tan(math.radians(fov_y) / 2)
+ return torch.tensor(
+ [
+ [f / aspect, 0, 0, 0],
+ [0, f, 0, 0],
+ [0, 0, (far + near) / (near - far), 2 * far * near / (near - far)],
+ [0, 0, -1, 0],
+ ],
+ dtype=torch.float32,
+ device=device,
+ )
+
+
+def look_at(eye: Tensor, target: Tensor | None = None, up: Tensor | None = None) -> Tensor:
+ """View matrices ``[batch, 4, 4]`` for cameras at ``eye`` (``[batch, 3]``) facing ``target``."""
+ target = torch.zeros_like(eye) if target is None else target.expand_as(eye)
+ up = eye.new_tensor([0.0, 1.0, 0.0]) if up is None else up
+ forward = F.normalize(target - eye, dim=-1)
+ right = F.normalize(torch.linalg.cross(forward, up.expand_as(eye), dim=-1), dim=-1)
+ true_up = torch.linalg.cross(right, forward, dim=-1)
+ rotation = torch.stack([right, true_up, -forward], -2)
+ view = torch.eye(4, device=eye.device).repeat(eye.shape[0], 1, 1)
+ view[:, :3, :3] = rotation
+ view[:, :3, 3] = -(rotation @ eye[..., None]).squeeze(-1)
+ return view
+
+
+def orbit(yaw: Tensor, pitch: Tensor, distance: float) -> Tensor:
+ """Camera positions ``[batch, 3]`` on a sphere around the origin; angles in radians."""
+ return distance * torch.stack(
+ [torch.sin(yaw) * torch.cos(pitch), torch.sin(pitch), torch.cos(yaw) * torch.cos(pitch)],
+ -1,
+ )
+
+
+def to_clip(positions: Tensor, matrix: Tensor) -> Tensor:
+ """Transform ``[vertices, 3]`` positions by ``[batch, 4, 4]`` matrices to clip space."""
+ homogeneous = F.pad(positions, (0, 1), value=1.0)
+ return (homogeneous @ matrix.transpose(-1, -2)).contiguous()
+
+
+def to_srgb(linear: Tensor) -> Tensor:
+ """Linear radiance to display values, with a filmic shoulder so highlights roll off."""
+ x = linear.clamp(min=0)
+ x = x * (2.51 * x + 0.03) / (x * (2.43 * x + 0.59) + 0.14)
+ return x.clamp(0, 1) ** (1 / 2.2)
+
+
+def from_srgb(
+ display: Sequence[float] | Tensor, device: torch.device | str | None = None
+) -> Tensor:
+ """Inverse of ``to_srgb``: the linear colour that it maps to ``display``.
+
+ A render that fills its backdrop with ``from_srgb(PANEL)`` can be antialiased and tone-mapped
+ as a whole, and the backdrop still comes out as the panel colour exactly.
+ """
+ t = torch.as_tensor(display, dtype=torch.float32, device=device) ** 2.2
+ a, b, c = 2.43 * t - 2.51, 0.59 * t - 0.03, 0.14 * t
+ return (-b - torch.sqrt(b * b - 4 * a * c)) / (2 * a)
+
+
+def lighting(
+ normal: Tensor,
+ key: Sequence[float],
+ fill: Sequence[float],
+ ambient: float = 0.22,
+ fill_colour: Sequence[float] = (0.05, 0.065, 0.09),
+) -> Tensor:
+ """Linear light ``[..., 3]`` that falls on surfaces with the given normals.
+
+ ``key`` and ``fill`` are the directions towards a white key light and a faint cool fill. A
+ surface that faces the key light receives one; a surface turned away from both lights is left
+ with ``ambient``.
+ """
+ normal = F.normalize(normal, dim=-1)
+
+ def lambert(direction: Sequence[float]) -> Tensor:
+ towards = F.normalize(normal.new_tensor(direction), dim=0)
+ return (normal * towards).sum(-1, keepdim=True).clamp(min=0)
+
+ return ambient + (1 - ambient) * lambert(key) + normal.new_tensor(fill_colour) * lambert(fill)
+
+
+def downsample(image: Tensor, factor: int) -> Tensor:
+ """Average ``factor`` by ``factor`` blocks of an image ``[..., height, width, channels]``.
+
+ The examples render their pictures larger than needed and average them down after
+ ``to_srgb``. Averaged in linear light, a pixel half on a bright surface and half on the dark
+ backdrop would come out almost as bright as the surface, and the outline would look jagged.
+ Only images that are still to be blended, like the layers of depth_peeling.py, are averaged
+ before ``to_srgb``.
+ """
+ if factor == 1:
+ return image
+ return F.avg_pool2d(image.movedim(-1, -3), factor).movedim(-3, -1)
+
+
+def psnr(image: Tensor, reference: Tensor) -> float:
+ """Peak signal-to-noise ratio in dB between two tensors, for a peak value of one."""
+ return -10 * math.log10(max(F.mse_loss(image, reference).item(), 1e-12))
+
+
+def to_image(image: Tensor, size: int | None = None) -> Image.Image:
+ """Tensor ``[height, width, 3]`` with row 0 at the bottom to a PIL image ``size`` wide."""
+ array = (image.detach().flip(0).clamp(0, 1) * 255).round().byte().cpu().numpy()
+ picture = Image.fromarray(array)
+ if size is not None and size != picture.width:
+ height = round(size * picture.height / picture.width)
+ picture = picture.resize((size, height), Image.Resampling.LANCZOS)
+ return picture
+
+
+def rgb(color: Sequence[float]) -> tuple[int, int, int]:
+ """A colour with components in ``[0, 1]`` as the bytes that Pillow draws with."""
+ return tuple(round(255 * c) for c in color)
+
+
+def font(size: int) -> ImageFont.FreeTypeFont:
+ """Pillow's built-in font, ``size`` pixels high."""
+ return ImageFont.load_default(size=size)
+
+
+def text_mask(
+ text: str, width: int, height: int, size: int, device: torch.device | str = "cpu"
+) -> Tensor:
+ """Text rendered into a ``[height, width]`` mask in ``[0, 1]``, with row 0 at the bottom."""
+ image = Image.new("L", (width, height), 0)
+ centre = (width / 2, height / 2)
+ ImageDraw.Draw(image).text(centre, text, fill=255, font=font(size), anchor="mm")
+ return torch.from_numpy(np.array(image)).to(device).float().flip(0) / 255
+
+
+def layout(width: int, count: int) -> tuple[int, int, int]:
+ """Gap, panel width and label size for ``count`` panels in a row ``width`` pixels wide.
+
+ Passed on to ``panels``, they give a figure of exactly that width. An animation 960 pixels
+ wide gets 18-pixel labels, which can still be read at half size.
+ """
+ gap = width // 64
+ # A few pixels more between the panels let them fill the width exactly.
+ gap += (width - (count + 1) * gap) % count
+ return gap, (width - (count + 1) * gap) // count, width // 53
+
+
+def panels(
+ images: Sequence[Image.Image],
+ labels: Sequence[str],
+ gap: int = 16,
+ label_size: int = 18,
+ *,
+ details: Sequence[str] | None = None,
+ columns: int | None = None,
+) -> Image.Image:
+ """Lay images out in a row on the background colour, each with a label above it.
+
+ ``columns`` wraps the row after that many images. ``details`` adds a second line under every
+ label; the label is then drawn bright and the detail muted.
+ """
+ columns = columns or len(images)
+ cells = list(zip(images, labels, details or labels, strict=True))
+ rows = [cells[start : start + columns] for start in range(0, len(cells), columns)]
+ heights = [max(image.height for image, _, _ in row) for row in rows]
+ header = label_size + gap if details is None else round(2.9 * label_size)
+ width = max(sum(image.width + gap for image, _, _ in row) for row in rows) + gap
+ height = sum(header + row_height + gap for row_height in heights) + gap
+ canvas = Image.new("RGB", (width, height), rgb(BACKGROUND))
+ draw = ImageDraw.Draw(canvas)
+ y = gap
+ for row, row_height in zip(rows, heights, strict=True):
+ x = gap
+ for image, label, detail in row:
+ if details is None:
+ draw.text((x, y), label, fill=rgb(MUTED), font=font(label_size))
+ else:
+ draw.text((x, y), label, fill=rgb(TEXT), font=font(label_size))
+ below = (x, y + round(1.3 * label_size))
+ draw.text(below, detail, fill=rgb(MUTED), font=font(label_size))
+ canvas.paste(image, (x, y + header))
+ x += image.width + gap
+ y += header + row_height + gap
+ return canvas
+
+
+def titled_panels(
+ images: Sequence[Image.Image], titles: Sequence[str], details: Sequence[str], columns: int
+) -> Image.Image:
+ """Panels in rows of ``columns``, each under a bright title and a muted line of detail.
+
+ Gaps and text follow the size of the panels. A figure 1660 pixels wide gets 28-pixel text,
+ a little smaller than the labels of ``layout`` so that two lines fit above a narrow panel.
+ """
+ scale = images[0].width * columns / 1560
+ gap, text = max(4, round(20 * scale)), max(8, round(28 * scale))
+ return panels(images, titles, gap, text, details=details, columns=columns)
+
+
+def stack(rows: Sequence[Image.Image], overlap: int = 0) -> Image.Image:
+ """Figures below each other on the background colour, aligned on the left.
+
+ Every figure brings its own margin. Letting neighbours share ``overlap`` pixels keeps the
+ gap between two figures equal to the gaps inside them.
+ """
+ height = sum(row.height - overlap for row in rows) + overlap
+ canvas = Image.new("RGB", (max(row.width for row in rows), height), rgb(BACKGROUND))
+ # Pasted from the bottom up: a figure may draw into its lower margin, as with a frame around
+ # a panel, while its upper margin is empty.
+ bottom = height
+ for row in reversed(rows):
+ canvas.paste(row, (0, bottom - row.height))
+ bottom -= row.height - overlap
+ return canvas
+
+
+def save_animation(
+ frames: Sequence[Image.Image],
+ path: str,
+ frame_ms: int = 60,
+ hold_ms: int = 2500,
+ *,
+ holds: Mapping[int, int] | None = None,
+ seamless: bool = False,
+ dither: bool = True,
+) -> None:
+ """Write frames as an animation, in the format that the extension of ``path`` names.
+
+ ``.gif`` and ``.webp`` are written by Pillow. ``.mp4`` (H.264) and ``.webm`` (VP9) are
+ encoded by ffmpeg, which has to be on the PATH.
+
+ Every frame is shown for ``frame_ms`` milliseconds and the last one for ``hold_ms``.
+ ``holds`` maps the index of a frame to a longer time for that frame. ``seamless`` is for a
+ loop whose last frame leads back into the first: the last frame is then not held.
+
+ A GIF has 256 colours, and here all frames share them. The flat colours of a figure (canvas,
+ panels, labels and any other colour that fills a visible share of a frame) are stored as they
+ are. Shading in between is dithered, unless ``dither`` is off: that leaves faint bands on
+ smooth surfaces, and a smaller file when much of every frame changes.
+ """
+ frames = [frame.convert("RGB") for frame in frames]
+ durations = [frame_ms] * len(frames)
+ if not seamless:
+ durations[-1] = hold_ms
+ for index, duration in (holds or {}).items():
+ durations[index] = duration
+
+ suffix = Path(path).suffix.lower()
+ if suffix in _VIDEO_CODECS:
+ # A video has one frame rate, so a frame that stays longer is sent several times.
+ repeats = [max(1, round(duration / frame_ms)) for duration in durations]
+ _encode_video(frames, repeats, frame_ms, path)
+ elif suffix == ".webp":
+ frames[0].save(
+ path, save_all=True, append_images=frames[1:], duration=durations, loop=0, quality=88
+ )
+ else:
+ frames = _to_shared_palette(frames, dither)
+ frames[0].save(
+ path, save_all=True, append_images=frames[1:], duration=durations, loop=0, optimize=True
+ )
+
+
+# A colour that fills at least this share of a frame counts as flat and is never dithered.
+_FLAT_SHARE = 0.001
+# Dithering moves a pixel by at most this many levels before it is matched to the palette.
+_DITHER_LEVELS = 3.0
+# Without dithering, other palette colours keep this distance in levels from the flat ones. Noise
+# around a flat colour then falls onto it instead of flickering between two entries, which a GIF
+# compresses badly. With dithering, such a gap in the palette would show as a band.
+_FLAT_MARGIN = 5.0
+_VIDEO_CODECS = {
+ ".mp4": ["-c:v", "libx264", "-preset", "slow", "-crf", "16", "-movflags", "+faststart"],
+ ".webm": ["-c:v", "libvpx-vp9", "-crf", "24", "-b:v", "0", "-row-mt", "1"],
+}
+
+
+def _count_colours(pixels: np.ndarray) -> tuple[np.ndarray, np.ndarray, np.ndarray]:
+ """Distinct colours ``[count, 3]`` of RGB pixels, where each pixel is among them, and counts."""
+ codes = pixels.reshape(-1, 3).astype(np.uint32) @ np.array([65536, 256, 1], dtype=np.uint32)
+ codes, inverse, counts = np.unique(codes, return_inverse=True, return_counts=True)
+ colours = np.stack([codes >> 16, codes >> 8 & 255, codes & 255], -1).astype(np.uint8)
+ return colours, inverse, counts
+
+
+def _closest(colours: np.ndarray, palette: np.ndarray) -> tuple[np.ndarray, np.ndarray]:
+ """For each colour ``[count, 3]`` the index of the closest palette entry, and its distance."""
+ palette = torch.from_numpy(palette).float()
+ found = [
+ torch.cdist(part.float(), palette, compute_mode="donot_use_mm_for_euclid_dist").min(1)
+ for part in torch.from_numpy(colours).split(1 << 16)
+ ]
+ index = torch.cat([part.indices for part in found]).numpy()
+ return index, torch.cat([part.values for part in found]).numpy()
+
+
+def _shared_palette(arrays: Sequence[np.ndarray], margin: float, size: int = 255) -> np.ndarray:
+ """Colours ``[count, 3]`` for a set of frames: the flat ones exactly, the rest fitted.
+
+ A GIF palette has 256 entries, and ``size`` leaves one of them free. Pillow uses it to mark
+ the pixels that did not change since the previous frame, which then compress to almost
+ nothing.
+ """
+ present = np.zeros((0, 3), dtype=np.uint8)
+ for array in arrays:
+ present = _count_colours(np.concatenate([present, _count_colours(array)[0]]))[0]
+ if len(present) > 256:
+ break
+ else:
+ # Frames that were reduced to a palette before are stored as they are.
+ return present
+
+ sample = np.concatenate([a.reshape(-1, 3) for a in arrays[:: max(1, len(arrays) // 8)]])
+ colours, inverse, counts = _count_colours(sample)
+ flat = np.array([rgb(c) for c in (BACKGROUND, PANEL, TEXT, MUTED, ACCENT)], dtype=np.uint8)
+ for index in np.argsort(-counts)[:256]:
+ if counts[index] < _FLAT_SHARE * len(sample) or len(flat) == 64:
+ break
+ if _closest(colours[index : index + 1], flat)[1] >= margin:
+ flat = np.concatenate([flat, colours[index : index + 1]])
+
+ shaded = sample[(_closest(colours, flat)[1] >= margin)[inverse]]
+ if len(shaded) == 0:
+ return flat
+ shaded = shaded[:: max(1, len(shaded) // 2_000_000)]
+ # This quantiser spreads its colours over everything that occurs. Median cut would spend
+ # them on the large surfaces and leave a small one, like a highlight, with too few.
+ fitted = Image.fromarray(shaded[None]).quantize(
+ size - len(flat), Image.Quantize.MAXCOVERAGE, kmeans=3
+ )
+ fitted = np.array(fitted.getpalette(), dtype=np.uint8).reshape(-1, 3)[: size - len(flat)]
+ return np.concatenate([flat, fitted[_closest(fitted, flat)[1] >= margin]])
+
+
+def _dither_pattern(height: int, width: int) -> np.ndarray:
+ """Ordered-dither offsets ``[height, width, 1]``, spread evenly between -1 and 1."""
+ tile = np.zeros((1, 1))
+ for _ in range(3):
+ tile = np.block([[4 * tile, 4 * tile + 2], [4 * tile + 3, 4 * tile + 1]])
+ tile = (2 * tile + 1) / tile.size - 1
+ return np.tile(tile, (height // 8 + 1, width // 8 + 1))[:height, :width, None]
+
+
+def _to_shared_palette(frames: Sequence[Image.Image], dither: bool) -> list[Image.Image]:
+ """The frames as palette images that all use the colours of ``_shared_palette``."""
+ arrays = [np.asarray(frame) for frame in frames]
+ # Distinct colours are at least one level apart, so a margin of one only avoids duplicates.
+ palette = _shared_palette(arrays, margin=1.0 if dither else _FLAT_MARGIN)
+ # An ordered pattern, not error diffusion: it is the same in every frame, so still surfaces
+ # do not shimmer and still compress, and no pixel can end up far from its colour.
+ offsets = _DITHER_LEVELS * _dither_pattern(*arrays[0].shape[:2])
+
+ reduced = []
+ for array in arrays:
+ colours, inverse, counts = _count_colours(array)
+ index, distance = _closest(colours, palette)
+ index = index[inverse]
+ if dither:
+ # Colours that the palette holds stay as they are too, however few pixels have them.
+ flat = (counts >= _FLAT_SHARE * len(inverse)) | (distance == 0)
+ shifted = np.rint(array + offsets).clip(0, 255).astype(np.uint8)
+ shifted, place, _ = _count_colours(shifted)
+ index = np.where(flat[inverse], index, _closest(shifted, palette)[0][place])
+ picture = Image.fromarray(index.reshape(array.shape[:2]).astype(np.uint8))
+ picture.putpalette(palette.tobytes())
+ reduced.append(picture)
+ return reduced
+
+
+def _encode_video(
+ frames: Sequence[Image.Image], repeats: Sequence[int], frame_ms: int, path: str
+) -> None:
+ """Pipe RGB frames to ffmpeg; ``repeats`` says how often each one is sent."""
+ ffmpeg = shutil.which("ffmpeg")
+ if ffmpeg is None:
+ raise RuntimeError(
+ f"Writing {Path(path).suffix} needs ffmpeg on the PATH. "
+ "A .gif or .webp is written without it."
+ )
+ # yuv420p stores colour at half resolution, which takes an even width and height. The canvas
+ # ends in a margin, so repeating its last row or column does not show.
+ width, height = frames[0].size
+ pad = ((0, height % 2), (0, width % 2), (0, 0))
+ # Converted with exact rounding, which keeps the flat colours within a level of the frames,
+ # and tagged as BT.709, so that a player does not have to guess how to get back to RGB.
+ # Recent versions of ffmpeg take the tags from the filter, older ones from the options.
+ convert = (
+ "scale=out_color_matrix=bt709:out_range=tv:flags=accurate_rnd+full_chroma_int,"
+ "setparams=color_primaries=bt709:color_trc=bt709"
+ )
+ command = [
+ ffmpeg, "-y", "-loglevel", "error",
+ "-f", "rawvideo", "-pix_fmt", "rgb24",
+ "-s", f"{width + width % 2}x{height + height % 2}", "-r", f"1000/{frame_ms}", "-i", "-",
+ "-vf", convert, "-pix_fmt", "yuv420p",
+ "-colorspace", "bt709", "-color_primaries", "bt709", "-color_trc", "bt709",
+ *_VIDEO_CODECS[Path(path).suffix.lower()], str(path),
+ ] # fmt: skip
+ encoder = subprocess.Popen(command, stdin=subprocess.PIPE, stderr=subprocess.PIPE)
+ try:
+ for frame, count in zip(frames, repeats, strict=True):
+ data = np.pad(np.asarray(frame), pad, mode="edge").tobytes()
+ for _ in range(count):
+ encoder.stdin.write(data)
+ except OSError:
+ pass # ffmpeg stopped reading; the message it left says why
+ _, errors = encoder.communicate()
+ if encoder.returncode != 0:
+ raise RuntimeError(f"ffmpeg could not write {path}:\n{errors.decode(errors='replace')}")
diff --git a/examples/depth_peeling.py b/examples/depth_peeling.py
new file mode 100644
index 0000000..f675d91
--- /dev/null
+++ b/examples/depth_peeling.py
@@ -0,0 +1,356 @@
+"""Order-independent transparency with depth peeling.
+
+A glass torus knot with an opaque sphere at its centre. ``dr.DepthPeeler`` returns one depth layer
+per call: first the nearest surface in every pixel, then the surface behind it, and so on. A layer
+has the same format as the output of ``dr.rasterize``, so each one is shaded with the ordinary ops,
+and the layers are blended front to back. No triangle is ever sorted, and it does not matter that
+the sphere pokes through the glass.
+
+ python examples/depth_peeling.py --out glass.png --layers layers.png --gif layers.gif
+
+Without arguments it only prints how much of the image each layer covers. ``--check-gradients``
+backpropagates through the blended image and shows how far into the layers the gradients reach.
+
+The glass is a stylised thin-wall model: it mirrors one light and dims what is behind it, more so
+at grazing angles, but it does not refract.
+
+``--gif`` writes the format that its file name ends in: ``.gif``, ``.webp`` or, with ffmpeg on the
+PATH, ``.mp4`` and ``.webm``.
+
+Requires Pillow (``pip install -e . --group examples``).
+"""
+
+from __future__ import annotations
+
+import argparse
+import math
+from typing import NamedTuple
+
+import torch
+import torch.nn.functional as F
+from PIL import Image
+from torch import Tensor
+
+import diffrast as dr
+from common import (
+ ACCENT,
+ BACKGROUND,
+ PANEL,
+ downsample,
+ from_srgb,
+ icosphere,
+ layout,
+ look_at,
+ orbit,
+ panels,
+ perspective,
+ save_animation,
+ to_clip,
+ to_image,
+ to_srgb,
+ torus_knot,
+ vertex_normals,
+)
+
+CORE_RADIUS = 0.42
+# Turn of the knot at which the camera sees its three lobes apart.
+KNOT_TURN = 0.65
+CAMERA_PITCH = 1.05
+CAMERA_DISTANCE = 4.3
+# Perspective enlarges the near half of the knot, so the camera aims a little in front of the
+# knot's centre to centre it in the image.
+CAMERA_TARGET = (0.0, 0.0, 0.1)
+FOV = 30.0
+
+# Direction towards the key light, and the light on a surface that is turned away from it.
+KEY_LIGHT = (0.55, 0.75, -0.05)
+AMBIENT = 0.22
+# The key light is a softbox, which reflections show as a disc: its brightness, and the cosines
+# of the angle from its centre between which its edge fades in.
+SOFTBOX = 18.0
+SOFTBOX_EDGE = (0.97, 0.99)
+# A smooth surface mirrors this fraction of its surroundings head-on and all of them edge-on.
+REFLECTANCE = 0.04
+# Cool light from all around, which only shows where the glass mirrors strongly: at its rim.
+RIM_LIGHT = (0.32, 0.52, 0.76)
+GLASS_TINT = (0.25, 0.55, 1.0)
+# Fraction of the light that one wall of the knot holds back when it is seen head-on.
+GLASS_OPACITY = 0.025
+# Linear brightness that marks the outline of the nearest layer in the panels of later layers.
+OUTLINE = 0.006
+FRAME_MS = 70
+
+
+class Scene(NamedTuple):
+ """Glass knot and opaque sphere in one mesh; the knot's triangles come first."""
+
+ positions: Tensor
+ tri: Tensor
+ knot_triangles: int
+ core_colour: Tensor
+
+
+class Camera(NamedTuple):
+ """Position of the eye and the matrix that takes world space to clip space."""
+
+ eye: Tensor
+ matrix: Tensor
+
+
+class Render(NamedTuple):
+ """Blended image in display values, and per layer its linear RGBA and the fraction it covers."""
+
+ image: Tensor
+ layers: list[Tensor]
+ coverage: list[float]
+
+
+def build_scene(segments: int, subdivisions: int, device: torch.device) -> Scene:
+ """Torus knot lying flat around the y axis, with a sphere in the middle."""
+ knot = torus_knot(segments=segments, sides=max(3, segments // 8), device=device, flat=True)
+ core = icosphere(subdivisions, device)
+ positions = torch.cat([knot.positions, CORE_RADIUS * core.positions])
+ tri = torch.cat([knot.tri, core.tri + knot.positions.shape[0]])
+ core_colour = torch.tensor(ACCENT, device=device) ** 2.2
+ return turned(Scene(positions, tri, knot.tri.shape[0], core_colour), KNOT_TURN)
+
+
+def turned(scene: Scene, angle: float) -> Scene:
+ """The scene rotated around the y axis, as on a turntable."""
+ c, s = math.cos(angle), math.sin(angle)
+ rotation = scene.positions.new_tensor([[c, 0.0, s], [0.0, 1.0, 0.0], [-s, 0.0, c]])
+ return scene._replace(positions=scene.positions @ rotation.T)
+
+
+def make_camera(aspect: float, device: torch.device) -> Camera:
+ """Camera that looks down on the knot from the front."""
+ yaw, pitch = torch.zeros(1, device=device), torch.full((1,), CAMERA_PITCH, device=device)
+ eye = orbit(yaw, pitch, CAMERA_DISTANCE)
+ target = eye.new_tensor(CAMERA_TARGET)
+ return Camera(eye[0], perspective(FOV, aspect, device=device) @ look_at(eye, target))
+
+
+def shade(
+ position: Tensor, normal: Tensor, is_core: Tensor, eye: Tensor, core_colour: Tensor
+) -> Tensor:
+ """Premultiplied RGBA of the surface in one layer, in linear light."""
+ view = F.normalize(eye - position, dim=-1)
+ normal = F.normalize(normal, dim=-1)
+ facing = (normal * view).sum(-1, keepdim=True)
+ # Every second layer is the inside of a wall. Its normal points away from the camera, so it
+ # is flipped to light the side that is seen.
+ normal = torch.where(facing < 0, -normal, normal)
+ facing = facing.abs()
+
+ light = F.normalize(position.new_tensor(KEY_LIGHT), dim=0)
+ diffuse = AMBIENT + (normal @ light).clamp(min=0)[..., None]
+
+ # Both materials are glossy: they mirror the softbox, weakly where the surface faces the
+ # camera and strongly towards its rim.
+ grazing = (1 - facing) ** 3
+ reflectance = REFLECTANCE + (1 - REFLECTANCE) * grazing
+ mirrored = 2 * facing * normal - view
+ low, high = SOFTBOX_EDGE
+ softbox = (((mirrored @ light)[..., None] - low) / (high - low)).clamp(0, 1)
+ highlight = reflectance * SOFTBOX * softbox
+
+ # The path through a thin wall gets longer at grazing angles, which makes the rim denser.
+ wall = 1 - (1 - GLASS_OPACITY) ** (1 / facing.clamp(min=0.02))
+ # Clear glass mirrors its surroundings as brightly as dense glass does, so the reflections
+ # are added to the premultiplied colour without being weighted by the wall's opacity.
+ glass = position.new_tensor(GLASS_TINT) * diffuse * wall
+ glass = glass + highlight + grazing * position.new_tensor(RIM_LIGHT)
+ # Whatever the wall absorbs or reflects does not arrive from behind it.
+ glass_alpha = 1 - (1 - wall) * (1 - reflectance)
+
+ core = core_colour * diffuse + highlight
+ colour = torch.where(is_core, core, glass)
+ alpha = torch.where(is_core, torch.ones_like(facing), glass_alpha)
+ return torch.cat([colour, alpha], -1)
+
+
+def render(
+ ctx: dr.RasterizeContext,
+ scene: Scene,
+ camera: Camera,
+ size: tuple[int, int],
+ num_layers: int,
+ supersample: int,
+ background: Tensor,
+) -> Render:
+ """Peel ``num_layers`` depth layers and blend them front to back over ``background``.
+
+ Going from front to back, every layer adds its colour, dimmed by the layers already passed,
+ and then dims what is still to come by its own opacity.
+ """
+ width, height = size
+ resolution = (height * supersample, width * supersample)
+ pos = to_clip(scene.positions, camera.matrix)
+ normals = vertex_normals(scene.positions, scene.tri)
+ attributes = torch.cat([scene.positions, normals], -1)
+
+ colour, transmittance = 0.0, 1.0
+ layers, coverage = [], []
+ with dr.DepthPeeler(ctx, pos, scene.tri, resolution) as peeler:
+ for _ in range(num_layers):
+ rast, _ = peeler.rasterize_next_layer()
+ surface, _ = dr.interpolate(attributes, rast, scene.tri)
+
+ # The last channel of rast is the triangle index plus one, and zero where empty.
+ covered = rast[..., 3:] > 0
+ is_core = rast[..., 3:] > scene.knot_triangles
+ position, normal = surface[..., :3], surface[..., 3:]
+ rgba = shade(position, normal, is_core, camera.eye, scene.core_colour)
+ rgba = dr.antialias(rgba * covered, rast, pos, scene.tri)
+
+ colour = colour + transmittance * rgba[..., :3]
+ transmittance = transmittance * (1 - rgba[..., 3:])
+
+ # The layers stay linear, because layer_strip still blends them over a backdrop.
+ layers.append(downsample(rgba, supersample)[0])
+ coverage.append(covered.float().mean().item())
+
+ image = colour + transmittance * background
+ return Render(downsample(to_srgb(image), supersample)[0], layers, coverage)
+
+
+def layer_strip(
+ result: Render, background: Tensor, shown: int, gap: int, label_size: int
+) -> Image.Image:
+ """The first ``shown`` layers on their own, then all of them blended, as labelled panels.
+
+ A layer holds whatever surface comes next, also where the opaque sphere in front of it lets
+ nothing through, so the panels show the far side of the sphere and the glass inside it.
+ """
+ # Later layers are fragments. A faint outline of the nearest layer shows where they belong.
+ backdrop = background + OUTLINE * (result.layers[0][..., 3:] > 0)
+ alone = [
+ to_srgb(layer[..., :3] + (1 - layer[..., 3:]) * backdrop) for layer in result.layers[:shown]
+ ]
+ labels = ["layer 1 (nearest)", *[f"layer {index}" for index in range(2, len(alone) + 1)]]
+ labels.append(f"{len(result.layers)} layers blended")
+ return panels([to_image(image) for image in [*alone, result.image]], labels, gap, label_size)
+
+
+def check_gradients(
+ ctx: dr.RasterizeContext,
+ scene: Scene,
+ camera: Camera,
+ size: int,
+ num_layers: int,
+ background: Tensor,
+ seed: int,
+) -> None:
+ """Backpropagate the mean of the blended image to the vertices and to the sphere's colour.
+
+ Blending more layers lets the gradient reach vertices that the nearest surface hides.
+ """
+ generator = torch.Generator().manual_seed(seed)
+ start = torch.rand(3, generator=generator).to(background.device)
+
+ def mean_brightness(positions: Tensor, core_colour: Tensor, layers: int) -> Tensor:
+ changed = scene._replace(positions=positions, core_colour=core_colour)
+ return render(ctx, changed, camera, (size, size), layers, 1, background).image.mean()
+
+ print(f"gradients of the mean of a {size}x{size} image, for a sphere of a random colour")
+ print("layers vertices reached |d/d positions| |d/d sphere colour|")
+ for layers in sorted({1, 2, 3, 4, num_layers}):
+ positions = scene.positions.clone().requires_grad_()
+ core_colour = start.clone().requires_grad_()
+ mean_brightness(positions, core_colour, layers).backward()
+ reached = (positions.grad.abs().sum(-1) > 0).float().mean().item()
+ print(
+ f"{layers:6d} {100 * reached:14.1f} % {positions.grad.norm().item():15.3e}"
+ f" {core_colour.grad.norm().item():19.3e}"
+ )
+ print("the rest are behind the opaque sphere, or in triangles that no pixel centre falls in")
+
+ # The image varies smoothly with the sphere's colour, so a central difference is an
+ # independent check on the gradient, part of which arrives through the glass.
+ with torch.no_grad():
+ step = torch.tensor([0.01, 0.0, 0.0], device=start.device)
+ high = mean_brightness(scene.positions, start + step, num_layers)
+ low = mean_brightness(scene.positions, start - step, num_layers)
+ print(
+ f"d/d red of the sphere: autograd {core_colour.grad[0].item():.6f}, "
+ f"finite difference {((high - low) / 0.02).item():.6f}"
+ )
+
+
+def main() -> None:
+ parser = argparse.ArgumentParser(description=__doc__.split("\n\n")[0])
+ parser.add_argument("--out", help="write the blended image to this PNG")
+ parser.add_argument("--width", type=int, default=1600, help="width of the blended image")
+ parser.add_argument("--height", type=int, default=1000, help="height of the blended image")
+ parser.add_argument("--layers", help="write single layers next to the blend to this PNG")
+ parser.add_argument("--panel-size", type=int, default=308, help="panel side in --layers")
+ parser.add_argument(
+ "--gif",
+ help="write a turntable of layers and blend to this animation; "
+ "the extension picks the format: .gif, .webp, .mp4 or .webm",
+ )
+ parser.add_argument("--frames", type=int, default=48, help="frames in a third of a turn")
+ parser.add_argument("--gif-width", type=int, default=960, help="width of the animation")
+ parser.add_argument(
+ "--check-gradients", action="store_true", help="print gradients through the layers"
+ )
+ parser.add_argument("--check-size", type=int, default=512, help="image side for the check")
+ parser.add_argument("--num-layers", type=int, default=8, help="depth layers to peel")
+ parser.add_argument(
+ "--supersample", type=int, default=2, help="render at this multiple and average down"
+ )
+ parser.add_argument("--segments", type=int, default=768, help="segments along the knot")
+ parser.add_argument("--subdivisions", type=int, default=4, help="icosphere subdivisions")
+ parser.add_argument("--seed", type=int, default=0, help="picks the sphere colour of the check")
+ parser.add_argument(
+ "--device", default="cuda" if torch.cuda.is_available() else "cpu", help="cuda or cpu"
+ )
+ args = parser.parse_args()
+
+ device = torch.device(args.device)
+ ctx = dr.RasterizeContext(device)
+ scene = build_scene(args.segments, args.subdivisions, device)
+ canvas, panel = from_srgb(BACKGROUND, device), from_srgb(PANEL, device)
+
+ def draw(subject: Scene, size: tuple[int, int], background: Tensor) -> Render:
+ camera = make_camera(size[0] / size[1], device)
+ with torch.no_grad():
+ return render(ctx, subject, camera, size, args.num_layers, args.supersample, background)
+
+ still = draw(scene, (args.width, args.height), canvas)
+ print(f"{args.width}x{args.height} at {args.supersample}x supersampling on {device}")
+ print("layer pixels covered")
+ for index, fraction in enumerate(still.coverage):
+ print(f"{index + 1:5d} {100 * fraction:12.3f} %")
+ print("a ray enters and leaves each closed surface, so layers come in pairs and thin out")
+ if args.out:
+ to_image(still.image).save(args.out)
+ print(f"wrote {args.out}")
+
+ if args.layers:
+ result = draw(scene, (args.panel_size, args.panel_size), panel)
+ # Five panels of the default size and six gaps make a figure 1660 pixels wide.
+ scale = args.panel_size / 308
+ gap, label_size = round(20 * scale), round(28 * scale)
+ layer_strip(result, panel, shown=4, gap=gap, label_size=label_size).save(args.layers)
+ print(f"wrote {args.layers}")
+
+ if args.gif:
+ gap, side, label_size = layout(args.gif_width, 4)
+ frames = []
+ for index in range(args.frames):
+ # The knot has three-fold symmetry, so a third of a turn loops without a seam.
+ turn = turned(scene, 2 * math.pi / 3 * index / args.frames)
+ result = draw(turn, (side, side), panel)
+ frames.append(layer_strip(result, panel, shown=3, gap=gap, label_size=label_size))
+ save_animation(frames, args.gif, frame_ms=FRAME_MS, seamless=True)
+ print(f"wrote {args.gif} ({len(frames)} frames)")
+
+ if args.check_gradients:
+ check_gradients(
+ ctx, scene, make_camera(1.0, device), args.check_size, args.num_layers, panel, args.seed
+ )
+
+
+if __name__ == "__main__":
+ main()
diff --git a/examples/env_lighting.py b/examples/env_lighting.py
new file mode 100644
index 0000000..f99350a
--- /dev/null
+++ b/examples/env_lighting.py
@@ -0,0 +1,461 @@
+"""Recover an environment map from renders of a mirror-like object.
+
+A glossy torus knot reflects its surroundings, which are stored in a cube map: six square faces
+that are looked up with a direction instead of texture coordinates. A second cube map starts out
+flat grey and is optimised until renders of the knot from random viewpoints match renders made
+with the first. The fit sees the knot on black, so everything it learns about the environment
+comes from reflections.
+
+ python examples/env_lighting.py --gif env_lighting.gif --out env_lighting.png
+ python examples/env_lighting.py --iterations 0 --cover env_lighting_cover.png
+
+The animation shows the target and the fit from a slowly turning camera, and next to them both
+cube maps unfolded as a cross: the four sides in a row (-x, +z, +x, -z), with +y above and -y
+below +z. Behind the knot each panel shows its own cube map, out of focus; the fit never saw that
+backdrop. The still adds the fitted map on a rougher knot. The cover is the knot alone, in a finer
+version of the target environment.
+
+``render`` uses the cube map three times. The mirror image comes from a mipmapped lookup along the
+reflected view direction, whose screen-space derivatives pick the mip level; ``mip_level_bias``
+shifts that level, which blurs the reflection like a rougher surface would. Diffuse light and the
+backdrop are lookups that name their mip level directly.
+
+The reflected direction is computed per vertex and interpolated, which is an approximation: on
+the default mesh it stays within half a degree of the exact per-pixel direction, on a coarse mesh
+reflections bend visibly. The knot does not reflect itself.
+
+The targets come from the same renderer and carry no noise, so the fit ends up close to exact. A
+curved mirror shows nearly all of its surroundings from any side, and pixels near its outline
+read coarse mip levels that average whole faces, so no texel is left without gradient. What
+limits the sharpness of the result is how much of the environment one pixel of the mirror covers.
+The fit therefore looks from close by, which halves that footprint to between one and two texels.
+
+Requires Pillow (``pip install -e . --group examples``).
+"""
+
+from __future__ import annotations
+
+import argparse
+import math
+from typing import NamedTuple
+
+import torch
+import torch.nn.functional as F
+from PIL import Image, ImageDraw
+from torch import Tensor
+
+import diffrast as dr
+from common import (
+ BACKGROUND,
+ MUTED,
+ Mesh,
+ font,
+ look_at,
+ orbit,
+ panels,
+ perspective,
+ psnr,
+ rgb,
+ save_animation,
+ text_mask,
+ to_clip,
+ to_image,
+ to_srgb,
+ torus_knot,
+ vertex_normals,
+)
+
+# Per cube face, in the order diffrast stores them: the direction through its centre, and the
+# directions in which its columns and rows run (the OpenGL convention).
+FACES = (
+ ((1, 0, 0), (0, 0, -1), (0, -1, 0)),
+ ((-1, 0, 0), (0, 0, 1), (0, -1, 0)),
+ ((0, 1, 0), (1, 0, 0), (0, 0, 1)),
+ ((0, -1, 0), (1, 0, 0), (0, 0, -1)),
+ ((0, 0, 1), (1, 0, 0), (0, -1, 0)),
+ ((0, 0, -1), (-1, 0, 0), (0, -1, 0)),
+)
+# Row and column of each face in the unfolded cross.
+CROSS = ((1, 2), (1, 0), (0, 1), (2, 1), (1, 1), (1, 3))
+
+# The knot mirrors most of the light and scatters a little, tinted like warm clay.
+MIRROR = 0.9
+DIFFUSE = (0.040, 0.038, 0.036)
+# Mip level bias of the rougher knot in the still.
+ROUGH = 2.0
+# The backdrop is read from the mip level whose faces are this many texels wide.
+BACKDROP_FACE = 32
+# Radiance of every texel when the fit starts.
+GREY = 0.02
+
+# Directions towards the lights of the studio.
+SOFTBOX = (0.55, 0.75, 0.55)
+STRIP = (-1.0, 0.1, 0.25)
+ACCENT_PANEL = (-0.35, -0.6, 0.7)
+BACKLIGHT = (-0.3, -0.25, -0.9)
+
+FOV = 30.0
+# From this far away the unit sphere, which bounds the knot, fits in a square image.
+CAMERA_DISTANCE = 4.2
+# One pixel of a curved mirror covers less of the environment from close by.
+FIT_DISTANCE = 2.4
+HELD_OUT_VIEWS = 16
+
+FIGURE_YAW, FIGURE_PITCH, FIGURE_SWEEP = 0.05, 0.25, 0.7
+COVER_SIZE = (1600, 1000)
+COVER_YAW, COVER_PITCH, COVER_DISTANCE = 0.3, 0.25, 4.4
+# The cover uses an environment with this many times the texels of the fitted one along a side.
+COVER_DETAIL = 8
+
+
+class Camera(NamedTuple):
+ """A batch of views: eye positions ``[batch, 3]``, view matrices and one projection."""
+
+ eye: Tensor
+ view: Tensor
+ proj: Tensor
+
+
+def render(
+ ctx: dr.RasterizeContext,
+ mesh: Mesh,
+ env: Tensor,
+ camera: Camera,
+ resolution: tuple[int, int],
+ roughness: float = 0.0,
+ backdrop: bool = True,
+) -> Tensor:
+ """Linear images ``[batch, height, width, 3]`` of the knot lit by the cube map ``env``.
+
+ ``roughness`` is added to the mip level of the reflection. Without ``backdrop`` the pixels
+ around the knot are black instead of showing the environment.
+ """
+ pos = to_clip(mesh.positions, camera.proj @ camera.view)
+ normals = vertex_normals(mesh.positions, mesh.tri)
+ # The direction a mirror sends the eye's ray in, per view and per vertex.
+ towards_eye = F.normalize(camera.eye[:, None] - mesh.positions, dim=-1)
+ mirrored = 2 * (towards_eye * normals).sum(-1, keepdim=True) * normals - towards_eye
+ mip = dr.texture_construct_mip(env, cube_mode=True)
+
+ rast, rast_db = dr.rasterize(ctx, pos, mesh.tri, resolution)
+ # A three-channel attribute with all its derivatives is what a cube lookup takes.
+ direction, direction_da = dr.interpolate(
+ mirrored, rast, mesh.tri, rast_db=rast_db, diff_attrs="all"
+ )
+ level = torch.ones_like(rast[..., 0])
+ reflection = dr.texture(
+ env, direction, direction_da, roughness * level, mip=mip, boundary_mode="cube"
+ )
+
+ # Diffuse light changes slowly over the surface. It is read once per vertex, with the normals
+ # laid out as an image one pixel wide, from the level that has two texels along a face.
+ coarse = normals.new_full((1, normals.shape[0], 1), math.log2(env.shape[2]) - 1)
+ soft = dr.texture(
+ env, normals[None, :, None], mip_level_bias=coarse, mip=mip, boundary_mode="cube"
+ )
+ diffuse, _ = dr.interpolate(soft[0, :, 0], rast, mesh.tri)
+ colour = MIRROR * reflection + diffuse * diffuse.new_tensor(DIFFUSE)
+
+ if backdrop:
+ blur = math.log2(env.shape[2] / BACKDROP_FACE) * level
+ rays = camera_rays(camera, resolution)
+ behind = dr.texture(env, rays, mip_level_bias=blur, mip=mip, boundary_mode="cube")
+ colour = torch.where(rast[..., 3:] > 0, colour, behind)
+ return dr.antialias(colour, rast, pos, mesh.tri)
+
+
+def camera_rays(camera: Camera, resolution: tuple[int, int]) -> Tensor:
+ """World-space direction ``[batch, height, width, 3]`` of the ray through every pixel."""
+ height, width = resolution
+ device = camera.eye.device
+ y, x = torch.meshgrid(
+ (torch.arange(height, device=device) + 0.5) / height * 2 - 1,
+ (torch.arange(width, device=device) + 0.5) / width * 2 - 1,
+ indexing="ij",
+ )
+ local = torch.stack([x / camera.proj[0, 0], y / camera.proj[1, 1], -torch.ones_like(x)], -1)
+ # The rows of the view rotation are the camera's axes in world space.
+ return (local @ camera.view[:, None, :3, :3]).contiguous()
+
+
+def orbit_cameras(yaw: Tensor, pitch: Tensor, distance: float, aspect: float = 1.0) -> Camera:
+ """Cameras on a sphere around the origin, looking at it; angles in radians."""
+ eye = orbit(yaw, pitch, distance)
+ return Camera(eye, look_at(eye), perspective(FOV, aspect, device=eye.device))
+
+
+def random_cameras(
+ count: int, generator: torch.Generator, device: torch.device, distance: float
+) -> Camera:
+ """Cameras all around the knot."""
+ yaw = torch.rand(count, generator=generator) * 2 * math.pi
+ pitch = (torch.rand(count, generator=generator) - 0.5) * 2.4
+ return orbit_cameras(yaw.to(device), pitch.to(device), distance)
+
+
+def cube_directions(size: int, device: torch.device) -> Tensor:
+ """Unit direction ``[6, size, size, 3]`` through the centre of every texel of a cube map."""
+ faces = torch.tensor(FACES, dtype=torch.float32, device=device)
+ centre, along_columns, along_rows = faces[:, :, None, None].unbind(1)
+ step = (torch.arange(size, device=device) + 0.5) / size * 2 - 1
+ row, column = torch.meshgrid(step, step, indexing="ij")
+ directions = centre + column[..., None] * along_columns + row[..., None] * along_rows
+ return F.normalize(directions, dim=-1)
+
+
+def rectangle(
+ directions: Tensor, centre: tuple[float, ...], half: tuple[float, float], edge: float
+) -> Tensor:
+ """Mask ``[..., 1]`` of a rectangular light that faces the origin from the direction ``centre``.
+
+ ``half`` is its half width and half height at distance one, ``edge`` the width over which it
+ fades out.
+ """
+ forward = F.normalize(directions.new_tensor(centre), dim=0)
+ right = F.normalize(torch.linalg.cross(directions.new_tensor([0.0, 1.0, 0.0]), forward), dim=0)
+ up = torch.linalg.cross(forward, right)
+ depth = (directions @ forward).clamp(min=1e-6)
+ across = (half[0] - (directions @ right / depth).abs()) / edge + 0.5
+ along = (half[1] - (directions @ up / depth).abs()) / edge + 0.5
+ mask = across.clamp(0, 1) * along.clamp(0, 1) * (directions @ forward > 0)
+ return mask[..., None]
+
+
+def glow(directions: Tensor, centre: tuple[float, ...], width: float) -> Tensor:
+ """Soft spot ``[..., 1]`` around the direction ``centre``; ``width`` is roughly in radians."""
+ towards = F.normalize(directions.new_tensor(centre), dim=0)
+ return torch.exp(-2 * (1 - directions @ towards) / width**2)[..., None]
+
+
+def studio(size: int, device: torch.device, supersample: int = 4) -> Tensor:
+ """The target environment ``[1, 6, size, size, 3]``, in linear radiance: a dark studio.
+
+ A warm softbox, a cool strip light and a small orange panel are far brighter than one, so
+ their reflections stay bright after tone mapping. A grid of ceiling lights and the word
+ "diffrast" are the fine detail that shows how sharp the recovered map is.
+ """
+ fine = size * supersample
+ d = cube_directions(fine, device)
+ x, y, z = d.unbind(-1)
+
+ def colour(*values: float) -> Tensor:
+ return d.new_tensor(values)
+
+ floor = ((0.02 - y) / 0.04).clamp(0, 1)[..., None]
+ env = torch.lerp(colour(0.0115, 0.0115, 0.0125), colour(0.0147, 0.0132, 0.0125), floor)
+ env = env + torch.exp(-((y / 0.09) ** 2))[..., None] * colour(0.005, 0.0035, 0.0025)
+ env = env + glow(d, BACKLIGHT, 0.3) * colour(0.010, 0.0075, 0.006)
+
+ env = env + glow(d, SOFTBOX, 0.5) * colour(0.12, 0.09, 0.06)
+ env = env + rectangle(d, SOFTBOX, (0.50, 0.34), 0.10) * colour(6.5, 5.2, 3.9)
+ env = env + glow(d, STRIP, 0.6) * colour(0.06, 0.10, 0.18)
+ env = env + rectangle(d, STRIP, (0.055, 0.75), 0.03) * colour(2.0, 3.4, 5.5)
+ env = env + glow(d, ACCENT_PANEL, 0.4) * colour(0.12, 0.012, 0.004)
+ env = env + rectangle(d, ACCENT_PANEL, (0.16, 0.16), 0.03) * colour(2.6, 0.075, 0.02)
+
+ # Four by four lights in one corner of the ceiling, at positions on the plane y = 1.
+ u, v = x / y.clamp(min=1e-6), z / y.clamp(min=1e-6)
+ spacing, radius = 0.2, 0.045
+ to_nearest = torch.hypot(
+ u - (u / spacing).round() * spacing, v - (v / spacing).round() * spacing
+ )
+ lights = ((radius - to_nearest) / 0.02).clamp(0, 1)
+ lights = lights * (y > 0) * (u > -0.9) * (u < -0.1) * (v > -0.9) * (v < -0.1)
+ env = env + lights[..., None] * colour(6.0, 5.5, 5.0)
+
+ # Faces are stored as seen from outside the cube, which is how a mirror shows them, so the
+ # word reads the right way round in reflections. Their rows start at the top.
+ word = text_mask("diffrast", fine, fine // 4, fine // 6, device).flip(0)
+ top = fine * 5 // 8
+ env[4, top : top + word.shape[0]] += word[..., None] * colour(2.5, 2.3, 2.0)
+
+ env = F.avg_pool2d(env.permute(0, 3, 1, 2), supersample).permute(0, 2, 3, 1)
+ return env[None].contiguous()
+
+
+def compress(linear: Tensor) -> Tensor:
+ """Radiance squeezed into ``[0, 1)``, so that the lights do not drown out the rest."""
+ return linear / (1 + linear)
+
+
+def unfold(env: Tensor, face: int) -> Image.Image:
+ """Cube map as a cross of display values on the canvas colour, ``face`` pixels per face."""
+ size = env.shape[2]
+ cross = env.new_tensor(BACKGROUND).repeat(3 * size, 4 * size, 1)
+ for texels, (row, column) in zip(to_srgb(env[0]), CROSS, strict=True):
+ cross[row * size : (row + 1) * size, column * size : (column + 1) * size] = texels
+ # to_image expects row 0 at the bottom; the rows of a cube face start at its top.
+ return to_image(cross.flip(0), 4 * face)
+
+
+def figure(
+ ctx: dr.RasterizeContext,
+ mesh: Mesh,
+ target: Tensor,
+ env: Tensor,
+ step: int,
+ turn: float,
+ width: int,
+ still: bool = False,
+) -> Image.Image:
+ """Target and fit from one camera, next to both cube maps.
+
+ ``turn`` moves the camera along its sweep, from 0 to 1. The animation has the cube maps in a
+ column beside the renders. The ``still`` puts them below, larger, and adds the fitted
+ environment on a rougher knot.
+ """
+ gap, label_size = width // 60, width // 53
+ if still:
+ # A pixel or two more between the panels lets them fill the width exactly.
+ gap += (width - 4 * gap) % 3
+ side = (width - 4 * gap) // 3
+ face = (width - 3 * gap) // 8
+ else:
+ # The largest faces for which two crosses and a label are as high as a render.
+ face = (width - 8 * gap - 2 * label_size) // 16
+ side = (width - 4 * gap - 4 * face) // 2
+
+ yaw = torch.tensor([FIGURE_YAW + FIGURE_SWEEP * (turn - 0.5)], device=env.device)
+ camera = orbit_cameras(yaw, torch.full_like(yaw, FIGURE_PITCH), CAMERA_DISTANCE)
+ # Rendered at twice the size of a panel; to_image averages it down.
+ views = [(target, 0.0), (env, 0.0)] + ([(env, ROUGH)] if still else [])
+ with torch.no_grad():
+ renders = [
+ to_image(to_srgb(render(ctx, mesh, cube, camera, (2 * side, 2 * side), rough)[0]), side)
+ for cube, rough in views
+ ]
+ crosses = [unfold(target, face), unfold(env, face)]
+ decibel = psnr(to_srgb(env), to_srgb(target))
+ labels = ["target", f"fitted, step {step}", f"fitted, mip level bias +{ROUGH:g}"]
+ # The column of the animation is too narrow for more words.
+ fitted_cube = "fitted cube map" if still else "fitted"
+ cube_labels = ["target cube map", f"{fitted_cube}, psnr {decibel:.1f} dB"]
+
+ if still:
+ rows = [
+ panels(renders, labels, gap, label_size),
+ panels(crosses, cube_labels, gap, label_size),
+ ]
+ # Every row brings its own margin; overlapping them keeps the gaps between rows equal.
+ canvas = Image.new("RGB", (width, rows[0].height + rows[1].height - gap), rgb(BACKGROUND))
+ canvas.paste(rows[1], (0, rows[0].height - gap))
+ canvas.paste(rows[0], (0, 0))
+ return canvas
+
+ # The second cross sits under the first, with its label in between like a panel label.
+ column = Image.new("RGB", (crosses[0].width, side), rgb(BACKGROUND))
+ column.paste(crosses[0], (0, 0))
+ column.paste(crosses[1], (0, side - crosses[1].height))
+ label_top = side - crosses[1].height - gap - label_size
+ ImageDraw.Draw(column).text(
+ (0, label_top), cube_labels[1], fill=rgb(MUTED), font=font(label_size)
+ )
+ return panels([*renders, column], [*labels[:2], cube_labels[0]], gap, label_size)
+
+
+def cover(ctx: dr.RasterizeContext, mesh: Mesh, env: Tensor) -> Image.Image:
+ """The knot in the target environment, composed like a product shot."""
+ width, height = COVER_SIZE
+ device = env.device
+ camera = orbit_cameras(
+ torch.tensor([COVER_YAW], device=device),
+ torch.tensor([COVER_PITCH], device=device),
+ COVER_DISTANCE,
+ width / height,
+ )
+ with torch.no_grad():
+ image = to_srgb(render(ctx, mesh, env, camera, (2 * height, 2 * width)))
+ image = F.avg_pool2d(image.permute(0, 3, 1, 2), 2).permute(0, 2, 3, 1)[0].cpu()
+ # Eight bits leave visible steps in the dark backdrop; half a step of noise hides them.
+ noise = torch.rand(image.shape, generator=torch.Generator().manual_seed(0)) - 0.5
+ return to_image(image + noise / 255)
+
+
+def main() -> None:
+ parser = argparse.ArgumentParser(description=__doc__.split("\n\n")[0])
+ parser.add_argument("--iterations", type=int, default=300)
+ parser.add_argument("--views", type=int, default=4, help="random views per iteration")
+ parser.add_argument("--resolution", type=int, default=384, help="size of the views")
+ parser.add_argument("--env-size", type=int, default=64, help="texels along a cube face")
+ parser.add_argument("--segments", type=int, default=768, help="knot subdivisions along")
+ parser.add_argument("--lr", type=float, default=0.2)
+ parser.add_argument("--seed", type=int, default=0)
+ parser.add_argument("--gif", help="write the optimisation progress to this GIF")
+ parser.add_argument("--frames", type=int, default=56)
+ parser.add_argument("--gif-width", type=int, default=960)
+ parser.add_argument("--out", help="write the result and the target to this PNG")
+ parser.add_argument("--out-width", type=int, default=1660)
+ parser.add_argument("--cover", help="write the knot in the target environment to this PNG")
+ parser.add_argument("--device", default="cuda" if torch.cuda.is_available() else "cpu")
+ args = parser.parse_args()
+
+ device = torch.device(args.device)
+ generator = torch.Generator().manual_seed(args.seed)
+ ctx = dr.RasterizeContext(device)
+ mesh = torus_knot(segments=args.segments, sides=max(3, args.segments // 8), device=device)
+ target = studio(args.env_size, device)
+ # Radiance spans three orders of magnitude. Adam takes steps of a fixed size, which in the
+ # logarithm of the radiance are steps of a fixed ratio, for dim texels and bright ones alike.
+ log_env = torch.full_like(target, math.log(GREY), requires_grad=True)
+ optimizer = torch.optim.Adam([log_env], lr=args.lr)
+ resolution = (args.resolution, args.resolution)
+ reached = torch.zeros_like(target[..., 0], dtype=torch.bool)
+
+ frames = []
+ # Most of the change happens early, so the frames crowd towards the first steps, while the
+ # camera turns at an even pace.
+ last = max(1, args.frames - 1)
+ capture = [round(args.iterations * (i / last) ** 3) for i in range(args.frames)]
+ for step in range(args.iterations + 1):
+ while args.gif and len(frames) < args.frames and capture[len(frames)] == step:
+ env = log_env.detach().exp()
+ frames.append(figure(ctx, mesh, target, env, step, len(frames) / last, args.gif_width))
+ if step == args.iterations:
+ break
+
+ camera = random_cameras(args.views, generator, device, FIT_DISTANCE)
+ with torch.no_grad():
+ reference = render(ctx, mesh, target, camera, resolution, backdrop=False)
+
+ optimizer.zero_grad()
+ fitted = render(ctx, mesh, log_env.exp(), camera, resolution, backdrop=False)
+ loss = F.mse_loss(compress(fitted), compress(reference))
+ loss.backward()
+ reached |= log_env.grad.abs().sum(-1) > 0
+ optimizer.step()
+
+ if step % 100 == 0 or step == args.iterations - 1:
+ decibel = psnr(to_srgb(fitted), to_srgb(reference))
+ print(f"step {step:5d} loss {loss.item():.2e} psnr {decibel:.2f} dB")
+
+ env = log_env.detach().exp()
+ camera = random_cameras(HELD_OUT_VIEWS, generator, device, CAMERA_DISTANCE)
+ with torch.no_grad():
+ fitted = to_srgb(render(ctx, mesh, env, camera, resolution))
+ reference = to_srgb(render(ctx, mesh, target, camera, resolution))
+ error = (to_srgb(env) - to_srgb(target)).abs().amax(-1)
+ print(
+ f"renders psnr {psnr(fitted, reference):.2f} dB on {HELD_OUT_VIEWS} new views with "
+ "their backdrop, in display values"
+ )
+ print(
+ f"cube map psnr {psnr(to_srgb(env), to_srgb(target)):.2f} dB, "
+ f"{(error < 0.05).float().mean().item():.1%} of its texels within 0.05; "
+ f"{reached.float().mean().item():.1%} of them received gradient"
+ )
+
+ if args.gif and frames:
+ save_animation(frames, args.gif, frame_ms=70, dither=False)
+ print(f"wrote {args.gif}")
+ if args.out:
+ figure(ctx, mesh, target, env, args.iterations, 0.5, args.out_width, still=True).save(
+ args.out
+ )
+ print(f"wrote {args.out}")
+ if args.cover:
+ cover(ctx, mesh, studio(COVER_DETAIL * args.env_size, device, 2)).save(args.cover)
+ print(f"wrote {args.cover}")
+
+
+if __name__ == "__main__":
+ main()
diff --git a/examples/gbuffer.py b/examples/gbuffer.py
new file mode 100644
index 0000000..d84d8ed
--- /dev/null
+++ b/examples/gbuffer.py
@@ -0,0 +1,228 @@
+"""Show what each diffrast op returns, on one object.
+
+A torus knot is rendered with one chain of ops, and every intermediate result becomes a panel of
+the figure: triangle ids, barycentrics and depth from ``rasterize``; texture coordinates, normals
+and screen-space derivatives (shown as the mip level they select) from ``interpolate``; the
+sampled colours from ``texture``; and the shaded image after ``antialias``. The mesh is coarse on
+purpose, so that single triangles stay visible.
+
+ python examples/gbuffer.py --out gbuffer.png
+
+Requires Pillow (``pip install -e . --group examples``).
+"""
+
+from __future__ import annotations
+
+import argparse
+import math
+from typing import NamedTuple
+
+import torch
+import torch.nn.functional as F
+from torch import Tensor
+
+import diffrast as dr
+from common import (
+ ACCENT,
+ PANEL,
+ Mesh,
+ downsample,
+ look_at,
+ orbit,
+ perspective,
+ titled_panels,
+ to_clip,
+ to_image,
+ to_srgb,
+ torus_knot,
+ vertex_normals,
+)
+
+MIP_COLOURS = ((0.12, 0.16, 0.30), (0.20, 0.50, 0.55), (0.85, 0.76, 0.52), (0.97, 0.94, 0.88))
+
+
+class Buffers(NamedTuple):
+ """Everything the chain of ops produces for one view, each ``[1, height, width, channels]``."""
+
+ rast: Tensor
+ uv: Tensor
+ uv_da: Tensor
+ normal: Tensor
+ albedo: Tensor
+ image: Tensor
+
+
+def render(
+ ctx: dr.RasterizeContext, mesh: Mesh, tex: Tensor, eye: Tensor, resolution: tuple[int, int]
+) -> Buffers:
+ """Run the whole chain once and keep every intermediate result."""
+ height, width = resolution
+ mvp = perspective(30, width / height, device=eye.device) @ look_at(eye)
+ pos = centre_in_frame(to_clip(mesh.positions, mvp))
+ normals = vertex_normals(mesh.positions, mesh.tri)
+
+ rast, rast_db = dr.rasterize(ctx, pos, mesh.tri, resolution)
+ uv, uv_da = dr.interpolate(mesh.uvs, rast, mesh.tri_uv, rast_db=rast_db, diff_attrs="all")
+ normal, _ = dr.interpolate(normals, rast, mesh.tri)
+ albedo = dr.texture(tex, uv, uv_da, filter_mode="linear-mipmap-linear")
+
+ normal = F.normalize(normal, dim=-1)
+ shaded = on_panel(to_srgb(albedo * irradiance(normal)), rast)
+ image = dr.antialias(shaded, rast, pos, mesh.tri)
+ return Buffers(rast, uv, uv_da, normal, albedo, image)
+
+
+def centre_in_frame(pos: Tensor, fill: float = 0.82) -> Tensor:
+ """Shift and scale clip-space positions so the object spans ``fill`` of the image."""
+ ndc = pos[..., :2] / pos[..., 3:]
+ low, high = ndc.amin(1, keepdim=True), ndc.amax(1, keepdim=True)
+ scale = 2 * fill / (high - low).amax()
+ xy = (pos[..., :2] - (low + high) / 2 * pos[..., 3:]) * scale
+ return torch.cat([xy, pos[..., 2:]], -1)
+
+
+def irradiance(normal: Tensor) -> Tensor:
+ """Linear light on the surface: a warm key from the upper front, ambient and a cool fill."""
+ key = F.normalize(normal.new_tensor([0.45, 0.85, 0.55]), dim=0)
+ fill = F.normalize(normal.new_tensor([-0.8, 0.2, 0.4]), dim=0)
+ warm = normal.new_tensor([1.0, 0.96, 0.9])
+ cool = normal.new_tensor([0.55, 0.65, 1.0])
+ diffuse = (normal @ key).clamp(min=0)[..., None]
+ wrap = (0.5 + 0.5 * (normal @ fill))[..., None]
+ return 0.22 + 0.75 * warm * diffuse + 0.08 * cool * wrap
+
+
+def on_panel(colours: Tensor, rast: Tensor) -> Tensor:
+ """``colours`` where a triangle was drawn and the panel colour elsewhere."""
+ return torch.where(rast[..., 3:] > 0, colours, colours.new_tensor(PANEL))
+
+
+def stripe_texture(size: int, device: torch.device) -> Tensor:
+ """Linear-colour texture, ``8 * size`` wide: a striped band between two thin lines on cream."""
+ v, u = torch.meshgrid(
+ torch.linspace(0, 1, size, device=device),
+ torch.linspace(0, 1, 8 * size, device=device),
+ indexing="ij",
+ )
+ cream = torch.tensor((0.85, 0.79, 0.70), device=device)
+ orange = torch.tensor(ACCENT, device=device) ** 2.2
+ charcoal = torch.tensor((0.05, 0.046, 0.043), device=device)
+
+ across = (v - 0.5).abs()[..., None]
+ stripes = ((u * 48 + v * 2) % 1 < 0.5)[..., None]
+ colour = torch.where(across < 0.11, torch.where(stripes, orange, charcoal), cream)
+ colour = torch.where((across > 0.15) & (across < 0.175), charcoal, colour)
+ return colour[None].contiguous()
+
+
+def id_colours(rast: Tensor, triangles: int, seed: int) -> Tensor:
+ """A fixed pseudo-random hue per triangle. ``rast[..., 3]`` holds the triangle id plus one."""
+ generator = torch.Generator().manual_seed(seed)
+ hue = torch.rand(triangles + 1, 1, generator=generator)
+ value = 0.75 + 0.25 * torch.rand(triangles + 1, 1, generator=generator)
+ phase = torch.tensor([0.0, 1 / 3, 2 / 3])
+ table = value * (0.62 + 0.3 * torch.cos(2 * math.pi * (hue + phase)))
+ return table.to(rast.device)[rast[..., 3].long()]
+
+
+def barycentric_colours(rast: Tensor) -> Tensor:
+ """The weights of the three corners as red, green and blue; ``rast`` stores the first two."""
+ u, v = rast[..., 0], rast[..., 1]
+ return torch.stack([u, v, 1 - u - v], -1)
+
+
+def depth_shades(rast: Tensor) -> Tensor:
+ """``z / w`` stretched over the range the object covers, with near surfaces bright."""
+ z = rast[..., 2:3]
+ drawn = z[rast[..., 3:] > 0]
+ near, far = drawn.min(), drawn.max()
+ return (0.12 + 0.88 * (far - z) / (far - near)).expand(-1, -1, -1, 3)
+
+
+def mip_level(uv_da: Tensor, tex: Tensor) -> Tensor:
+ """The level of detail that ``texture`` derives from ``uv_da``.
+
+ ``uv_da`` holds how far ``uv`` moves from one pixel to the next along x and along y. Measured
+ in texels, the longer of those two steps is the footprint of the pixel, and its base-two
+ logarithm is the mip level whose texels are about as large as the pixel.
+ """
+ du_dx, du_dy, dv_dx, dv_dy = uv_da.unbind(-1)
+ height, width = tex.shape[1:3]
+ step_x = torch.hypot(du_dx * width, dv_dx * height)
+ step_y = torch.hypot(du_dy * width, dv_dy * height)
+ return torch.log2(torch.maximum(step_x, step_y).clamp(min=1e-8)).clamp(min=0)
+
+
+def mip_colours(level: Tensor) -> Tensor:
+ """Blend through ``MIP_COLOURS``, which has one colour per whole level."""
+ stops = level.new_tensor(MIP_COLOURS)
+ level = level.clamp(0, len(MIP_COLOURS) - 1 - 1e-4)
+ lower = level.floor().long()
+ blend = (level - lower)[..., None]
+ return torch.lerp(stops[lower], stops[lower + 1], blend)
+
+
+def figure_cells(
+ buffers: Buffers, tex: Tensor, triangles: int, seed: int
+) -> list[tuple[str, str, Tensor]]:
+ """Title, origin and display colours of every panel, in the order of the pipeline."""
+ rast, uv = buffers.rast, buffers.uv
+ uv_colours = torch.cat([uv, torch.full_like(uv[..., :1], 0.25)], -1)
+ levels = mip_colours(mip_level(buffers.uv_da, tex))
+ cells = [
+ ("triangle id", "rasterize · rast[..., 3]", id_colours(rast, triangles, seed)),
+ ("barycentrics", "rasterize · rast[..., :2]", barycentric_colours(rast)),
+ ("depth, near is bright", "rasterize · rast[..., 2]", depth_shades(rast)),
+ ("texture coordinates", "interpolate · uv", uv_colours),
+ ("normals", "interpolate · normal", buffers.normal * 0.5 + 0.5),
+ (f"mip level, 0 dark to {len(MIP_COLOURS) - 1} pale", "interpolate · uv_da", levels),
+ ("texture", "texture · albedo", to_srgb(buffers.albedo)),
+ ]
+ cells = [(title, origin, on_panel(colours, rast)) for title, origin, colours in cells]
+ return [*cells, ("shaded and antialiased", "antialias · image", buffers.image)]
+
+
+def main() -> None:
+ parser = argparse.ArgumentParser(description=__doc__.split("\n\n")[0])
+ parser.add_argument("--panel", type=int, default=390, help="panel size in pixels")
+ parser.add_argument(
+ "--supersample", type=int, default=2, help="render at this multiple and average down"
+ )
+ parser.add_argument("--segments", type=int, default=112, help="segments along the knot")
+ parser.add_argument("--sides", type=int, default=10, help="segments around the tube")
+ parser.add_argument("--texture-size", type=int, default=512, help="texture height")
+ parser.add_argument("--seed", type=int, default=0, help="picks the triangle id colours")
+ parser.add_argument("--out", help="write the figure to this PNG")
+ parser.add_argument(
+ "--device", default="cuda" if torch.cuda.is_available() else "cpu", help="cuda or cpu"
+ )
+ args = parser.parse_args()
+
+ device = torch.device(args.device)
+ ctx = dr.RasterizeContext(device)
+ mesh = torus_knot(segments=args.segments, sides=args.sides, device=device)
+ tex = stripe_texture(args.texture_size, device)
+ eye = orbit(torch.tensor([0.55], device=device), torch.tensor([0.36], device=device), 4.1)
+ side = args.panel * args.supersample
+
+ with torch.no_grad():
+ buffers = render(ctx, mesh, tex, eye, (side, side))
+ cells = figure_cells(buffers, tex, mesh.tri.shape[0], args.seed)
+
+ drawn = buffers.rast[..., 3] > 0
+ visible = buffers.rast[..., 3][drawn].unique().numel()
+ level = mip_level(buffers.uv_da, tex)[drawn]
+ print(f"{mesh.tri.shape[0]} triangles, {visible} of them visible, at {side} x {side} px")
+ print(f"the knot covers {drawn.float().mean().item():.1%} of the image")
+ print(f"mip level: median {level.median().item():.2f}, highest {level.max().item():.2f}")
+
+ if args.out:
+ titles, origins, colours = zip(*cells, strict=True)
+ # Panels are rendered larger and averaged down, which also smooths the data panels.
+ pictures = [to_image(downsample(panel, args.supersample)[0]) for panel in colours]
+ titled_panels(pictures, titles, origins, columns=4).save(args.out)
+ print(f"wrote {args.out}")
+
+
+if __name__ == "__main__":
+ main()
diff --git a/examples/pose_fitting.py b/examples/pose_fitting.py
new file mode 100644
index 0000000..e23656a
--- /dev/null
+++ b/examples/pose_fitting.py
@@ -0,0 +1,532 @@
+"""Recover the rotation of a die from a single image by fitting many pose hypotheses at once.
+
+A die is rendered in a hidden pose. A batch of hypotheses, each with its own quaternion, is rendered
+by one call of each op and compared with that image. The loss of a hypothesis depends on its own
+image only, so one backward pass gives every quaternion its own gradient.
+
+Gradient descent from a random rotation rarely ends on the true pose: about 1 start in 40 does.
+Every second start settles on a pose that is 90, 120 or 180 degrees off, where the outline matches
+and only the pips differ, because 24 rotations map a cube onto itself. The search therefore has
+two stages, and the batch dimension carries both:
+
+1. Random starts are fitted together. The one with the lowest loss has found the outline.
+2. That pose is turned by each of the 24 rotations and the copies are fitted together. Now the
+ pips decide: the copy with the lowest loss is the answer.
+
+ python examples/pose_fitting.py --gif pose_fitting.gif --out pose_fitting.png
+
+The animation shows the target beside all hypotheses. A tile is brighter the lower its loss, the
+lowest is framed, and when a stage has finished every tile is captioned with its distance from
+the true pose. Between the stages the best start is copied to every tile and the copies turn into
+place. The still shows the end of both stages.
+
+With the default settings and seeds 0 to 99, the answer was within 0.5 degrees of the true pose
+97 times in one sweep and 98 times in another; stage 1 on its own was right 42 and 43 times.
+Five of those hidden poses show a single face, an image that fits two or four poses equally well.
+The script reports such a tie. Which of the tied poses comes out is left to rounding, and every
+miss was one of these five. Stage 2 relies on knowing that the object is a cube, and the target
+is a render without noise from this same renderer.
+
+``--gif`` writes the format that its file name ends in: ``.gif``, ``.webp`` or, with ffmpeg on the
+PATH, ``.mp4`` and ``.webm``.
+
+Requires Pillow (``pip install -e . --group examples``).
+"""
+
+from __future__ import annotations
+
+import argparse
+import math
+from collections.abc import Iterator
+from functools import partial
+from typing import NamedTuple
+
+import torch
+import torch.nn.functional as F
+from PIL import Image, ImageDraw
+from torch import Tensor
+
+import diffrast as dr
+from common import (
+ ACCENT,
+ BACKGROUND,
+ CLAY,
+ INK,
+ MUTED,
+ PANEL,
+ TEXT,
+ downsample,
+ font,
+ from_srgb,
+ lighting,
+ look_at,
+ perspective,
+ rgb,
+ save_animation,
+ stack,
+ to_clip,
+ to_image,
+ to_srgb,
+)
+
+# Pips and outward direction (axis, sign) of each face; opposite faces sum to seven. Face k is
+# drawn in cell (k % 3, k // 3) of the atlas.
+FACES = [(1, 1, 1.0), (6, 1, -1.0), (2, 2, 1.0), (5, 2, -1.0), (3, 0, 1.0), (4, 0, -1.0)]
+PIP_LAYOUT = {
+ 1: [(0, 0)],
+ 2: [(-1, -1), (1, 1)],
+ 3: [(-1, -1), (0, 0), (1, 1)],
+ 4: [(-1, -1), (-1, 1), (1, -1), (1, 1)],
+ 5: [(-1, -1), (-1, 1), (0, 0), (1, -1), (1, 1)],
+ 6: [(-1, -1), (-1, 0), (-1, 1), (1, -1), (1, 0), (1, 1)],
+}
+
+# Directions towards the lights. The key light is far enough to the side that the three visible
+# faces of the die get three different shades.
+KEY_LIGHT = (0.55, 0.75, 0.36)
+FILL_LIGHT = (-0.7, -0.2, 0.4)
+
+FOV = 30.0
+# From this far away the die leaves a margin in every pose, with room for a caption in a corner.
+CAMERA_DISTANCE = 4.2
+
+# A hypothesis this close to the true pose, in degrees, counts as having found it.
+FOUND = 2.0
+# Two losses closer than this cannot be told apart: the image fits both poses.
+TIE = 5e-6
+# Milliseconds per frame of the animation, and for which it stops on the result of stage 1.
+FRAME_MS = 80
+PAUSE_MS = 1120
+
+
+class Die(NamedTuple):
+ """Cube with one index buffer per attribute.
+
+ The eight corners are shared by all faces, so ``tri`` describes a closed surface, which is
+ what ``antialias`` needs to tell silhouette edges from the edges between two visible faces.
+ Texture coordinates and normals differ per face and are indexed by their own buffers.
+ """
+
+ positions: Tensor # [8, 3]
+ tri: Tensor # [12, 3]
+ uvs: Tensor # [24, 2]
+ tri_uv: Tensor # [12, 3]
+ normals: Tensor # [6, 3]
+ tri_normal: Tensor # [12, 3]
+
+
+class Scene(NamedTuple):
+ """Everything a render needs besides the poses."""
+
+ ctx: dr.RasterizeContext
+ die: Die
+ atlas: Tensor
+ camera: Tensor
+
+
+def make_die(device: torch.device) -> Die:
+ """Unit cube whose face ``k`` maps onto cell ``k`` of a 3x2 texture atlas."""
+ signs = (-1.0, 1.0)
+ corners = [[x, y, z] for x in signs for y in signs for z in signs]
+ tri, uvs, tri_uv, normals, tri_normal = [], [], [], [], []
+ for face, (_, axis, sign) in enumerate(FACES):
+ u_axis, v_axis = (axis + 1) % 3, (axis + 2) % 3
+ quad = []
+ for u, v in ((0, 0), (1, 0), (1, 1), (0, 1)):
+ corner = [0.0, 0.0, 0.0]
+ corner[axis] = sign
+ corner[u_axis] = (2 * u - 1) * sign # keeps the face from being mirrored
+ corner[v_axis] = 2 * v - 1
+ quad.append(corners.index(corner))
+ uvs.append([(face % 3 + u) / 3, (face // 3 + v) / 2])
+ first = 4 * face
+ tri += [[quad[0], quad[1], quad[2]], [quad[0], quad[2], quad[3]]]
+ tri_uv += [[first, first + 1, first + 2], [first, first + 2, first + 3]]
+ normals.append([sign if k == axis else 0.0 for k in range(3)])
+ tri_normal += [[face] * 3] * 2
+
+ def floats(values):
+ return torch.tensor(values, dtype=torch.float32, device=device)
+
+ def indices(values):
+ return torch.tensor(values, dtype=torch.int32, device=device)
+
+ return Die(
+ 0.5 * floats(corners),
+ indices(tri),
+ floats(uvs),
+ indices(tri_uv),
+ floats(normals),
+ indices(tri_normal),
+ )
+
+
+def pip_atlas(cell: int, device: torch.device) -> Tensor:
+ """Linear albedo of the six faces as a ``[1, 2 * cell, 3 * cell, 3]`` texture."""
+ y, x = torch.meshgrid(
+ (torch.arange(2 * cell, device=device) + 0.5) / cell,
+ (torch.arange(3 * cell, device=device) + 0.5) / cell,
+ indexing="ij",
+ )
+ ink = torch.zeros_like(x)
+ for face, (pips, _, _) in enumerate(FACES):
+ radius = 0.15 if pips == 1 else 0.095
+ for pip_x, pip_y in PIP_LAYOUT[pips]:
+ centre_x = face % 3 + 0.5 + 0.25 * pip_x
+ centre_y = face // 3 + 0.5 + 0.25 * pip_y
+ distance = torch.hypot(x - centre_x, y - centre_y)
+ # A ramp one texel wide keeps the edge of the pip smooth.
+ ink = torch.maximum(ink, ((radius - distance) * cell + 0.5).clamp(0, 1))
+ # A slightly darker rim reads as a bevel and makes the edges between faces visible.
+ to_edge = torch.minimum(0.5 - (x % 1 - 0.5).abs(), 0.5 - (y % 1 - 0.5).abs())
+ rim = 1 - 0.22 * (1 - to_edge / 0.045).clamp(0, 1) ** 2
+ clay, dark = x.new_tensor(CLAY), x.new_tensor(INK)
+ albedo = torch.lerp(clay * rim[..., None], dark, ink[..., None])
+ return albedo[None].contiguous()
+
+
+def quaternion_to_matrix(q: Tensor) -> Tensor:
+ """Rotation matrices ``[n, 3, 3]`` of quaternions ``[n, 4]`` in ``(w, x, y, z)`` order."""
+ w, x, y, z = F.normalize(q, dim=-1).unbind(-1)
+ return torch.stack(
+ [
+ 1 - 2 * (y * y + z * z), 2 * (x * y - z * w), 2 * (x * z + y * w),
+ 2 * (x * y + z * w), 1 - 2 * (x * x + z * z), 2 * (y * z - x * w),
+ 2 * (x * z - y * w), 2 * (y * z + x * w), 1 - 2 * (x * x + y * y),
+ ],
+ -1,
+ ).view(-1, 3, 3) # fmt: skip
+
+
+def compose(a: Tensor, b: Tensor) -> Tensor:
+ """Quaternion of the rotation ``b`` followed by the rotation ``a``."""
+ aw, ax, ay, az = a.unbind(-1)
+ bw, bx, by, bz = b.unbind(-1)
+ return torch.stack(
+ [
+ aw * bw - ax * bx - ay * by - az * bz,
+ aw * bx + ax * bw + ay * bz - az * by,
+ aw * by - ax * bz + ay * bw + az * bx,
+ aw * bz + ax * by - ay * bx + az * bw,
+ ],
+ -1,
+ )
+
+
+def cube_rotations(device: torch.device) -> Tensor:
+ """Quaternions ``[24, 4]`` of the rotations that map a cube onto itself.
+
+ They are the quaternions with one, two or four entries of equal size and zeros elsewhere:
+ turns about a face by a multiple of 90 degrees, about an edge by 180 and about a corner by
+ 120.
+ """
+ q = torch.cartesian_prod(*[torch.tensor([0.0, 1.0, -1.0])] * 4)
+ entries = (q != 0).sum(-1)
+ q = q[(entries == 1) | (entries == 2) | (entries == 4)]
+ # q and -q are the same rotation. The weights let the first non-zero entry decide the sign.
+ q = q[q @ torch.tensor([8.0, 4.0, 2.0, 1.0]) > 0]
+ return F.normalize(q, dim=-1).to(device)
+
+
+def turned(pose: Tensor, rotations: Tensor, amount: float = 1.0) -> Tensor:
+ """The die in ``pose`` after turning it by each of ``rotations``.
+
+ An ``amount`` below one stops part of the way, for the animation.
+ """
+ identity = rotations.new_tensor([1.0, 0.0, 0.0, 0.0])
+ return compose(pose, F.normalize(torch.lerp(identity, rotations, amount), dim=-1))
+
+
+def random_quaternions(count: int, generator: torch.Generator, device: torch.device) -> Tensor:
+ """Uniformly distributed rotations, drawn on the CPU so a seed gives the same on any device."""
+ return F.normalize(torch.randn(count, 4, generator=generator), dim=-1).to(device)
+
+
+def angle_between(q: Tensor, reference: Tensor) -> Tensor:
+ """Angle in degrees of the rotation that takes each ``q`` to ``reference``."""
+ dot = (F.normalize(q, dim=-1) * reference).sum(-1).abs().clamp(max=1)
+ return torch.rad2deg(2 * torch.acos(dot))
+
+
+def matches_outline(q: Tensor, reference: Tensor, tolerance: float = 0.1) -> Tensor:
+ """Whether each ``q`` differs from ``reference`` by a rotation that maps a cube onto itself.
+
+ Such a rotation permutes the axes of the die, so its matrix holds only 0, 1 and -1.
+ """
+ relative = quaternion_to_matrix(reference).transpose(1, 2) @ quaternion_to_matrix(q)
+ return (relative - relative.round()).abs().amax(dim=(1, 2)) < tolerance
+
+
+def render(scene: Scene, poses: Tensor, resolution: int) -> Tensor:
+ """Linear images ``[n, resolution, resolution, 3]`` of the die, one per quaternion."""
+ die = scene.die
+ rotation = quaternion_to_matrix(poses).transpose(1, 2)
+ pos = to_clip(die.positions @ rotation, scene.camera)
+
+ rast, rast_db = dr.rasterize(scene.ctx, pos, die.tri, (resolution, resolution))
+ uv, uv_da = dr.interpolate(die.uvs, rast, die.tri_uv, rast_db=rast_db, diff_attrs="all")
+ normal, _ = dr.interpolate(die.normals @ rotation, rast, die.tri_normal)
+ albedo = dr.texture(
+ scene.atlas, uv, uv_da, filter_mode="linear-mipmap-linear", boundary_mode="clamp"
+ )
+
+ shaded = albedo * lighting(normal, KEY_LIGHT, FILL_LIGHT)
+ covered = rast[..., 3:] > 0
+ colour = torch.where(covered, shaded, from_srgb(PANEL, pos.device))
+ return dr.antialias(colour, rast, pos, die.tri)
+
+
+def image_loss(scene: Scene, poses: Tensor, target: Tensor) -> Tensor:
+ """Mean squared difference between the image of each pose and the target, ``[n]``."""
+ image = render(scene, poses, target.shape[1])
+ # Every image is compared with the target on its own: one loss per hypothesis.
+ return (image - target).square().mean(dim=(1, 2, 3))
+
+
+def fit(
+ scene: Scene, target: Tensor, poses: Tensor, steps: int, lr: float, momentum: float
+) -> Iterator[tuple[int, Tensor, Tensor]]:
+ """Fit all poses to the target at once by gradient descent with momentum.
+
+ Yields ``(step, poses, losses)`` before every update and once more after the last one.
+ """
+ poses = poses.clone().requires_grad_(True)
+ optimiser = torch.optim.SGD([poses], lr=lr, momentum=momentum)
+ for step in range(steps + 1):
+ loss = image_loss(scene, poses, target)
+ yield step, poses.detach().clone(), loss.detach()
+ if step == steps:
+ return
+ optimiser.zero_grad()
+ # No loss depends on another hypothesis, so the gradient of their sum holds the gradient
+ # of each hypothesis with respect to its own quaternion.
+ loss.sum().backward()
+ optimiser.step()
+ with torch.no_grad():
+ # Only the direction of a quaternion matters; unit length keeps the steps comparable.
+ poses.copy_(F.normalize(poses, dim=-1))
+
+
+def report(stage: int, step: int, loss: Tensor, error: Tensor) -> None:
+ """Print how the hypothesis with the lowest loss is doing, and how many found the pose."""
+ best = int(loss.argmin())
+ print(
+ f"stage {stage} step {step:3d} lowest loss {loss[best].item():.6f}, "
+ f"{error[best].item():6.2f} deg off within {FOUND:g} deg: "
+ f"{int((error < FOUND).sum())}/{len(loss)}"
+ )
+
+
+def early_steps(steps: int, count: int) -> set[int]:
+ """``count`` steps to draw a frame at. Most turning happens early, so they crowd there."""
+ return {round(steps * (i / count) ** 2) for i in range(count)}
+
+
+class Layout(NamedTuple):
+ """Pixel geometry of a figure: one large image on the left, a grid of tiles on the right."""
+
+ width: int
+ height: int
+ pad: int
+ gap: int
+ text: int
+ top: int
+ large: int
+ cell: int
+ columns: int
+ grid_x: int
+
+
+def plan_layout(width: int, tiles: int) -> Layout:
+ """Square tiles sized so that the grid is as tall as the large image and fills ``width``."""
+ unit = width / 960
+ pad, gap, text = round(16 * unit), round(6 * unit), round(18 * unit)
+ rows = math.ceil(math.sqrt(tiles / 2))
+ columns = math.ceil(tiles / rows)
+ cell = (width - 3 * pad - (rows + columns - 2) * gap) // (rows + columns)
+ large = rows * cell + (rows - 1) * gap
+ top = 2 * pad + text
+ grid_x = width - pad - columns * cell - (columns - 1) * gap
+ return Layout(width, top + large + pad, pad, gap, text, top, large, cell, columns, grid_x)
+
+
+def figure(
+ scene: Scene,
+ true_pose: Tensor,
+ layout: Layout,
+ label: str,
+ large_pose: Tensor,
+ heading: str,
+ poses: Tensor,
+ loss: Tensor,
+ captions: bool = False,
+) -> Image.Image:
+ """The die in ``large_pose`` beside all hypotheses, each dimmed by its loss.
+
+ The hypothesis with the lowest loss is framed. With ``captions``, every tile shows its
+ distance from the true pose, muted where not even the outline fits.
+ """
+ # Rendered at twice the size and averaged down.
+ with torch.no_grad():
+ large = downsample(to_srgb(render(scene, large_pose, 2 * layout.large)), 2)[0]
+ tiles = downsample(to_srgb(render(scene, poses, 2 * layout.cell)), 2)
+ error = angle_between(poses, true_pose)
+ settled = matches_outline(poses, true_pose)
+ best = int(loss.argmin())
+
+ canvas = Image.new("RGB", (layout.width, layout.height), rgb(BACKGROUND))
+ draw = ImageDraw.Draw(canvas)
+ big, small = font(layout.text), font(round(layout.text * 8 / 9))
+ draw.text((layout.pad, layout.pad), label, rgb(MUTED), big)
+ canvas.paste(to_image(large), (layout.pad, layout.top))
+ draw.text((layout.grid_x, layout.pad), heading, rgb(MUTED), big)
+ # The number ends at the right edge and its label before a slot of fixed width, so that
+ # nothing shifts between frames.
+ right = layout.width - layout.pad
+ slot = round(draw.textlength(" 000.0°", font=big))
+ draw.text((right - slot, layout.pad), "best is off by", rgb(MUTED), big, anchor="ra")
+ draw.text((right, layout.pad), f"{error[best].item():.1f}°", rgb(TEXT), big, anchor="ra")
+
+ # Tiles fade towards the panel colour with their loss, measured between the best and the
+ # worst of the moment, so the ranking stays readable while every loss shrinks.
+ excess = (loss - loss.min()) / (loss.max() - loss.min()).clamp(min=TIE)
+ opacity = 1 - 0.68 * excess.sqrt()
+ tiles = torch.lerp(tiles.new_tensor(PANEL), tiles, opacity[:, None, None, None])
+ for index in range(len(loss)):
+ x = layout.grid_x + (index % layout.columns) * (layout.cell + layout.gap)
+ y = layout.top + (index // layout.columns) * (layout.cell + layout.gap)
+ canvas.paste(to_image(tiles[index]), (x, y))
+ if captions:
+ caption = f"{error[index].item():.0f}°"
+ corner = (x + layout.gap, y + layout.cell - layout.gap // 2)
+ draw.text(corner, caption, rgb(TEXT if settled[index] else MUTED), small, anchor="ls")
+ if index == best:
+ line = max(2, round(layout.text / 7))
+ box = [x - line, y - line, x + layout.cell + line - 1, y + layout.cell + line - 1]
+ draw.rectangle(box, outline=rgb(ACCENT), width=line)
+ return canvas
+
+
+def main() -> None:
+ parser = argparse.ArgumentParser(description=__doc__.split("\n\n")[0])
+ parser.add_argument("--hypotheses", type=int, default=24, help="random starts of stage 1")
+ parser.add_argument("--iterations", type=int, default=60, help="steps of stage 1")
+ parser.add_argument("--refine", type=int, default=60, help="steps of stage 2")
+ parser.add_argument("--resolution", type=int, default=64, help="size of the fitted images")
+ parser.add_argument("--texture-size", type=int, default=256, help="size of one atlas cell")
+ parser.add_argument("--lr", type=float, default=0.1, help="learning rate")
+ parser.add_argument("--momentum", type=float, default=0.9, help="momentum of gradient descent")
+ parser.add_argument(
+ "--seed",
+ type=int,
+ default=14,
+ help="picks the hidden pose and the starts; with the default, stage 1 alone ends a "
+ "quarter turn off",
+ )
+ parser.add_argument(
+ "--gif",
+ help="write the optimisation progress to this animation; "
+ "the extension picks the format: .gif, .webp, .mp4 or .webm",
+ )
+ parser.add_argument(
+ "--frames", type=int, default=32, help="frames of stage 1; the later parts scale with it"
+ )
+ parser.add_argument("--gif-width", type=int, default=960, help="width of the animation")
+ parser.add_argument("--out", help="write a still of both stages to this PNG")
+ parser.add_argument("--out-width", type=int, default=1660, help="width of the PNG")
+ parser.add_argument(
+ "--device", default="cuda" if torch.cuda.is_available() else "cpu", help="cuda or cpu"
+ )
+ args = parser.parse_args()
+
+ device = torch.device(args.device)
+ generator = torch.Generator().manual_seed(args.seed)
+ eye = torch.tensor([[0.0, 0.0, CAMERA_DISTANCE]], device=device)
+ scene = Scene(
+ dr.RasterizeContext(device),
+ make_die(device),
+ pip_atlas(args.texture_size, device),
+ perspective(FOV, 1.0, device=device) @ look_at(eye),
+ )
+ true_pose = random_quaternions(1, generator, device)
+ starts = random_quaternions(args.hypotheses, generator, device)
+ rotations = cube_rotations(device)
+ with torch.no_grad():
+ target = render(scene, true_pose, args.resolution)
+
+ draw = partial(figure, scene, true_pose)
+ tiles = max(args.hypotheses, len(rotations))
+ layout = plan_layout(args.gif_width, tiles)
+ # The frames of the animation, and how long the ones that pause stay on screen.
+ frames, holds = [], {}
+
+ # Stage 1: from random rotations, most hypotheses turn until their outline fits.
+ heading = f"{args.hypotheses} random starts in one batch"
+ capture = early_steps(args.iterations, args.frames)
+ for step, poses, loss in fit(scene, target, starts, args.iterations, args.lr, args.momentum):
+ error = angle_between(poses, true_pose)
+ if step % 20 == 0 or step == args.iterations:
+ report(1, step, loss, error)
+ if args.gif and step in capture:
+ frames.append(draw(layout, "target", true_pose, f"{heading}, step {step}", poses, loss))
+ best_start = poses[loss.argmin()]
+ first = (f"{heading}, step {args.iterations}", poses, loss) # kept for the figures
+ found = int((error < FOUND).sum())
+ # The smallest turn that maps a cube onto itself is a quarter turn.
+ symmetric = int((matches_outline(poses, true_pose) & (error > 45)).sum())
+ print(
+ f"stage 1: of {args.hypotheses} random starts, {found} reached the true pose, "
+ f"{symmetric} a symmetric pose and {args.hypotheses - found - symmetric} neither; "
+ f"the one with the lowest loss is {error[loss.argmin()].item():.2f} deg off"
+ )
+
+ # Stage 2: the true pose has the same outline as the best start, so it is one of the 24
+ # turned copies of it, and the pips single it out.
+ heading = f"the best start, turned {len(rotations)} ways"
+ if args.gif:
+ # Pause on the settled poses with their errors, then show where the copies come from:
+ # every tile starts as the best start, rests for a moment and turns into its place.
+ holds[len(frames)] = PAUSE_MS
+ frames.append(draw(layout, "target", true_pose, *first, captions=True))
+ holds[len(frames)] = PAUSE_MS // 2
+ turn_frames = max(1, args.frames // 2)
+ for frame in range(turn_frames):
+ amount = frame / turn_frames
+ poses = turned(best_start, rotations, amount * amount * (3 - 2 * amount))
+ with torch.no_grad():
+ loss = image_loss(scene, poses, target)
+ frames.append(draw(layout, "target", true_pose, heading, poses, loss))
+ capture = early_steps(args.refine, max(1, args.frames // 8))
+ copies = turned(best_start, rotations)
+ for step, poses, loss in fit(scene, target, copies, args.refine, args.lr, args.momentum):
+ error = angle_between(poses, true_pose)
+ if step % 20 == 0 or step == args.refine:
+ report(2, step, loss, error)
+ if args.gif and step in capture:
+ frames.append(draw(layout, "target", true_pose, f"{heading}, step {step}", poses, loss))
+ best, runner_up = loss.argsort()[:2].tolist()
+ second = (f"{heading}, step {args.refine}", poses, loss)
+ print(
+ f"stage 2: hypothesis {best} has the lowest loss ({loss[best].item():.6f}) and is "
+ f"{error[best].item():.2f} deg off; the runner-up ({loss[runner_up].item():.6f}) is "
+ f"{error[runner_up].item():.0f} deg off"
+ )
+ if loss[runner_up] - loss[best] < TIE:
+ print("the two fit the image equally well: this view of the die does not tell them apart")
+
+ if args.gif:
+ frames.append(draw(layout, "target", true_pose, *second, captions=True))
+ save_animation(frames, args.gif, frame_ms=FRAME_MS, holds=holds)
+ print(f"wrote {args.gif}")
+ if args.out:
+ layout = plan_layout(args.out_width, tiles)
+ rows = [
+ draw(layout, "target", true_pose, *first, captions=True),
+ draw(layout, "the best random start", best_start[None], *second, captions=True),
+ ]
+ stack(rows, layout.pad).save(args.out)
+ print(f"wrote {args.out}")
+
+
+if __name__ == "__main__":
+ main()
diff --git a/examples/shape_fitting.py b/examples/shape_fitting.py
new file mode 100644
index 0000000..a13e601
--- /dev/null
+++ b/examples/shape_fitting.py
@@ -0,0 +1,417 @@
+"""Recover a mesh from rendered images alone.
+
+A sphere is deformed until its renders match renders of a target shape from random viewpoints.
+Which triangle a pixel shows is a step function of the vertex positions, so a plain rasterizer
+gives no gradient for moving a silhouette. ``dr.antialias`` turns that step into a ramp, and the
+ramp is what lets the outline of the sphere travel to the outline of the target.
+
+ python examples/shape_fitting.py --gif shape_fitting.gif --out shape_fitting.png
+
+The images do not say where each vertex should go, only where the outline and the shading are
+wrong, and a naive optimisation folds the surface over itself. Three things prevent that here: the
+positions are optimised through a smoothing change of variables, the optimiser keeps the direction
+of the smoothed gradient, and shading is compared only where the target is. None of the three is
+part of diffrast; they are spelled out below.
+
+The animation shows the target, the mesh on a slow turntable, and four views that are never
+trained on, in which the mesh is painted over the target: orange is what the mesh has yet to
+cover. The script prints how well the outlines overlap on such held-out views, and at the end the
+fraction of triangles that ended up flipped.
+
+The target is a chess pawn, or any OBJ file given with ``--mesh``. The optimisation moves vertices
+and cannot change how they are connected, so the target must have the topology of a sphere: a
+shape with a hole or a handle will not be recovered.
+
+``--gif`` writes the format that its file name ends in: ``.gif``, ``.webp`` or, with ffmpeg on the
+PATH, ``.mp4`` and ``.webm``.
+
+Requires Pillow (``pip install -e . --group examples``).
+"""
+
+from __future__ import annotations
+
+import argparse
+import math
+from collections.abc import Sequence
+
+import numpy as np
+import torch
+import torch.nn.functional as F
+from PIL import Image
+from torch import Tensor
+
+import diffrast as dr
+from common import (
+ BACKGROUND,
+ CLAY,
+ PANEL,
+ Mesh,
+ downsample,
+ from_srgb,
+ icosphere,
+ lathe,
+ layout,
+ load_obj,
+ look_at,
+ orbit,
+ panels,
+ perspective,
+ rgb,
+ save_animation,
+ to_clip,
+ to_image,
+ to_srgb,
+ vertex_normals,
+)
+
+# From this far away the unit sphere, which bounds every mesh, fits in the image with a margin.
+FOV, CAMERA_DISTANCE = 40.0, 3.4
+# Camera of the pictures. The views that are trained on are random.
+PICTURE_YAW, PICTURE_PITCH = 0.6, 0.3
+HELD_OUT_VIEWS = 16
+
+# A small start, so that most of the surface has to grow. Where a wide sphere must shrink onto a
+# thin part of the target, its triangles are squeezed into slivers that flip easily.
+START_RADIUS = 0.4
+# The learning rate ends at this fraction of its peak.
+LR_DECAY = 0.05
+
+# Direction towards each light in camera space, and its colour. The lights move with the camera,
+# so every side of the shape is lit in some view: a key light from the upper front and a faint
+# cool fill. Together they put a lit clay surface just below white after common.to_srgb.
+LIGHTS = (
+ ((0.65, 0.60, 0.45), (0.70, 0.67, 0.63)),
+ ((-0.80, 0.00, 0.30), (0.10, 0.13, 0.18)),
+)
+AMBIENT = 0.14
+
+# Linear albedo of the target in the pictures, which comes out close to common.ACCENT in the key
+# light. The fitted mesh is drawn in common.CLAY.
+ORANGE = (1.5, 0.114, 0.014)
+
+Camera = tuple[Tensor, Tensor] # clip-space matrices and world-to-camera rotations
+
+
+def pawn(segments: int = 96, device: torch.device | str = "cpu") -> Mesh:
+ """Chess pawn as a surface of revolution, centred and scaled to the unit sphere."""
+ angle = np.radians(np.linspace(90, -62, 13))
+ head = np.stack([0.185 * np.cos(angle), 0.83 + 0.185 * np.sin(angle)], -1)
+ head[0, 0] = 0.0
+ body = [
+ (0.100, 0.670), (0.105, 0.650), (0.170, 0.630), (0.215, 0.605), (0.170, 0.585),
+ (0.100, 0.555), (0.095, 0.500), (0.115, 0.370), (0.150, 0.250), (0.200, 0.170),
+ (0.250, 0.140), (0.290, 0.110), (0.360, 0.085), (0.385, 0.050), (0.370, 0.015),
+ (0.300, 0.000), (0.000, 0.000),
+ ] # fmt: skip
+ profile = np.concatenate([head, body])
+
+ # Chaikin corner cutting rounds the polyline; its two ends stay on the axis.
+ for _ in range(3):
+ cut = np.stack([0.75 * profile[:-1] + 0.25 * profile[1:],
+ 0.25 * profile[:-1] + 0.75 * profile[1:]], 1) # fmt: skip
+ profile = np.concatenate([profile[:1], cut.reshape(-1, 2), profile[-1:]])
+
+ # Rings at equal arc length, about as far apart as the vertices of the widest ring.
+ along = np.concatenate([[0.0], np.cumsum(np.linalg.norm(np.diff(profile, axis=0), axis=1))])
+ samples = np.linspace(0, along[-1], segments * 5 // 3)
+ radius = torch.from_numpy(np.interp(samples, along, profile[:, 0]))
+ height = torch.from_numpy(np.interp(samples, along, profile[:, 1]))
+
+ mesh = lathe(radius, height, segments, device)
+ positions = mesh.positions - (mesh.positions.amax(0) + mesh.positions.amin(0)) / 2
+ return Mesh(positions / positions.norm(dim=-1).max(), mesh.tri)
+
+
+def smoothing_matrices(vertices: int, tri: Tensor, weight: float) -> tuple[Tensor, Tensor]:
+ """The matrix ``I + weight * L`` and its inverse, with ``L`` the graph Laplacian of the mesh.
+
+ Both are dense, which is fine up to about ten thousand vertices (400 MB each).
+ """
+ i, j = tri.long().flatten(), tri.long().roll(-1, dims=1).flatten()
+ system = torch.zeros(vertices, vertices, device=tri.device)
+ system[i, j] = system[j, i] = -weight
+ system.diagonal().copy_(1 - system.sum(1))
+ return system, torch.cholesky_inverse(torch.linalg.cholesky(system))
+
+
+class UniformAdam:
+ """Adam with a single second moment shared by all coordinates.
+
+ Adam divides every coordinate by its own gradient magnitude. That throws away the relative
+ sizes the smoothing has just given the gradient, so vertices that hardly matter move as far
+ as those on a silhouette and the surface folds. Dividing by one number, the largest squared
+ gradient, keeps the step parallel to the smoothed gradient, and ``lr`` becomes the furthest
+ any coordinate moves in a step.
+ """
+
+ def __init__(self, parameter: Tensor, betas: tuple[float, float] = (0.9, 0.99)) -> None:
+ self.parameter, self.betas = parameter, betas
+ self.mean = torch.zeros_like(parameter)
+ self.peak = 0.0
+ self.steps = 0
+
+ @torch.no_grad()
+ def step(self, gradient: Tensor, lr: float) -> None:
+ beta1, beta2 = self.betas
+ self.steps += 1
+ self.mean = beta1 * self.mean + (1 - beta1) * gradient
+ self.peak = beta2 * self.peak + (1 - beta2) * gradient.square().max().item()
+ mean = self.mean / (1 - beta1**self.steps)
+ peak = self.peak / (1 - beta2**self.steps)
+ self.parameter -= lr * mean / max(math.sqrt(peak), 1e-20)
+
+
+def learning_rate(step: int, iterations: int, peak: float, warmup: float) -> float:
+ """Linear warm-up over the first ``warmup`` share of the iterations, then a slow decay.
+
+ Full-size steps while the sphere is still far from the target overshoot and fold the surface
+ before it has found the rough shape. The decay lets the last steps settle the fine detail.
+ """
+ ramp = min(1.0, (step + 1) / max(1.0, warmup * iterations))
+ return peak * ramp * LR_DECAY ** (step / iterations)
+
+
+def cameras(yaw: Tensor, pitch: Tensor) -> Camera:
+ """Clip-space matrices ``[views, 4, 4]`` and world-to-camera rotations ``[views, 3, 3]``."""
+ view = look_at(orbit(yaw, pitch, CAMERA_DISTANCE))
+ return perspective(FOV, 1.0, device=yaw.device) @ view, view[:, :3, :3]
+
+
+def random_views(count: int, generator: torch.Generator, device: torch.device) -> Camera:
+ """Cameras spread evenly over all directions, including from above and below."""
+ yaw = torch.rand(count, generator=generator) * 2 * math.pi
+ pitch = torch.asin(torch.rand(count, generator=generator) * 2 - 1)
+ return cameras(yaw.to(device), pitch.to(device))
+
+
+def render(ctx: dr.RasterizeContext, mesh: Mesh, camera: Camera, resolution: int) -> Tensor:
+ """Antialiased RGBA renders of a white surface, ``[views, height, width, 4]``.
+
+ RGB is the shading and alpha the coverage, both zero outside the shape. Everything from the
+ vertex positions to the output is differentiable.
+ """
+ matrix, rotation = camera
+ pos = to_clip(mesh.positions, matrix)
+ rast, _ = dr.rasterize(ctx, pos, mesh.tri, (resolution, resolution))
+ normal, _ = dr.interpolate(vertex_normals(mesh.positions, mesh.tri), rast, mesh.tri)
+ normal = F.normalize(normal, dim=-1)
+
+ shade = torch.full_like(normal, AMBIENT)
+ for direction, colour in LIGHTS:
+ # A row vector times the world-to-camera rotation is that vector in world space.
+ towards = F.normalize(normal.new_tensor(direction), dim=0) @ rotation
+ lambert = (normal * towards[:, None, None]).sum(-1, keepdim=True).clamp(min=0)
+ shade = shade + lambert * normal.new_tensor(colour)
+
+ covered = (rast[..., 3:] > 0).float()
+ image = torch.cat([shade * covered, covered], -1)
+ # Without this call the coverage is a step function of the vertex positions and the
+ # silhouette would never move.
+ return dr.antialias(image, rast, pos, mesh.tri)
+
+
+def image_loss(image: Tensor, reference: Tensor) -> Tensor:
+ """Squared error of the coverage, plus that of the shading where the target is.
+
+ Pixels that the mesh covers and the target does not are left to the coverage term alone.
+ Comparing their shading with the black around the target would reward turning the surface
+ away from the lights, and that creases it.
+ """
+ covered = reference[..., 3:]
+ shading = (covered * (image[..., :3] - reference[..., :3]).square()).mean()
+ return F.mse_loss(image[..., 3:], covered) + shading
+
+
+@torch.no_grad()
+def silhouette_iou(
+ ctx: dr.RasterizeContext, mesh: Mesh, target: Mesh, camera: Camera, resolution: int
+) -> float:
+ """Intersection over union of the pixels that two meshes cover, over all the views."""
+ ours = render(ctx, mesh, camera, resolution)[..., 3] > 0.5
+ theirs = render(ctx, target, camera, resolution)[..., 3] > 0.5
+ return ((ours & theirs).sum() / (ours | theirs).sum()).item()
+
+
+def flipped_fraction(mesh: Mesh) -> float:
+ """Fraction of triangles that face against the vertex normals around them.
+
+ A smooth closed surface has none. Folds and creases show up here.
+ """
+ corners = mesh.positions[mesh.tri.long()]
+ face = torch.linalg.cross(corners[:, 1] - corners[:, 0], corners[:, 2] - corners[:, 0])
+ around = vertex_normals(mesh.positions, mesh.tri)[mesh.tri.long()].sum(1)
+ return ((face * around).sum(-1) < 0).float().mean().item()
+
+
+def composite(layers: Sequence[tuple[Tensor, tuple[float, ...]]]) -> Image.Image:
+ """Paint RGBA renders, each tinted with an albedo, back to front on the panel colour.
+
+ The renders are twice the size of the picture and are averaged down.
+ """
+ colour = from_srgb(PANEL, layers[0][0].device)
+ for image, albedo in layers:
+ colour = image[..., :3] * image.new_tensor(albedo) + (1 - image[..., 3:]) * colour
+ return to_image(downsample(to_srgb(colour), 2))
+
+
+@torch.no_grad()
+def portrait(
+ ctx: dr.RasterizeContext, mesh: Mesh, albedo: tuple[float, ...], yaw: float, size: int
+) -> Image.Image:
+ """Picture of a mesh from slightly above, with the camera ``yaw`` radians around it."""
+ device = mesh.positions.device
+ camera = cameras(
+ torch.tensor([yaw], device=device), torch.tensor([PICTURE_PITCH], device=device)
+ )
+ return composite([(render(ctx, mesh, camera, 2 * size)[0], albedo)])
+
+
+@torch.no_grad()
+def overlays(
+ ctx: dr.RasterizeContext, mesh: Mesh, target: Mesh, camera: Camera, size: int
+) -> Image.Image:
+ """The first four views in a grid, with the mesh in clay painted over the target in orange.
+
+ Orange is visible wherever the target is not covered yet.
+ """
+ gap = max(1, size // 75)
+ cell = (size - gap) // 2
+ camera = (camera[0][:4], camera[1][:4])
+ behind = render(ctx, target, camera, 2 * cell)
+ front = render(ctx, mesh, camera, 2 * cell)
+ grid = Image.new("RGB", (size, size), rgb(BACKGROUND))
+ for k in range(behind.shape[0]):
+ picture = composite([(behind[k], ORANGE), (front[k], CLAY)])
+ grid.paste(picture, ((k % 2) * (size - cell), (k // 2) * (size - cell)))
+ return grid
+
+
+def frame_steps(iterations: int, count: int) -> list[int]:
+ """Steps at which to draw the frames of the animation.
+
+ Most of the change happens early, so the distance between frames grows geometrically: the
+ last two are about fifty times further apart than the first two.
+ """
+ last = max(1, count - 1)
+ steps = {round(iterations * math.expm1(4 * i / last) / math.expm1(4)) for i in range(count)}
+ return sorted(steps)
+
+
+def progress_frame(
+ ctx: dr.RasterizeContext,
+ mesh: Mesh,
+ target: Mesh,
+ held_out: Camera,
+ step: int,
+ iou: float,
+ turn: float,
+ width: int,
+) -> Image.Image:
+ """The target, the mesh on a turntable and four of the held-out views side by side.
+
+ ``turn`` runs from 0 to 1 over the animation.
+ """
+ gap, panel, label_size = layout(width, 3)
+ # Half a turn that ends on the view of the target picture.
+ yaw = PICTURE_YAW + math.pi * (turn - 1)
+ pictures = [
+ portrait(ctx, target, ORANGE, PICTURE_YAW, panel),
+ portrait(ctx, mesh, CLAY, yaw, panel),
+ overlays(ctx, mesh, target, held_out, panel),
+ ]
+ labels = ["target", f"fitted mesh, step {step}", f"held-out views, IoU {iou:.3f}"]
+ return panels(pictures, labels, gap, label_size)
+
+
+def main() -> None:
+ parser = argparse.ArgumentParser(description=__doc__.split("\n\n")[0])
+ parser.add_argument("--mesh", help="OBJ file to use as the target instead of the pawn")
+ parser.add_argument("--iterations", type=int, default=600, help="optimisation steps")
+ parser.add_argument("--views", type=int, default=8, help="random views per iteration")
+ parser.add_argument("--resolution", type=int, default=256, help="size of the views")
+ parser.add_argument("--subdivisions", type=int, default=5, help="icosphere subdivisions")
+ parser.add_argument("--segments", type=int, default=96, help="segments around the pawn")
+ parser.add_argument("--smoothing", type=float, default=20.0, help="weight of the Laplacian")
+ parser.add_argument("--lr", type=float, default=0.1, help="peak learning rate")
+ parser.add_argument("--warmup", type=float, default=0.1, help="share of steps spent warming up")
+ parser.add_argument("--seed", type=int, default=0, help="picks the random views")
+ parser.add_argument(
+ "--gif",
+ help="write the optimisation progress to this animation; "
+ "the extension picks the format: .gif, .webp, .mp4 or .webm",
+ )
+ parser.add_argument("--frames", type=int, default=64, help="frames of the animation")
+ parser.add_argument("--gif-width", type=int, default=960, help="width of the animation")
+ parser.add_argument("--out", help="write a filmstrip of the optimisation to this PNG")
+ parser.add_argument(
+ "--snapshots", type=int, nargs="*", default=[0, 40, 70, 120], help="steps in the filmstrip"
+ )
+ parser.add_argument("--out-width", type=int, default=1660, help="width of the PNG")
+ parser.add_argument(
+ "--device", default="cuda" if torch.cuda.is_available() else "cpu", help="cuda or cpu"
+ )
+ args = parser.parse_args()
+
+ device = torch.device(args.device)
+ generator = torch.Generator().manual_seed(args.seed)
+ ctx = dr.RasterizeContext(device)
+ target = load_obj(args.mesh, device) if args.mesh else pawn(args.segments, device)
+ sphere = icosphere(args.subdivisions, device)
+ held_out = random_views(HELD_OUT_VIEWS, generator, device)
+
+ # Moving the vertices directly gives a crumpled, self-intersecting surface, because each
+ # view pulls hardest on the few vertices at its silhouettes. Following Nicolet et al. 2021,
+ # "Large Steps in Inverse Rendering of Geometry", the optimised variable is u = (I + w L) x
+ # instead of the positions x. The gradient with respect to u is the gradient with respect to
+ # x spread over each vertex's neighbourhood, so every step moves the surface as a whole.
+ to_latent, to_positions = smoothing_matrices(len(sphere.positions), sphere.tri, args.smoothing)
+ latent = (to_latent @ (START_RADIUS * sphere.positions)).requires_grad_(True)
+ optimiser = UniformAdam(latent)
+
+ gif_steps = frame_steps(args.iterations, args.frames)
+ strip_steps = sorted({s for s in args.snapshots if s < args.iterations} | {args.iterations})
+ strip_gap, strip_panel, strip_label = layout(args.out_width, len(strip_steps) + 1)
+ frames, strip = [], []
+
+ for step in range(args.iterations + 1):
+ mesh = Mesh(to_positions @ latent, sphere.tri)
+
+ report = step % 100 == 0 or step == args.iterations
+ draw = bool(args.gif) and step in gif_steps
+ if report or draw:
+ iou = silhouette_iou(ctx, mesh, target, held_out, args.resolution)
+ if report:
+ print(f"step {step:5d} silhouette IoU on held-out views {iou:.4f}")
+ if draw:
+ turn = len(frames) / max(1, len(gif_steps) - 1)
+ frames.append(
+ progress_frame(ctx, mesh, target, held_out, step, iou, turn, args.gif_width)
+ )
+ if args.out and step in strip_steps:
+ strip.append(portrait(ctx, mesh, CLAY, PICTURE_YAW, strip_panel))
+ if step == args.iterations:
+ break
+
+ camera = random_views(args.views, generator, device)
+ with torch.no_grad():
+ reference = render(ctx, target, camera, args.resolution)
+ image = render(ctx, mesh, camera, args.resolution)
+ loss = image_loss(image, reference)
+ (gradient,) = torch.autograd.grad(loss, latent)
+ optimiser.step(gradient, learning_rate(step, args.iterations, args.lr, args.warmup))
+
+ flipped = flipped_fraction(Mesh(mesh.positions.detach(), mesh.tri))
+ print(f"final: silhouette IoU {iou:.4f}, flipped triangles {100 * flipped:.2f} %")
+
+ if args.gif:
+ save_animation(frames, args.gif, frame_ms=70)
+ print(f"wrote {args.gif}")
+ if args.out:
+ strip.append(portrait(ctx, target, ORANGE, PICTURE_YAW, strip_panel))
+ labels = [f"step {step}" for step in strip_steps] + ["target"]
+ panels(strip, labels, strip_gap, strip_label).save(args.out)
+ print(f"wrote {args.out}")
+
+
+if __name__ == "__main__":
+ main()
diff --git a/examples/texture_fitting.py b/examples/texture_fitting.py
index 62bf367..0f4ef20 100644
--- a/examples/texture_fitting.py
+++ b/examples/texture_fitting.py
@@ -1,10 +1,23 @@
-"""Recover a texture from rendered images of a sphere.
+"""Recover a texture from rendered images of a mesh.
-A target texture is rendered onto a shaded sphere from random viewpoints. A second texture, starting
-out flat grey, is optimized so that its renders match, using gradients that flow back through
-antialiasing, texture sampling with mipmaps, interpolation and rasterization.
+A target texture is rendered onto a torus knot from random viewpoints. A second texture, starting
+out flat grey, is optimised until its renders match. Only images are compared: the gradient of
+their difference reaches the texels through antialiasing and mipmapped texture sampling.
- python examples/texture_fitting.py --gif docs/images/texture_fitting.gif
+ python examples/texture_fitting.py --gif texture_fitting.gif --out texture_fitting.png
+
+The animation shows the target and the fit from a camera that goes around the knot, a close-up of
+the fit, and below them the texture as it fills in. That texture is a strip, with ``u`` along the
+knot and ``v`` around the tube. Other meshes work too: ``--mesh sphere``, or ``--mesh model.obj
+--texture model.png`` for an OBJ file with texture coordinates.
+
+The targets come from the same renderer and carry no noise, and the cameras reach every part of
+the knot, so the fit ends up close to exact. Where a mesh hides part of its surface, or an atlas
+has unused space, the texels that no view samples stay grey, apart from a faint tint that reaches
+them through the coarser mip levels. The share of texels that came back is printed at the end.
+
+``--gif`` writes the format that its file name ends in: ``.gif``, ``.webp`` or, with ffmpeg on the
+PATH, ``.mp4`` and ``.webm``.
Requires Pillow (``pip install -e . --group examples``).
"""
@@ -13,226 +26,303 @@
import argparse
import math
+from functools import partial
import numpy as np
import torch
-from PIL import Image, ImageDraw, ImageFont
+import torch.nn.functional as F
+from PIL import Image
+from torch import Tensor
import diffrast as dr
-
-
-def uv_sphere(rings: int, segments: int, device: torch.device):
- """Sphere with separate position and texture-coordinate index buffers.
-
- Positions are shared across the texture seam and at the poles, so ``tri_pos`` describes a
- closed surface; ``tri_uv`` indexes a grid of texture coordinates that is cut along the seam.
+from common import (
+ CLAY,
+ INK,
+ PANEL,
+ Mesh,
+ downsample,
+ from_srgb,
+ layout,
+ lighting,
+ load_obj,
+ look_at,
+ orbit,
+ panels,
+ perspective,
+ psnr,
+ save_animation,
+ stack,
+ text_mask,
+ to_clip,
+ to_image,
+ to_srgb,
+ torus_knot,
+ uv_sphere,
+ vertex_normals,
+)
+
+# Linear albedo of the stripes, and the grey that the fitted texture starts from.
+ORANGE = (0.95, 0.07, 0.02)
+GREY = 0.18
+
+# Directions towards the lights, in camera space.
+KEY_LIGHT = (0.4, 0.7, 0.6)
+FILL_LIGHT = (-0.7, -0.3, 0.4)
+
+FOV = 30.0
+# From this far away the unit sphere, which bounds every mesh, fits in a square image.
+CAMERA_DISTANCE = 4.2
+# Texture width in heights, for texels that come out roughly square on the surface.
+TEXTURE_ASPECT = {"knot": 8, "sphere": 2}
+
+# The figures look down on the mesh from a camera that goes around it. The knot lies flat, so
+# that camera can come closer; raising the knot a little centres it in the view.
+FIGURE_ASPECT = 1.5
+FIGURE_YAW, FIGURE_PITCH = 0.5, 0.45
+FIGURE_DISTANCE = {"knot": 3.2}
+KNOT_LIFT = 0.12
+# The close-up looks at the surface point with these texture coordinates: on the knot, a spot
+# next to the middle of a word of the built-in texture.
+CLOSE_UP_UV, CLOSE_UP_ZOOM = (0.37, 0.7), 1.7
+
+
+def load_mesh(name: str, segments: int, device: torch.device) -> Mesh:
+ """The knot, a sphere or the OBJ file ``name``, with texture coordinates."""
+ if name == "knot":
+ # flip_v keeps the lettering of the texture from showing as its mirror image.
+ knot = torus_knot(
+ segments=segments, sides=max(3, segments // 8), device=device, flat=True, flip_v=True
+ )
+ lift = knot.positions.new_tensor([0.0, KNOT_LIFT, 0.0])
+ return knot._replace(positions=knot.positions + lift)
+ if name == "sphere":
+ return uv_sphere(max(2, segments // 2), segments, device)
+ mesh = load_obj(name, device)
+ if mesh.uvs is None:
+ raise SystemExit(f"{name} has no texture coordinates.")
+ return mesh
+
+
+def target_texture(height: int, width: int, device: torch.device) -> Tensor:
+ """Diagonal stripes, a fine checker and the word "diffrast", in linear colour.
+
+ The stripes are readable long before the optimisation has converged; the checker and the
+ letters show whether fine detail comes back. Returns ``[1, height, width, 3]``.
"""
- theta = torch.linspace(0, math.pi, rings + 1, device=device)
- phi = torch.linspace(0, 2 * math.pi, segments + 1, device=device)
-
- inner = theta[1:-1, None]
- ring_xyz = torch.stack(
- [
- torch.sin(inner) * torch.cos(phi[None, :-1]),
- torch.cos(inner).expand(-1, segments),
- -torch.sin(inner) * torch.sin(phi[None, :-1]),
- ],
- -1,
- ).reshape(-1, 3)
- poles = torch.tensor([[0.0, 1.0, 0.0], [0.0, -1.0, 0.0]], device=device)
- positions = torch.cat([poles[:1], ring_xyz, poles[1:]])
-
- u, v = torch.meshgrid(phi / (2 * math.pi), 1 - theta / math.pi, indexing="xy")
- uvs = torch.stack([u, v], -1).reshape(-1, 2)
-
- def pos_index(r, s):
- if r == 0:
- return 0
- if r == rings:
- return positions.shape[0] - 1
- return 1 + (r - 1) * segments + s % segments
-
- def uv_index(r, s):
- return r * (segments + 1) + s
-
- tri_pos, tri_uv = [], []
- for r in range(rings):
- for s in range(segments):
- a, b, c, d = (r, s), (r + 1, s), (r + 1, s + 1), (r, s + 1)
- if r == 0:
- cell = [(a, b, c)] # a and d are the north pole
- elif r == rings - 1:
- cell = [(a, b, d)] # b and c are the south pole
- else:
- cell = [(a, b, c), (a, c, d)]
- for corners in cell:
- tri_pos.append([pos_index(*corner) for corner in corners])
- tri_uv.append([uv_index(*corner) for corner in corners])
- tri_pos = torch.tensor(tri_pos, dtype=torch.int32, device=device)
- tri_uv = torch.tensor(tri_uv, dtype=torch.int32, device=device)
- return positions, tri_pos, uvs, tri_uv
-
-
-def target_texture(size: int, device: torch.device) -> torch.Tensor:
- """Colourful bands, a checkerboard and a word, so that progress is easy to see."""
- v, u = torch.meshgrid(
- torch.linspace(0, 1, size, device=device),
- torch.linspace(0, 1, 2 * size, device=device),
+ y, x = torch.meshgrid(
+ (torch.arange(height, device=device) + 0.5) / height,
+ (torch.arange(width, device=device) + 0.5) / height,
indexing="ij",
)
- hue = 2 * math.pi * u
- color = torch.stack(
- [
- 0.5 + 0.5 * torch.cos(hue),
- 0.5 + 0.5 * torch.cos(hue - 2.1),
- 0.5 + 0.5 * torch.cos(hue - 4.2),
- ],
- -1,
- )
- checker = ((u * 24).floor() + (v * 12).floor()) % 2
- color = torch.where(
- ((v - 0.5).abs() > 0.22)[..., None], color * (0.55 + 0.45 * checker[..., None]), color
- )
+ clay, ink, orange = (torch.tensor(c, device=device) for c in (CLAY, INK, ORANGE))
+
+ def blend(colour: Tensor, other: Tensor, mask: Tensor) -> Tensor:
+ return torch.lerp(colour, other, mask[..., None].float())
+
+ # From bottom to top: stripes, a checker, the word on a clay band, a checker, stripes. The
+ # band sits above the middle because that side of the knot's tube faces outwards.
+ low, high = 16 / 32, 25 / 32
+ edge = torch.minimum((y - low).abs(), (y - high).abs())
+ stripes = (4 * x + 2 * y) % 1 < 0.5
+ checker = ((32 * x).floor() + (32 * y).floor()) % 2 == 0
+ colour = blend(ink.expand(height, width, 3), orange, stripes)
+ colour = blend(colour, blend(clay.expand_as(colour), ink, checker), edge < 2 / 32)
+ colour = blend(colour, clay, (y > low) & (y < high))
+ colour = blend(colour, ink, edge < 1 / 64)
+
+ # One word per stretch of texture that is about twice as long as it is high.
+ words = max(2, round(width / height / 2))
+ rows = slice(round(low * height), round(high * height))
+ size = max(4, round(min(0.27 * height, 0.21 * width / words)))
+ word = text_mask("diffrast", width // words, rows.stop - rows.start, size, device)
+ word = word.repeat(1, words)
+ colour[rows, : word.shape[1]] = blend(colour[rows, : word.shape[1]], ink, word)
+ return colour[None].contiguous()
+
+
+def load_texture(path: str, height: int, device: torch.device) -> Tensor:
+ """Image file as a linear texture ``[1, height, width, 3]`` with row 0 at the bottom."""
+ image = Image.open(path).convert("RGB")
+ width = max(1, round(height * image.width / image.height))
+ image = image.resize((width, height), Image.Resampling.LANCZOS)
+ texels = torch.from_numpy(np.array(image)).to(device).float().flip(0) / 255
+ return (texels**2.2)[None].contiguous()
+
+
+def render(
+ ctx: dr.RasterizeContext,
+ mesh: Mesh,
+ tex: Tensor,
+ view: Tensor,
+ proj: Tensor,
+ resolution: tuple[int, int],
+) -> Tensor:
+ """Linear images ``[batch, height, width, 3]`` of the textured mesh, one per view matrix."""
+ pos = to_clip(mesh.positions, proj @ view)
+ # The lights are fixed to the camera, so every view looks at a lit surface.
+ normals = vertex_normals(mesh.positions, mesh.tri) @ view[:, :3, :3].transpose(1, 2)
+
+ rast, rast_db = dr.rasterize(ctx, pos, mesh.tri, resolution)
+ uv, uv_da = dr.interpolate(mesh.uvs, rast, mesh.tri_uv, rast_db=rast_db, diff_attrs="all")
+ normal, _ = dr.interpolate(normals, rast, mesh.tri)
+ albedo = dr.texture(tex, uv, uv_da, filter_mode="linear-mipmap-linear", boundary_mode="wrap")
- image = Image.new("L", (2 * size, size), 0)
- font = ImageFont.load_default(size=size // 5)
- draw = ImageDraw.Draw(image)
- for offset in (0.25, 0.75):
- draw.text((offset * 2 * size, size / 2), "diffrast", fill=255, font=font, anchor="mm")
- text = torch.from_numpy(np.asarray(image)).to(device).float().flip(0) / 255
- color = color * (1 - text[..., None]) + 0.05 * text[..., None]
- return color[None].contiguous()
-
-
-def rotation(yaw: torch.Tensor, pitch: torch.Tensor) -> torch.Tensor:
- """Rotation matrices that turn the sphere by ``yaw`` around y and ``pitch`` around x."""
- cy, sy, cp, sp = torch.cos(yaw), torch.sin(yaw), torch.cos(pitch), torch.sin(pitch)
- zero, one = torch.zeros_like(yaw), torch.ones_like(yaw)
- ry = torch.stack([cy, zero, sy, zero, one, zero, -sy, zero, cy], -1).view(-1, 3, 3)
- rx = torch.stack([one, zero, zero, zero, cp, -sp, zero, sp, cp], -1).view(-1, 3, 3)
- return rx @ ry
-
-
-def render(ctx, tex, mesh, turn, resolution, light):
- """Shaded, antialiased renders of the textured sphere, one per rotation."""
- positions, tri_pos, uvs, tri_uv = mesh
- camera = positions @ turn.transpose(1, 2)
- distance, focal, near, far = 3.0, 2.2, 0.1, 10.0
- z = camera[..., 2] - distance
- pos = torch.stack(
- [
- focal * camera[..., 0],
- focal * camera[..., 1],
- -(far + near) / (far - near) * z - 2 * far * near / (far - near),
- -z,
- ],
- -1,
- )
+ shaded = albedo * lighting(normal, KEY_LIGHT, FILL_LIGHT)
+ covered = rast[..., 3:] > 0
+ colour = torch.where(covered, shaded, from_srgb(PANEL, pos.device))
+ return dr.antialias(colour, rast, pos, mesh.tri)
- rast, rast_db = dr.rasterize(ctx, pos, tri_pos, resolution)
- uv, uv_da = dr.interpolate(uvs, rast, tri_uv, rast_db=rast_db, diff_attrs="all")
- normal, _ = dr.interpolate(camera, rast, tri_pos)
- albedo = dr.texture(tex, uv, uv_da, filter_mode="linear-mipmap-linear", boundary_mode="wrap")
- normal = torch.nn.functional.normalize(normal, dim=-1)
- shade = 0.35 + 0.65 * (normal @ light).clamp(min=0)[..., None]
- mask = (rast[..., 3:] > 0).float()
- color = albedo * shade * mask + 0.92 * (1 - mask)
- return dr.antialias(color.contiguous(), rast, pos, tri_pos)
+def random_views(
+ count: int, generator: torch.Generator, device: torch.device
+) -> tuple[Tensor, Tensor]:
+ """View matrices ``[count, 4, 4]`` of cameras all around the mesh, and their projection."""
+ yaw = torch.rand(count, generator=generator) * 2 * math.pi
+ pitch = (torch.rand(count, generator=generator) - 0.5) * 2.4
+ view = look_at(orbit(yaw.to(device), pitch.to(device), CAMERA_DISTANCE))
+ return view, perspective(FOV, 1.0, device=device)
-def to_image(image: torch.Tensor, size: int) -> Image.Image:
- """Tensor in ``[height, width, 3]`` with row 0 at the bottom to a PIL image."""
- array = (image.detach().flip(0).clamp(0, 1) * 255).byte().cpu().numpy()
- return Image.fromarray(array).resize((size, round(size * array.shape[0] / array.shape[1])))
+def figure_views(mesh: Mesh, turn: float, distance: float) -> tuple[Tensor, Tensor]:
+ """View and projection matrices ``[2, 4, 4]`` for the figures: an overview and a close-up.
+
+ ``turn`` is how far the overview camera is on its way around the mesh, from 0 to 1. The
+ close-up stays where that round starts, turned towards the surface point at ``CLOSE_UP_UV``
+ and zoomed in.
+ """
+ device = mesh.positions.device
+ # Positions and texture coordinates pair up corner by corner of the triangles.
+ offset = mesh.uvs[mesh.tri_uv.long()] - mesh.uvs.new_tensor(CLOSE_UP_UV)
+ focus = mesh.positions[mesh.tri.flatten()[offset.norm(dim=-1).argmin()]]
+ yaw = FIGURE_YAW + 2 * math.pi * torch.tensor([turn, 0.0], device=device)
+ eye = orbit(yaw, torch.full_like(yaw, FIGURE_PITCH), distance)
+ view = look_at(eye, torch.stack([torch.zeros_like(focus), focus]))
+ fovs = (FOV, FOV / CLOSE_UP_ZOOM)
+ proj = torch.stack([perspective(fov, FIGURE_ASPECT, device=device) for fov in fovs])
+ return view, proj
+
+
+def figure(
+ ctx: dr.RasterizeContext,
+ mesh: Mesh,
+ target: Tensor,
+ tex: Tensor,
+ distance: float,
+ step: int,
+ turn: float,
+ width: int,
+ compare: bool = False,
+) -> Image.Image:
+ """The target, the fit and a close-up of the fit in a row, above the texture being fitted.
+
+ ``compare`` adds the target texture, for a still that has to stand on its own.
+ """
+ gap, panel, label_size = layout(width, 3)
+ # Rendered at twice the size of a panel and averaged down.
+ resolution = (2 * round(panel / FIGURE_ASPECT), 2 * panel)
+ view, proj = figure_views(mesh, turn, distance)
+ with torch.no_grad():
+ wanted = render(ctx, mesh, target, view[:1], proj[:1], resolution)
+ fitted = render(ctx, mesh, tex, view, proj, resolution)
+ renders = torch.cat([wanted, fitted])
+ images = [to_image(image) for image in downsample(to_srgb(renders), 2)]
+ labels = ["target", f"fitted, step {step}", "fitted, close-up"]
+ rows = [panels(images, labels, gap, label_size)]
+
+ textures = [(tex, f"fitted texture, psnr {psnr(tex, target):.1f} dB")]
+ if compare:
+ textures.insert(0, (target, "target texture"))
+ # A long strip spans the figure; a squarer texture is as high as the renders.
+ aspect = tex.shape[2] / tex.shape[1]
+ strip = min(rows[0].width - 2 * gap, round(images[0].height * aspect))
+ for texels, label in textures:
+ rows.append(panels([to_image(to_srgb(texels[0]), strip)], [label], gap, label_size))
+ return stack(rows, overlap=gap)
def main() -> None:
parser = argparse.ArgumentParser(description=__doc__.split("\n\n")[0])
- parser.add_argument("--iterations", type=int, default=400)
- parser.add_argument("--views", type=int, default=6, help="random views per iteration")
- parser.add_argument("--resolution", type=int, default=256)
+ parser.add_argument("--mesh", default="knot", help="knot, sphere or the path of an OBJ file")
+ parser.add_argument("--texture", help="image to recover instead of the built-in texture")
+ parser.add_argument("--iterations", type=int, default=250, help="optimisation steps")
+ parser.add_argument("--views", type=int, default=4, help="random views per iteration")
+ parser.add_argument("--resolution", type=int, default=1024, help="size of the views")
parser.add_argument("--texture-size", type=int, default=256, help="texture height")
- parser.add_argument("--segments", type=int, default=96, help="sphere subdivisions around")
- parser.add_argument("--lr", type=float, default=0.03)
- parser.add_argument("--gif", help="write the optimization progress to this GIF")
- parser.add_argument("--frames", type=int, default=40)
- parser.add_argument("--device", default="cuda" if torch.cuda.is_available() else "cpu")
+ parser.add_argument("--segments", type=int, default=384, help="segments of the knot or sphere")
+ parser.add_argument("--lr", type=float, default=0.03, help="learning rate")
+ parser.add_argument("--seed", type=int, default=0, help="picks the random views")
+ parser.add_argument(
+ "--gif",
+ help="write the optimisation progress to this animation; "
+ "the extension picks the format: .gif, .webp, .mp4 or .webm",
+ )
+ parser.add_argument("--frames", type=int, default=48, help="frames of the animation")
+ parser.add_argument("--gif-width", type=int, default=960, help="width of the animation")
+ parser.add_argument("--out", help="write the result and the target to this PNG")
+ parser.add_argument("--out-width", type=int, default=1660, help="width of the PNG")
+ parser.add_argument(
+ "--device", default="cuda" if torch.cuda.is_available() else "cpu", help="cuda or cpu"
+ )
args = parser.parse_args()
device = torch.device(args.device)
- torch.manual_seed(0)
+ generator = torch.Generator().manual_seed(args.seed)
ctx = dr.RasterizeContext(device)
- mesh = uv_sphere(args.segments // 2, args.segments, device)
- light = torch.nn.functional.normalize(torch.tensor([0.4, 0.6, 0.7], device=device), dim=0)
- target = target_texture(args.texture_size, device)
- tex = torch.full_like(target, 0.5, requires_grad=True)
- optimizer = torch.optim.Adam([tex], lr=args.lr)
+ mesh = load_mesh(args.mesh, args.segments, device)
+ if args.texture:
+ target = load_texture(args.texture, args.texture_size, device)
+ else:
+ width = TEXTURE_ASPECT.get(args.mesh, 1) * args.texture_size
+ target = target_texture(args.texture_size, width, device)
+ tex = torch.full_like(target, GREY, requires_grad=True)
+ optimiser = torch.optim.Adam([tex], lr=args.lr)
resolution = (args.resolution, args.resolution)
+ distance = FIGURE_DISTANCE.get(args.mesh, CAMERA_DISTANCE)
+ draw = partial(figure, ctx, mesh, target, tex, distance)
frames = []
- # Most of the change happens early, so frames are spaced quadratically in time.
- capture = {round(args.iterations * (i / args.frames) ** 2) for i in range(args.frames + 1)}
+ # Most of the change happens early, so the frames crowd towards the first steps, while the
+ # camera goes around the mesh at an even pace.
+ last = max(1, args.frames - 1)
+ capture = [round(args.iterations * (i / last) ** 3) for i in range(args.frames)]
for step in range(args.iterations + 1):
- if args.gif and step in capture:
- frames.append(progress_frame(ctx, target, tex, mesh, step, args, light))
+ while args.gif and len(frames) < args.frames and capture[len(frames)] == step:
+ frames.append(draw(step, len(frames) / last, args.gif_width))
if step == args.iterations:
break
- yaw = torch.rand(args.views, device=device) * 2 * math.pi
- pitch = (torch.rand(args.views, device=device) - 0.5) * 1.6
- turn = rotation(yaw, pitch)
+ view, proj = random_views(args.views, generator, device)
with torch.no_grad():
- reference = render(ctx, target, mesh, turn, resolution, light)
+ reference = render(ctx, mesh, target, view, proj, resolution)
- optimizer.zero_grad()
- fitted = render(ctx, tex, mesh, turn, resolution, light)
- loss = torch.nn.functional.mse_loss(fitted, reference)
+ optimiser.zero_grad()
+ fitted = render(ctx, mesh, tex, view, proj, resolution)
+ loss = F.mse_loss(fitted, reference)
loss.backward()
- optimizer.step()
+ optimiser.step()
with torch.no_grad():
tex.clamp_(0, 1)
if step % 100 == 0 or step == args.iterations - 1:
- psnr = -10 * math.log10(loss.item())
- print(f"step {step:5d} loss {loss.item():.6f} psnr {psnr:.2f} dB")
+ decibel = psnr(fitted, reference)
+ print(f"step {step:5d} loss {loss.item():.6f} psnr {decibel:.2f} dB")
+
+ view, proj = random_views(args.views, generator, device)
+ with torch.no_grad():
+ fitted = render(ctx, mesh, tex, view, proj, resolution)
+ reference = render(ctx, mesh, target, view, proj, resolution)
+ close = ((tex - target).abs().amax(-1) < 0.02).float().mean().item()
+ print(f"renders psnr {psnr(fitted, reference):.2f} dB on {args.views} new views")
+ print(f"texture psnr {psnr(tex, target):.2f} dB, {close:.1%} of its texels within 0.02")
if args.gif:
- save_gif(frames, args.gif)
+ # Most of every frame changes from one to the next. Dithering makes a GIF of them about
+ # a fifth larger, for little gain on a surface this busy.
+ save_animation(frames, args.gif, frame_ms=80, dither=False)
print(f"wrote {args.gif}")
-
-
-def save_gif(frames: list[Image.Image], path: str) -> None:
- """One palette for all frames, built from a sample of them, with dithering against it."""
- sample = frames[:: max(1, len(frames) // 6)]
- montage = Image.new("RGB", (sample[0].width, sample[0].height * len(sample)))
- for i, frame in enumerate(sample):
- montage.paste(frame, (0, i * frame.height))
- palette = montage.quantize(colors=256)
- frames = [
- frame.quantize(palette=palette, dither=Image.Dither.FLOYDSTEINBERG) for frame in frames
- ]
- durations = [80] * (len(frames) - 1) + [2500]
- frames[0].save(path, save_all=True, append_images=frames[1:], duration=durations, loop=0)
-
-
-def progress_frame(ctx, target, tex, mesh, step, args, light) -> Image.Image:
- """Target render, current render and current texture side by side, from a turning view."""
- yaw = torch.tensor([0.6 + step / args.iterations * 2 * math.pi], device=tex.device)
- turn = rotation(yaw, torch.tensor([0.35], device=tex.device))
- with torch.no_grad():
- images = [render(ctx, t, mesh, turn, (256, 256), light)[0] for t in (target, tex)]
- panel = 200
- canvas = Image.new("RGB", (panel * 4 + 40, panel + 36), (255, 255, 255))
- canvas.paste(to_image(images[0], panel), (10, 26))
- canvas.paste(to_image(images[1], panel), (panel + 20, 26))
- canvas.paste(to_image(tex[0], 2 * panel), (2 * panel + 30, 26))
- draw = ImageDraw.Draw(canvas)
- font = ImageFont.load_default(size=16)
- draw.text((10, 4), "target", fill=(40, 40, 40), font=font)
- draw.text((panel + 20, 4), f"fitted, step {step}", fill=(40, 40, 40), font=font)
- draw.text((2 * panel + 30, 4), "fitted texture", fill=(40, 40, 40), font=font)
- return canvas
+ if args.out:
+ draw(args.iterations, 0.0, args.out_width, compare=True).save(args.out)
+ print(f"wrote {args.out}")
if __name__ == "__main__":
diff --git a/tests/test_examples.py b/tests/test_examples.py
index cf39ee5..7130a71 100644
--- a/tests/test_examples.py
+++ b/tests/test_examples.py
@@ -8,13 +8,51 @@
EXAMPLES = Path(__file__).resolve().parents[1] / "examples"
+# Script, arguments for a run of a few seconds on the CPU, the flag that names the output file,
+# and a phrase the script prints when it has finished.
+CASES = {
+ "texture_fitting": (
+ "--iterations 4 --views 2 --resolution 32 --texture-size 16 --segments 24 "
+ "--frames 2 --gif-width 160",
+ "--gif",
+ "texture psnr",
+ ),
+ "shape_fitting": (
+ "--iterations 20 --views 2 --resolution 32 --subdivisions 2 --segments 12 "
+ "--frames 4 --gif-width 240",
+ "--gif",
+ "flipped triangles",
+ ),
+ "pose_fitting": (
+ "--hypotheses 8 --iterations 8 --refine 4 --resolution 32 --texture-size 32 "
+ "--frames 4 --gif-width 480",
+ "--gif",
+ "has the lowest loss",
+ ),
+ "depth_peeling": (
+ "--width 96 --height 60 --supersample 2 --num-layers 4 --segments 48 "
+ "--subdivisions 1 --panel-size 48 --check-size 32 --check-gradients",
+ "--layers",
+ "pixels covered",
+ ),
+ "env_lighting": (
+ "--iterations 4 --views 2 --resolution 32 --env-size 8 --segments 48 --frames 2 "
+ "--gif-width 240",
+ "--gif",
+ "cube map psnr",
+ ),
+ "gbuffer": ("--panel 64 --supersample 1 --texture-size 32", "--out", "the knot covers"),
+ "antialias_gradients": ("--resolution 64 --zoom 8", "--out", "vertices receive gradient"),
+}
-def test_texture_fitting_runs(tmp_path, monkeypatch, capsys):
- gif = tmp_path / "progress.gif"
- argv = ["texture_fitting.py", "--device", "cpu", "--iterations", "4", "--views", "2"]
- argv += ["--resolution", "32", "--texture-size", "16", "--segments", "12"]
- argv += ["--frames", "2", "--gif", str(gif)]
+
+@pytest.mark.parametrize("name", CASES)
+def test_example_runs(name, tmp_path, monkeypatch, capsys):
+ arguments, output_flag, phrase = CASES[name]
+ output = tmp_path / ("out.gif" if output_flag == "--gif" else "out.png")
+ argv = [f"{name}.py", "--device", "cpu", *arguments.split(), output_flag, str(output)]
monkeypatch.setattr(sys, "argv", argv)
- runpy.run_path(str(EXAMPLES / "texture_fitting.py"), run_name="__main__")
- assert gif.exists()
- assert "step 3" in capsys.readouterr().out
+ monkeypatch.syspath_prepend(str(EXAMPLES))
+ runpy.run_path(str(EXAMPLES / f"{name}.py"), run_name="__main__")
+ assert output.stat().st_size > 0
+ assert phrase in capsys.readouterr().out
From 4ab9686f2111a9247ff06e76af6bcc99674cd2ae Mon Sep 17 00:00:00 2001
From: Senne Cools <113857183+sennecools@users.noreply.github.com>
Date: Mon, 16 Nov 2026 22:13:37 +0100
Subject: [PATCH 3/4] Add a benchmark of the full render pipeline
---
benchmarks/bench_pipeline.py | 113 +++++++++++++++++++++++
benchmarks/plot_pipeline.py | 169 +++++++++++++++++++++++++++++++++++
2 files changed, 282 insertions(+)
create mode 100644 benchmarks/bench_pipeline.py
create mode 100644 benchmarks/plot_pipeline.py
diff --git a/benchmarks/bench_pipeline.py b/benchmarks/bench_pipeline.py
new file mode 100644
index 0000000..68b7cbc
--- /dev/null
+++ b/benchmarks/bench_pipeline.py
@@ -0,0 +1,113 @@
+"""Time a full differentiable render: rasterize, interpolate, mipmapped texture and antialias.
+
+The scene is the displaced grid of ``bench_rasterize.py`` with a 1024 x 1024 RGB texture. The
+backward pass carries gradients to both the vertex positions and the texture.
+
+Usage: python benchmarks/bench_pipeline.py [--backends triton reference] [--json results.json]
+"""
+
+from __future__ import annotations
+
+import argparse
+import json
+import platform
+
+import torch
+
+import diffrast as dr
+from bench_rasterize import grid_mesh, time_ms
+
+
+def measure(ctx, pos, tri, res: int, repeats: int, warmup_s: float) -> tuple[float, float]:
+ """Return forward and forward + backward time in milliseconds."""
+ gen = torch.Generator(device=pos.device).manual_seed(0)
+ # Planar mapping: the grid's vertices are laid out row by row, (n + 1) per row.
+ n = round(pos.shape[1] ** 0.5) - 1
+ steps = torch.linspace(0, 1, n + 1, device=pos.device)
+ uv_attr = torch.stack(torch.meshgrid(steps, steps, indexing="xy"), -1).reshape(-1, 2)
+ tex = torch.rand(1, 1024, 1024, 3, device=pos.device, generator=gen, requires_grad=True)
+ pos = pos.clone().requires_grad_(True)
+
+ def render():
+ rast, rast_db = dr.rasterize(ctx, pos, tri, (res, res))
+ uv, uv_da = dr.interpolate(uv_attr, rast, tri, rast_db=rast_db, diff_attrs="all")
+ color = dr.texture(tex, uv, uv_da, filter_mode="linear-mipmap-linear")
+ return dr.antialias(color, rast, pos, tri)
+
+ def forward():
+ with torch.no_grad():
+ render()
+
+ def forward_backward():
+ render().sum().backward()
+
+ return time_ms(forward, repeats, warmup_s), time_ms(forward_backward, repeats, warmup_s)
+
+
+def main() -> None:
+ parser = argparse.ArgumentParser()
+ parser.add_argument("--backends", nargs="+", default=["triton", "reference"])
+ parser.add_argument("--triangles", nargs="+", type=int, default=[10_000, 100_000, 1_000_000])
+ parser.add_argument("--resolutions", nargs="+", type=int, default=[256, 512, 1024, 2048])
+ parser.add_argument("--views", nargs="+", type=int, default=[8])
+ parser.add_argument("--repeats", type=int, default=15)
+ parser.add_argument("--warmup", type=float, default=8.0, help="warmup seconds per case")
+ parser.add_argument("--memory-fraction", type=float, default=0.6)
+ parser.add_argument("--max-reference-work", type=float, default=2e10)
+ parser.add_argument("--json", help="also write the results to this file")
+ args = parser.parse_args()
+
+ torch.cuda.set_per_process_memory_fraction(args.memory_fraction)
+ ctx = dr.RasterizeContext()
+ device = torch.cuda.get_device_name(ctx.device)
+ print(f"device: {device}, torch {torch.__version__}")
+ row = "{:<10} {:>10} {:>5} {:>5} {:>9} {:>11}"
+ print(row.format("backend", "triangles", "res", "views", "fwd ms", "fwd+bwd ms"))
+
+ results = []
+ for num_tri in args.triangles:
+ for views in args.views:
+ pos, tri = grid_mesh(num_tri, views, ctx.device)
+ for res in args.resolutions:
+ for backend in args.backends:
+ work = tri.shape[0] * views * res * res
+ if backend == "reference" and work > args.max_reference_work:
+ continue
+ dr.set_backend(backend)
+ try:
+ fwd, fwd_bwd = measure(ctx, pos, tri, res, args.repeats, args.warmup)
+ except torch.OutOfMemoryError:
+ torch.cuda.empty_cache()
+ print(row.format(backend, tri.shape[0], res, views, "OOM", "OOM"))
+ continue
+ times = (f"{fwd:.2f}", f"{fwd_bwd:.2f}")
+ print(row.format(backend, tri.shape[0], res, views, *times))
+ results.append(
+ {
+ "backend": backend,
+ "triangles": tri.shape[0],
+ "resolution": res,
+ "views": views,
+ "forward_ms": round(fwd, 3),
+ "forward_backward_ms": round(fwd_bwd, 3),
+ }
+ )
+
+ if args.json:
+ import triton
+
+ report = {
+ "device": device,
+ "torch": torch.__version__,
+ "triton": triton.__version__,
+ "diffrast": dr.__version__,
+ "platform": platform.platform(),
+ "results": results,
+ }
+ with open(args.json, "w") as file:
+ json.dump(report, file, indent=1)
+ print(f"wrote {args.json}")
+
+
+if __name__ == "__main__":
+ main()
diff --git a/benchmarks/plot_pipeline.py b/benchmarks/plot_pipeline.py
new file mode 100644
index 0000000..161de5a
--- /dev/null
+++ b/benchmarks/plot_pipeline.py
@@ -0,0 +1,169 @@
+"""Draw the results of ``bench_pipeline.py --json`` as an SVG chart.
+
+Usage: python benchmarks/plot_pipeline.py results.json chart.svg
+"""
+
+from __future__ import annotations
+
+import argparse
+import itertools
+import json
+import math
+from html import escape
+
+SURFACE = "#121110"
+GRID = "#2a2725"
+TEXT = "#f0eadf"
+MUTED = "#a09b93"
+# One hue, lighter for more triangles; the reference backend is the grey baseline.
+TRITON = ["#1c5cab", "#5598e7", "#cde2fb"]
+REFERENCE = "#8a8580"
+
+WIDTH, HEIGHT = 830, 452
+PLOT_TOP, PLOT_BOTTOM = 132, 372
+PANELS = (
+ ("forward_ms", "forward", 64, 372),
+ ("forward_backward_ms", "forward + backward", 474, 782),
+)
+FONT = "ui-sans-serif, system-ui, -apple-system, 'Segoe UI', Helvetica, Arial, sans-serif"
+
+
+def count_label(triangles: int) -> str:
+ """Triangle count rounded to a short label; the grid meshes are a little off round numbers."""
+ if triangles >= 950_000:
+ return f"{triangles / 1e6:.0f}M"
+ return f"{round(triangles / 1000, -1 if triangles > 20_000 else 0):.0f}k"
+
+
+def duration(ms: float) -> str:
+ if ms >= 1000:
+ return f"{ms / 1000:.1f} s"
+ return f"{ms:.0f} ms" if ms >= 10 else f"{ms:.1f} ms"
+
+
+def text(x, y, body, size=12, fill=MUTED, anchor="start", weight=400) -> str:
+ return (
+ f'
| + + + +**[Texture fitting](examples/texture_fitting.py).** A 2048 x 256 texture starts flat grey and is +optimised until its renders of a torus knot match the targets from random views. + + | + + + +**[Shape fitting](examples/shape_fitting.py).** A sphere with 10,242 vertices is deformed into a +chess pawn using only silhouettes and shading, through `antialias`. + + |
| + + + +**[Pose fitting](examples/pose_fitting.py).** The rotation of a die from one 64-pixel image: 24 +random starts fitted in a single batched call, then the best one turned through the cube's +symmetries so the pips decide. + + | + + + +**[Environment map](examples/env_lighting.py).** A cube map that starts grey is recovered from +reflections on a mirror-like knot alone, with mipmapped cube lookups driven by `uv_da`. + + |
| + + + +**[Depth peeling](examples/depth_peeling.py).** Order-independent transparency: `DepthPeeler` +returns the nearest surface in every pixel, then the one behind it, and so on; eight layers are +shaded, antialiased and blended front to back, and gradients pass through all of them. + + | |
BR5XGCL^q0 zvqM88miIA3)^y&Qpuqc}n-E%(@=2ZH3CGWnh>+b#1;FE^E9vX#G{Uxht}xSpCQ0f1yy40f- 8Hh6(P;=G10t%0*Lz>@aC1(*sfv9upBra_d@~hhew?y zKO@93MmxcsBnCeFKI$gbaJb9j2|uW!hnsbZv?_ETlK?6)Lj26gLEqBfm@Gtk)WAJ3 zqKf>@)|Y(xuuS!*plPR~EI)B_=#D*_oF2+(_~Pg{E*bdDavQf_r|d_^WPTxHF$X0o zP@u!V`v_N!7|@oj{0kF4*YOiM9m8Z6gGTjuY8ZNW(%a@y*kP++O~}H@7q&P|`@46$ zqT%;fRtxlNQko4(t^ryoHqSR$TB(9PSwnYcrH;<+Y=EMnqHtR3>HMz8Vx_wC=Cb !+XdbTZxz82Mhh3a7R)=u@)bZ%?W~G(RF#gpZ#;OiuaKH1BZW<>T6WBR3{a zEk|&6pYw-V8K%|jgZ%e<#z{)qi?PEk+hV?7tuie6!( o1)8Vc8G{4}1V8^+*V1Z6zQnYk*rYryb^%vLhj&&N$ejS{> zTo WWE`K~*$;&`;7~10O7| zE78-tH~Y0JAG5Hw_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