torch_em.util.prediction

  1import queue
  2import threading
  3import warnings
  4from copy import deepcopy
  5from concurrent import futures
  6from typing import Tuple, Union, Callable, Any, List, Optional
  7
  8import numpy as np
  9import bioimage_cpp as bic
 10import torch
 11from numpy.typing import ArrayLike
 12
 13try:
 14    from napari.utils import progress as tqdm
 15except ImportError:
 16    from tqdm import tqdm
 17
 18from ..transform.raw import standardize
 19
 20
 21def predict_with_padding(
 22    model: torch.nn.Module,
 23    input_: np.ndarray,
 24    min_divisible: Tuple[int, ...],
 25    device: Optional[Union[torch.device, str]] = None,
 26    with_channels: bool = False,
 27    prediction_function: Callable[[Any], Any] = None
 28) -> np.ndarray:
 29    """Run prediction with padding for a model that can only deal with inputs divisible by specific factors.
 30
 31    Args:
 32        model: The model.
 33        input_: The input for prediction.
 34        min_divisible: The minimal factors the input shape must be divisible by.
 35            For example, (16, 16) for a model that needs 2D inputs divisible by at least 16 pixels.
 36        device: The device of the model. If not given, will be derived from the model parameters.
 37        with_channels: Whether the input data contains channels.
 38        prediction_function: A wrapper function for prediction to enable custom prediction procedures.
 39
 40    Returns:
 41        np.ndarray: The ouptut of the model.
 42    """
 43    if with_channels:
 44        assert len(min_divisible) + 1 == input_.ndim, f"{min_divisible}, {input_.ndim}"
 45        min_divisible_ = (1,) + min_divisible
 46    else:
 47        assert len(min_divisible) == input_.ndim
 48        min_divisible_ = min_divisible
 49
 50    if any(sh % md != 0 for sh, md in zip(input_.shape, min_divisible_)):
 51        pad_width = tuple(
 52            (0, 0 if sh % md == 0 else md - sh % md)
 53            for sh, md in zip(input_.shape, min_divisible_)
 54        )
 55        crop_padding = tuple(slice(0, sh) for sh in input_.shape)
 56        input_ = np.pad(input_, pad_width, mode="reflect")
 57    else:
 58        crop_padding = None
 59
 60    ndim = input_.ndim
 61    ndim_model = 1 + ndim if with_channels else 2 + ndim
 62
 63    if device is None:
 64        device = next(model.parameters()).device
 65
 66    expand_dim = (None,) * (ndim_model - ndim)
 67    with torch.no_grad():
 68        model_input = torch.from_numpy(input_[expand_dim]).to(device)
 69        output = model(model_input) if prediction_function is None else prediction_function(model, model_input)
 70        output = output.cpu().numpy()
 71
 72    if crop_padding is not None:
 73        crop_padding = (slice(None),) * (output.ndim - len(crop_padding)) + crop_padding
 74        output = output[crop_padding]
 75
 76    return output
 77
 78
 79def _pad_for_shift_left(arr, pad_vox, with_channels, mode="constant", constant_values=0.0):
 80    pad_left = tuple(pad_vox)
 81    pad_right = tuple(0 for _ in pad_vox)
 82
 83    pad_width = tuple((pl, pr) for pl, pr in zip(pad_left, pad_right))
 84    if with_channels:
 85        pad_width = ((0, 0),) + pad_width
 86
 87    arr_pad = np.pad(arr, pad_width, mode=mode, constant_values=constant_values)
 88    return arr_pad, pad_left
 89
 90
 91def _crop_after_shift_left(arr, pad_left, with_channels, original_shape_spatial):
 92    starts = pad_left
 93    stops = tuple(st + sh for st, sh in zip(starts, original_shape_spatial))
 94    spatial_slices = tuple(slice(st, sp) for st, sp in zip(starts, stops))
 95    return arr[(slice(None),) + spatial_slices] if with_channels else arr[spatial_slices]
 96
 97
 98def _load_block(input_, offset, block_shape, halo, padding_mode="reflect", with_channels=False):
 99    shape = input_.shape
