Custom reductions
Many applications of kNN and radius searches need reductions over neighbours: kernel density estimates, smoothed particle hydrodynamics, or neighbourhood aggregation in graph message-passing algorithms. Outputting full neighbour lists requires a lot of memory. In multi-GPU setups, communicating neighbour data can also dominate runtime. Accumulating while visiting neighbours avoids storing their full lists in device memory.
For density estimation, start with the KDE user guide: the built-in
interface requires no CUDA programming. Built-in reduction configurations can
also be passed directly to knn_reduction or query_ball_reduction without
adding backend code. See the radius-query API for an
example using GaussianKDE.
Implementing a new custom reduction uses the lower-level interface described below. This can notably reduce memory usage when an application needs only accumulated values, rather than all neighbour indices and distances; it does not guarantee a runtime speedup.
For this, jz-tree offers a lower-level CUDA interface. It requires a source installation: you add a CUDA class, describe it in Python, and rebuild the backend. We recommend creating a fork of the jztree repository and following the source installation guide. Search, sorting and communication are handled by the library. The extra work can be worthwhile when a neighbour reduction is a significant part of your calculation or dominates its memory requirements.
Here we estimate density from k=128 neighbours using a truncated Gaussian.
Each particle can carry a scalar weight, such as its mass. Omitting weights
means one per particle and gives a number-density estimate.
We first write a JAX reference, then the CUDA kernel, and finally its Python
interface.
The built-in PolynomialKDE and GaussianKDE support 1–10 input fields.
This guide keeps the CUDA example scalar for clarity; its template values 0 and 1
match the unweighted and scalar specializations of the built-in implementation.
Calculating gradients requires an additional, optional VJP kernel, introduced
at the end.
Start with a JAX reference
Let R be the kth-neighbour distance and a = cutoff_sigma. The Gaussian width
is sigma = R/a. We truncate at R and normalize inside that sphere:
F(a) is the fraction of an ordinary 3D Gaussian inside a standard deviations.
Outside the cutoff the kernel is zero. The truncated kernel has unit spatial
integral. Unit weights estimate number density; masses estimate mass density.
For a probability-density estimate, normalize the weights to sum to one. Normalization over continuous volume does not force the discrete
sum over particle samples to equal one.
In gather mode each query collects contributions from its selected neighbours
with its own kernel size scaled with the kth-neighbour distance.
In scatter mode each query deposits its Gaussian at its selected neighbours,
using atomics in CUDA. In both cases R belongs to the query. With separate
populations, gather returns one density per query; scatter returns one per source.
Scatter does not perform a search using source-owned smoothing radii.
import jax
import jax.numpy as jnp
from jax.scipy.special import gammainc
import numpy as np
import jztree as jz
n = 500_000
pos = jax.random.uniform(jax.random.key(13), (n, 3), dtype=jnp.float32)
def reference(pos, particle_weights=None, mode="gather", cutoff_sigma=3., indices=None):
if indices is None:
radii, indices = jz.knn.knn(pos, k=128)
else:
# Fixed neighbours, but distances (including the kth radius) vary with pos.
dx = pos[indices] - pos[:, None]
r2 = jnp.sum(dx*dx, axis=-1)
# Self-neighbours have zero distance and zero displacement derivative.
radii = jnp.where(r2 > 0, jnp.sqrt(jnp.maximum(r2, jnp.finfo(pos.dtype).tiny)), 0.)
sigma = radii[:, -1:] / cutoff_sigma
# Equivalent to F(a), without subtracting two nearly equal terms for small a.
enclosed = gammainc(1.5, cutoff_sigma**2 / 2)
weights = jnp.exp(-.5*(radii/sigma)**2)
weights /= (2*jnp.pi)**1.5 * sigma**3 * enclosed
if particle_weights is not None:
weights *= (particle_weights[indices, 0] if mode == "gather"
else particle_weights[:, 0, None])
if mode == "gather":
return weights.sum(axis=1, keepdims=True)
return jnp.zeros((len(pos), 1), pos.dtype).at[indices.reshape(-1), 0].add(
weights.reshape(-1))
reference_jit = jax.jit(reference, static_argnames=("mode",))
reference_result = reference_jit(pos)
jax.block_until_ready(reference_result)
Self-queries include the particle itself. We include the selected kth neighbour,
where the truncated Gaussian is still nonzero. Equal-distance ties follow kNN’s
selection order: exactly the selected k neighbours contribute, rather than
all particles tied at the boundary. The sharp truncation introduces a jump;
the VJP below differentiates with that selection fixed.
The reference materializes (N, k) distances and indices. The CUDA reduction
keeps only the kth-neighbour boundary per query and visits the selected neighbours
again, reusing the tree and interaction list.
Accumulate density in CUDA
Add the following class in src/jztree_cuda/neighbour_reductions.cuh. The
search machinery stays in knn.cuh. We will pack three parameters in Python:
the cutoff in standard deviations, a normalization factor, and a scatter flag.
The normalization factor is independent of R, so we calculate it once in
Python rather than evaluate an error function for every query.
template<int dim, typename T, bool weighted>
struct GaussianKDE {
const T *fields, *query;
T* output;
T radius, inv_sigma2, norm, sum;
bool scatter, valid;
__device__ GaussianKDE(const T* params, const T* source_fields,
const T* query_fields, T* result, T rmax) {
fields = source_fields;
query = query_fields;
output = result;
radius = rmax;
valid = radius > 0 && isfinite(radius);
inv_sigma2 = (params[0]/radius)*(params[0]/radius);
norm = params[1]/(radius*radius*radius);
scatter = static_cast<int>(params[2]) != 0;
sum = 0;
}
__device__ T weight(T r2) const {
return norm * exp(-T(.5)*r2*inv_sigma2);
}
__device__ void accumulate(const Vec<dim,T>& dx, T r2, int source_index) {
if (!valid) return;
T value = T(1);
if constexpr (weighted) value = scatter ? query[0] : fields[source_index];
T w = weight(r2) * value;
if (scatter) atomicAdd(output + source_index, w);
else sum += w;
}
__device__ void finalize() const {
if (!scatter) output[0] = valid ? sum : T(NAN);
}
};
The constructor runs once per active query. It stores the output pointer,
initializes a scalar sum and checks once whether the radius is usable, so that
accumulate() only tests a flag. Gather reads the neighbour’s weight from fields[source_index];
scatter reads the current query’s weight from query[0]. The weighted template
parameter removes these reads when weights are omitted, using one instead.
In gather mode output addresses this
query’s single output; in scatter mode it addresses the whole source output array.
The launcher initializes outputs to zero before traversal.
accumulate(dx, r2, source_index) is called for each selected neighbour in
arbitrary order. dx is the minimum-image displacement from query to source,
and r2 is its squared length. The source index addresses the sorted, possibly
communicated source buffer. The library handles restoring the user’s output order.
The traversal already enforces neighbour selection; this class needs no additional
cutoff check.
Gather keeps its sum in the class and writes it in finalize(). Scatter writes
directly through atomic additions and has nothing to do at finalization.
Forward finalize() returns nothing. Only valid query lanes accumulate and
finalize, so padded lanes do not duplicate scatter contributions.
For zero or nonfinite R, gather writes NaN; scatter is rejected by the wrapper
because an undefined contribution has no single destination row. Coincident
particles can give a zero kth radius. For meaningful density estimates, use
positive, finite radii and finite particle positions.
Describe the interface in Python
In src/jztree/neighbour_reductions.py, add this configuration alongside the
existing reductions:
from typing import Literal
import jax.numpy as jnp
from .config_utils import config_dataclass, static_field
# NeighbourReduction is defined earlier in this module.
@config_dataclass(slots=True)
class GaussianKDE(NeighbourReduction):
"""Truncated, unit-integral 3D Gaussian density with optional scalar weights."""
mode: Literal['gather', 'scatter'] = static_field(default='gather')
cutoff_sigma: float = 3.
def cuda_type(self, source_shape, query_shape, k: int | None) -> str:
if source_shape[-1] > 1 or query_shape[-1] > 1:
raise ValueError('GaussianKDE accepts one scalar field per particle')
width = (query_shape if self.mode == 'scatter' else source_shape)[-1]
return f"GaussianKDE<dim, T, {width}>"
@property
def output_mode(self) -> Literal['query', 'source_atomic']:
if self.mode not in ('gather', 'scatter'):
raise ValueError(f'Unknown reduction mode: {self.mode}')
return 'source_atomic' if self.mode == 'scatter' else 'query'
@property
def requires_positive_radius(self) -> bool:
return True
def params(self, dtype=jnp.float32, k: int | None = None):
from jax.scipy.special import gammainc
from .jax_ext import raise_if
cutoff = jnp.asarray(self.cutoff_sigma, dtype=dtype)
cutoff = cutoff + raise_if(~(jnp.isfinite(cutoff) & (cutoff > 0)),
'cutoff_sigma must be finite and positive')
enclosed = gammainc(jnp.asarray(1.5, dtype), cutoff**2 / 2)
norm = cutoff**3 / ((2*jnp.pi)**1.5 * enclosed)
return jnp.asarray([cutoff, norm, self.output_mode == 'source_atomic'], dtype=dtype)
cuda_type() names the C++ class and selects template arguments based on the
configuration, input shapes, or k when needed. Here it chooses weighted=true
for a scalar input field and weighted=false for omitted weights. The backend
supplies the coordinate dimension and floating-point dtype. Other kernels can
use this same method to specialize on configuration parameters or neighbour count.
output_mode tells the wrapper whether to return query rows or to sum atomic
contributions at source owners. The CUDA class learns the direction independently
from the packed parameter; this is an example-specific convention, not a
mandatory argument for every reduction.
requires_positive_radius makes query_ball_reduction reject zero query radii,
since a density with zero smoothing radius is undefined. It defaults to False.
params(dtype, k=None) supplies a flat array in the particle dtype. The cutoff
is a runtime value; mode is a static configuration choice. Both the type
selector and parameter method receive k: another implementation can specialize
its CUDA type on k, or pack it for runtime branching. This example needs neither.
Radius searches pass None.
For reductions that consume fields, source_fields and query_fields are
optional independent arrays with shapes (N_source, D_source) and
(N_query, D_query). Both must have the position dtype. Omitted arrays have
width zero and their pointers must not be dereferenced. Currently the wrapper
allocates max(1, D_source) outputs per query in gather mode, or
max(1, D_query) per source in scatter mode. This example accepts zero or one field, so it
always returns a single density column.
Register, rebuild, and call it
Append the exact type string to the literal REDUCTIONS list in the same
Python module:
# Append to REDUCTIONS; retain the existing entries:
"GaussianKDE<dim, T, 0>",
"GaussianKDE<dim, T, 1>",
The generator reads this list without importing JAX. Python selects the list index during tracing; generated C++ uses the same index to choose the concrete class. There is no additional mapping file to edit. The example is already registered in the source distribution, so do not add a duplicate entry.
Regenerate and rebuild in your build environment, as described in the developer guide’s CUDA kernels and automatic FFI generation section:
python src/jztree_cuda/_generate_ffi.py
python -m pip install -e . --no-build-isolation -Cbuild-dir=build
Use the compiler and architecture settings from the installation guide. Restart Python after rebuilding an imported native module.
from jztree.neighbour_reductions import GaussianKDE
for mode in ("gather", "scatter"):
density = jz.knn.knn_reduction.jit(
pos, k=128, reduction_type=GaussianKDE(mode=mode, cutoff_sigma=3.))
expected = reference_jit(pos, mode=mode)
np.testing.assert_allclose(density, expected, rtol=5e-5)
Omitting the fields in the calls above gives unit weights. To provide scalar
weights, pass an (N, 1) array with the position dtype. For example, equal masses
summing to one can be supplied as follows:
particle_weights = jnp.full((len(pos), 1), 1/len(pos), dtype=pos.dtype)
for mode in ("gather", "scatter"):
fields = {"source_fields" if mode == "gather" else "query_fields": particle_weights}
density = jz.knn.knn_reduction.jit(
pos, k=128, reduction_type=GaussianKDE(mode=mode), **fields)
expected = reference_jit(pos, particle_weights, mode=mode)
np.testing.assert_allclose(density, expected, rtol=5e-5)
The output has shape (N, 1). For separate query points, supply
part_query=query_positions. boxsize, th, and output_order follow the
usual kNN conventions. A supplied tree requires sorted sources and aligned
fields and cannot currently be combined with separate query particles.
Distributed calls use .smap(mesh, jit=True) as in the
multi-GPU guide. Source-bound scatter contributions are
returned to their owners and added there. Floating-point atomic addition order
can vary, so small differences between runs are expected. The measurements
below are local and do not establish distributed performance for this example.
Use the same reduction with radius queries
query_ball_reduction uses a supplied scalar or per-query radius instead of
selecting k neighbours. The same reduction configuration and optional VJP apply:
density = jz.knn.query_ball_reduction.jit(
pos, radius=0.1, reduction_type=GaussianKDE(mode="gather"),
)
Radii belong to queries. Gather returns one row per query; scatter accumulates
at sources. There is no packed neighbour-output allocation. A custom reduction’s
cuda_type, cuda_vjp_type and params methods must accept k=None for radius
queries. See the API reference for gradients, fields and
distributed layouts.
Compare memory and runtime
Compile and warm up each implementation before timing, and synchronize each call. This includes tree construction and the reduction, but excludes compilation:
import time
for mode in ("gather", "scatter"):
cfg = GaussianKDE(mode=mode)
functions = [
("JAX neighbours", jax.jit(lambda x: reference(x, mode=mode))),
("CUDA reduction", jax.jit(lambda x: jz.knn.knn_reduction(
x, k=128, reduction_type=cfg))),
]
for name, fn in functions:
compiled = fn.lower(pos).compile()
for _ in range(2):
jax.block_until_ready(compiled(pos))
samples = []
for _ in range(8):
start = time.perf_counter()
jax.block_until_ready(compiled(pos))
samples.append(time.perf_counter() - start)
memory = compiled.memory_analysis()
peak_memory = memory.peak_memory_in_bytes / 2**20
print(f"{mode} {name}: {np.median(samples)*1000:.1f} ms {peak_memory:.1f} MiB")
Measurements on Jens’s laptop on 1 December 2026, using revision cf7e276,
JAX/jaxlib 0.10.1 and NumPy 2.2.6, for 500,000 particles, k=128, and unit
weights. Runtime is the median of eight synchronized calls after two warm-ups.
Memory is the compiled executable peak reported by JAX, not the observed
physical GPU peak:
Mode |
Method |
Runtime |
Peak memory |
|---|---|---|---|
Gather |
JAX neighbours |
40.7 ms |
537.4 MiB |
Gather |
CUDA reduction |
38.6 ms |
78.6 MiB |
Scatter |
JAX neighbours |
38.3 ms |
537.4 MiB |
Scatter |
CUDA reduction |
39.3 ms |
78.6 MiB |
Runtime is almost unchanged. The main gain is the large reduction in memory:
about 6.8 times smaller (approximately 85% less), because full neighbour
lists do not have to be written out. Both gather and scatter outputs passed the
tutorial’s comparison against the JAX reference (rtol=5e-5).
Add an optional VJP
Suppose we use the estimated density in a loss function and want to optimize particle positions or weights. JAX’s reverse-mode automatic differentiation propagates gradients backwards through the computation using vector–Jacobian products (VJPs). Each operation receives the gradient of the loss with respect to its outputs and turns it into gradients with respect to its inputs.
JAX cannot automatically differentiate the code inside our custom CUDA kernel.
To make the reduction work with jax.grad, we must supply that backward
operation ourselves. The custom reduction interface lets us define an optional
CUDA VJP alongside the forward kernel.
Write our reduction as y = f(x, w), where x includes the source and query
positions and w contains the particle weights. Given the incoming output
cotangent, the VJP must compute:
The bars denote gradients of the final scalar loss L. We do not construct the
Jacobian matrices: each neighbour contributes directly to these weighted sums
of derivatives. Position gradients must include both the pair displacement and
the adaptive Gaussian width, because moving the kth neighbour changes R.
Configuration parameters stay fixed in this example.
Implement the backward operation in CUDA
Add the following class to the CUDA header. It reuses the forward class’s
normalization and weight calculation. The interface sends its results back in
three ways: it writes weight gradients through the supplied pointers, returns a
pair-displacement gradient from accumulate(), and returns the radius cotangent
from finalize(). The common traversal distributes the two returned gradients
to the appropriate particle positions.
template<int dim, typename T, bool weighted>
struct GaussianKDEVJP : GaussianKDE<dim,T,weighted> {
const T* cotangent;
T *grad_fields, *grad_query;
T radius_grad;
__device__ GaussianKDEVJP(const T* params, const T* source_fields,
const T* query_fields, const T* cot, T* source_gradient,
T* query_gradient, T rmax)
: GaussianKDE<dim,T,weighted>(params, source_fields, query_fields, nullptr, rmax) {
cotangent = cot;
grad_fields = source_gradient;
grad_query = query_gradient;
radius_grad = 0;
}
__device__ Vec<dim,T> accumulate(const Vec<dim,T>& dx, T r2, int source_index) {
Vec<dim,T> grad;
for (int d=0; d<dim; ++d) grad[d] = 0;
if (!this->valid) return grad;
T cot = cotangent[this->scatter ? source_index : 0];
T weighted_cot = cot * this->weight(r2);
if constexpr (weighted) {
if (this->scatter) grad_query[0] += weighted_cot;
else atomicAdd(grad_fields + source_index, weighted_cot);
weighted_cot *= this->scatter ? this->query[0] : this->fields[source_index];
}
radius_grad += weighted_cot * (r2*this->inv_sigma2-T(3)) / this->radius;
for (int d=0; d<dim; ++d) grad[d] = -weighted_cot*this->inv_sigma2*dx[d];
return grad;
}
__device__ T finalize() const { return radius_grad; }
};
For a fixed neighbour and cutoff parameter, the needed derivatives are:
The second term matters because moving the kth neighbour changes the width of
every contribution. accumulate() returns the displacement gradient; the
traversal adds it to the source and subtracts it from the query. finalize()
returns the accumulated radius cotangent, which the traversal propagates through
the selected kth-neighbour distance. No full neighbour list or separate global
radius-gradient array is needed.
The cotangent pointer addresses the query’s output row for gather and the
whole source output array for scatter. All gradient buffers start at zero.
The weight derivative of a contribution value * W is W. Gather therefore
atomically adds cotangent * W to the neighbour’s weight gradient; scatter
adds it directly to the current query’s weight-gradient row. Position and radius
derivatives are additionally multiplied by the particle weight. With omitted
weights, the template removes field reads and gradient writes.
For weight gradients, the direction reverses: forward gather scatters gradient
contributions to source weights, while forward scatter gathers contributions
into each query’s weight gradient. The VJP does not switch output_mode, though.
That flag still describes the forward output and therefore tells the backward
launcher where to read the incoming cotangent. The backward operation has
separate gradient buffers for source positions, query positions, source fields,
and query fields. Position gradients can contribute to both populations in
either mode, so there is no single reversed output mode for the whole VJP.
Connect the VJP to the Python config
Append these two entries to the literal VJP_REDUCTIONS list:
"GaussianKDEVJP<dim, T, 0>",
"GaussianKDEVJP<dim, T, 1>",
Then add this method to the same Python config, regenerate the bindings, and rebuild:
def cuda_vjp_type(self, source_shape, query_shape, k: int | None) -> str | None:
width = (query_shape if self.mode == 'scatter' else source_shape)[-1]
if width:
return "GaussianKDEVJP<dim, T, 1>"
return "GaussianKDEVJP<dim, T, 0>"
Both registrations and the method are already present in the included example.
There is one config for forward and backward; no separate user-facing VJP
configuration is needed. If you omit cuda_vjp_type(), the inherited method
returns None: forward calculations still work, but attempting to differentiate
that reduction raises a clear error.
Use and check the gradients
The following loss assigns a different factor to each density output. JAX
uses these factors as the incoming output gradient. We compare the CUDA VJP
against autodiff through the JAX reference, on a smaller sample to keep this
check inexpensive. Fix the neighbour indices before differentiating, then let
JAX differentiate the reference’s distances, adaptive width, and weights.
check_pos = pos[:4096]
check_weights = jnp.linspace(.5, 1.5, len(check_pos), dtype=pos.dtype)[:, None] / len(check_pos)
factor = jnp.linspace(.5, 1.5, len(check_pos), dtype=pos.dtype)[:, None]
indices = jz.knn.knn.jit(check_pos, k=128, result="globalidx")
for mode in ("gather", "scatter"):
cfg = GaussianKDE(mode=mode)
def loss(x, particle_weights):
fields = {"source_fields" if mode == "gather" else "query_fields": particle_weights}
density = jz.knn.knn_reduction(x, k=128, reduction_type=cfg, **fields)
return jnp.sum(density * factor)
def reference_loss(x, particle_weights):
density = reference(x, particle_weights, mode=mode, indices=indices)
return jnp.sum(density * factor)
grad_pos, grad_weights = jax.jit(jax.grad(loss, argnums=(0, 1)))(check_pos, check_weights)
ref_pos, ref_weights = jax.jit(jax.grad(reference_loss, argnums=(0, 1)))(check_pos, check_weights)
np.testing.assert_allclose(grad_pos, ref_pos, rtol=5e-4, atol=5e-5)
np.testing.assert_allclose(grad_weights, ref_weights, rtol=5e-4, atol=5e-5)
Tree topology, neighbour selection and periodic image choices are fixed during
differentiation. Both pair-distance and adaptive-radius derivatives are included.
The sharp cutoff and neighbour ties have no unique derivative at selection
changes; their jumps are not represented by the VJP. A larger cutoff_sigma
reduces the Gaussian weight at the boundary, but does not make that jump vanish.
Zero pair distance has zero displacement gradient; zero smoothing radius remains
undefined.
Config-parameter gradients, including cutoff_sigma, are unsupported for now.
This interface supports first-order reverse mode, not forward-mode JVP or higher
derivatives. Sorting and communication have their own reverse rules, so gradients
return to the original particle owners. Shared source/query populations receive
the sum of both position-gradient paths.
When checking a new VJP, use a pure-JAX reference with independently selected,
fixed neighbour indices but differentiable distances and kth radius. Check both
directions with a nonconstant cotangent and compare position gradients against
finite differences away from selection changes. The Gaussian cases in
test_knn_reduction follow this approach.