Skip to content

Devices & ONNX

plakakia.backend

Run tiling and box suppression on GPUs (PyTorch, CuPy) as well as on the CPU.

plakakia's tiling functions accept NumPy arrays, PyTorch tensors and CuPy arrays. A tensor on a GPU stays on that GPU: tiles are cut out of a zero-copy strided view of it and gathered in a single device operation, so the image is never copied to the host. Tile coordinates are always small NumPy arrays.

Neither PyTorch nor CuPy is a dependency of plakakia. This module only imports them when it is handed one of their arrays.

import numpy as np array_namespace(np.zeros(3)) 'numpy' boxes = np.array([[0, 0, 10, 10], [1, 1, 10, 10], [20, 20, 30, 30]]) nms(boxes, np.array([0.9, 0.8, 0.7]), iou_threshold=0.5).tolist() [0, 2]

array_namespace

array_namespace(array: object) -> Namespace

Name the library that owns array: "torch", "cupy" or "numpy".

Anything that is neither a PyTorch tensor nor a CuPy array (lists, memory maps, h5py datasets...) counts as "numpy".

is_device_array

is_device_array(array: object) -> bool

Whether array is a PyTorch tensor or CuPy array (on any device, CPU included).

to_numpy

to_numpy(array: object) -> np.ndarray

Return array as a NumPy array, copying from the GPU when needed.

nms

nms(
    boxes: Any,
    scores: Any,
    iou_threshold: float = 0.5,
    *,
    class_ids: Any | None = None,
) -> Any

Non-maximum suppression, on the GPU when the boxes are on the GPU.

PyTorch tensors go through :func:torchvision.ops.batched_nms when torchvision is installed (CUDA, MPS or CPU, wherever the tensors are). Everything else, and PyTorch without torchvision, uses a NumPy implementation.

Parameters:

Name Type Description Default
boxes Any

(N, 4) boxes (x1, y1, x2, y2), in any supported array library.

required
scores Any

(N,) confidence per box.

required
iou_threshold float

Boxes whose IoU with a higher-scoring kept box is above this value are dropped.

0.5
class_ids Any | None

Optional (N,) class per box. When given, boxes only suppress boxes of the same class.

None

Returns:

Type Description
Any

Indices of the kept boxes, highest score first, in the input's array library

Any

and on its device.

plakakia.onnx

Run ONNX models on tiles, on GPUs and NPUs, through ONNX Runtime.

:class:OnnxModel wraps an :class:onnxruntime.InferenceSession as a plain callable model(batch) -> list of outputs, so it can be fed batches of tiles straight from :func:plakakia.tile_image. With providers="auto" it picks the fastest execution provider your ONNX Runtime build offers: TensorRT or CUDA on NVIDIA GPUs, ROCm/MIGraphX on AMD GPUs, CoreML on Apple silicon (GPU and Neural Engine), DirectML on Windows GPUs and NPUs, OpenVINO on Intel CPUs, GPUs and NPUs, QNN on Qualcomm NPUs, Vitis AI on AMD Ryzen AI NPUs, CANN on Huawei Ascend, and the CPU otherwise.

ONNX Runtime is not a dependency of plakakia: install the build for your hardware, e.g. pip install onnxruntime-gpu, onnxruntime-openvino, onnxruntime-qnn or onnxruntime-directml (pip install "plakakia[onnx]" installs the CPU build).

PREFERRED_PROVIDERS module-attribute

PREFERRED_PROVIDERS: tuple[str, ...] = (
    "TensorrtExecutionProvider",
    "CUDAExecutionProvider",
    "MIGraphXExecutionProvider",
    "ROCMExecutionProvider",
    "CoreMLExecutionProvider",
    "DmlExecutionProvider",
    "OpenVINOExecutionProvider",
    "QNNExecutionProvider",
    "VitisAIExecutionProvider",
    "CANNExecutionProvider",
    "CPUExecutionProvider",
)

Execution providers tried by providers="auto", fastest first.

ProviderSpec module-attribute

ProviderSpec = str | tuple[str, dict[str, Any]]

A provider name, or a (name, options) pair.

OnnxModel

OnnxModel(
    model: str | PathLike[str] | bytes,
    *,
    providers: Literal["auto"]
    | Sequence[ProviderSpec]
    | None = "auto",
    input_name: str | None = None,
    output_names: Sequence[str] | None = None,
    channels_first: bool = False,
    scale: float | None = None,
    dtype: dtype[Any] | type | str | None = None,
    session_options: Any = None,
)

An ONNX model as a callable that runs a batch of tiles on the best device.

Parameters:

Name Type Description Default
model str | PathLike[str] | bytes

Path to a .onnx file, or the serialized model as bytes.

required
providers Literal['auto'] | Sequence[ProviderSpec] | None

"auto" (default) to use the fastest available accelerator, or an explicit list such as ["OpenVINOExecutionProvider"] or [("OpenVINOExecutionProvider", {"device_type": "NPU"})]. See :func:select_providers.

'auto'
input_name str | None

Model input to feed. Defaults to the model's first input.

None
output_names Sequence[str] | None

Outputs to return. Defaults to all of them.

None
channels_first bool

Transpose (N, H, W, C) batches (the layout of :func:plakakia.tile_image on an (H, W, C) image) to (N, C, H, W) before running the model.

False
scale float | None

Multiply the batch by this factor, e.g. 1 / 255 for 8-bit images.

None
dtype dtype[Any] | type | str | None

Cast the batch to this dtype. Defaults to the model input's type.

None
session_options Any

An :class:onnxruntime.SessionOptions to create the session with.

None
Example

from plakakia import tile_image from plakakia.onnx import OnnxModel model = OnnxModel("detector.onnx", channels_first=True, scale=1 / 255) # doctest: +SKIP tiles, coords = tile_image(image, 640, 512) # doctest: +SKIP outputs = model(tiles[:16]) # doctest: +SKIP model.providers # doctest: +SKIP ['CUDAExecutionProvider', 'CPUExecutionProvider']

providers property

providers: list[str]

The execution providers the session actually runs on, in priority order.

prepare

prepare(batch: Any) -> np.ndarray

Convert a batch of tiles (NumPy, PyTorch or CuPy) into the model's input.

__call__

__call__(batch: Any) -> list[np.ndarray]

Run the model on batch and return its outputs as NumPy arrays.

available_providers

available_providers() -> list[str]

Execution providers offered by the installed ONNX Runtime build.

select_providers

select_providers(
    providers: Literal["auto"]
    | Sequence[ProviderSpec]
    | None = "auto",
    *,
    available: Sequence[str] | None = None,
) -> list[ProviderSpec]

Resolve a provider request into the list ONNX Runtime expects.

Parameters:

Name Type Description Default
providers Literal['auto'] | Sequence[ProviderSpec] | None

"auto" or None for every available provider in :data:PREFERRED_PROVIDERS order, or an explicit list of names (or (name, options) pairs), kept in your order and filtered to those available.

'auto'
available Sequence[str] | None

Providers to choose from. Defaults to :func:available_providers.

None

Returns:

Type Description
list[ProviderSpec]

The providers to pass to :class:onnxruntime.InferenceSession, always ending with

list[ProviderSpec]

the CPU provider so that unsupported operators can fall back to it.

select_providers("auto", available=["CPUExecutionProvider", "CUDAExecutionProvider"]) ['CUDAExecutionProvider', 'CPUExecutionProvider']