Pipeline

The stages behind the CLI (prepare, seed, run, repair, finalize), tiling and batching, the per-GPU worker and the launcher, plus the whole-volume in-memory solver.

zvdvc.pipeline.coordinator

The run’s stages, one per CLI subcommand. Each is safe to re-run.

prepare (1 process) import a .roi into a zarr-vectors store if needed;

check that reference and deformed volumes match in shape; build the template; plan tiles; check memory; ResultStore.allocate (or check that an existing store was made from the same volumes, points and settings: fingerprint()); write plan.json.

seed (1 device) strategy-dependent: nothing (rigid); the coarse

sub-grid solve plus seed field (coarse); or the whole wavefront solve (parity mode, which needs the problem to fit in memory). Re-plans the tiles’ brick boxes from the seeds.

run (devices) the tile loop, skipping tiles already written, one

process per GPU. Refuses a config that differs from the plan’s in anything that changes results, and a seed stage that has not run.

repair (M5) repair_candidates, then re-solve and rewrite

the affected tiles. Only after run has finished everywhere.

finalize (1 process) ResultStore.finalize; .stat summary;

optional .disp export; optional pyramid for Neuroglancer.

Files in cfg.workdir: plan.json, points.zarrvectors (when the points came as a .roi), seeds.npz (coarse seeding), run_stats.json, failed_tiles.json (if any tile failed twice), results.stat and the optional results.disp.

zvdvc.pipeline.coordinator.points_store(cfg)[source]

The zarr-vectors store the pipeline reads: cfg.points itself, or its import in the workdir.

Parameters:

cfg (RunConfig)

Return type:

Path

zvdvc.pipeline.coordinator.result_settings(cfg)[source]

The settings that change results: all but the volume, points and output paths, volumes.gpu_io, cluster, workdir, uncertainty_seeds and seeding.repair_passes.

Parameters:

cfg (RunConfig)

Return type:

dict[str, Any]

zvdvc.pipeline.coordinator.volume_identity(cfg, which)[source]

Resolved path, shape, dtype, and the data file’s size and mtime (raw/mhd/npy) or zarr.json digest (zarr).

Parameters:
Return type:

dict[str, Any]

zvdvc.pipeline.coordinator.points_digest(pc)[source]

Digest of the point ids and positions (in id order); refuses repeated ids, which results are matched by.

Parameters:

pc (Any)

Return type:

str

zvdvc.pipeline.coordinator.fingerprint(cfg, pc)[source]

What a results store’s values depend on: settings, both volumes’ identities and the points.

Parameters:
Return type:

dict[str, Any]

zvdvc.pipeline.coordinator.host_memory()[source]

(total, available) bytes of host RAM; available is None where the OS does not report it (e.g. macOS).

Return type:

tuple[int, int | None]

zvdvc.pipeline.coordinator.prepare(cfg, *, backend=None)[source]
Parameters:
Return type:

dict[str, Any]

zvdvc.pipeline.coordinator.seed(cfg, *, backend=None)[source]

Strategy-dependent seeding; see the module docstring.

Parameters:
Return type:

dict[str, Any]

class zvdvc.pipeline.coordinator.RunStats(stats, missing)[source]

Bases: list

The workers’ WorkerStats, plus missing: this node’s tiles still unwritten.

Parameters:
zvdvc.pipeline.coordinator.check_plan(cfg, doc)[source]

Refuse to run cfg against a plan (and results store) made from other volumes, points or settings.

Parameters:
Return type:

None

zvdvc.pipeline.coordinator.run(cfg, *, backend=None, devices=None, cpu_workers=1, max_tiles=None, tile_ids=None)[source]

Solve this node’s unwritten tiles: one process per GPU (or cpu_workers CPU processes).

max_tiles solves only the first tiles of this node’s share (short profiling runs); tile_ids names the tiles to solve instead (benchmarks). Every run logs per-tile events and, on GPUs, 1 Hz telemetry under <workdir>/events/<run id>/ (zvdvc.profiling).

Resubmitting after a time-out, a node failure or a killed worker solves only the tiles still missing. Tiles that failed twice are listed in failed_tiles.json, tiles still incomplete in run_stats.json and in the returned missing.

Parameters:
Return type:

RunStats

zvdvc.pipeline.coordinator.repair(cfg)[source]
Parameters:

cfg (RunConfig)

Return type:

None

zvdvc.pipeline.coordinator.finalize(cfg, *, export_disp=False, pyramid=False, allow_partial=False)[source]