100    if with_channels:
101        shape = shape[1:]
102
103    starts = [off - ha for off, ha in zip(offset, halo)]
104    stops = [off + bs + ha for off, bs, ha in zip(offset, block_shape, halo)]
105
106    # we pad the input volume if necessary
107    pad_left = None
108    pad_right = None
109
110    # check for padding to the left
111    if any(start < 0 for start in starts):
112        pad_left = tuple(abs(start) if start < 0 else 0 for start in starts)
113        starts = [max(0, start) for start in starts]
114
115    # check for padding to the right
116    if any(stop > shape[i] for i, stop in enumerate(stops)):
117        pad_right = tuple(stop - shape[i] if stop > shape[i] else 0 for i, stop in enumerate(stops))
118        stops = [min(shape[i], stop) for i, stop in enumerate(stops)]
119
120    bb = tuple(slice(start, stop) for start, stop in zip(starts, stops))
121    if with_channels:
122        data = input_[(slice(None),) + bb]
123    else:
124        data = input_[bb]
125
126    ndim = len(shape)
127    # pad if necessary
128    if pad_left is not None or pad_right is not None:
129        pad_left = (0,) * ndim if pad_left is None else pad_left
130        pad_right = (0,) * ndim if pad_right is None else pad_right
131        pad_width = tuple((pl, pr) for pl, pr in zip(pad_left, pad_right))
132        if with_channels:
133            pad_width = ((0, 0),) + pad_width
134        data = np.pad(data, pad_width, mode=padding_mode)
135
136        # extend the bounding box for downstream
137        bb = tuple(
138            slice(b.start - pl, b.stop + pr)
139            for b, pl, pr in zip(bb, pad_left, pad_right)
140        )
141
142    return data, bb
143
144
145def predict_with_halo(
146    input_: ArrayLike,
147    model: torch.nn.Module,
148    gpu_ids: List[Union[str, int]],
149    block_shape: Tuple[int, ...],
150    halo: Tuple[int, ...],
151    output: Optional[Union[ArrayLike, List[Tuple[ArrayLike, slice]]]] = None,
152    preprocess: Callable[[Union[torch.Tensor, np.ndarray]], Union[torch.Tensor, np.ndarray]] = standardize,
153    postprocess: Callable[[np.ndarray], np.ndarray] = None,
154    with_channels: bool = False,
155    skip_block: Callable[[Any], bool] = None,
156    mask: Optional[ArrayLike] = None,
157    disable_tqdm: bool = False,
158    tqdm_desc: str = "predict with halo",
159    prediction_function: Optional[Callable] = None,
160    roi: Optional[Tuple[slice]] = None,
161    iter_list: Optional[List[int]] = None,
162    grid_shift: Optional[Tuple[float, ...]] = None,
163) -> ArrayLike:
164    """Run block-wise network prediction with a halo.
165
166    Args:
167        input_: The input data, can be a numpy array, a hdf5/zarr/z5py dataset or similar
168        model: The network.
169        gpu_ids: List of device ids to use for prediction. To run prediction on the CPU, pass `["cpu"]`.
170        block_shape: The shape of the inner block to use for prediction.
171        halo: The shape of the halo to use for prediction
172        output: The output data, will be allocated if None is passed.
173            Instead of a single output, this can also be a list of outputs and a slice for the corresponding channel.
174        preprocess: Function to preprocess input data before passing it to the network.
175        postprocess: Function to postprocess the network predictions.
176        with_channels: Whether the input has a channel axis.
177        skip_block: Function to evaluate whether a given input block will be skipped.
178        mask: Elements outside the mask will be ignored in the prediction.
179        disable_tqdm: Flag that allows to disable tqdm output (e.g. if function is called multiple times).
180        tqdm_desc: Fescription shown by the tqdm output.
181        prediction_function: A wrapper function for prediction to enable custom prediction procedures.
182        roi: A region of interest of the input for which to run prediction.
183        iter_list: Optional list of block ids to iterate over.
184        grid_shift: Per-axis fractional shift of the grid in units of the block size. E.g. (0, 0.25, 0).
185    Returns:
186        The model output.
187    """
188    devices = [torch.device(gpu) for gpu in gpu_ids]
189    models = [
190        (model if next(model.parameters()).device == device else deepcopy(model).to(device), device)
191        for device in devices
192    ]
193    n_workers = len(gpu_ids)
194
195    # original shape (spatial only)
196    shape0 = input_.shape
197    shape_spatial0 = shape0[1:] if with_channels else shape0
198    ndim = len(shape_spatial0)
199    assert len(block_shape) == len(halo) == ndim
200
201    # apply grid_shift via padding+cropping (zero padding)
202    input_eff = input_
203    mask_eff = mask
204
205    if grid_shift is not None:
206        assert len(grid_shift) == ndim, "grid_shift must match number of spatial dims"
207        pad_vox = tuple(int(np.rint(abs(gs) * bs)) for gs, bs in zip(grid_shift, block_shape))
208
209        if not isinstance(input_eff, np.ndarray):
210            raise TypeError("grid_shift padding currently requires input_ to be a numpy array")
211
212        input_eff, pad_left = _pad_for_shift_left(input_eff, pad_vox, with_channels=with_channels, mode="constant",
213                                                  constant_values=0)
214
215        if mask_eff is not None:
216            if not isinstance(mask_eff, np.ndarray):
217                raise TypeError("grid_shift padding currently requires mask to be a numpy array")
218            mask_eff, _ = _pad_for_shift_left(mask_eff, pad_vox, with_channels=False, mode="constant",
219                                              constant_values=0)
220    else:
221        pad_left = (0,) * ndim
222
223    # shapes after shift-padding
224    shape_eff = input_eff.shape
225    shape_spatial_eff = shape_eff[1:] if with_channels else shape_eff
226
227    # blocking (on the padded input)
228    if roi is None:
229        blocking = bic.utils.Blocking([0] * ndim, list(shape_spatial_eff), block_shape)
230    else:
231        assert len(roi) == ndim
232        blocking_start = [0 if ro.start is None else ro.start for ro in roi]
233        blocking_stop = [sh if ro.stop is None else ro.stop for ro, sh in zip(roi, shape_spatial_eff)]
234        blocking = bic.utils.Blocking(blocking_start, blocking_stop, block_shape)
235
236    # output allocation (for padded shape)
237    if output is None:
238        n_out = models[0][0].out_channels
239        output = np.zeros((n_out,) + tuple(shape_spatial_eff), dtype="float32")
240    elif grid_shift:
241        raise ValueError(
242            "grid_shift is not supported together with a user-provided `output`, because "
243            "grid_shift requires internal zero-padding and a final cropping step. "
244            "Pass `output=None` (let this function allocate the output) or disable `grid_shift`. "
245            "Or pad the input manually beforehand."
246        )
247
248    def predict_block(block_id):
249        worker_id = block_id % n_workers
250        net, device = models[worker_id]
251
252        with torch.no_grad():
253            block = blocking.get_block(block_id)
254            offset = [beg for beg in block.begin]
255            inner_bb = tuple(slice(ha, ha + bs) for ha, bs in zip(halo, block.shape))
256
257            if mask_eff is not None:
258                mask_block, _ = _load_block(mask_eff, offset, block_shape, halo, with_channels=False)
259                mask_block = mask_block[inner_bb].astype("bool")
260                if mask_block.sum() == 0:
261                    return
262
263            inp, _ = _load_block(input_eff, offset, block_shape, halo, with_channels=with_channels)
264
265            if skip_block is not None and skip_block(inp):
266                return
267
268            if preprocess is not None:
269                inp = preprocess(inp)
270
271            # add (channel) and batch axis
272            expand_dims = np.s_[None] if with_channels else np.s_[None, None]
273            inp = torch.from_numpy(inp[expand_dims]).to(device)
274
275            prediction = net(inp) if prediction_function is None else prediction_function(net, inp)
276
277            # allow for list of tensors
278            try:
279                prediction = prediction.cpu().numpy().squeeze(0)
280            except AttributeError:
281                prediction = prediction[0]
282                prediction = prediction.cpu().numpy().squeeze(0)
283
284            if postprocess is not None:
285                prediction = postprocess(prediction)
286
287            if prediction.ndim == ndim + 1:
288                inner_bb_pred = (slice(None),) + inner_bb
289            else:
290                inner_bb_pred = inner_bb
291            prediction = prediction[inner_bb_pred]
292
293            if mask_eff is not None:
294                if prediction.ndim == ndim + 1:
295                    mb = np.broadcast_to(mask_block[None], prediction.shape)
296                else:
297                    mb = mask_block
298                prediction[~mb] = 0
299
300            bb = tuple(slice(beg, end) for beg, end in zip(block.begin, block.end))
301            if isinstance(output, list):  # we have multiple outputs and split the prediction channels
302                for out, channel_slice in output:
303                    this_bb = bb if out.ndim == ndim else (slice(None),) + bb
304                    out[this_bb] = prediction[channel_slice]
305            else:  # we only have a single output array
306                if output.ndim == ndim + 1:
307                    bb = (slice(None),) + bb
308                output[bb] = prediction
309
310    n_blocks = blocking.number_of_blocks
311    iteration_ids = range(n_blocks) if iter_list is None else np.array(iter_list)
312
313    with futures.ThreadPoolExecutor(n_workers) as tp:
314        list(tqdm(tp.map(predict_block, iteration_ids),
315                  total=len(iteration_ids),
316                  disable=disable_tqdm,
317                  desc=tqdm_desc))
318
319    # crop away the shift padding so the returned output matches original shape
320    if grid_shift is not None:
321        output = _crop_after_shift_left(output, pad_left, with_channels=(output.ndim == ndim+1),
322                                        original_shape_spatial=tuple(shape_spatial0))
323
324    return output
325
326
327# Sentinel returned by _prepare_block_input when a block should be skipped.
328_SKIP = object()
329# Sentinel pushed onto the pipeline queues to signal end-of-stream.
330_STOP = object()
331
332
333class _Aborted(Exception):
334    """@private
335    Raised inside worker threads to unwind cleanly once `stop_event` is set."""
336
337
338class _AtomicCounter:
339    """@private
340    Lock-guarded integer counter used for sentinel reference counting and progress tracking."""
341
342    def __init__(self, value: int):
343        self._value = value
344        self._lock = threading.Lock()
345
346    @property
347    def value(self) -> int:
348        with self._lock:
349            return self._value
350
351    def increment(self) -> int:
352        with self._lock:
353            self._value += 1
354            return self._value
355
356    def decrement(self) -> int:
357        with self._lock:
358            self._value -= 1
359            return self._value
360
361
362class _BlockJob:
363    """@private
364    A unit of work travelling through the prediction pipeline."""
365
366    __slots__ = ("block", "inner_bb", "mask_block", "tensor", "prediction")
367
368    def __init__(self, block, inner_bb, mask_block, tensor):
369        self.block = block
370        self.inner_bb = inner_bb
371        self.mask_block = mask_block
372        self.tensor = tensor  # CPU tensor [1, (C,) *spatial]; cleared after prediction
373        self.prediction = None  # filled by the consumer
374
375
376def _safe_get(q, stop_event, timeout=0.2):
377    """@private
378    Queue.get that aborts (raises _Aborted) once stop_event is set, to avoid deadlocks."""
379    while not stop_event.is_set():
380        try:
381            return q.get(timeout=timeout)
382        except queue.Empty:
383            continue
384    raise _Aborted()
385
386
387def _safe_put(q, item, stop_event, timeout=0.2):
388    """@private
389    Queue.put that aborts (raises _Aborted) once stop_event is set, to avoid deadlocks."""
390    while not stop_event.is_set():
391        try:
392            q.put(item, timeout=timeout)
393            return
394        except queue.Full:
395            continue
396    raise _Aborted()
397
398
399def _prepare_block_input(input_, mask, block, block_shape, halo, with_channels, skip_block, preprocess):
400    """@private
401    Producer-side block preparation: load + (optional) mask/skip check + preprocess.
402
403    Returns the `_SKIP` sentinel if the block should be skipped, otherwise a tuple
404    `(cpu_tensor, mask_block, inner_bb)` where `cpu_tensor` has a leading batch axis.
405    """
406    offset = [beg for beg in block.begin]
407    inner_bb = tuple(slice(ha, ha + bs) for ha, bs in zip(halo, block.shape))
408
409    mask_block = None
410    if mask is not None:
411        mask_block, _ = _load_block(mask, offset, block_shape, halo, with_channels=False)
412        mask_block = mask_block[inner_bb].astype("bool")
413        if mask_block.sum() == 0:
414            return _SKIP
415
416    inp, _ = _load_block(input_, offset, block_shape, halo, with_channels=with_channels)
417
418    if skip_block is not None and skip_block(inp):
419        return _SKIP
420
421    if preprocess is not None:
422        inp = preprocess(inp)
423
424    # add (channel) and batch axis -> [1, (C,) *spatial]
425    expand_dims = np.s_[None] if with_channels else np.s_[None, None]
426    tensor = torch.from_numpy(inp[expand_dims])
427    return tensor, mask_block, inner_bb
428
429
430def _write_prediction(prediction, block, output, ndim, mask_block, inner_bb, postprocess):
431    """@private
432    Writer-side logic: postprocess + inner crop + mask-zero + write to `output`."""
433    if postprocess is not None:
434        prediction = postprocess(prediction)
435
436    if prediction.ndim == ndim + 1:
437        inner_bb_pred = (slice(None),) + inner_bb
438    else:
439        inner_bb_pred = inner_bb
440    prediction = prediction[inner_bb_pred]
441
442    if mask_block is not None:
443        if prediction.ndim == ndim + 1:
444            mb = np.broadcast_to(mask_block[None], prediction.shape)
445        else:
446            mb = mask_block
447        prediction[~mb] = 0
448
449    bb = tuple(slice(beg, end) for beg, end in zip(block.begin, block.end))
450    if isinstance(output, list):  # multiple outputs: split the prediction channels
451        for out, channel_slice in output:
452            this_bb = bb if out.ndim == ndim else (slice(None),) + bb
453            out[this_bb] = prediction[channel_slice]
454    else:  # single output array
455        if output.ndim == ndim + 1:
456            bb = (slice(None),) + bb
457        output[bb] = prediction
458
459
460def _concurrent_write_safe(arr, block_shape, start):
461    """@private
462    Whether `arr` can be written to from multiple threads concurrently for the given block grid.
463
464    - numpy arrays are always safe (writers touch disjoint in-memory regions).
465    - hdf5 datasets are never safe (h5py is not thread-safe for concurrent writes).
466    - zarr / n5 datasets are safe iff the block grid is aligned with the chunks (and the shards,
467      for zarr v3), so that each chunk/shard is written by exactly one block.
468    - unknown / unchunked backends are treated conservatively as unsafe.
469    """
470    if isinstance(arr, np.ndarray):
471        return True
472
473    module = type(arr).__module__
474    if module.startswith("h5py"):
475        return False
476
477    chunks = getattr(arr, "chunks", None)
478    if chunks is None:  # unknown backend or unchunked -> be conservative
479        return False
480
481    # zarr v3 exposes the shard shape via .shards (None if not sharded); the shard is the atomic
482    # write unit when present, otherwise the chunk is. getattr covers z5py / older zarr (no shards).
483    shards = getattr(arr, "shards", None)
484    unit = shards if shards is not None else chunks
485
486    # compare only the spatial axes: every block writes the full channel range at a disjoint
487    # spatial bounding box, so channel-axis chunking never causes a write conflict.
488    ndim = len(block_shape)
489    unit_spatial = tuple(unit[-ndim:])
490    if any(bs % u != 0 for bs, u in zip(block_shape, unit_spatial)):
491        return False
492    if any(s % u != 0 for s, u in zip(start, unit_spatial)):
493        return False
494    return True
495
496
497def predict_with_halo_pipelined(
498    input_: ArrayLike,
499    model: torch.nn.Module,
500    gpu_ids: List[Union[str, int]],
501    block_shape: Tuple[int, ...],
502    halo: Tuple[int, ...],
503    output: Optional[Union[ArrayLike, List[Tuple[ArrayLike, slice]]]] = None,
504    preprocess: Callable[[Union[torch.Tensor, np.ndarray]], Union[torch.Tensor, np.ndarray]] = standardize,
505    postprocess: Callable[[np.ndarray], np.ndarray] = None,
506    with_channels: bool = False,
507    skip_block: Callable[[Any], bool] = None,
508    mask: Optional[ArrayLike] = None,
509    disable_tqdm: bool = False,
510    tqdm_desc: str = "predict with halo (pipelined)",
511    prediction_function: Optional[Callable] = None,
512    roi: Optional[Tuple[slice]] = None,
513    iter_list: Optional[List[int]] = None,
514    batch_size: int = 1,
515    num_prefetch_workers: int = 4,
516    queue_size: Optional[int] = None,
517    num_write_workers: int = 1,
518    write_queue_size: Optional[int] = None,
519    grid_shift: Optional[Tuple[float, ...]] = None,
520) -> ArrayLike:
521    """Run block-wise network prediction with a halo, pipelined for higher GPU throughput.
522
523    This is an alternate implementation of `predict_with_halo` that decouples block
524    loading, GPU prediction and output writing into a producer-consumer pipeline
525    connected by queues:
526
527        producers (CPU threads: load + preprocess) -> input queue
528          -> consumer(s), one per GPU (stack a batch, predict, unstack) -> output queue
529          -> writer thread(s) (postprocess + write).
530
531    While the GPU works on one batch, the prefetch workers load and preprocess the
532    next blocks and the writer drains finished predictions, keeping the GPU fed.
533    Blocks can additionally be stacked into batches for one forward pass via `batch_size`.
534
535    The pipeline is thread-based (not multiprocessing) so that lazy hdf5/zarr/n5 inputs
536    (whose file handles are not fork/pickle-safe) work, and so that writers can share the
537    output array directly. Note that heavy *Python-level* `preprocess`/`postprocess`
538    callbacks will not parallelize across prefetch workers due to the GIL; the default
539    `standardize` is numpy-vectorized and releases the GIL.
540
541    Args:
542        input_: The input data, can be a numpy array, a hdf5/zarr/z5py dataset or similar.
543        model: The network.
544        gpu_ids: List of device ids to use for prediction. To run prediction on the CPU, pass `["cpu"]`.
545            One prediction consumer thread (with its own model replica) is run per device.
546        block_shape: The shape of the inner block to use for prediction.
547        halo: The shape of the halo to use for prediction.
548        output: The output data, will be allocated if None is passed.
549            Instead of a single output, this can also be a list of outputs and a slice for the corresponding channel.
550        preprocess: Function to preprocess input data before passing it to the network.
551        postprocess: Function to postprocess the network predictions.
552        with_channels: Whether the input has a channel axis.
553        skip_block: Function to evaluate whether a given input block will be skipped.
554        mask: Elements outside the mask will be ignored in the prediction.
555        disable_tqdm: Flag that allows to disable tqdm output (e.g. if function is called multiple times).
556        tqdm_desc: Description shown by the tqdm output.
557        prediction_function: A wrapper function for prediction to enable custom prediction procedures.
558            It must operate on the leading batch axis; with the default `batch_size=1` it does not need changes.
559        roi: A region of interest of the input for which to run prediction.
560        iter_list: Optional list of block ids to iterate over.
561        batch_size: The number of blocks stacked into a single forward pass. Trades GPU memory for throughput.
562        num_prefetch_workers: The number of CPU threads used to load and preprocess blocks.
563        queue_size: The maximum size of the input (prefetch) queue. Provides backpressure to bound memory use.
564            If None, a value derived from the number of devices and `batch_size` is used.
565        num_write_workers: The number of threads used to write predictions. Values > 1 are safe for in-memory
566            numpy outputs, and for zarr/n5 outputs whose chunks (and shards, for zarr v3) are aligned with
567            block_shape. For hdf5, misaligned zarr/n5, or other outputs this is automatically clamped to 1.
568        write_queue_size: The maximum size of the output (write) queue. If None, a default is used.
569        grid_shift: Not supported by this function; raises NotImplementedError if passed. Use `predict_with_halo`.
570
571    Returns:
572        The model output.
573    """
574    if grid_shift is not None:
575        raise NotImplementedError(
576            "grid_shift is not supported by predict_with_halo_pipelined. "
577            "Use predict_with_halo for grid_shift, or pre-pad the input and use roi."
578        )
579
580    batch_size = max(1, int(batch_size))
581    num_prefetch_workers = max(1, int(num_prefetch_workers))
582    num_write_workers = max(1, int(num_write_workers))
583
584    devices = [torch.device(gpu) for gpu in gpu_ids]
585    models = [
586        (model if next(model.parameters()).device == device else deepcopy(model).to(device), device)
587        for device in devices
588    ]
589    n_consumers = len(devices)
590
591    shape0 = input_.shape
592    shape_spatial = shape0[1:] if with_channels else shape0
593    ndim = len(shape_spatial)
594    assert len(block_shape) == len(halo) == ndim
595
596    # blocking
597    if roi is None:
598        block_start = [0] * ndim
599        blocking = bic.utils.Blocking(block_start, list(shape_spatial), block_shape)
600    else:
601        assert len(roi) == ndim
602        block_start = [0 if ro.start is None else ro.start for ro in roi]
603        blocking_stop = [sh if ro.stop is None else ro.stop for ro, sh in zip(roi, shape_spatial)]
604        blocking = bic.utils.Blocking(block_start, blocking_stop, block_shape)
605
606    # output allocation
607    if output is None:
608        n_out = models[0][0].out_channels
609        output = np.zeros((n_out,) + tuple(shape_spatial), dtype="float32")
610
611    # guard against unsafe concurrent writes: numpy is always safe (disjoint regions),
612    # zarr/n5 are safe when their chunks/shards are aligned with the blocks, hdf5 is not.
613    if num_write_workers > 1:
614        out_arrays = [o for o, _ in output] if isinstance(output, list) else [output]
615        if any(not _concurrent_write_safe(o, block_shape, block_start) for o in out_arrays):
616            warnings.warn(
617                "num_write_workers > 1 requires either an in-memory numpy output or a zarr/n5 "
618                "output whose chunks (and shards, for zarr v3) are aligned with block_shape; "
619                "falling back to a single writer. HDF5 outputs are never safe for concurrent writes."
620            )
621            num_write_workers = 1
622
623    # queue sizes
624    if queue_size is None:
625        queue_size = max(2 * n_consumers * batch_size, 2 * batch_size)
626    queue_size = max(queue_size, batch_size)
627    if write_queue_size is None:
628        write_queue_size = max(2 * n_consumers, 4)
629
630    n_blocks = blocking.number_of_blocks
631    iteration_ids = list(range(n_blocks)) if iter_list is None else list(iter_list)
632    total = len(iteration_ids)
633
634    # pre-fill the block-id queue with all ids followed by one STOP per producer
635    id_queue = queue.Queue()
636    for bid in iteration_ids:
637        id_queue.put(bid)
638    for _ in range(num_prefetch_workers):
639        id_queue.put(_STOP)
640
641    input_queue = queue.Queue(maxsize=queue_size)
642    output_queue = queue.Queue(maxsize=write_queue_size)
643
644    stop_event = threading.Event()
645    error_box = []
646    error_lock = threading.Lock()
647    pbar = tqdm(total=total, disable=disable_tqdm, desc=tqdm_desc)
648    # The progress bar can be a GUI object (napari), which only the calling thread may update.
649    # The workers count the finished blocks and the calling thread reports them.
650    finished_blocks = _AtomicCounter(0)
651    n_reported = 0
652
653    remaining_producers = _AtomicCounter(num_prefetch_workers)
654    remaining_consumers = _AtomicCounter(n_consumers)
655
656    def record_error(exc):
657        with error_lock:
658            if not error_box:
659                error_box.append(exc)
660        stop_event.set()
661
662    def producer():
663        try:
664            while True:
665                bid = id_queue.get()
666                if bid is _STOP or stop_event.is_set():
667                    break
668                block = blocking.get_block(bid)
669                result = _prepare_block_input(
670                    input_, mask, block, block_shape, halo, with_channels, skip_block, preprocess
671                )
672                if result is _SKIP:
673                    finished_blocks.increment()
674                    continue
675                tensor, mask_block, inner_bb = result
676                _safe_put(input_queue, _BlockJob(block, inner_bb, mask_block, tensor), stop_event)
677        except _Aborted:
678            pass
679        except Exception as e:  # noqa
680            record_error(e)
681        finally:
682            # the last producer to finish signals the consumers (skipped on the abort path,
683            # where consumers unwind via _safe_get instead)
684            if remaining_producers.decrement() == 0 and not stop_event.is_set():
685                try:
686                    for _ in range(n_consumers):
687                        _safe_put(input_queue, _STOP, stop_event)
688                except _Aborted:
689                    pass
690
691    def consumer(worker_id):
692        net, device = models[worker_id]
693        try:
694            while True:
695                jobs = []
696                got_stop = False
697                while len(jobs) < batch_size:
698                    item = _safe_get(input_queue, stop_event)
699                    if item is _STOP:
700                        got_stop = True
701                        break
702                    jobs.append(item)
703
704                if jobs:  # run (possibly partial) batch
705                    batch = torch.cat([job.tensor for job in jobs], dim=0).to(device)
706                    with torch.no_grad():
707                        prediction = net(batch) if prediction_function is None \
708                            else prediction_function(net, batch)
709                    if not torch.is_tensor(prediction):  # list/tuple of outputs -> take the first
710                        prediction = prediction[0]
711                    prediction = prediction.cpu().numpy()
712                    for i, job in enumerate(jobs):
713                        job.prediction = np.array(prediction[i])
714                        job.tensor = None
715                        _safe_put(output_queue, job, stop_event)
716
717                if got_stop:
718                    break
719        except _Aborted:
720            pass
721        except Exception as e:  # noqa
722            record_error(e)
723        finally:
724            if remaining_consumers.decrement() == 0 and not stop_event.is_set():
725                try:
726                    for _ in range(num_write_workers):
727                        _safe_put(output_queue, _STOP, stop_event)
728                except _Aborted:
729                    pass
730
731    def writer():
732        try:
733            while True:
734                job = _safe_get(output_queue, stop_event)
735                if job is _STOP:
736                    break
737                _write_prediction(
738                    job.prediction, job.block, output, ndim, job.mask_block, job.inner_bb, postprocess
739                )
740                finished_blocks.increment()
741        except _Aborted:
742            pass
743        except Exception as e:  # noqa
744            record_error(e)
745
746    writers = [threading.Thread(target=writer, name=f"predict-writer-{i}") for i in range(num_write_workers)]
747    consumers = [threading.Thread(target=consumer, args=(i,), name=f"predict-consumer-{i}")
748                 for i in range(n_consumers)]
749    producers = [threading.Thread(target=producer, name=f"predict-producer-{i}")
750                 for i in range(num_prefetch_workers)]
751    threads = writers + consumers + producers
752
753    def report_progress():
754        nonlocal n_reported
755        n_finished = finished_blocks.value
756        if n_finished > n_reported:
757            pbar.update(n_finished - n_reported)
758            n_reported = n_finished
759
760    try:
761        for t in threads:
762            t.start()
763
764        for t in producers + consumers + writers:
765            while t.is_alive():
766                t.join(timeout=0.1)
767                report_progress()
768        report_progress()
769    finally:
770        stop_event.set()
771        for t in threads:
772            t.join()
773        pbar.close()
774
775    if error_box:
776        raise error_box[0]
777
778    return output
def predict_with_padding( model: torch.nn.modules.module.Module, input_: numpy.ndarray, min_divisible: Tuple[int, ...], device: Union[torch.device, str, NoneType] = None, with_channels: bool = False, prediction_function: Callable[[Any], Any] = None) -> numpy.ndarray:
22def predict_with_padding(
23    model: torch.nn.Module,
24    input_: np.ndarray,
25    min_divisible: Tuple[int, ...],
26    device: Optional[Union[torch.device, str]] = None,
27    with_channels: bool = False,
28    prediction_function: Callable[[Any], Any] = None
29) -> np.ndarray:
30    """Run prediction with padding for a model that can only deal with inputs divisible by specific factors.
31
32    Args:
33        model: The model.
34        input_: The input for prediction.
35        min_divisible: The minimal factors the input shape must be divisible by.
36            For example, (16, 16) for a model that needs 2D inputs divisible by at least 16 pixels.
37        device: The device of the model. If not given, will be derived from the model parameters.
38        with_channels: Whether the input data contains channels.
39        prediction_function: A wrapper function for prediction to enable custom prediction procedures.
40
41    Returns:
42        np.ndarray: The ouptut of the model.
43    """
44    if with_channels:
45        assert len(min_divisible) + 1 == input_.ndim, f"{min_divisible}, {input_.ndim}"
46        min_divisible_ = (1,) + min_divisible
47    else:
48        assert len(min_divisible) == input_.ndim
49        min_divisible_ = min_divisible
50
51    if any(sh % md != 0 for sh, md in zip(input_.shape, min_divisible_)):
52        pad_width = tuple(
53            (0, 0 if sh % md == 0 else md - sh % md)
54            for sh, md in zip(input_.shape, min_divisible_)
55        )
56        crop_padding = tuple(slice(0, sh) for sh in input_.shape)
57        input_ = np.pad(input_, pad_width, mode="reflect")
58    else:
59        crop_padding = None
60
61    ndim = input_.ndim
62    ndim_model = 1 + ndim if with_channels else 2 + ndim
63
64    if device is None:
65        device = next(model.parameters()).device
66
67    expand_dim = (None,) * (ndim_model - ndim)
68    with torch.no_grad():
69        model_input = torch.from_numpy(input_[expand_dim]).to(device)
70        output = model(model_input) if prediction_function is None else prediction_function(model, model_input)
71        output = output.cpu().numpy()
72
73    if crop_padding is not None:
74        crop_padding = (slice(None),) * (output.ndim - len(crop_padding)) + crop_padding
75        output = output[crop_padding]
76
77    return output

