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.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
- 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).
- zvdvc.kernels.interpolate.sample(brick, origin_xyz, positions, *, method='tricubic', with_grad=False, valid_lo_hi=None, centres=None)[source]¶
Interpolate
brickatpositions(B, M, 3). numpy or cupy, following the inputs.valid_lo_hi = (lo_xyz, hi_xyz)is the half-open voxel range (point space, likezvdvc.geometry.box.Boxbut in(x, y, z)) that holds real data. By default it is the whole brick. Samples whose stencil leaves it are markedinside = False; their values are finite but meaningless.With
centres(B, 3),positionsare 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).
- 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.
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,).
maskexcludes samples (e.g. outside the brick) from every sum.
- 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
sadthe residual is thessdone.
- 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().
- zvdvc.kernels.objective.normal_equations(ref, tar, jac, kind, *, mask=None)[source]¶
Gauss-Newton system for one iteration.
jac(B, M, ndof) isd tar / d p, i.e.grad(g)(x')^T dx'/dp. ReturnsH(B, ndof, ndof),b(B, ndof) and the exact objective (B,), where the step isH dp = -b.H = Jr'Jrandb = Jr'rfor the exact JacobianJrofresiduals(), computed from per-point sums only.
- zvdvc.kernels.objective.reference_terms(ref, kind)[source]¶
Per-sample reference term
q(B, M) and per-point target shifts(B,).qis the reference side of the residual:f(sad, ssd),f - fbar(zssd),f / |f|(nssd),(f - fbar) / |f~|(znssd).sisfbarfor the zero-mean objectives and 0 otherwise.
- 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.
- zvdvc.kernels.objective.normal_equations_from_sums(sums, shift, kind, ndof)[source]¶
H(B, ndof, ndof),b(B, ndof), objective (B,),sum |grad g|^2andsum 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.
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_sumsOne thread block per active point, threads striding over the M template samples. Per sample:
x' = c + t + F d(F, and theA_kwithdx'/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 rowj = grad(g)^T dx'/dp; accumulate the one-pass sums ofzvdvc.kernels.objective.sum_layout(): the upper triangle ofJ^T J(21 floats for 6-DOF, 78 for 12-DOF),sum j,sum v j,sum q jand seven scalars. Warp-shuffle, then block reduction.gn_solveOne thread per active point: exact normal equations from the sums (the ZSSD/NSSD/ZNSSD normalisation included, see
zvdvc.kernels.objective), Jacobi-scaled register Cholesky (SINGULARon a small pivot or a featureless target), the step, CCPi’s stopping tests (|d obj| < obj_tolor|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:
objectLaunches the kernels of
fused_gn.cuthroughcupy.RawModule.- emulated = False¶
- block = 256¶
- class zvdvc.kernels.fused.FusedBrick(data: 'Any', geom: 'Any', origin: 'tuple[float, float, float]', ctype: 'str')[source]¶
Bases:
object
- class zvdvc.kernels.fused.FusedEngine(kernels)[source]¶
Bases:
objectThe fused kernels behind the
zvdvc.solver.enginesinterface.- Parameters:
kernels (Any)
- dtype = dtype('float32')¶
- SAMPLES_PER_CALL = 67108864¶
- 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_batchcall: for GPU kernels, preparing a host brick copies it to the device.- Parameters:
brick (Brick | FusedBrick)
- Return type:
- sample(brick, centres, params, offsets, search)[source]¶
- Parameters:
brick (FusedBrick)
centres (Any)
params (Any)
offsets (Any)
search (SearchSpec)
- Return type:
- update(st, idx, sums, outside, shift, search)[source]¶
- Parameters:
st (BatchState)
idx (Any)
sums (Any)
outside (Any)
shift (Any)
search (SearchSpec)
- Return type:
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
- class zvdvc.kernels.cpu_fused.NumbaEngine[source]¶
Bases:
objectThe fused step on CPU cores, behind the
zvdvc.solver.enginesinterface.- 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¶
- prepare(brick)[source]¶
Flat contiguous data and geometry; a brick already prepared is returned as is.
- update(st, idx, sums, outside, shift, search)[source]¶
- Parameters:
st (BatchState)
idx (Any)
sums (Any)
outside (Any)
shift (Any)
search (SearchSpec)
- Return type:
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