Finish the results store and write the summaries; refuses while cells are unwritten.

With allow_partial the points of unwritten cells count, and are exported, as NOT_SEARCHED.

Parameters:
Return type:

RunSummary

zvdvc.pipeline.tiling

Tiles: the unit of work handed to a GPU.

A tile is a block of whole zarr-vectors point-cloud chunks (cluster.tile_shape / chunk_shape chunks per axis). Because tiles never share a cell, workers write results without locks, and a tile can be retried or resumed on its own.

Each tile carries two brick boxes:

  • ref_box: the tile’s point bbox grown by the halo (zvdvc.config.RunConfig.halo()).

  • def_box: ref_box shifted by the tile’s median seed and grown by the seed spread within the tile. A large rigid offset (the CCPi example has rigid_trans = 34, 4, 0) therefore moves the brick instead of fattening it.

Read amplification per volume is ((T + 2h) / T)^3 for tile edge T and halo h:

case (sphere, h = S/2 + dmax + 2)

h

T = 512

T = 1024

S=48, disp_max=10

36

1.49

1.23

S=80, disp_max=38 (CCPi example)

80

2.26

1.55

With 80 GB per H100 and prefetch_depth = 2, 1024^3 u16 tiles use about 2 bricks x 2 in flight x 1096^3 x 2 B = 10.5 GB. That is why T = 1024 is the H100 default (docs/ARCHITECTURE.md, memory budget).

Assignment: LPT (longest processing time first) over nodes, using the cost model n_points x n_samples x iterations x dof_factor. Within a node a shared queue hands out tiles dynamically, which absorbs errors in the cost model.

class zvdvc.pipeline.tiling.Tile(id: 'int', cells: 'tuple[CellCoord, ...]', n_points: 'int', points_box: 'Box', ref_box: 'Box', def_box: 'Box', cost: 'float')[source]

Bases: object

Parameters:
id: int
cells: tuple[tuple[int, int, int], ...]
n_points: int
points_box: Box
ref_box: Box
def_box: Box
cost: float
class zvdvc.pipeline.tiling.MemoryReport(brick_bytes: 'int', in_flight_bytes: 'int', batch_bytes: 'int', device_bytes: 'int', fits: 'bool')[source]

Bases: object

Parameters:
  • brick_bytes (int)

  • in_flight_bytes (int)

  • batch_bytes (int)

  • device_bytes (int)

  • fits (bool)

brick_bytes: int
in_flight_bytes: int
batch_bytes: int
device_bytes: int
fits: bool
zvdvc.pipeline.tiling.cells_per_tile(cfg, chunk_shape)[source]

Cells per tile along (x, y, z); the tile shape must be a whole number of cells.

Parameters:
Return type:

tuple[int, int, int]

zvdvc.pipeline.tiling.load_seed_field(path)[source]

(point_id, seed) sorted by id, from seeds.npz written by the seed stage.

Parameters:

path (str | Path | None)

Return type:

tuple[ndarray, ndarray] | None

zvdvc.pipeline.tiling.lookup_seeds(point_id, field, rigid)[source]

Seeds for point_id: from the seed field where present, else rigid_trans.

Parameters:
Return type:

ndarray

zvdvc.pipeline.tiling.plan_tiles(points, cfg, *, seed_field_path=None)[source]

Group occupied chunks into tiles and compute brick boxes and costs.

Reads the points once (positions for tight point boxes, ids for seeds); never touches the image volumes.

Parameters:
Return type:

list[Tile]

zvdvc.pipeline.tiling.check_memory(tiles, cfg, *, device_total_bytes, dtype_bytes)[source]
Parameters:
Return type:

MemoryReport

zvdvc.pipeline.tiling.assign_lpt(tiles, n_bins)[source]

Tile ids per bin (node), balancing summed cost: longest processing time first.

Parameters:
Return type:

list[list[int]]

zvdvc.pipeline.tiling.save_plan(path, tiles, assignment, cfg, **extra)[source]

plan.json: tiles, node assignment, template hash, package versions (zarr-vectors commit included).

Parameters:
Return type:

None

zvdvc.pipeline.tiling.load_plan(path)[source]
Parameters:

path (str | Path)

Return type:

tuple[list[Tile], list[list[int]]]

zvdvc.pipeline.tiling.plan_document(path)[source]
Parameters:

path (str | Path)

Return type:

dict[str, Any]