Run prediction with padding for a model that can only deal with inputs divisible by specific factors.

Arguments:
  • model: The model.
  • input_: The input for prediction.
  • min_divisible: The minimal factors the input shape must be divisible by. For example, (16, 16) for a model that needs 2D inputs divisible by at least 16 pixels.
  • device: The device of the model. If not given, will be derived from the model parameters.
  • with_channels: Whether the input data contains channels.
  • prediction_function: A wrapper function for prediction to enable custom prediction procedures.
Returns:

np.ndarray: The ouptut of the model.

def predict_with_halo( input_: Union[numpy._typing._array_like._Buffer, numpy._typing._array_like._SupportsArray[numpy.dtype[Any]], numpy._typing._nested_sequence._NestedSequence[numpy._typing._array_like._SupportsArray[numpy.dtype[Any]]], complex, bytes, str, numpy._typing._nested_sequence._NestedSequence[complex | bytes | str]], model: torch.nn.modules.module.Module, gpu_ids: List[Union[str, int]], block_shape: Tuple[int, ...], halo: Tuple[int, ...], output: Union[numpy._typing._array_like._Buffer, numpy._typing._array_like._SupportsArray[numpy.dtype[Any]], numpy._typing._nested_sequence._NestedSequence[numpy._typing._array_like._SupportsArray[numpy.dtype[Any]]], complex, bytes, str, numpy._typing._nested_sequence._NestedSequence[complex | bytes | str], List[Tuple[Union[numpy._typing._array_like._Buffer, numpy._typing._array_like._SupportsArray[numpy.dtype[Any]], numpy._typing._nested_sequence._NestedSequence[numpy._typing._array_like._SupportsArray[numpy.dtype[Any]]], complex, bytes, str, numpy._typing._nested_sequence._NestedSequence[complex | bytes | str]], slice]], NoneType] = None, preprocess: Callable[[Union[torch.Tensor, numpy.ndarray]], Union[torch.Tensor, numpy.ndarray]] = <function standardize>, postprocess: Callable[[numpy.ndarray], numpy.ndarray] = None, with_channels: bool = False, skip_block: Callable[[Any], bool] = None, mask: Union[numpy._typing._array_like._Buffer, numpy._typing._array_like._SupportsArray[numpy.dtype[Any]], numpy._typing._nested_sequence._NestedSequence[numpy._typing._array_like._SupportsArray[numpy.dtype[Any]]], complex, bytes, str, numpy._typing._nested_sequence._NestedSequence[complex | bytes | str], NoneType] = None, disable_tqdm: bool = False, tqdm_desc: str = 'predict with halo', prediction_function: Optional[Callable] = None, roi: Optional[Tuple[slice]] = None, iter_list: Optional[List[int]] = None, grid_shift: Optional[Tuple[float, ...]] = None) -> Union[numpy._typing._array_like._Buffer, numpy._typing._array_like._SupportsArray[numpy.dtype[Any]], numpy._typing._nested_sequence._NestedSequence[numpy._typing._array_like._SupportsArray[numpy.dtype[Any]]], complex, bytes, str, numpy._typing._nested_sequence._NestedSequence[complex | bytes | str]]:
146def predict_with_halo(
147    input_: ArrayLike,
148    model: torch.nn.Module,
149    gpu_ids: List[Union[str, int]],
150    block_shape: Tuple[int, ...],
151    halo: Tuple[int, ...],
152    output: Optional[Union[ArrayLike, List[Tuple[ArrayLike, slice]]]] = None,
153    preprocess: Callable[[Union[torch.Tensor, np.ndarray]], Union[torch.Tensor, np.ndarray]] = standardize,
154    postprocess: Callable[[np.ndarray], np.ndarray] = None,
155    with_channels: bool = False,
156    skip_block: Callable[[Any], bool] = None,
157    mask: Optional[ArrayLike] = None,
158    disable_tqdm: bool = False,
159    tqdm_desc: str = "predict with halo",
160    prediction_function: Optional[Callable] = None,
161    roi: Optional[Tuple[slice]] = None,
162    iter_list: Optional[List[int]] = None,
163    grid_shift: Optional[Tuple[float, ...]] = None,
164) -> ArrayLike:
165    """Run block-wise network prediction with a halo.
166
167    Args:
168        input_: The input data, can be a numpy array, a hdf5/zarr/z5py dataset or similar
169        model: The network.
170        gpu_ids: List of device ids to use for prediction. To run prediction on the CPU, pass `["cpu"]`.
171        block_shape: The shape of the inner block to use for prediction.
172        halo: The shape of the halo to use for prediction
173        output: The output data, will be allocated if None is passed.
174            Instead of a single output, this can also be a list of outputs and a slice for the corresponding channel.
175        preprocess: Function to preprocess input data before passing it to the network.
176        postprocess: Function to postprocess the network predictions.
177        with_channels: Whether the input has a channel axis.
178        skip_block: Function to evaluate whether a given input block will be skipped.
179        mask: Elements outside the mask will be ignored in the prediction.
180        disable_tqdm: Flag that allows to disable tqdm output (e.g. if function is called multiple times).
181        tqdm_desc: Fescription shown by the tqdm output.
182        prediction_function: A wrapper function for prediction to enable custom prediction procedures.
183        roi: A region of interest of the input for which to run prediction.
184        iter_list: Optional list of block ids to iterate over.
185        grid_shift: Per-axis fractional shift of the grid in units of the block size. E.g. (0, 0.25, 0).
186    Returns:
187        The model output.
188    """
189    devices = [torch.device(gpu) for gpu in gpu_ids]
190    models = [
191        (model if next(model.parameters()).device == device else deepcopy(model).to(device), device)
192        for device in devices
193    ]
194    n_workers = len(gpu_ids)
195
196    # original shape (spatial only)
197    shape0 = input_.shape
198    shape_spatial0 = shape0[1:] if with_channels else shape0
199    ndim = len(shape_spatial0)
200    assert len(block_shape) == len(halo) == ndim
201
202    # apply grid_shift via padding+cropping (zero padding)
203    input_eff = input_
204    mask_eff = mask
205
206    if grid_shift is not None:
207        assert len(grid_shift) == ndim, "grid_shift must match number of spatial dims"
208        pad_vox = tuple(int(np.rint(abs(gs) * bs)) for gs, bs in zip(grid_shift, block_shape))
209
210        if not isinstance(input_eff, np.ndarray):
211            raise TypeError("grid_shift padding currently requires input_ to be a numpy array")
212
213        input_eff, pad_left = _pad_for_shift_left(input_eff, pad_vox, with_channels=with_channels, mode="constant",
214                                                  constant_values=0)
215
216        if mask_eff is not None:
217            if not isinstance(mask_eff, np.ndarray):
218                raise TypeError("grid_shift padding currently requires mask to be a numpy array")
219            mask_eff, _ = _pad_for_shift_left(mask_eff, pad_vox, with_channels=False, mode="constant",
220                                              constant_values=0)
221    else:
222        pad_left = (0,) * ndim
223
224    # shapes after shift-padding
225    shape_eff = input_eff.shape
226    shape_spatial_eff = shape_eff[1:] if with_channels else shape_eff
227
228    # blocking (on the padded input)
229    if roi is None:
230        blocking = bic.utils.Blocking([0] * ndim, list(shape_spatial_eff), block_shape)
231    else:
232        assert len(roi) == ndim
233        blocking_start = [0 if ro.start is None else ro.start for ro in roi]
234        blocking_stop = [sh if ro.stop is None else ro.stop for ro, sh in zip(roi, shape_spatial_eff)]
235        blocking = bic.utils.Blocking(blocking_start, blocking_stop, block_shape)
236
237    # output allocation (for padded shape)
238    if output is None:
239        n_out = models[0][0].out_channels
240        output = np.zeros((n_out,) + tuple(shape_spatial_eff), dtype="float32")
241    elif grid_shift:
242        raise ValueError(
243            "grid_shift is not supported together with a user-provided `output`, because "
244            "grid_shift requires internal zero-padding and a final cropping step. "
245            "Pass `output=None` (let this function allocate the output) or disable `grid_shift`. "
246            "Or pad the input manually beforehand."
247        )
248
249    def predict_block(block_id):
250        worker_id = block_id % n_workers
251        net, device = models[worker_id]
252
253        with torch.no_grad():
254            block = blocking.get_block(block_id)
255            offset = [beg for beg in block.begin]
256            inner_bb = tuple(slice(ha, ha + bs) for ha, bs in zip(halo, block.shape))
257
258            if mask_eff is not None:
259                mask_block, _ = _load_block(mask_eff, offset, block_shape, halo, with_channels=False)
260                mask_block = mask_block[inner_bb].astype("bool")
261                if mask_block.sum() == 0:
262                    return
263
264            inp, _ = _load_block(input_eff, offset, block_shape, halo, with_channels=with_channels)
265
266            if skip_block is not None and skip_block(inp):
267                return
268
269            if preprocess is not None:
270                inp = preprocess(inp)
271
272            # add (channel) and batch axis
273            expand_dims = np.s_[None] if with_channels else np.s_[None, None]
274            inp = torch.from_numpy(inp[expand_dims]).to(device)
275
276            prediction = net(inp) if prediction_function is None else prediction_function(net, inp)
277
278            # allow for list of tensors
279            try:
280                prediction = prediction.cpu().numpy().squeeze(0)
281            except AttributeError:
282                prediction = prediction[0]
283                prediction = prediction.cpu().numpy().squeeze(0)
284
285            if postprocess is not None:
286                prediction = postprocess(prediction)
287
288            if prediction.ndim == ndim + 1:
289                inner_bb_pred = (slice(None),) + inner_bb
290            else:
291                inner_bb_pred = inner_bb
292            prediction = prediction[inner_bb_pred]
293
294            if mask_eff is not None:
295                if prediction.ndim == ndim + 1:
296                    mb = np.broadcast_to(mask_block[None], prediction.shape)
297                else:
298                    mb = mask_block
299                prediction[~mb] = 0
300
301            bb = tuple(slice(beg, end) for beg, end in zip(block.begin, block.end))
302            if isinstance(output, list):  # we have multiple outputs and split the prediction channels
303                for out, channel_slice in output:
304                    this_bb = bb if out.ndim == ndim else (slice(None),) + bb
305                    out[this_bb] = prediction[channel_slice]
306            else:  # we only have a single output array
307                if output.ndim == ndim + 1:
308                    bb = (slice(None),) + bb
309                output[bb] = prediction
310
311    n_blocks = blocking.number_of_blocks
312    iteration_ids = range(n_blocks) if iter_list is None else np.array(iter_list)
313
314    with futures.ThreadPoolExecutor(n_workers) as tp:
315        list(tqdm(tp.map(predict_block, iteration_ids),
316                  total=len(iteration_ids),
317                  disable=disable_tqdm,
318                  desc=tqdm_desc))
319
320    # crop away the shift padding so the returned output matches original shape
321    if grid_shift is not None:
322        output = _crop_after_shift_left(output, pad_left, with_channels=(output.ndim == ndim+1),
323                                        original_shape_spatial=tuple(shape_spatial0))
324
325    return output

