Kernels

Batched numerics on numpy or cupy arrays: interpolation, objectives, the fused CUDA Gauss–Newton step and its CPU (numba) counterpart.

zvdvc.kernels.xp

Array-namespace dispatch: numpy on the host, cupy on the device.

Same contract as zarr-vectors’ _xp: device arrays are recognised by __cuda_array_interface__, and asking for "cuda" without cupy is an error, never a silent host fallback. zarr-vectors’ module is internal upstream, so zvDVC keeps its own.

zvdvc.kernels.xp.is_device_array(a)[source]
Parameters:

a (Any)

Return type:

bool

zvdvc.kernels.xp.get_xp(device)[source]
Parameters:

device (Literal['cpu', 'cuda'])

Return type:

ModuleType

zvdvc.kernels.xp.xp_of(*arrays)[source]

Namespace of the inputs: cupy if any is a device array, else numpy.

Parameters:

arrays (Any)

Return type:

ModuleType

zvdvc.kernels.interpolate

Batched interpolation of a brick at warped sample positions, with gradients.

tricubic is separable Catmull-Rom (cubic convolution, a = -0.5): 4 taps per axis, 64 voxel reads, with weights and derivative weights computed once per axis. CCPi’s tricubic is Lekien-Marsden, fed with central-difference derivative kernels (f, fx, fy, fz, fxy, fxz, fyz, fxyz) precomputed over the whole box. A tensor-product cubic Hermite interpolant with tensor-product central-difference derivatives is tensor-product Catmull-Rom. So the same interpolant needs no derivative kernels and no 64x64 coefficient solve per cell, which were CCPi’s two largest per-point costs. M1 checks this equivalence against a direct port of the Lekien path on random data (target: max relative difference below 1e-5). If it does not hold, a tricubic_lekien variant evaluates the 64-voxel stencil with CCPi’s exact weights. It costs the same memory traffic and more FLOPs.

trilinear has 8 taps and a piecewise-constant gradient; it is fine for tuning but biased for strain. nearest is for the coarse grid search only, since its gradient is zero.

Positions are point-space (x, y, z). The brick is (z, y, x) in native dtype with its origin at Brick.origin_xyz. Samples whose stencil leaves the brick’s valid region are reported in inside so the solver can flag RANGE_FAIL.

class zvdvc.kernels.interpolate.Samples(values: 'Any', grad: 'Any | None', inside: 'Any')[source]

Bases: object

Parameters:
  • values (Any)

  • grad (Any | None)

  • inside (Any)

values: Any
grad: Any | None
inside: Any
zvdvc.kernels.interpolate.catmull_rom_weights(t)[source]

Fractional position (…,) -> (weights (…, 4), derivative weights (…, 4)).

Taps at offsets -1, 0, 1, 2 from floor(x); t = x - floor(x).

Parameters:

t (Any)

Return type:

tuple[Any, Any]

zvdvc.kernels.interpolate.sample(brick, origin_xyz, positions, *, method='tricubic', with_grad=False, valid_lo_hi=None, centres=None)[source]

Interpolate brick at positions (B, M, 3). numpy or cupy, following the inputs.

valid_lo_hi = (lo_xyz, hi_xyz) is the half-open voxel range (point space, like zvdvc.geometry.box.Box but in (x, y, z)) that holds real data. By default it is the whole brick. Samples whose stencil leaves it are marked inside = False; their values are finite but meaningless.

With centres (B, 3), positions are offsets from them. Each centre is split into an integer voxel and a fraction in float64, and only the small part is added in the working precision, so float32 keeps ~1e-6 voxel resolution at any coordinate (the GPU kernels do the same).

Parameters:
Return type:

Samples

zvdvc.kernels.interpolate.lekien_marsden_reference(brick, positions)[source]

float64 numpy port of CCPi’s kernels_derivs + tri_cub_Lek (values only), for the M1 equivalence test.

Clean-room, from the published method: per-voxel derivative estimates by central differences (fx = (f[i+1] - f[i-1]) / 2, mixed terms as products of those operators), then the Lekien-Marsden tricubic on the enclosing cell. Test-only: slow, not vectorised over the stencil.

Parameters:
Return type:

Any

zvdvc.kernels.objective

Batched matching criteria, as defined in CCPi ObjectiveFunctions.cpp (after Pan 2010).