zvdvc.pipeline.batching

Batches inside a tile.

Batch size is limited by per-point solver scratch, not by the bricks. Scratch per point is dominated by the reference samples: M x 4 B for FA-GN, plus M x 12 B of reference gradients for IC-GN. At M = 8 000 that is 32-128 KB, so 16 k points need 0.5-2 GB. Batches are ordered along a Morton (Z-order) curve so that consecutive thread blocks read overlapping brick regions and hit in L2.

zvdvc.pipeline.batching.batch_size(free_bytes, n_samples, dof, *, method='fagn', fraction=0.5)[source]

Points per batch that fit fraction of free_bytes of device memory.

Per point: the reference term q (M floats, plus the reference gradient for IC-GN), the reference and final sample buffers, the parameters and state, and one sums row. The fused kernels never materialise per-sample Jacobians, so the batch is not limited by dof beyond the sums row.

Parameters:
Return type:

int

zvdvc.pipeline.batching.morton_order(xyz, *, cell=1.0)[source]

(N, 3) -> (N,) permutation along a Z-order curve (quantised to cell voxels).

Host computation; the permutation is cheap next to a tile’s solve.

Parameters:
Return type:

Any

zvdvc.pipeline.batching.iter_batches(order, size)[source]

Consecutive slices of order of at most size indices.

Parameters:
Return type:

Iterator[Any]

zvdvc.pipeline.worker

Per-device worker: one process, one device, a stream of tiles.

Loop (a prefetch thread, the compute loop, and a writer thread):

prefetch:  bricks + points for the next ``prefetch_depth`` tiles  (host decode, pinned copy up)
compute:   seeds = seed field lookup                              (rigid / interpolated coarse field)
           for batch in iter_batches(morton_order(points)):
               solve_batch(ref_brick, def_brick, ...)
