Solver¶
Batched Gauss–Newton, the engines behind it, coarse search, seeding and per-point uncertainty. See Correlation method.
zvdvc.solver.gauss_newton¶
Batched Gauss-Newton: CCPi’s per-point search, run for B points at once.
For each batch (following Search::process_point):
Sample the reference brick at
centre + templateto getf(B, M) and its stats. This happens once per point; IC-GN also keepsgrad f.Optional threshold test (
subvol_thresh) ->THRESH_FAIL; then a reference with no texture ->SINGULAR.params <- [seed, 0, ...]. As in CCPi, only the translation is seeded; rotations and strains start at zero.Optional translation grid search (
basin_radius > 0), fromzvdvc.solver.coarse.Up to
max_iterationsGauss-Newton steps on the active set: the engine reduces each point’s samples to the one-pass sums (zvdvc.kernels.objective.sum_layout()), then solves and tests convergence (zvdvc.solver.engines.gn_update(), or thegn_solvekernel on the fused engine).Exact final objective, and status.
The loop is written once; zvdvc.solver.engines supplies the numerics
(numpy reference, cupy, fused CUDA, the CUDA source emulated on the host, and
numba on CPU cores).
- Methods
fagn: forward-additive, the CCPi-parity default. CCPi forms the Jacobian by forward differences (h = 1e-10,ndof + 1objective evaluations per step) and solvesJ^T J dp = -J^T rby QR with no damping. zvDVC uses the analytic Jacobiangrad(g)(x')^T dx'/dp(one value+gradient pass) and a batched Cholesky solve. It keeps the same undamped step and the same stopping rules.icgn: inverse-compositional (M5). The Hessian comes from the reference gradient and is built once per point. Each iteration needs target values only, with no target gradient, which makes it roughly 2-3x cheaper per iteration.- Differences from CCPi (also listed in docs/ARCHITECTURE.md)
Range test: zvDVC tests
|u - seed|_inf > disp_maxdirectly, plus brick validity. CCPi’s test is implicit: samples leaving a box of margindisp_max + 2around the seeded subvolume.Convergence: CCPi’s LM path returns after
maxitwithout flagging. zvDVC reportsCONVG_FAILunlesssearch.report_convg_failis False.Arithmetic: float32 on device (CCPi uses float64). Positions are formed relative to the point centre, so float32 keeps about 1e-4 voxel resolution across 4096^3 volumes. The numpy reference is float64.
Linear solve: Cholesky of the Jacobi-scaled
J^T J. A point whose scaled system has a pivot below the precision’s threshold (zvdvc.solver.engines.singular_pivot()), or whose target has no texture (FEATURELESS), isSINGULAR.Texture: a point whose reference samples are constant (air, zero padding;
zvdvc.solver.engines.textureless()) isSINGULARbefore any iteration, for every objective; so is one whose final target samples are constant. A point whose parameters or final objective are not finite isSINGULAR, neverGOOD.Stencils: any reference or target sample whose interpolation stencil leaves the brick’s valid region makes the point
RANGE_FAIL(CCPi’s implicit range test, made explicit).
Stopping (CCPi): after each step, a point stops if |obj_k - obj_{k-1}| <
obj_tol or |dt| < disp_tol (Euclidean norm of the translation step).
The reported objective is re-evaluated at the final parameters.
- class zvdvc.solver.gauss_newton.BatchResult(params: 'Any', status: 'Any', objmin: 'Any', n_iter: 'Any', seed: 'Any')[source]¶
Bases:
object
- zvdvc.solver.gauss_newton.solve_batch(ref_brick, def_brick, centres, seeds, template, search, *, backend='fused', engine=None)[source]¶
Correlate B points on one engine (
zvdvc.solver.engines).numpyis the float64 reference (M1).cupyis the unfused GPU path,fusedthe production CUDA kernels andcputhe same fused step on CPU cores (M2). Results come back on the engine’s device. Passengineto reuse one (and its compiled kernels) across calls.Callers that solve the same bricks repeatedly (wavefront shells, batches of a tile) should pass bricks already put through
engine.prepare: preparing a host brick for a GPU engine copies the whole brick to the device.
zvdvc.solver.engines¶
Compute engines behind zvdvc.solver.gauss_newton.solve_batch().
The Gauss-Newton driver is written once. An engine supplies four operations:
prepare(brick)Put a brick where the engine computes (device memory for GPU engines).
sample(brick, centres, params, offsets, search)Interpolated values (B, M) at the warped template, and whether every stencil stayed in the valid region (B,).
sums(brick, centres, params, idx, q, shift, offsets, search)For the points
idx: the one-pass normal-equation sums (A, n_sums) (zvdvc.kernels.objective.sum_layout()) and whether any sample left the valid region (A,).update(state, idx, sums, outside, shift, search)Solve, step, and apply the stopping, range and singularity tests; returns which of
idxare finished.gn_update()is the reference; the fused engine does the same per point in one kernel.
Engines
backend |
engine |
precision |
|---|---|---|
|
|
float64 |
|
|
float32 |
|
|
float32 |
|
|
float32 |
|
the same fused kernels, run on the host by
|
float32 |
|
|
float32 |
- zvdvc.solver.engines.singular_pivot(dtype)[source]¶
Smallest acceptable Cholesky pivot of the unit-diagonal (Jacobi-scaled) system.
- zvdvc.solver.engines.flat_reference(dtype)[source]¶
Largest
(max f - min f) / max |f|of a point’s reference samples that counts as no texture (SINGULAR).Well above the interpolation rounding of a constant volume (about 1e-6 in float32, 1e-15 in float64), and below any texture the precision can resolve.
- zvdvc.solver.engines.textureless(xp, f, dtype)[source]¶
(B,) whether the reference samples
f(B, M) are constant to withinflat_reference().Non-finite samples count as no texture too.
- class zvdvc.solver.engines.BatchState(params: 'Any', seeds: 'Any', status: 'Any', objmin: 'Any', prev_obj: 'Any', n_iter: 'Any')[source]¶
Bases:
object
- zvdvc.solver.engines.cholesky_step(H, b, pivot_tol)[source]¶
Solve
H dp = -bper point: Jacobi scaling, then an unrolled batched Cholesky.Returns
(dp, singular). Written with array operations over the batch and loops over the (at most 12) unknowns, so numpy and cupy run the same arithmetic as the per-point solve in the CUDA kernel.
- zvdvc.solver.engines.gn_update(st, idx, sums, outside, shift, search)[source]¶
One Gauss-Newton update of the points
idxfrom their sums; returns which are finished.- Parameters:
st (BatchState)
idx (Any)
sums (Any)
outside (Any)
shift (Any)
search (SearchSpec)
- Return type:
- class zvdvc.solver.engines.XpBrick(data: 'Any', origin_xyz: 'tuple[float, float, float]', valid_lo_hi: 'tuple[tuple[int, int, int], tuple[int, int, int]]')[source]¶
Bases:
object- Parameters:
- class zvdvc.solver.engines.XpEngine(xp, dtype)[source]¶
Bases:
objectUnfused array path: numpy (reference) or cupy (M2’s first GPU path).
- Parameters:
xp (Any)
dtype (Any)
- SAMPLES_PER_CALL = 1048576¶
- prepare(brick)[source]¶
The engine’s form of a brick (a device copy on cupy); a brick already in that form 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.solver.coarse¶
Global (coarse) searches that produce a starting translation.
translation_grid_searchCCPi’s
basin_radiuscoarse search, batched. Withn = floor(disp_max / basin_radius)and stepdisp_max / n, it evaluates the objective at(2n + 1)^3translations around the seed and keeps the best. The batch is B points x G translations with value-only interpolation, chunked over G to fit memory. It is expensive:disp_max = 38, basin_radius = 4gives 6 859 evaluations per point. That is cheap per point on the GPU, but it dominates the solve, so prefer good seeds.fft_seed(M5)Path-independent start, the FFT cross-correlation + Gauss-Newton scheme common in the DIC/DVC literature. It runs a batched zero-normalised cross correlation by cuFFT over a
(S + 2 * disp_max)^3window per point and takes the integer peak with a parabolic sub-voxel fit. Every point is independent, so no serial seeding order is needed at all. The cost is about three FFTs of the window per point, so it suits sparse coarse grids, or pyramid levels wheredisp_maxshrinks.
- zvdvc.solver.coarse.grid_offsets(search, xp, dtype)[source]¶
The
(2n + 1)^3translations,n = floor(disp_max / basin_radius), stepdisp_max / n.- Parameters:
search (SearchSpec)
xp (Any)
dtype (Any)
- Return type:
- zvdvc.solver.coarse.translation_grid_search(sample, ref_values, centres, params, idx, search)[source]¶
Keep, per point, the grid translation (around its seed) with the best objective.
sample(centres, translations)returns values (n, M) and inside (n,) for 3-DOF parameters; every engine provides it, so this runs unchanged on numpy, cupy, the fused kernels and numba. Translations whose samples leave the brick are never chosen.
zvdvc.solver.seeding¶
Starting displacements, without CCPi’s serial point order.
CCPi (DataCloud, Search::starting_param) sorts points by distance from
the start point, then processes them one at a time. Each point starts from the
mean translation of the already-solved point_good points among its 75
nearest neighbours, or from rigid_trans if there are none. Neighbours come
from an O(N^2) full sort.
zvDVC strategies (SeedingSpec.strategy):
rigidEvery point starts at
rigid_trans. Fully parallel; enough for small, smooth deformations.wavefront(CCPi parity; single GPU, whole problem resident)Points are bucketed into shells of width
shell_widthby distance from the start point. Shells are solved in order, each shell as one batch seeded from GOOD neighbours in earlier shells. It differs from CCPi only in that points within the same shell cannot seed each other. With the shell width equal to the lattice spacing, ak^3-point lattice has about1.7 kshells from a corner (half that from the centre). Shell sizes grow asr^2, so all but the first few shells fill a GPU.coarse(production, multi-GPU)Solve every
coarse_stride-th lattice point first, on OME-Zarr pyramid levelcoarse_level. Subvolume size,disp_maxand coordinates are scaled by2**-level, so the pass reads 1/8 of the bytes per level and fits one GPU. It useswavefrontorfft. That field is then interpolated to seed every full-resolution point. Tiles become independent, which is what lets 8+ GPUs run without coordination.fftzvdvc.solver.coarse.fft_seed()for every point (M5).
After the main solve, repair_candidates() finds failed points with
enough GOOD neighbours and re-seeds them from the neighbour median for another
pass (zvdvc repair).
Neighbours come from a KD-tree (scipy, host) in O(N log N), or a uniform-grid hash on the GPU for clouds of more than about 10^7 points (M5).
- zvdvc.solver.seeding.knn(xyz, k, *, device='cpu')[source]¶
(N, 3) -> (N, k) neighbour indices (self excluded), nearest first.
kis capped atN - 1.
- zvdvc.solver.seeding.processing_order(xyz, start_xyz)[source]¶
CCPi’s order: indices sorted by distance from the start point.
- zvdvc.solver.seeding.median_spacing(xyz)[source]¶
Median nearest-neighbour distance: the default wavefront shell width.
- zvdvc.solver.seeding.wavefront_shells(xyz, start_xyz, width)[source]¶
Index arrays, one per shell, in solve order.
The point nearest the start is a shell of its own, like CCPi’s first point: it is seeded from
rigid_transand everything after it from neighbours. The rest fall in shellsfloor(distance / width).
- zvdvc.solver.seeding.seed_from_neighbours(idx, neighbours, displacement, status, rigid_trans)[source]¶
CCPi
starting_param: mean of GOOD neighbours’ (u, v, w), elserigid_trans.
- zvdvc.solver.seeding.coarse_subset(xyz, stride, *, spacing=None)[source]¶
Indices of every
stride-th lattice point along each axis.Space is cut into cubes of
stride x spacing(spacingdefaults to the median point spacing) and the point nearest each cube’s lower corner is kept. On a regular lattice that is exactly the points whose lattice index is a multiple ofstrideon every axis; on irregular clouds it is an even thinning. Indices come back sorted.
- zvdvc.solver.seeding.interpolate_seed_field(coarse_xyz, coarse_disp, coarse_status, xyz, *, k=8, fallback=(0.0, 0.0, 0.0))[source]¶
Seeds for
xyzfrom the GOOD coarse points (kNN inverse-distance weighting).A point that coincides with a GOOD coarse point takes its displacement exactly. With no GOOD coarse point at all, every seed is
fallback.
zvdvc.solver.uncertainty¶
Per-point displacement uncertainty from repeat solves with other template seeds.
On real data the largest random error is which sample points each subvolume uses
(docs/benchmarks/2026-09-26-error-floor-case-A.md: ~0.03 voxel per axis at 8 000 samples,
falling as 1/sqrt(n)). With uncertainty_seeds = k in the run config, every GOOD point is
solved k more times, each with a template drawn with another seed, and the per-axis standard
deviation over the k + 1 estimates is stored as displacement_sd. Each repeat starts from the
same seed displacement as the main solve, not from its answer: a solve that starts at an answer
stops within the convergence tolerance (0.01 voxel) of it and would understate the spread. With
k = 2 the cost is about twice the main solve’s; the estimate of each sd has about 2 degrees of
freedom, so it is rough per point and good in aggregate.