For reference samples f and target samples g of one subvolume (bars are means, ~ is mean-subtracted):

sad    sum |g - f|
ssd    sum (g - f)^2
zssd   sum (g~ - f~)^2
nssd   1/2 * sum (g/|g| - f/|f|)^2          in [0, 1]
znssd  1/4 * sum (g~/|g~| - f~/|f~|)^2      in [0, 1]

The residual vectors are CCPi’s (the bracketed terms). Gauss-Newton minimises their sum of squares, which for sad means it steps as if the objective were ssd, exactly as CCPi does. The reported objective is always the exact value above.

The normal equations (normal_equations()) use the exact Jacobian of the residual vector, normalisation included. CCPi differentiates its full objective numerically, so this is the parity choice. Holding the target mean and norm fixed within an iteration (common FA-GN/IC-GN practice) moves the fixed point for NSSD/ZNSSD by a term proportional to (1 - rho) * d|g~|/dp, which is not zero under noise. The exact form costs only two more per-point sums, sum J and sum g J, which the fused kernel accumulates in the same pass. With J the target Jacobian (B, M, ndof) and g^ = g~/|g~|:

zssd   H = J'J - M m m',                 b = J'r
nssd   H = (J'J - a a') / |g|^2,         b = (J'r - a (g^.r)) / |g|
znssd  H = (J'J - M m m' - a a') / |g~|^2,  b = (J'r - a (g^.r)) / |g~|

where m is the sample mean of J and a = g^'J.

zvdvc.kernels.objective.objective(ref, tar, kind, *, mask=None)[source]

(B, M), (B, M) -> (B,). mask excludes samples (e.g. outside the brick) from every sum.

Parameters:
  • ref (Any)

  • tar (Any)

  • kind (Literal['sad', 'ssd', 'zssd', 'nssd', 'znssd'])

  • mask (Any)

Return type:

Any

zvdvc.kernels.objective.residuals(ref, tar, kind, *, mask=None)[source]

(B, M) residuals and (B,) per-point scale (1/|g~| etc.) applied to the target gradient in the Jacobian.

Masked samples have zero residual. For sad the residual is the ssd one.

Parameters:
  • ref (Any)

  • tar (Any)

  • kind (Literal['sad', 'ssd', 'zssd', 'nssd', 'znssd'])

  • mask (Any)

Return type:

tuple[Any, Any]

zvdvc.kernels.objective.reference_stats(ref, kind)[source]

Per-point reference mean and norm, computed once per point and reused every iteration.

(B, 2): column 0 is the mean subtracted (0 unless zero-mean), column 1 the norm divided by (1 unless normalised), matching residuals().

Parameters:
  • ref (Any)

  • kind (Literal['sad', 'ssd', 'zssd', 'nssd', 'znssd'])

Return type:

Any

zvdvc.kernels.objective.normal_equations(ref, tar, jac, kind, *, mask=None)[source]

Gauss-Newton system for one iteration.

jac (B, M, ndof) is d tar / d p, i.e. grad(g)(x')^T dx'/dp. Returns H (B, ndof, ndof), b (B, ndof) and the exact objective (B,), where the step is H dp = -b. H = Jr'Jr and b = Jr'r for the exact Jacobian Jr of residuals(), computed from per-point sums only.

Parameters:
  • ref (Any)

  • tar (Any)

  • jac (Any)

  • kind (Literal['sad', 'ssd', 'zssd', 'nssd', 'znssd'])

  • mask (Any)

Return type:

tuple[Any, Any, Any]

zvdvc.kernels.objective.n_upper(ndof)[source]
Parameters:

ndof (int)

Return type:

int

zvdvc.kernels.objective.sum_layout(ndof)[source]

Column ranges of the per-point sums row.

Parameters:

ndof (int)

Return type:

dict[str, slice]

zvdvc.kernels.objective.n_sums(ndof)[source]
Parameters:

ndof (int)

Return type:

int

zvdvc.kernels.objective.reference_terms(ref, kind)[source]

Per-sample reference term q (B, M) and per-point target shift s (B,).

q is the reference side of the residual: f (sad, ssd), f - fbar (zssd), f / |f| (nssd), (f - fbar) / |f~| (znssd). s is fbar for the zero-mean objectives and 0 otherwise.

Parameters:
  • ref (Any)

  • kind (Literal['sad', 'ssd', 'zssd', 'nssd', 'znssd'])

Return type:

tuple[Any, Any]

zvdvc.kernels.objective.accumulate_sums(q, v, jac, kind)[source]

The sums row (B, n_sums) from dense per-sample arrays: the unfused path’s reduction.

Parameters:
  • q (Any)

  • v (Any)

  • jac (Any)

  • kind (Literal['sad', 'ssd', 'zssd', 'nssd', 'znssd'])

Return type:

Any

zvdvc.kernels.objective.normal_equations_from_sums(sums, shift, kind, ndof)[source]

H (B, ndof, ndof), b (B, ndof), objective (B,), sum |grad g|^2 and sum g^2 (B,).

Identical, up to rounding, to normal_equations() on the dense arrays (exact Jacobian of the normalised residual). The last two feed the featureless-subvolume test.

Parameters:
  • sums (Any)

  • shift (Any)

  • kind (Literal['sad', 'ssd', 'zssd', 'nssd', 'znssd'])

  • ndof (int)

Return type:

tuple[Any, Any, Any, Any, Any]

zvdvc.kernels.fused

Fused Gauss-Newton step for a batch of points, as CUDA kernels.

The unfused path (warp -> interpolate.sample -> objective sums) materialises (B, M, ndof) intermediates. At B = 16k points and M = 8000 samples that is gigabytes per iteration. These kernels keep all of it in registers and shared memory. Source: kernels/cuda/fused_gn.cu, templated on DOF, OBJECTIVE, INTERP and the brick type, compiled through cupy.RawModule on first use (one specialisation per run configuration, cached by cupy).

Kernels, per Gauss-Newton iteration

gn_sums

One thread block per active point, threads striding over the M template samples. Per sample: x' = c + t + F d (F, and the A_k with dx'/dp_k = A_k d, computed once per point into shared memory); Catmull-Rom value and gradient from the native-dtype brick (converted in registers, read through the read-only cache); Jacobian row j = grad(g)^T dx'/dp; accumulate the one-pass sums of zvdvc.kernels.objective.sum_layout(): the upper triangle of J^T J (21 floats for 6-DOF, 78 for 12-DOF), sum j, sum v j, sum q j and seven scalars. Warp-shuffle, then block reduction.

gn_solve

One thread per active point: exact normal equations from the sums (the ZSSD/NSSD/ZNSSD normalisation included, see zvdvc.kernels.objective), Jacobi-scaled register Cholesky (SINGULAR on a small pivot or a featureless target), the step, CCPi’s stopping tests (|d obj| < obj_tol or |dt| < disp_tol) and the range test (|u - seed|_inf > disp_max).

One pass suffices even for ZNSSD. The sums are formed on the target shifted by the reference mean, so the target mean and norm follow from them without cancellation, and no second pass over the samples is needed (an earlier design stored the M target values in shared memory for a second pass).

sample_values (one thread per sample) serves the reference samples, the final objective and the basin_radius grid search.

Active set

Finished points leave the index list after each iteration, so late iterations launch only for stragglers. There is no per-point control flow inside a block.

Batches are ordered spatially (zvdvc.pipeline.batching) so that neighbouring blocks read overlapping footprints and hit in L2 (50 MB on H100). Positions are formed from an integer voxel plus a float32 fraction, so precision does not depend on the coordinate’s magnitude.

Without a GPU, zvdvc.kernels.cuda.emulate.EmulatedKernels runs the same source on the host (backend "emulated"), which is how the kernels are tested in CI.

class zvdvc.kernels.fused.CudaKernels[source]

Bases: object

Launches the kernels of fused_gn.cu through cupy.RawModule.

emulated = False
block = 256
function(name, targs)[source]
Parameters:
Return type:

Any

launch(name, targs, grid, block, args)[source]
Parameters:
Return type:

None

class zvdvc.kernels.fused.FusedBrick(data: 'Any', geom: 'Any', origin: 'tuple[float, float, float]', ctype: 'str')[source]

Bases: object

Parameters:
data: Any
geom: Any
origin: tuple[float, float, float]
ctype: str
zvdvc.kernels.fused.brick_geometry(brick)[source]
Parameters:

brick (Brick)

Return type:

ndarray

class zvdvc.kernels.fused.FusedEngine(kernels)[source]

Bases: object

The fused kernels behind the zvdvc.solver.engines interface.

Parameters:

kernels (Any)

dtype = dtype('float32')
SAMPLES_PER_CALL = 67108864
points_per_call(n_samples, ndof)[source]
Parameters:
Return type:

int

prepare(brick)[source]

The kernels’ form of a brick (on their device); a brick already in that form is returned as is.

Prepare each brick once and pass the result to every solve_batch call: for GPU kernels, preparing a host brick copies it to the device.

Parameters:

brick (Brick | FusedBrick)

Return type:

FusedBrick

sample(brick, centres, params, offsets, search)[source]
Parameters:
Return type:

tuple[Any, Any]

sums(brick, centres, params, idx, q, shift, offsets, search)[source]
Parameters:
Return type:

tuple[Any, Any]

update(st, idx, sums, outside, shift, search)[source]
Parameters:
Return type:

Any

zvdvc.kernels.cpu_fused

The fused Gauss-Newton step on multi-core CPUs (numba, prange over points).

This is not a production path. It exists so the benchmarks can separate the gain from restructuring (bricks, analytic Jacobian, batching) from the gain from the GPU (docs/PERFORMANCE.md section 5, MVP question Q5). It is a line for line port of kernels/cuda/fused_gn.cu: the same template, warp, Catmull-Rom stencil, one-pass sums and stopping rules, with points spread across cores. The per-point solve is the shared zvdvc.solver.engines.gn_update(). Accumulation is in float64 (free on a CPU); results are returned as float32 like the GPU paths.

Needs numba (pip install 'zvdvc[cpu-fast]'). NUMBA_NUM_THREADS sets the core count.

class zvdvc.kernels.cpu_fused.CpuBrick(flat: 'np.ndarray', geom: 'np.ndarray', origin: 'tuple[float, float, float]')[source]

Bases: object

Parameters:
flat: ndarray
geom: ndarray
origin: tuple[float, float, float]
class zvdvc.kernels.cpu_fused.NumbaEngine[source]

Bases: object

The fused step on CPU cores, behind the zvdvc.solver.engines interface.

xp = <module 'numpy' from '/home/docs/checkouts/zvdvc/envs/latest/lib/python3.11/site-packages/numpy/__init__.py'>
dtype = dtype('float32')
SAMPLES_PER_CALL = 67108864
points_per_call(n_samples, ndof)[source]
Parameters:
Return type:

int

prepare(brick)[source]

Flat contiguous data and geometry; a brick already prepared is returned as is.

Parameters:

brick (Brick | CpuBrick)

Return type:

CpuBrick

sample(brick, centres, params, offsets, search)[source]
Parameters:
Return type:

tuple[Any, Any]

sums(brick, centres, params, idx, q, shift, offsets, search)[source]
Parameters:
Return type:

tuple[Any, Any]

update(st, idx, sums, outside, shift, search)[source]
Parameters:
Return type:

Any

zvdvc.kernels.cuda.emulate

Run fused_gn.cu on the host: g++ builds each specialisation against cuda_emu.h.

EmulatedKernels has the same launch interface as zvdvc.kernels.fused.CudaKernels, with numpy arrays in place of cupy ones, so zvdvc.kernels.fused.FusedEngine runs unchanged on top of either. Tests use it to check the CUDA source against the numpy reference on machines without a GPU. Every emulated GPU thread is an OS thread, so keep problems small (tens of points, hundreds of samples).

Needs a C++20 compiler ($CXX, default g++). Libraries are cached in $ZVDVC_CACHE (default ~/.cache/zvdvc) under a hash of the sources.

zvdvc.kernels.cuda.emulate.compiler()[source]

The C++ compiler for the emulator, or None if there is none that builds C++20 <barrier> code.

Return type:

str | None

class zvdvc.kernels.cuda.emulate.EmulatedKernels(block=64)[source]

Bases: object

Parameters:

block (int)

xp = <module 'numpy' from '/home/docs/checkouts/zvdvc/envs/latest/lib/python3.11/site-packages/numpy/__init__.py'>
emulated = True
launch(name, targs, grid, block, args)[source]
Parameters:
Return type:

None