Run block-wise network prediction with a halo.

Arguments:
  • input_: The input data, can be a numpy array, a hdf5/zarr/z5py dataset or similar
  • model: The network.
  • gpu_ids: List of device ids to use for prediction. To run prediction on the CPU, pass ["cpu"].
  • block_shape: The shape of the inner block to use for prediction.
  • halo: The shape of the halo to use for prediction
  • output: The output data, will be allocated if None is passed. Instead of a single output, this can also be a list of outputs and a slice for the corresponding channel.
  • preprocess: Function to preprocess input data before passing it to the network.
  • postprocess: Function to postprocess the network predictions.
  • with_channels: Whether the input has a channel axis.
  • skip_block: Function to evaluate whether a given input block will be skipped.
  • mask: Elements outside the mask will be ignored in the prediction.
  • disable_tqdm: Flag that allows to disable tqdm output (e.g. if function is called multiple times).
  • tqdm_desc: Fescription shown by the tqdm output.
  • prediction_function: A wrapper function for prediction to enable custom prediction procedures.
  • roi: A region of interest of the input for which to run prediction.
  • iter_list: Optional list of block ids to iterate over.
  • grid_shift: Per-axis fractional shift of the grid in units of the block size. E.g. (0, 0.25, 0).
Returns:

The model output.