writer:    ResultStore.write_tile(...)                            (overlaps the next tile's compute)
source.done(tile)

Target: while there is work in the queue, the compute loop never waits on I/O; WorkerStats.seconds_io_wait measures how far from that a run is. Idempotent: a tile whose cells are all present in the results store is skipped, which is how an interrupted or pre-empted job resumes. A tile that raises is reported and requeued once, then left for the coordinator to report.

The same worker drives every backend: fused/cupy put bricks on the GPU; cpu (numba) and numpy keep them on the host.

class zvdvc.pipeline.worker.TileSource(*args, **kwargs)[source]

Bases: Protocol

next()[source]
Return type:

Tile | None

done(tile, ok)[source]
Parameters:
Return type:

None

class zvdvc.pipeline.worker.QueueSource(tiles, *, retries=1)[source]

Bases: object

A node-local tile queue shared by the threads (or, via a manager, processes) of one node.

A failed tile is requeued once; after a second failure it is recorded in failed.

Parameters:
next()[source]
Return type:

Tile | None

done(tile, ok)[source]
Parameters:
Return type:

None

class zvdvc.pipeline.worker.WorkerStats(device: 'int', tiles: 'int' = 0, points: 'int' = 0, seconds_compute: 'float' = 0.0, seconds_io_wait: 'float' = 0.0, bytes_read: 'int' = 0, status_counts: 'dict[int, int]' = <factory>, tiles_skipped: 'int' = 0, seconds_write_wait: 'float' = 0.0, errors: 'list[str]' = <factory>, tiles_written: 'int' = 0, io: 'str' = '')[source]

Bases: object

Parameters:
device: int
tiles: int = 0
points: int = 0
seconds_compute: float = 0.0
seconds_io_wait: float = 0.0
bytes_read: int = 0
status_counts: dict[int, int]
tiles_skipped: int = 0
seconds_write_wait: float = 0.0
errors: list[str]
tiles_written: int = 0
io: str = ''
class zvdvc.pipeline.worker.TileWorker(cfg, device=0, *, backend=None, points_store=None, seed_field_path=None)[source]

Bases: object

Parameters:
  • cfg (RunConfig)

  • device (int)

  • backend (str | None)

  • points_store (str | Path | None)

  • seed_field_path (str | Path | None)

solve_tile(loaded)[source]

Solve every point of a loaded tile; results in the tile’s row order, on the host.

Parameters:

loaded (_Loaded)

Return type:

dict[str, ndarray]

run(source)[source]
Parameters:

source (TileSource)

Return type:

WorkerStats

zvdvc.pipeline.launch

Launching workers: one process per GPU.

Single node (the MVP target, 8x H100)

launch_local spawns one process per visible GPU (the spawn start method, because CUDA is not fork-safe; each child probes its own device, as zarr-vectors advises). The processes share a multiprocessing queue of tile ids, so scheduling is dynamic. GPUs need no inter-GPU communication (no NCCL): tiles are independent once seeds exist.

Multiple nodes (M5)

Run one task per node (srun --ntasks-per-node=1 --gpus-per-node=8). Each node takes its LPT share from plan.json using SLURM_NODEID (or the torchrun or Open MPI equivalents) and runs launch_local over that share. Nodes never talk to each other. The shared file system (results written to disjoint cells) is the only thing they have in common.

class zvdvc.pipeline.launch.NodeInfo(node_rank: 'int', n_nodes: 'int', local_devices: 'tuple[int, ...]')[source]

Bases: object

Parameters:
node_rank: int
n_nodes: int
local_devices: tuple[int, ...]
zvdvc.pipeline.launch.node_info(env=None)[source]

Discover node rank and local GPUs from SLURM, torchrun or Open MPI variables; single node if none are set.

Parameters:

env (dict[str, str] | None)

Return type:

NodeInfo

zvdvc.pipeline.launch.node_share(plan_path, info)[source]

This node’s tile ids: its LPT share from plan.json, re-balanced if the plan was made for another node count.

Parameters:
Return type:

list[int]

zvdvc.pipeline.launch.launch_local(cfg, *, tile_ids=None, devices=None, backend=None, cpu_workers=1)[source]

Run tile_ids (default: this node’s share of the plan) on devices (default: all visible).

GPU backends get one process per device. CPU backends (cpu, numpy) get cpu_workers processes that split the cores. With one slot the worker runs in this process. A worker that dies (kill -9, OOM) takes only its in-flight tile with it: the others drain the queue, and the missing tile is solved when the job is resubmitted.

Parameters:
Return type:

list[WorkerStats]

zvdvc.pipeline.inmemory

Single-process, whole-volume correlation: the numpy reference path (M1).

Both volumes are read once as whole bricks, the points come from a .roi, and seeding follows the configured strategy (rigid or CCPi-parity wavefront). It needs the whole problem in memory, so it serves the accuracy tests, the CCPi parity case and later the M2 GPU parity runs. The tiled, multi-GPU pipeline (M3/M4) produces the same per-point results from bricks instead.

class zvdvc.pipeline.inmemory.Results(point_id: 'np.ndarray', xyz: 'np.ndarray', status: 'np.ndarray', objmin: 'np.ndarray', params: 'np.ndarray', n_iter: 'np.ndarray', seed: 'np.ndarray', seconds: 'float' = 0.0, timings: 'dict[str, float]' = <factory>, displacement_sd: 'np.ndarray | None' = None)[source]

Bases: object

Parameters:
point_id: ndarray
xyz: ndarray
status: ndarray
objmin: ndarray
params: ndarray
n_iter: ndarray
seed: ndarray
seconds: float = 0.0
timings: dict[str, float]
displacement_sd: ndarray | None = None
property displacement: ndarray
status_counts()[source]
Return type:

dict[int, int]

save(path)[source]
Parameters:

path (str | Path)

Return type:

None

classmethod load(path)[source]
Parameters:

path (str | Path)

Return type:

Results

write_disp(path)[source]
Parameters:

path (str | Path)

Return type:

None

zvdvc.pipeline.inmemory.load_points(cfg)[source]

(point_id, xyz) from the configured point cloud (.roi or zarr-vectors store), in point-id order.

Parameters:

cfg (RunConfig)

Return type:

tuple[ndarray, ndarray]

zvdvc.pipeline.inmemory.run_in_memory(cfg, *, backend='numpy', progress=None)[source]

Correlate every point of cfg with both volumes held in memory.

Parameters:
Return type:

Results

zvdvc.pipeline.inmemory.solve_in_memory(cfg, point_id, xyz, *, strategy=None, seeds=None, backend='numpy', progress=None, on_solved=None)[source]

Correlate the given points against whole-volume bricks.

strategy overrides cfg.seeding.strategy (rigid or wavefront); seeds (N, 3), if given, replaces rigid_trans for the rigid strategy. on_solved(idx, results) is called after each batch (each wavefront shell) with the indices just solved, so a caller can report progress point by point (zvdvc ccpi).

Parameters:
Return type:

Results