def predict_with_halo_pipelined( input_: Union[numpy._typing._array_like._Buffer, numpy._typing._array_like._SupportsArray[numpy.dtype[Any]], numpy._typing._nested_sequence._NestedSequence[numpy._typing._array_like._SupportsArray[numpy.dtype[Any]]], complex, bytes, str, numpy._typing._nested_sequence._NestedSequence[complex | bytes | str]], model: torch.nn.modules.module.Module, gpu_ids: List[Union[str, int]], block_shape: Tuple[int, ...], halo: Tuple[int, ...], output: Union[numpy._typing._array_like._Buffer, numpy._typing._array_like._SupportsArray[numpy.dtype[Any]], numpy._typing._nested_sequence._NestedSequence[numpy._typing._array_like._SupportsArray[numpy.dtype[Any]]], complex, bytes, str, numpy._typing._nested_sequence._NestedSequence[complex | bytes | str], List[Tuple[Union[numpy._typing._array_like._Buffer, numpy._typing._array_like._SupportsArray[numpy.dtype[Any]], numpy._typing._nested_sequence._NestedSequence[numpy._typing._array_like._SupportsArray[numpy.dtype[Any]]], complex, bytes, str, numpy._typing._nested_sequence._NestedSequence[complex | bytes | str]], slice]], NoneType] = None, preprocess: Callable[[Union[torch.Tensor, numpy.ndarray]], Union[torch.Tensor, numpy.ndarray]] = <function standardize>, postprocess: Callable[[numpy.ndarray], numpy.ndarray] = None, with_channels: bool = False, skip_block: Callable[[Any], bool] = None, mask: Union[numpy._typing._array_like._Buffer, numpy._typing._array_like._SupportsArray[numpy.dtype[Any]], numpy._typing._nested_sequence._NestedSequence[numpy._typing._array_like._SupportsArray[numpy.dtype[Any]]], complex, bytes, str, numpy._typing._nested_sequence._NestedSequence[complex | bytes | str], NoneType] = None, disable_tqdm: bool = False, tqdm_desc: str = 'predict with halo (pipelined)', prediction_function: Optional[Callable] = None, roi: Optional[Tuple[slice]] = None, iter_list: Optional[List[int]] = None, batch_size: int = 1, num_prefetch_workers: int = 4, queue_size: Optional[int] = None, num_write_workers: int = 1, write_queue_size: Optional[int] = None, grid_shift: Optional[Tuple[float, ...]] = None) -> Union[numpy._typing._array_like._Buffer, numpy._typing._array_like._SupportsArray[numpy.dtype[Any]], numpy._typing._nested_sequence._NestedSequence[numpy._typing._array_like._SupportsArray[numpy.dtype[Any]]], complex, bytes, str, numpy._typing._nested_sequence._NestedSequence[complex | bytes | str]]:
498def predict_with_halo_pipelined(
499    input_: ArrayLike,
500    model: torch.nn.Module,
501    gpu_ids: List[Union[str, int]],
502    block_shape: Tuple[int, ...],
503    halo: Tuple[int, ...],
504    output: Optional[Union[ArrayLike, List[Tuple[ArrayLike, slice]]]] = None,
505    preprocess: Callable[[Union[torch.Tensor, np.ndarray]], Union[torch.Tensor, np.ndarray]] = standardize,
506    postprocess: Callable[[np.ndarray], np.ndarray] = None,
507    with_channels: bool = False,
508    skip_block: Callable[[Any], bool] = None,
509    mask: Optional[ArrayLike] = None,
510    disable_tqdm: bool = False,
511    tqdm_desc: str = "predict with halo (pipelined)",
512    prediction_function: Optional[Callable] = None,
513    roi: Optional[Tuple[slice]] = None,
514    iter_list: Optional[List[int]] = None,
515    batch_size: int = 1,
516    num_prefetch_workers: int = 4,
517    queue_size: Optional[int] = None,
518    num_write_workers: int = 1,
519    write_queue_size: Optional[int] = None,
520    grid_shift: Optional[Tuple[float, ...]] = None,
521) -> ArrayLike:
522    """Run block-wise network prediction with a halo, pipelined for higher GPU throughput.
523
524    This is an alternate implementation of `predict_with_halo` that decouples block
525    loading, GPU prediction and output writing into a producer-consumer pipeline
526    connected by queues:
527
528        producers (CPU threads: load + preprocess) -> input queue
529          -> consumer(s), one per GPU (stack a batch, predict, unstack) -> output queue
530          -> writer thread(s) (postprocess + write).
531
532    While the GPU works on one batch, the prefetch workers load and preprocess the
533    next blocks and the writer drains finished predictions, keeping the GPU fed.
534    Blocks can additionally be stacked into batches for one forward pass via `batch_size`.
535
536    The pipeline is thread-based (not multiprocessing) so that lazy hdf5/zarr/n5 inputs
537    (whose file handles are not fork/pickle-safe) work, and so that writers can share the
538    output array directly. Note that heavy *Python-level* `preprocess`/`postprocess`
539    callbacks will not parallelize across prefetch workers due to the GIL; the default
540    `standardize` is numpy-vectorized and releases the GIL.
541
542    Args:
543        input_: The input data, can be a numpy array, a hdf5/zarr/z5py dataset or similar.
544        model: The network.
545        gpu_ids: List of device ids to use for prediction. To run prediction on the CPU, pass `["cpu"]`.
546            One prediction consumer thread (with its own model replica) is run per device.
547        block_shape: The shape of the inner block to use for prediction.
548        halo: The shape of the halo to use for prediction.
549        output: The output data, will be allocated if None is passed.
550            Instead of a single output, this can also be a list of outputs and a slice for the corresponding channel.
551        preprocess: Function to preprocess input data before passing it to the network.
552        postprocess: Function to postprocess the network predictions.
553        with_channels: Whether the input has a channel axis.
554        skip_block: Function to evaluate whether a given input block will be skipped.
555        mask: Elements outside the mask will be ignored in the prediction.
556        disable_tqdm: Flag that allows to disable tqdm output (e.g. if function is called multiple times).
557        tqdm_desc: Description shown by the tqdm output.
558        prediction_function: A wrapper function for prediction to enable custom prediction procedures.
559            It must operate on the leading batch axis; with the default `batch_size=1` it does not need changes.
560        roi: A region of interest of the input for which to run prediction.
561        iter_list: Optional list of block ids to iterate over.
562        batch_size: The number of blocks stacked into a single forward pass. Trades GPU memory for throughput.
563        num_prefetch_workers: The number of CPU threads used to load and preprocess blocks.
564        queue_size: The maximum size of the input (prefetch) queue. Provides backpressure to bound memory use.
565            If None, a value derived from the number of devices and `batch_size` is used.
566        num_write_workers: The number of threads used to write predictions. Values > 1 are safe for in-memory
567            numpy outputs, and for zarr/n5 outputs whose chunks (and shards, for zarr v3) are aligned with
568            block_shape. For hdf5, misaligned zarr/n5, or other outputs this is automatically clamped to 1.
569        write_queue_size: The maximum size of the output (write) queue. If None, a default is used.
570        grid_shift: Not supported by this function; raises NotImplementedError if passed. Use `predict_with_halo`.
571
572    Returns:
573        The model output.
574    """
575    if grid_shift is not None:
576        raise NotImplementedError(
577            "grid_shift is not supported by predict_with_halo_pipelined. "
578            "Use predict_with_halo for grid_shift, or pre-pad the input and use roi."
579        )
580
581    batch_size = max(1, int(batch_size))
582    num_prefetch_workers = max(1, int(num_prefetch_workers))
583    num_write_workers = max(1, int(num_write_workers))
584
585    devices = [torch.device(gpu) for gpu in gpu_ids]
586    models = [
587        (model if next(model.parameters()).device == device else deepcopy(model).to(device), device)
588        for device in devices
589    ]
590    n_consumers = len(devices)
591
592    shape0 = input_.shape
593    shape_spatial = shape0[1:] if with_channels else shape0
594    ndim = len(shape_spatial)
595    assert len(block_shape) == len(halo) == ndim
596
597    # blocking
598    if roi is None:
599        block_start = [0] * ndim
600        blocking = bic.utils.Blocking(block_start, list(shape_spatial), block_shape)
601    else:
602        assert len(roi) == ndim
603        block_start = [0 if ro.start is None else ro.start for ro in roi]
604        blocking_stop = [sh if ro.stop is None else ro.stop for ro, sh in zip(roi, shape_spatial)]
605        blocking = bic.utils.Blocking(block_start, blocking_stop, block_shape)
606
607    # output allocation
608    if output is None:
609        n_out = models[0][0].out_channels
610        output = np.zeros((n_out,) + tuple(shape_spatial), dtype="float32")
611
612    # guard against unsafe concurrent writes: numpy is always safe (disjoint regions),
613    # zarr/n5 are safe when their chunks/shards are aligned with the blocks, hdf5 is not.
614    if num_write_workers > 1:
615        out_arrays = [o for o, _ in output] if isinstance(output, list) else [output]
616        if any(not _concurrent_write_safe(o, block_shape, block_start) for o in out_arrays):
617            warnings.warn(
618                "num_write_workers > 1 requires either an in-memory numpy output or a zarr/n5 "
619                "output whose chunks (and shards, for zarr v3) are aligned with block_shape; "
620                "falling back to a single writer. HDF5 outputs are never safe for concurrent writes."
621            )
622            num_write_workers = 1
623
624    # queue sizes
625    if queue_size is None:
626        queue_size = max(2 * n_consumers * batch_size, 2 * batch_size)
627    queue_size = max(queue_size, batch_size)
628    if write_queue_size is None:
629        write_queue_size = max(2 * n_consumers, 4)
630
631    n_blocks = blocking.number_of_blocks
632    iteration_ids = list(range(n_blocks)) if iter_list is None else list(iter_list)
633    total = len(iteration_ids)
634
635    # pre-fill the block-id queue with all ids followed by one STOP per producer
636    id_queue = queue.Queue()
637    for bid in iteration_ids:
638        id_queue.put(bid)
639    for _ in range(num_prefetch_workers):
640        id_queue.put(_STOP)
641
642    input_queue = queue.Queue(maxsize=queue_size)
643    output_queue = queue.Queue(maxsize=write_queue_size)
644
645    stop_event = threading.Event()
646    error_box = []
647    error_lock = threading.Lock()
648    pbar = tqdm(total=total, disable=disable_tqdm, desc=tqdm_desc)
649    # The progress bar can be a GUI object (napari), which only the calling thread may update.
650    # The workers count the finished blocks and the calling thread reports them.
651    finished_blocks = _AtomicCounter(0)
652    n_reported = 0
653
654    remaining_producers = _AtomicCounter(num_prefetch_workers)
655    remaining_consumers = _AtomicCounter(n_consumers)
656
657    def record_error(exc):
658        with error_lock:
659            if not error_box:
660                error_box.append(exc)
661        stop_event.set()
662
663    def producer():
664        try:
665            while True:
666                bid = id_queue.get()
667                if bid is _STOP or stop_event.is_set():
668                    break
669                block = blocking.get_block(bid)
670                result = _prepare_block_input(
671                    input_, mask, block, block_shape, halo, with_channels, skip_block, preprocess
672                )
673                if result is _SKIP:
674                    finished_blocks.increment()
675                    continue
676                tensor, mask_block, inner_bb = result
677                _safe_put(input_queue, _BlockJob(block, inner_bb, mask_block, tensor), stop_event)
678        except _Aborted:
679            pass
680        except Exception as e:  # noqa
681            record_error(e)
682        finally:
683            # the last producer to finish signals the consumers (skipped on the abort path,
684            # where consumers unwind via _safe_get instead)
685            if remaining_producers.decrement() == 0 and not stop_event.is_set():
686                try:
687                    for _ in range(n_consumers):
688                        _safe_put(input_queue, _STOP, stop_event)
689                except _Aborted:
690                    pass
691
692    def consumer(worker_id):
693        net, device = models[worker_id]
694        try:
695            while True:
696                jobs = []
697                got_stop = False
698                while len(jobs) < batch_size:
699                    item = _safe_get(input_queue, stop_event)
700                    if item is _STOP:
701                        got_stop = True
702                        break
703                    jobs.append(item)
704
705                if jobs:  # run (possibly partial) batch
706                    batch = torch.cat([job.tensor for job in jobs], dim=0).to(device)
707                    with torch.no_grad():
708                        prediction = net(batch) if prediction_function is None \
709                            else prediction_function(net, batch)
710                    if not torch.is_tensor(prediction):  # list/tuple of outputs -> take the first
711                        prediction = prediction[0]
712                    prediction = prediction.cpu().numpy()
713                    for i, job in enumerate(jobs):
714                        job.prediction = np.array(prediction[i])
715                        job.tensor = None
716                        _safe_put(output_queue, job, stop_event)
717
718                if got_stop:
719                    break
720        except _Aborted:
721            pass
722        except Exception as e:  # noqa
723            record_error(e)
724        finally:
725            if remaining_consumers.decrement() == 0 and not stop_event.is_set():
726                try:
727                    for _ in range(num_write_workers):
728                        _safe_put(output_queue, _STOP, stop_event)
729                except _Aborted:
730                    pass
731
732    def writer():
733        try:
734            while True:
735                job = _safe_get(output_queue, stop_event)
736                if job is _STOP:
737                    break
738                _write_prediction(
739                    job.prediction, job.block, output, ndim, job.mask_block, job.inner_bb, postprocess
740                )
741                finished_blocks.increment()
742        except _Aborted:
743            pass
744        except Exception as e:  # noqa
745            record_error(e)
746
747    writers = [threading.Thread(target=writer, name=f"predict-writer-{i}") for i in range(num_write_workers)]
748    consumers = [threading.Thread(target=consumer, args=(i,), name=f"predict-consumer-{i}")
749                 for i in range(n_consumers)]
750    producers = [threading.Thread(target=producer, name=f"predict-producer-{i}")
751                 for i in range(num_prefetch_workers)]
752    threads = writers + consumers + producers
753
754    def report_progress():
755        nonlocal n_reported
756        n_finished = finished_blocks.value
757        if n_finished > n_reported:
758            pbar.update(n_finished - n_reported)
759            n_reported = n_finished
760
761    try:
762        for t in threads:
763            t.start()
764
765        for t in producers + consumers + writers:
766            while t.is_alive():
767                t.join(timeout=0.1)
768                report_progress()
769        report_progress()
770    finally:
771        stop_event.set()
772        for t in threads:
773            t.join()
774        pbar.close()
775
776    if error_box:
777        raise error_box[0]
778
779    return output

Run block-wise network prediction with a halo, pipelined for higher GPU throughput.

This is an alternate implementation of predict_with_halo that decouples block loading, GPU prediction and output writing into a producer-consumer pipeline connected by queues:

producers (CPU threads: load + preprocess) -> input queue
  -> consumer(s), one per GPU (stack a batch, predict, unstack) -> output queue
  -> writer thread(s) (postprocess + write).

While the GPU works on one batch, the prefetch workers load and preprocess the next blocks and the writer drains finished predictions, keeping the GPU fed. Blocks can additionally be stacked into batches for one forward pass via batch_size.

The pipeline is thread-based (not multiprocessing) so that lazy hdf5/zarr/n5 inputs (whose file handles are not fork/pickle-safe) work, and so that writers can share the output array directly. Note that heavy Python-level preprocess/postprocess callbacks will not parallelize across prefetch workers due to the GIL; the default standardize is numpy-vectorized and releases the GIL.

Arguments:
  • input_: The input data, can be a numpy array, a hdf5/zarr/z5py dataset or similar.
  • model: The network.
  • gpu_ids: List of device ids to use for prediction. To run prediction on the CPU, pass ["cpu"]. One prediction consumer thread (with its own model replica) is run per device.
  • block_shape: The shape of the inner block to use for prediction.
  • halo: The shape of the halo to use for prediction.
  • output: The output data, will be allocated if None is passed. Instead of a single output, this can also be a list of outputs and a slice for the corresponding channel.
  • preprocess: Function to preprocess input data before passing it to the network.
  • postprocess: Function to postprocess the network predictions.
  • with_channels: Whether the input has a channel axis.
  • skip_block: Function to evaluate whether a given input block will be skipped.
  • mask: Elements outside the mask will be ignored in the prediction.
  • disable_tqdm: Flag that allows to disable tqdm output (e.g. if function is called multiple times).
  • tqdm_desc: Description shown by the tqdm output.
  • prediction_function: A wrapper function for prediction to enable custom prediction procedures. It must operate on the leading batch axis; with the default batch_size=1 it does not need changes.
  • roi: A region of interest of the input for which to run prediction.
  • iter_list: Optional list of block ids to iterate over.
  • batch_size: The number of blocks stacked into a single forward pass. Trades GPU memory for throughput.
  • num_prefetch_workers: The number of CPU threads used to load and preprocess blocks.
  • queue_size: The maximum size of the input (prefetch) queue. Provides backpressure to bound memory use. If None, a value derived from the number of devices and batch_size is used.
  • num_write_workers: The number of threads used to write predictions. Values > 1 are safe for in-memory numpy outputs, and for zarr/n5 outputs whose chunks (and shards, for zarr v3) are aligned with block_shape. For hdf5, misaligned zarr/n5, or other outputs this is automatically clamped to 1.
  • write_queue_size: The maximum size of the output (write) queue. If None, a default is used.
  • grid_shift: Not supported by this function; raises NotImplementedError if passed. Use predict_with_halo.
Returns:

The model output.