Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

benchmarks: module flagships + one shared CLI/header/JSON format (#4723)

Dmytro Mishkin8cce1b7fb552
diff --git a/benchmarks/README.md b/benchmarks/README.md
index 2483fa15a..ca041b3a1 100644
--- a/benchmarks/README.md
+++ b/benchmarks/README.md
@@ -6,12 +6,39 @@ baselines. Goal: current, citable numbers with disclosed methodology β€” where k
## Directory map
+Every kornia module with image or tensor ops a user would time has one `flagship.py`: a small,
+representative set of that module's ops β€” not every export β€” against the libraries users would
+otherwise reach for. All flagships share one command line, one console layout and one JSON format
+(see [Shared output format](#shared-output-format)).
+
+| Suite | Flagship ops | Baselines |
+| --- | --- | --- |
+| [`augmentation`](augmentation/flagship.py) | flip, affine, perspective, resized crop, color jiggle, blur, brightness, grayscale (class API, sampling included) | torchvision v2, albumentations, OpenCV, PIL |
+| [`color`](color/flagship.py) | grayscale, HSV, Lab, YCbCr, Bayer demosaic | torchvision v2, scikit-image, OpenCV (per image and stacked), PIL |
+| [`contrib`](contrib/flagship.py) | exact connected components, distance transform | scikit-image, SciPy, OpenCV |
+| [`enhance`](enhance/flagship.py) | normalize, gamma, hue, saturation, equalize, CLAHE | torchvision v2, albumentations, scikit-image, OpenCV, PIL |
+| [`feature`](feature/flagship.py) | Harris and GFTT responses, SIFT detect+describe, SNN matching | scikit-image, OpenCV |
+| [`filters`](filters/flagship.py) | Gaussian, Sobel, Laplacian, median, box, Canny, unsharp, bilateral, guided, motion, Otsu | torchvision v2, albumentations, scikit-image, OpenCV, kornia-rs, PIL |
+| [`geometry`](geometry/flagship.py) | warp perspective/affine, rotate, resize, perspective-transform solve | torchvision v2, OpenCV |
+| [`io`](io/flagship.py) | JPEG and PNG decode to an RGB uint8 tensor | torchvision, OpenCV, PIL |
+| [`losses`](losses/flagship.py) | binary focal, focal, Dice, SSIM, total variation (forward + backward) | torchvision |
+| [`metrics`](metrics/flagship.py) | PSNR, SSIM, mean IoU | scikit-image, OpenCV |
+| [`morphology`](morphology/flagship.py) | dilation, erosion, opening, gradient | torchmorph (CUDA only), albumentations, scikit-image, OpenCV |
+
+Modules without a flagship: `models`, `tracking` and the model wrappers in `contrib` need
+downloaded weights (learned local features are covered by `feature/local_features.py`); `nerf`,
+`sensors`, `x`, `onnx`, `transpiler`, `grad_estimator`, `image`, `core`, `utils` and `testing`
+are training loops, containers, exporters or plumbing whose cost is the ops above.
+
+Deeper, single-topic scripts:
+
| Directory | Contents |
| --- | --- |
| [`augmentation/`](augmentation/) | Cross-library augmentation benchmarks β€” [`flagship.py`](augmentation/flagship.py) (class-API, parameter sampling included, vs torchvision v2/albumentations/OpenCV/PIL) plus pipeline/per-op scripts; see its [README](augmentation/README.md). |
| [`geometry/`](geometry/) | [`flagship.py`](geometry/flagship.py): core geometry ops vs OpenCV/torchvision v2. |
| [`filters/`](filters/) | [`flagship.py`](filters/flagship.py): core filters vs OpenCV/albumentations/torchvision v2/kornia-rs/PIL/scikit-image. [`gaussian_cpu.py`](filters/gaussian_cpu.py): Gaussian blur and scale-pyramid base/branch timing and numerical comparisons; [report](filters/gaussian_cpu.md). |
-| [`color/`](color/) | pytest-benchmark microbenchmarks for color conversions. |
+| [`color/`](color/) | pytest-benchmark microbenchmarks for color conversions (`*_test.py`). |
+| [`contrib/`](contrib/) | [`connected_components.py`](contrib/connected_components.py): union-find vs pooling labeling, validated against SciPy; [report](contrib/connected_components.md). |
| [`feature/`](feature/) | Local-feature detector benchmarks incl. quality (matching) metrics; [`laf_ops.py`](feature/laf_ops.py) microbenchmarks the shared LAF operations and [`ellipse_to_laf.py`](feature/ellipse_to_laf.py) drills into one of them (both base-revision A/B β€” no cross-library baseline exists). [`local_features.py`](feature/local_features.py) measures Oxford graf speed and homography corner error for SIFT, SIFT-AffNet-HardNet and KeyNet-HardNet on CPU, CUDA or MPS (`--device cpu --timing-pairs 2` times the representative 1–2 pair and still scores all five); results in [`graf_benchmark.md`](feature/graf_benchmark.md). [`sift_runtime.py`](feature/sift_runtime.py) and [`plot_sift_runtime.py`](feature/plot_sift_runtime.py) chart scale-space SIFT runtime across releases and batch sizes; results in [`sift_runtime.md`](feature/sift_runtime.md). |
| [`common.py`](common.py) | Shared methodology utilities β€” use these in every new benchmark. |
@@ -37,11 +64,12 @@ Every benchmark here must follow the same rules (utilities in [`common.py`](comm
Hybrid CPUs (performance + efficiency cores) keep lightly loaded threads on efficiency cores
until they have carried sustained load, and WSL2 cannot pin them. On an i7-14700K this moved a
5x5 oneDNN convolution from 0.56 ms to 0.22 ms while a slice-based filter barely changed, so
- an unwarmed A/B can pick the wrong implementation. The filters and augmentation flagships do
- this, including accelerator runs because they also time CPU-only library baselines.
-- **Checkout provenance:** the filters and augmentation flagship scripts import Kornia from
- their own checkout and print the source path. Direct script execution must not silently benchmark an
- installed wheel or another editable checkout while recording the current tree's commit.
+ an unwarmed A/B can pick the wrong implementation. Every flagship does this through
+ `common.setup_run`, including accelerator runs because they also time CPU-only library baselines.
+- **Checkout provenance:** every flagship imports Kornia from its own checkout, prints the source
+ path, warns when kornia resolved elsewhere, and exports the checkout-relative path as
+ `kornia_module`. Direct script execution must not silently benchmark an installed wheel or
+ another editable checkout while recording the current tree's commit.
- **Device sync inside the timed region:** `blocked_autorange` syncs CUDA; for MPS pass
`sync=torch.mps.synchronize` to `time_us`. A hand-rolled `time.time()` around a GPU call
measures launch latency, not work.
@@ -64,6 +92,21 @@ Every benchmark here must follow the same rules (utilities in [`common.py`](comm
- **Equal footing + honest regimes:** identical transform parameters and interpolation across
backends; state each backend's regime (batched float tensor vs per-image uint8 loop) instead
of pretending the columns are apples-to-apples. Publish losses alongside wins.
+- **Every baseline at its best:** a baseline cell times the library's idiomatic fastest call,
+ not a convenient one. Build its inputs outside the timed call, as kornia's tensor is: PIL gets
+ ready-made `Image` objects, a mask gets the dtype the library's fast path takes (`bool` for
+ scikit-image's `label`). Use the library's own idioms (`cv2.split`/`cv2.merge`, not strided
+ slices plus `np.stack`), and fill a column wherever the library has the op (`cv2.PSNR`,
+ albumentations' transforms). When the call does different work, such as albumentations' `CLAHE`
+ equalizing only L in Lab, say so in the regime text. Each of these cost a published ratio 1.3x
+ to 3.3x in #4723's first review.
+- **One thread count for every library:** `setup_run` pins OpenCV to `--threads` as well as torch
+ and records `opencv_num_threads`; the header prints both. OpenCV builds whose parallel backend
+ ignores `setNumThreads` (GCD in the macOS wheels) keep every core, and the header says so in a
+ `NOTE`. Suites with no OpenCV-backed column (`losses`, `feature/laf_ops.py`) leave OpenCV out.
+ The `0.9.0rc1` result files predate the pin and have no `opencv_num_threads`: on the
+ i7-14700K Linux runs, the OpenCV and albumentations cells used every core while torch used 4.
+ The Apple runs are unaffected, because GCD ignores the pin.
- **Public API only:** benchmark `kornia.*` as users call it β€” no private helpers, no
reimplementations inside the script.
@@ -83,6 +126,7 @@ One file per run:
"kornia": "0.9.0rc1",
"device": "cpu",
"torch_num_threads": 4,
+ "opencv_num_threads": 4,
"opencv": "4.11.0",
"torchvision": null,
"numpy": "2.4.0"
@@ -104,14 +148,38 @@ One file per run:
```
`throughput_per_s` counts items per second β€” images for image ops, point-set solves for
-`get_perspective_transform`. `null` means the measurement failed (backend raised).
+`get_perspective_transform`. `metadata.units` names the item for the whole file (`img/s`,
+`items/s`, `LAFs/s`); the docs page labels its tables from it. `metadata.kornia_module` is the
+checkout-relative path kornia was imported from (`outside-checkout` otherwise), and
+`metadata.load` holds the aggregate load snapshot. A row whose timings are `null` carries an
+`error`: the exception name when the backend or its `torch.compile` warmup raised, or
+`unavailable` when the library is missing or has no counterpart for that op.
+
+## Shared output format
+
+All flagships build on the same helpers in [`common.py`](common.py), so their output lines up:
+
+- **Command line** (`add_flagship_args`): `--batches`, `--size`, `--device`, `--dtype`,
+ `--threads`, `--compile`, `--ops`, `--skip-compile-ops`, `--min-run-time`, `--json`,
+ `--contribute`, `--machine-slug`. `--ops` rejects names the suite does not have.
+- **Header** (`start_run`), in this order: `# <suite> benchmark β€” commit … β€” platform`, the
+ software stack, `# kornia source: …`, the CUDA device when there is one,
+ `# device=…, dtype=…, threads=… (opencv …), size=… β€” throughput <units>`, one line per backend regime,
+ the meaning of `-`, then one `# NOTE:` per unavailable library or eager-only op.
+- **Tables** (`run_batch_sweep`): one per batch size, op names left, one right-aligned
+ throughput column per backend, units at the end of the header row. `-` is a skipped cell,
+ `βœ—` a call that raised; both are explained in the JSON `error` field.
+- **Footer** (`finish_run`): `# results written to <path>` for `--json`, and the canonical
+ path plus the `git add` line for `--contribute`.
## Adding a new benchmark
-1. Import the utilities (`benchmarks/` is not a package β€” scripts under a subdirectory add the
- parent to `sys.path`, see the top of `geometry/flagship.py`).
-2. Time every backend with `time_us`, print a table with the git commit, platform, and device
- name in the header, and support `--json` via `save_json(path, run_metadata(device), results)`.
+1. Start from the smallest flagship (`morphology/flagship.py`): it puts the checkout root and
+ `benchmarks/` on `sys.path` (`benchmarks/` is not a package), then uses `add_flagship_args`,
+ `setup_run`, `start_run`, `KorniaRows`, `run_batch_sweep` and `finish_run`. Do not hand-roll
+ the header, the compile warmup or the JSON writing; that is how suites drifted apart.
+2. Pick a representative handful of the module's ops, not every export, and list them in the
+ module docstring with each baseline's counterpart.
3. Baselines run **correctly and on equal footing** (same parameters, same interpolation, their
native data regime) β€” a misconfigured baseline is worse than no baseline.
4. Missing optional libraries must degrade to a skip note, never a crash.
@@ -244,7 +312,8 @@ and
so the docs performance page renders it; the tables below are the B=1 N=20000 slice of those
files. Linux/WSL2 (kernel 6.18, x86_64), Intel i7-14700K + NVIDIA RTX 4090, Python 3.13,
torch 2.14.0+cu130, CUDA 13.0, kornia 0.9.0rc1, float32, image 256Γ—256, patch size 32,
-14 threads; LAF scales are stratified across all four pyramid levels that a 256Γ—256 image at
+14 threads (torch's default there; the script now defaults to `--threads 4` like every flagship, so pass
+`--threads 14` to reproduce); LAF scales are stratified across all four pyramid levels that a 256Γ—256 image at
PS=32 provides. Throughput in LAFs/s (higher is better); no cross-library column exists β€” no
other library exposes LAFs. Every op compiled on both devices on this stack, so there is no `-`
cell. Compare columns within one table, never numbers across machines.
@@ -374,7 +443,8 @@ torchvision 0.24.1, albumentations 2.0.8, OpenCV 4.11.0, Pillow 12.3, float32, 2
4 threads, batch 32, throughput img/s. Timed region = parameter sampling + application through
each library's random-transform class API; kornia/torchvision run a batched float tensor,
albumentations/OpenCV/PIL a per-image uint8 CPU loop. CUDA tables follow the PR-thread protocol
-used for the geometry suite.
+used for the geometry suite. These runs predate prebuilt PIL inputs: the PIL cells include the
+`Image.fromarray` conversion, so PIL is faster than shown.
`--device cpu --compile`:
diff --git a/benchmarks/augmentation/flagship.py b/benchmarks/augmentation/flagship.py
index 15edd853c..fd53fe2d6 100644
--- a/benchmarks/augmentation/flagship.py
+++ b/benchmarks/augmentation/flagship.py
@@ -40,7 +40,9 @@ CPU or GPU and kornia is differentiable; albumentations/OpenCV/PIL run single ui
CPU in a Python loop β€” their native regime. OpenCV and PIL are only listed where the augmentation
is parameter-free (flip via ``Image.transpose``, grayscale via ``convert("L")``): for
randomly-parameterized augmentations, albumentations *is* the OpenCV-backed baseline. PIL is
-usually the slowest but serves as the signal-processing-correct reference implementation.
+usually the slowest but serves as the signal-processing-correct reference implementation. PIL
+receives ready-made ``Image`` objects, as kornia receives a ready-made tensor; the PIL cells of the
+``0.9.0rc1`` result files still include the ``Image.fromarray`` conversion.
Parameter distributions are matched in spirit across libraries, but
parameterizations differ (e.g. perspective distortion scales) β€” columns are regime comparisons,
not bit-exact races. RandomResizedCrop outputs size//2 per side for every backend;
@@ -54,34 +56,42 @@ Usage:
from __future__ import annotations
import argparse
-import platform
-import random
import sys
from pathlib import Path
from types import ModuleType
-from typing import Callable, Optional
+from typing import Optional
-import numpy as np
import torch
# Prefer this checkout to an installed wheel or another editable checkout.
sys.path.insert(0, str(Path(__file__).resolve().parents[2]))
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
from common import (
- add_contribute_args,
- collect_load_metrics,
- contribute_result,
- print_preflight,
+ Backend,
+ KorniaRows,
+ add_flagship_args,
+ batch_list,
+ finish_run,
+ image_batch,
+ image_row_fields,
+ optional_import,
run_batch_sweep,
- run_metadata,
- save_json,
- versions_line,
- warm_up_cpu,
+ setup_run,
+ start_run,
)
import kornia.augmentation as KA
-Backend = Optional[Callable[[], object]]
+OPS = (
+ "RandomHorizontalFlip",
+ "RandomAffine",
+ "RandomPerspective",
+ "RandomResizedCrop",
+ "ColorJiggle",
+ "RandomGaussianBlur",
+ "RandomBrightness",
+ "RandomGrayscale",
+)
def build_ops(
@@ -96,44 +106,21 @@ def build_ops(
cv2: Optional[ModuleType],
pil: Optional[ModuleType],
skip_compile: frozenset[str] = frozenset(),
+ selected: Optional[frozenset[str]] = None,
) -> tuple[dict[str, dict[str, Backend]], dict[str, str]]:
- """Build {op: {backend: zero-arg callable}}; each callable transforms the whole batch once."""
- rng = np.random.default_rng(0)
- imgs_u8 = [(rng.random((h, w, 3)) * 255).astype(np.uint8) for _ in range(b)]
- batch_f = (
- torch.stack([torch.from_numpy(im).permute(2, 0, 1) for im in imgs_u8]).to(device=device, dtype=dtype).div(255)
- )
+ """Build {op: {backend: zero-arg callable}}; each callable transforms the whole batch once.
+
+ Rows outside ``selected`` (``--ops``) are not built, so they are neither compiled nor timed.
+ """
+ imgs_u8, batch_f = image_batch(b, h, w, device, dtype)
+ pil_imgs = [pil.fromarray(im) for im in imgs_u8] if pil else []
+ compiled_rows = KorniaRows(device, do_compile, skip_compile)
- compile_failures: dict[str, str] = {}
+ def include(name: str) -> bool:
+ return selected is None or name in selected
def kornia_row(label: str, aug: torch.nn.Module) -> dict[str, Backend]:
- aug = aug.to(device)
- row: dict[str, Backend] = {"kornia (eager)": lambda: aug(batch_f)}
- if do_compile and label not in skip_compile:
- torch._dynamo.reset()
- compiled = torch.compile(aug)
- try:
- compiled(batch_f) # warmup: compile + autotune before the timed region
- if device.type == "cuda":
- torch.cuda.synchronize() # surface async kernel faults HERE, not at the next op
- row["kornia (compiled)"] = lambda: compiled(batch_f)
- except Exception as e:
- errors = str(e)
- if device.type == "cuda":
- try:
- torch.cuda.synchronize() # a FAILED warmup may still have launched kernels
- except Exception as sync_err:
- errors += " | " + str(sync_err)
- if "illegal memory access" in errors:
- raise SystemExit(
- f"FATAL: CUDA context poisoned during torch.compile warmup of '{label}' "
- "(illegal memory access); no later measurement would be trustworthy. "
- f"Rerun with --skip-compile-ops {label} to keep it eager-only, or without "
- "--compile; CUDA_LAUNCH_BLOCKING=1 localizes the kernel."
- ) from e
- row["kornia (compiled)"] = None
- compile_failures[label] = type(e).__name__
- return row
+ return compiled_rows(label, aug.to(device), batch_f)
def tv(t: object) -> Backend:
return lambda: t(batch_f)
@@ -143,145 +130,109 @@ def build_ops(
ops: dict[str, dict[str, Backend]] = {}
- row = kornia_row("RandomHorizontalFlip", KA.RandomHorizontalFlip(p=1.0))
- row["torchvision v2"] = tv(T2.RandomHorizontalFlip(p=1.0)) if T2 else None
- row["albumentations"] = alb(A.HorizontalFlip(p=1.0)) if A else None
- row["opencv"] = (lambda: [cv2.flip(im, 1) for im in imgs_u8]) if cv2 else None
- row["PIL"] = (
- (lambda: [pil.fromarray(im).transpose(pil.Transpose.FLIP_LEFT_RIGHT) for im in imgs_u8]) if pil else None
- )
- ops["RandomHorizontalFlip"] = row
-
- row = kornia_row("RandomAffine", KA.RandomAffine(degrees=30.0, translate=(0.1, 0.1), scale=(0.8, 1.2), p=1.0))
- row["torchvision v2"] = tv(T2.RandomAffine(degrees=30.0, translate=(0.1, 0.1), scale=(0.8, 1.2))) if T2 else None
- row["albumentations"] = (
- alb(A.Affine(rotate=(-30.0, 30.0), translate_percent=(0.0, 0.1), scale=(0.8, 1.2), p=1.0)) if A else None
- )
- row["opencv"] = None
- ops["RandomAffine"] = row
-
- row = kornia_row("RandomPerspective", KA.RandomPerspective(0.5, p=1.0))
- row["torchvision v2"] = tv(T2.RandomPerspective(distortion_scale=0.5, p=1.0)) if T2 else None
- row["albumentations"] = alb(A.Perspective(scale=(0.05, 0.1), p=1.0)) if A else None
- row["opencv"] = None
- ops["RandomPerspective"] = row
-
- dst = (h // 2, w // 2)
- row = kornia_row("RandomResizedCrop", KA.RandomResizedCrop(dst))
- row["torchvision v2"] = tv(T2.RandomResizedCrop(dst, antialias=False)) if T2 else None
- row["albumentations"] = alb(A.RandomResizedCrop(size=dst, p=1.0)) if A else None
- row["opencv"] = None
- ops["RandomResizedCrop"] = row
-
- row = kornia_row("ColorJiggle", KA.ColorJiggle(0.2, 0.2, 0.2, 0.1, p=1.0))
- row["torchvision v2"] = tv(T2.ColorJitter(0.2, 0.2, 0.2, 0.1)) if T2 else None
- row["albumentations"] = alb(A.ColorJitter(0.2, 0.2, 0.2, 0.1, p=1.0)) if A else None
- row["opencv"] = None
- ops["ColorJiggle"] = row
-
- row = kornia_row("RandomGaussianBlur", KA.RandomGaussianBlur((5, 5), (0.1, 2.0), p=1.0))
- row["torchvision v2"] = tv(T2.GaussianBlur(5, sigma=(0.1, 2.0))) if T2 else None
- row["albumentations"] = alb(A.GaussianBlur(blur_limit=(5, 5), sigma_limit=(0.1, 2.0), p=1.0)) if A else None
- row["opencv"] = None
- ops["RandomGaussianBlur"] = row
-
- row = kornia_row("RandomBrightness", KA.RandomBrightness(brightness=(0.8, 1.2), p=1.0))
- row["torchvision v2"] = tv(T2.ColorJitter(brightness=(0.8, 1.2))) if T2 else None
- row["albumentations"] = (
- alb(A.RandomBrightnessContrast(brightness_limit=0.2, contrast_limit=0.0, p=1.0)) if A else None
- )
- row["opencv"] = None
- ops["RandomBrightness"] = row
-
- row = kornia_row("RandomGrayscale", KA.RandomGrayscale(p=1.0))
- row["torchvision v2"] = tv(T2.RandomGrayscale(p=1.0)) if T2 else None
- row["albumentations"] = alb(A.ToGray(p=1.0)) if A else None
- row["opencv"] = (lambda: [cv2.cvtColor(im, cv2.COLOR_RGB2GRAY) for im in imgs_u8]) if cv2 else None
- row["PIL"] = (lambda: [pil.fromarray(im).convert("L") for im in imgs_u8]) if pil else None
- ops["RandomGrayscale"] = row
-
- return ops, compile_failures
+ if include("RandomHorizontalFlip"):
+ row = kornia_row("RandomHorizontalFlip", KA.RandomHorizontalFlip(p=1.0))
+ row["torchvision v2"] = tv(T2.RandomHorizontalFlip(p=1.0)) if T2 else None
+ row["albumentations"] = alb(A.HorizontalFlip(p=1.0)) if A else None
+ row["opencv"] = (lambda: [cv2.flip(im, 1) for im in imgs_u8]) if cv2 else None
+ row["PIL"] = (lambda: [im.transpose(pil.Transpose.FLIP_LEFT_RIGHT) for im in pil_imgs]) if pil else None
+ ops["RandomHorizontalFlip"] = row
+
+ if include("RandomAffine"):
+ row = kornia_row("RandomAffine", KA.RandomAffine(degrees=30.0, translate=(0.1, 0.1), scale=(0.8, 1.2), p=1.0))
+ row["torchvision v2"] = (
+ tv(T2.RandomAffine(degrees=30.0, translate=(0.1, 0.1), scale=(0.8, 1.2))) if T2 else None
+ )
+ row["albumentations"] = (
+ alb(A.Affine(rotate=(-30.0, 30.0), translate_percent=(0.0, 0.1), scale=(0.8, 1.2), p=1.0)) if A else None
+ )
+ ops["RandomAffine"] = row
+
+ if include("RandomPerspective"):
+ row = kornia_row("RandomPerspective", KA.RandomPerspective(0.5, p=1.0))
+ row["torchvision v2"] = tv(T2.RandomPerspective(distortion_scale=0.5, p=1.0)) if T2 else None
+ row["albumentations"] = alb(A.Perspective(scale=(0.05, 0.1), p=1.0)) if A else None
+ ops["RandomPerspective"] = row
+
+ if include("RandomResizedCrop"):
+ dst = (h // 2, w // 2)
+ row = kornia_row("RandomResizedCrop", KA.RandomResizedCrop(dst))
+ row["torchvision v2"] = tv(T2.RandomResizedCrop(dst, antialias=False)) if T2 else None
+ row["albumentations"] = alb(A.RandomResizedCrop(size=dst, p=1.0)) if A else None
+ ops["RandomResizedCrop"] = row
+
+ if include("ColorJiggle"):
+ row = kornia_row("ColorJiggle", KA.ColorJiggle(0.2, 0.2, 0.2, 0.1, p=1.0))
+ row["torchvision v2"] = tv(T2.ColorJitter(0.2, 0.2, 0.2, 0.1)) if T2 else None
+ row["albumentations"] = alb(A.ColorJitter(0.2, 0.2, 0.2, 0.1, p=1.0)) if A else None
+ ops["ColorJiggle"] = row
+
+ if include("RandomGaussianBlur"):
+ row = kornia_row("RandomGaussianBlur", KA.RandomGaussianBlur((5, 5), (0.1, 2.0), p=1.0))
+ row["torchvision v2"] = tv(T2.GaussianBlur(5, sigma=(0.1, 2.0))) if T2 else None
+ row["albumentations"] = alb(A.GaussianBlur(blur_limit=(5, 5), sigma_limit=(0.1, 2.0), p=1.0)) if A else None
+ ops["RandomGaussianBlur"] = row
+
+ if include("RandomBrightness"):
+ row = kornia_row("RandomBrightness", KA.RandomBrightness(brightness=(0.8, 1.2), p=1.0))
+ row["torchvision v2"] = tv(T2.ColorJitter(brightness=(0.8, 1.2))) if T2 else None
+ row["albumentations"] = (
+ alb(A.RandomBrightnessContrast(brightness_limit=0.2, contrast_limit=0.0, p=1.0)) if A else None
+ )
+ ops["RandomBrightness"] = row
+
+ if include("RandomGrayscale"):
+ row = kornia_row("RandomGrayscale", KA.RandomGrayscale(p=1.0))
+ row["torchvision v2"] = tv(T2.RandomGrayscale(p=1.0)) if T2 else None
+ row["albumentations"] = alb(A.ToGray(p=1.0)) if A else None
+ row["opencv"] = (lambda: [cv2.cvtColor(im, cv2.COLOR_RGB2GRAY) for im in imgs_u8]) if cv2 else None
+ row["PIL"] = (lambda: [im.convert("L") for im in pil_imgs]) if pil else None
+ ops["RandomGrayscale"] = row
+
+ return ops, compiled_rows.compile_failures
def main() -> None:
parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
- parser.add_argument("--batches", type=str, default="1,8,32", help="comma-separated batch sizes to sweep")
- parser.add_argument("--size", type=int, default=256)
- parser.add_argument("--device", type=str, default="cpu")
- parser.add_argument("--dtype", type=str, default="float32", choices=["float32", "float16", "bfloat16"])
- parser.add_argument("--threads", type=int, default=4)
- parser.add_argument("--compile", action="store_true", help="also time torch.compile'd kornia")
- parser.add_argument(
- "--skip-compile-ops",
- type=str,
- default="",
- help="comma-separated op names to keep eager-only (workaround for faulting compiled kernels)",
- )
- parser.add_argument("--json", type=str, default=None, help="write machine-readable results to this path")
- add_contribute_args(parser)
+ add_flagship_args(parser, ops=OPS)
args = parser.parse_args()
- skip_compile = frozenset(s.strip() for s in args.skip_compile_ops.split(",") if s.strip())
-
- torch.set_num_threads(args.threads)
- warm_up_cpu() # CPU baselines are also timed in accelerator runs.
- torch.manual_seed(0)
- np.random.seed(0) # noqa: NPY002 β€” albumentations samples from the legacy global RNG
- random.seed(0)
- device = torch.device(args.device)
- dtype = getattr(torch, args.dtype)
- sync = torch.mps.synchronize if device.type == "mps" else None # Timer only syncs CUDA
-
- try:
- import torchvision.transforms.v2 as T2
- except Exception:
- T2 = None
- try:
- import albumentations as A
- except Exception:
- A = None
- try:
- import cv2
- except Exception:
- cv2 = None
- try:
- from PIL import Image as pil
- except Exception:
- pil = None
-
- meta = run_metadata(device)
- meta["load"] = collect_load_metrics()
- if args.contribute:
- print_preflight(meta["load"])
- print(f"# flagship augmentation benchmark β€” commit {meta['git_commit']} β€” {platform.platform()}")
- print(versions_line(meta))
- print(f"# Kornia source: {Path(KA.__file__).resolve()}")
- if device.type == "cuda":
- print(f"# CUDA device: {meta['cuda_device']} (CUDA {meta['cuda_version']})")
- print(f"# device={device}, dtype={args.dtype}, threads={args.threads}, size={args.size} β€” throughput img/s")
- print("# augmentation classes built once; timed region = parameter sampling + application per call")
- print(
- "# kornia/torchvision: batched float BCHW; albumentations/opencv/PIL: uint8 HWC per-image loop (CPU); "
- "'-' = skipped"
+ device, dtype, sync = setup_run(args)
+
+ T2, t2_error = optional_import("torchvision.transforms.v2")
+ A, a_error = optional_import("albumentations")
+ cv2, cv2_error = optional_import("cv2")
+ pil, pil_error = optional_import("PIL.Image")
+
+ libs = [
+ (T2, "torchvision", t2_error),
+ (A, "albumentations", a_error),
+ (cv2, "opencv", cv2_error),
+ (pil, "PIL", pil_error),
+ ]
+ meta = start_run(
+ "flagship augmentation",
+ args,
+ device,
+ units="img/s",
+ regimes=[
+ "augmentation classes built once; timed region = parameter sampling + application per call",
+ "kornia/torchvision: batched float BCHW; albumentations/opencv/PIL: uint8 HWC per-image loop (CPU)",
+ ],
+ missing=[(name, err) for lib, name, err in libs if lib is None],
)
- for lib, name in [(T2, "torchvision"), (A, "albumentations"), (cv2, "opencv"), (pil, "PIL")]:
- if lib is None:
- print(f"# NOTE: {name} not installed β€” its column is skipped")
- if skip_compile:
- print(f"# NOTE: --skip-compile-ops keeps eager-only: {', '.join(sorted(skip_compile))}")
-
backends = ["kornia (eager)", "kornia (compiled)", "torchvision v2", "albumentations", "opencv", "PIL"]
results = run_batch_sweep(
- [int(x) for x in args.batches.split(",") if x.strip()],
- lambda b: build_ops(b, args.size, args.size, device, dtype, args.compile, T2, A, cv2, pil, skip_compile),
+ batch_list(args),
+ lambda b: build_ops(
+ b, args.size, args.size, device, dtype, args.compile, T2, A, cv2, pil, args.skip_compile_ops, args.ops
+ ),
backends,
- row_fields=lambda b: {"height": args.size, "width": args.size, "dtype": args.dtype},
+ row_fields=image_row_fields(args),
sync=sync,
+ units="img/s",
+ min_run_time=args.min_run_time,
)
- if args.json:
- out = save_json(args.json, meta, results)
- print(f"# results written to {out}")
- if args.contribute:
- contribute_result(args.contribute, "augmentation", meta, results, slug_override=args.machine_slug)
+ finish_run(args, "augmentation", meta, results)
if __name__ == "__main__":
diff --git a/benchmarks/color/flagship.py b/benchmarks/color/flagship.py
new file mode 100644
index 000000000..a8aeedd3f
--- /dev/null
+++ b/benchmarks/color/flagship.py
@@ -0,0 +1,221 @@
+# LICENSE HEADER MANAGED BY add-license-header
+#
+# Copyright 2018 Kornia Team
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+
+"""Flagship color benchmark: kornia.color vs OpenCV, torchvision v2, scikit-image and PIL.
+
+Covers the conversions a pipeline typically pays for β€” the luma reduction, the two perceptual
+spaces, a video space and demosaicing β€” not every pair the module exports:
+
+==================== ============================== ==================== ============= ====================
+kornia.color OpenCV (``cv2.cvtColor``) torchvision v2 scikit-image PIL
+==================== ============================== ==================== ============= ====================
+``rgb_to_grayscale`` ``COLOR_RGB2GRAY`` (uint8) ``rgb_to_grayscale`` ``rgb2gray`` ``convert("L")``
+``rgb_to_hsv`` ``COLOR_RGB2HSV_FULL`` (uint8) β€” ``rgb2hsv`` ``convert("HSV")``
+``rgb_to_lab`` ``COLOR_RGB2Lab`` (float32) β€” ``rgb2lab`` β€”
+``rgb_to_ycbcr`` ``COLOR_RGB2YCrCb`` (uint8) β€” ``rgb2ycbcr`` ``convert("YCbCr")``
+``raw_to_rgb`` ``COLOR_BayerBG2RGB`` (uint8) β€” β€” β€”
+==================== ============================== ==================== ============= ====================
+
+Regimes (see ``benchmarks/README.md``): kornia/torchvision run a batched float BCHW tensor on CPU
+or GPU and kornia is differentiable; OpenCV and PIL run single uint8 HWC images on CPU in a Python
+loop, their native regime, except Lab, which OpenCV computes on float32 input so its output is real
+CIE Lab rather than the 8-bit rescaling; scikit-image runs normalized float HWC images per image.
+PIL receives ready-made ``Image`` objects, as kornia receives a ready-made tensor. OpenCV
+parallelizes ``cvtColor`` over rows, which a single 256x256 image barely feeds, so the pointwise
+conversions also get an ``opencv (stacked)`` column: one call on the whole batch viewed as a
+``(B*H, W, 3)`` image, built outside the timed call. Demosaicing is not pointwise and has no
+stacked cell. Output conventions differ and are not normalized away: OpenCV's YCrCb swaps the
+chroma channels, 8-bit HSV and YCbCr are rescaled to 0-255, scikit-image's ``rgb2ycbcr`` uses the
+16-235 studio range, and kornia's hue is in radians. OpenCV's Bayer pattern names are shifted by
+one pixel relative to kornia's ``CFA`` names; the ``raw_to_rgb`` row times bilinear demosaicing of
+the same single-channel mosaic in both. These are throughput comparisons, not output-equivalent
+ones. Throughput is img/s.
+
+Usage:
+ python benchmarks/color/flagship.py --batches 1,8,32 --size 256 --device cpu
+ python benchmarks/color/flagship.py --device cuda --compile --json color_cuda.json
+"""
+
+from __future__ import annotations
+
+import argparse
+import sys
+from pathlib import Path
+from types import ModuleType
+from typing import Optional
+
+import numpy as np
+import torch
+
+# Prefer this checkout to an installed wheel or another editable checkout.
+sys.path.insert(0, str(Path(__file__).resolve().parents[2]))
+sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
+from common import (
+ Backend,
+ KorniaRows,
+ add_flagship_args,
+ batch_list,
+ finish_run,
+ image_batch,
+ image_row_fields,
+ optional_import,
+ run_batch_sweep,
+ setup_run,
+ start_run,
+)
+
+import kornia.color as KC
+
+OPS = ("rgb_to_grayscale", "rgb_to_hsv", "rgb_to_lab", "rgb_to_ycbcr", "raw_to_rgb")
+
+
+def build_ops(
+ b: int,
+ h: int,
+ w: int,
+ device: torch.device,
+ dtype: torch.dtype,
+ do_compile: bool,
+ cv2: Optional[ModuleType],
+ tvf: Optional[ModuleType],
+ skc: Optional[ModuleType],
+ pil: Optional[ModuleType],
+ skip_compile: frozenset[str] = frozenset(),
+ selected: Optional[frozenset[str]] = None,
+) -> tuple[dict[str, dict[str, Backend]], dict[str, str]]:
+ """Build {op: {backend: zero-arg callable}}; each callable converts the whole batch once."""
+ imgs_u8, batch_f = image_batch(b, h, w, device, dtype)
+ imgs_f = [im.astype(np.float32) / 255.0 for im in imgs_u8]
+ # One sample per pixel, as a sensor delivers it: the green plane stands in for the mosaic.
+ raws_u8 = [np.ascontiguousarray(im[..., 1]) for im in imgs_u8]
+ raw_f = batch_f[:, 1:2].contiguous()
+ stacked_u8 = np.stack(imgs_u8).reshape(b * h, w, 3)
+ stacked_f = np.stack(imgs_f).reshape(b * h, w, 3)
+ pil_imgs = [pil.fromarray(im) for im in imgs_u8] if pil else []
+
+ kornia_row = KorniaRows(device, do_compile, skip_compile)
+ ops: dict[str, dict[str, Backend]] = {}
+
+ def include(name: str) -> bool:
+ return selected is None or name in selected
+
+ def cv_loop(code: int, images: list[np.ndarray]) -> Backend:
+ return (lambda: [cv2.cvtColor(im, code) for im in images]) if cv2 else None
+
+ def cv_stacked(code: int, stacked: np.ndarray) -> Backend:
+ return (lambda: cv2.cvtColor(stacked, code)) if cv2 else None
+
+ def sk_loop(fn_name: str) -> Backend:
+ return (lambda: [getattr(skc, fn_name)(im) for im in imgs_f]) if skc else None
+
+ def pil_loop(mode: str) -> Backend:
+ return (lambda: [im.convert(mode) for im in pil_imgs]) if pil else None
+
+ if include("rgb_to_grayscale"):
+ row = kornia_row("rgb_to_grayscale", KC.rgb_to_grayscale, batch_f)
+ row["torchvision v2"] = (lambda: tvf.rgb_to_grayscale(batch_f)) if tvf else None
+ row["opencv"] = cv_loop(cv2.COLOR_RGB2GRAY, imgs_u8) if cv2 else None
+ row["opencv (stacked)"] = cv_stacked(cv2.COLOR_RGB2GRAY, stacked_u8) if cv2 else None
+ row["scikit-image"] = sk_loop("rgb2gray")
+ row["PIL"] = pil_loop("L")
+ ops["rgb_to_grayscale"] = row
+
+ if include("rgb_to_hsv"):
+ row = kornia_row("rgb_to_hsv", KC.rgb_to_hsv, batch_f)
+ row["opencv"] = cv_loop(cv2.COLOR_RGB2HSV_FULL, imgs_u8) if cv2 else None
+ row["opencv (stacked)"] = cv_stacked(cv2.COLOR_RGB2HSV_FULL, stacked_u8) if cv2 else None
+ row["scikit-image"] = sk_loop("rgb2hsv")
+ row["PIL"] = pil_loop("HSV")
+ ops["rgb_to_hsv"] = row
+
+ if include("rgb_to_lab"):
+ row = kornia_row("rgb_to_lab", KC.rgb_to_lab, batch_f)
+ row["opencv"] = cv_loop(cv2.COLOR_RGB2Lab, imgs_f) if cv2 else None
+ row["opencv (stacked)"] = cv_stacked(cv2.COLOR_RGB2Lab, stacked_f) if cv2 else None
+ row["scikit-image"] = sk_loop("rgb2lab")
+ ops["rgb_to_lab"] = row
+
+ if include("rgb_to_ycbcr"):
+ row = kornia_row("rgb_to_ycbcr", KC.rgb_to_ycbcr, batch_f)
+ row["opencv"] = cv_loop(cv2.COLOR_RGB2YCrCb, imgs_u8) if cv2 else None
+ row["opencv (stacked)"] = cv_stacked(cv2.COLOR_RGB2YCrCb, stacked_u8) if cv2 else None
+ row["scikit-image"] = sk_loop("rgb2ycbcr")
+ row["PIL"] = pil_loop("YCbCr")
+ ops["rgb_to_ycbcr"] = row
+
+ if include("raw_to_rgb"):
+ row = kornia_row("raw_to_rgb", KC.raw_to_rgb, raw_f, KC.CFA.BG)
+ row["opencv"] = cv_loop(cv2.COLOR_BayerBG2RGB, raws_u8) if cv2 else None
+ ops["raw_to_rgb"] = row
+
+ return ops, kornia_row.compile_failures
+
+
+def main() -> None:
+ parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
+ add_flagship_args(parser, ops=OPS)
+ args = parser.parse_args()
+ device, dtype, sync = setup_run(args)
+
+ cv2, cv2_error = optional_import("cv2")
+ tvf, tvf_error = optional_import("torchvision.transforms.v2.functional")
+ skc, skc_error = optional_import("skimage.color")
+ pil, pil_error = optional_import("PIL.Image")
+
+ libs = [
+ (tvf, "torchvision", tvf_error),
+ (skc, "scikit-image", skc_error),
+ (cv2, "opencv", cv2_error),
+ (pil, "PIL", pil_error),
+ ]
+ meta = start_run(
+ "flagship color",
+ args,
+ device,
+ units="img/s",
+ regimes=[
+ "kornia/torchvision: batched float BCHW; opencv/PIL: uint8 HWC per-image loop (CPU), "
+ "opencv Lab on float32; scikit-image: normalized float HWC per-image loop",
+ "opencv (stacked): one cvtColor on the batch viewed as (B*H, W, 3); PIL: prebuilt Image objects",
+ ],
+ missing=[(name, err) for lib, name, err in libs if lib is None],
+ )
+ backends = [
+ "kornia (eager)",
+ "kornia (compiled)",
+ "torchvision v2",
+ "scikit-image",
+ "opencv",
+ "opencv (stacked)",
+ "PIL",
+ ]
+ results = run_batch_sweep(
+ batch_list(args),
+ lambda b: build_ops(
+ b, args.size, args.size, device, dtype, args.compile, cv2, tvf, skc, pil, args.skip_compile_ops, args.ops
+ ),
+ backends,
+ row_fields=image_row_fields(args),
+ sync=sync,
+ units="img/s",
+ min_run_time=args.min_run_time,
+ )
+ finish_run(args, "color", meta, results)
+
+
+if __name__ == "__main__":
+ main()
diff --git a/benchmarks/common.py b/benchmarks/common.py
index 5746956c3..e92897c06 100644
--- a/benchmarks/common.py
+++ b/benchmarks/common.py
@@ -27,10 +27,12 @@ machine-readable JSON export so every run is comparable and citable.
from __future__ import annotations
import argparse
+import importlib
import json
import math
import os
import platform
+import random
import re
import subprocess
import sys
@@ -38,6 +40,7 @@ import time
from collections.abc import Sequence
from datetime import UTC, datetime
from pathlib import Path
+from types import ModuleType
from typing import Any, Callable, Optional
import torch
@@ -59,19 +62,20 @@ def warm_up_cpu(seconds: float = 3.0) -> None:
a @ a
-def time_us(
+def time_us_or_error(
fn: Callable[[], object],
min_run_time: float = 1.0,
sync: Optional[Callable[[], None]] = None,
num_threads: Optional[int] = None,
-) -> tuple[float, float]:
- """Median and interquartile-range wall clock of ``fn`` in microseconds.
+) -> tuple[float, float, Optional[str]]:
+ """Median and interquartile-range wall clock of ``fn`` in microseconds, plus the failure's name.
``blocked_autorange`` warms up, runs many repeats, and synchronizes CUDA. Devices it does
- not sync (MPS) pass their sync as ``sync`` so it lands inside the timed region. Returns
- ``(nan, nan)`` if ``fn`` raises, so callers can render a skip cell instead of dying.
- ``num_threads`` controls the timed calls and defaults to the current ``torch.get_num_threads()``;
- Timer would otherwise override the caller's thread count with one.
+ not sync (MPS) pass their sync as ``sync`` so it lands inside the timed region. If ``fn``
+ raises, returns ``(nan, nan, exception class name)`` from that same call, so callers can render
+ a skip cell and say why without calling ``fn`` again. ``num_threads`` controls the timed calls
+ and defaults to the current ``torch.get_num_threads()``; Timer would otherwise override the
+ caller's thread count with one.
"""
stmt = "fn(); sync()" if sync is not None else "fn()"
try:
@@ -79,9 +83,20 @@ def time_us(
m = bench.Timer(stmt=stmt, globals={"fn": fn, "sync": sync}, num_threads=threads).blocked_autorange(
min_run_time=min_run_time
)
- return m.median * 1e6, m.iqr * 1e6
- except Exception:
- return float("nan"), float("nan")
+ return m.median * 1e6, m.iqr * 1e6, None
+ except Exception as exc:
+ return float("nan"), float("nan"), type(exc).__name__
+
+
+def time_us(
+ fn: Callable[[], object],
+ min_run_time: float = 1.0,
+ sync: Optional[Callable[[], None]] = None,
+ num_threads: Optional[int] = None,
+) -> tuple[float, float]:
+ """``time_us_or_error`` without the failure name: ``(nan, nan)`` if ``fn`` raises."""
+ median, iqr, _ = time_us_or_error(fn, min_run_time=min_run_time, sync=sync, num_threads=num_threads)
+ return median, iqr
def git_commit() -> str:
@@ -112,10 +127,18 @@ def _optional_version(module: str) -> Optional[str]:
return None
+def _opencv_num_threads() -> Optional[int]:
+ """OpenCV's thread count if a suite imported it, else ``None``; never imports it itself."""
+ cv2 = sys.modules.get("cv2")
+ return cv2.getNumThreads() if cv2 is not None else None
+
+
def run_metadata(device: torch.device) -> dict[str, Any]:
"""Hardware/software metadata embedded in every result file (W3: date, hardware, versions)."""
import kornia
+ # Read before the version probes below, which import cv2 even in a suite that left it alone.
+ opencv_num_threads = _opencv_num_threads()
meta: dict[str, Any] = {
"timestamp_utc": datetime.now(UTC).isoformat(timespec="seconds"),
"git_commit": git_commit(),
@@ -126,6 +149,7 @@ def run_metadata(device: torch.device) -> dict[str, Any]:
"kornia": kornia.__version__,
"device": str(device),
"torch_num_threads": torch.get_num_threads(),
+ "opencv_num_threads": opencv_num_threads,
"opencv": _optional_version("cv2"),
"torchvision": _optional_version("torchvision"),
"numpy": _optional_version("numpy"),
@@ -283,7 +307,7 @@ def run_batch_sweep(
items_fn: Optional[Callable[[Any], float]] = None,
units: str = "",
label_width: int = 26,
- col_width: int = 14,
+ col_width: int = 17,
min_run_time: float = 1.0,
) -> list[dict[str, Any]]:
"""Sweep configurations, print one throughput table per config, and return JSON-ready rows.
@@ -297,7 +321,9 @@ def run_batch_sweep(
the CPU-only ``"kornia-rs"`` backend never matches).
A config is a batch size by default: it labels the row ``batch=<b>``, is written to the row's
- ``"batch"`` field, and is the per-call item count the throughput divides by. A suite whose
+ ``"batch"`` field, and is the per-call item count the throughput divides by. A backend that
+ raises while timed prints ``βœ—`` and gets a row with ``null`` timings and its exception name in
+ ``error``. A suite whose
config is not a single batch size (a ``(batch, n)`` pair, say) passes ``label_fn`` for the
printed label, ``items_fn`` for the item count, and a ``"batch"`` key in ``row_fields`` β€” the
committed-result schema requires that field to stay an ``int``. ``units`` names what the
@@ -306,13 +332,15 @@ def run_batch_sweep(
label_of = label_fn if label_fn is not None else (lambda b: f"batch={b}")
items_of = items_fn if items_fn is not None else (lambda b: b)
results: list[dict[str, Any]] = []
+ failed: list[str] = []
header = ""
for b in batches:
ops, compile_failures = build_ops(b)
if compile_failures:
exc_names = sorted(set(compile_failures.values()))
print(f"# NOTE: torch.compile warmup failed ({', '.join(exc_names)}) for: {', '.join(compile_failures)}")
- header = f"{label_of(b):<{label_width}}" + "".join(f"{n[:col_width]:>{col_width + 1}}" for n in backends)
+ width = max([label_width, len(label_of(b)) + 1] + [len(op) + 1 for op in ops])
+ header = f"{label_of(b):<{width}}" + "".join(f"{n[:col_width]:>{col_width + 1}}" for n in backends)
print("-" * len(header))
print(header + (f" ({units})" if units else ""))
print("-" * len(header))
@@ -341,21 +369,289 @@ def run_batch_sweep(
cells.append(f"{'-':>{col_width + 1}}")
continue
backend_sync = sync if backend.startswith(torch_backends) else None
- median, iqr = time_us(fn, min_run_time=min_run_time, sync=backend_sync)
- thr = items / (median * 1e-6) if not math.isnan(median) else float("nan")
- results.append(
- {
- "op": op_name,
- "backend": backend,
- "batch": b,
- **row_fields(b),
- "median_us": median,
- "iqr_us": iqr,
- "throughput_per_s": thr,
- }
- )
+ median, iqr, error = time_us_or_error(fn, min_run_time=min_run_time, sync=backend_sync)
+ row_out: dict[str, Any] = {"op": op_name, "backend": backend, "batch": b, **row_fields(b)}
+ if error is not None:
+ # The JSON says why the cell is empty, like it does for a compile failure.
+ results.append(
+ {
+ **row_out,
+ "median_us": None,
+ "iqr_us": None,
+ "throughput_per_s": None,
+ "error": error,
+ }
+ )
+ failed.append(f"{op_name}/{backend}")
+ cells.append(f"{'βœ—':>{col_width + 1}}")
+ continue
+ thr = items / (median * 1e-6)
+ results.append({**row_out, "median_us": median, "iqr_us": iqr, "throughput_per_s": thr})
cells.append(f"{thr:>{col_width + 1}.0f}")
- print(f"{op_name:<{label_width}}" + "".join(cells))
+ print(f"{op_name:<{width}}" + "".join(cells))
if header:
print("-" * len(header))
+ if failed:
+ names = ", ".join(dict.fromkeys(failed))
+ print(f"# NOTE: 'βœ—' = the call raised (exception name in the JSON 'error' field): {names}")
return results
+
+
+Backend = Optional[Callable[[], object]]
+
+#: The checkout this file lives in. Suites put it at ``sys.path[0]`` before importing kornia so
+#: the measured kornia is this tree, not a wheel or another editable checkout.
+REPO_ROOT = Path(__file__).resolve().parents[1]
+
+
+def optional_import(name: str) -> tuple[Optional[ModuleType], Optional[str]]:
+ """Import an optional baseline library, returning ``(module, None)`` or ``(None, reason)``."""
+ try:
+ return importlib.import_module(name), None
+ except Exception as exc:
+ return None, f"{type(exc).__name__}: {exc}"
+
+
+def parse_names(value: str) -> frozenset[str]:
+ """Comma-separated names (``--ops``, ``--skip-compile-ops``) as a set; empty items are dropped."""
+ return frozenset(s.strip() for s in value.split(",") if s.strip())
+
+
+def add_flagship_args(
+ parser: argparse.ArgumentParser, *, ops: Sequence[str] = (), batches: str = "1,8,32", size: int = 256
+) -> None:
+ """The command-line options every suite shares, so every suite is driven the same way.
+
+ ``ops`` lists the suite's row names; ``--ops`` rejects any other name instead of silently
+ running nothing. Suites whose configuration is not a batch sweep (``feature/laf_ops.py``) pass
+ ``batches=""`` and add their own sweep option; ``--batches`` is then not registered.
+ """
+
+ def parse_ops(value: str) -> Optional[frozenset[str]]:
+ selected = parse_names(value)
+ unknown = selected.difference(ops)
+ if ops and unknown:
+ raise argparse.ArgumentTypeError(
+ f"unknown operation(s): {', '.join(sorted(unknown))}. Available: {', '.join(ops)}"
+ )
+ return selected or None
+
+ if batches:
+ parser.add_argument("--batches", type=str, default=batches, help="comma-separated batch sizes to sweep")
+ parser.add_argument("--size", type=int, default=size, help="square image side")
+ parser.add_argument("--device", type=str, default="cpu", help="cpu, cuda, or mps")
+ parser.add_argument("--dtype", type=str, default="float32", choices=["float32", "float16", "bfloat16", "float64"])
+ parser.add_argument("--threads", type=int, default=4, help="torch intra-op threads")
+ parser.add_argument("--compile", action="store_true", help="also time torch.compile'd kornia")
+ parser.add_argument("--ops", type=parse_ops, default=None, help="comma-separated op rows to run (default: all)")
+ parser.add_argument(
+ "--skip-compile-ops",
+ type=parse_names,
+ default=frozenset(),
+ help="comma-separated op names to keep eager-only (workaround for faulting compiled kernels)",
+ )
+ parser.add_argument("--min-run-time", type=float, default=1.0, help="seconds of repeats per measurement")
+ parser.add_argument("--json", type=str, default=None, help="write machine-readable results to this path")
+ add_contribute_args(parser)
+
+
+def setup_run(
+ args: argparse.Namespace, opencv: bool = True
+) -> tuple[torch.device, torch.dtype, Optional[Callable[[], None]]]:
+ """Thread counts, CPU warm-up and pinned seeds; returns ``(device, dtype, sync)``.
+
+ ``--threads`` pins OpenCV as well as torch when OpenCV is installed. Left alone, OpenCV uses
+ every core while torch uses ``--threads``, and the header would report only torch's count.
+ Some OpenCV builds ignore the request (the GCD backend of the macOS wheels); ``start_run``
+ then prints the count OpenCV actually uses. Suites without an OpenCV or albumentations column
+ pass ``opencv=False``: OpenCV is then not imported, and the header and metadata leave it out.
+
+ ``sync`` is the MPS synchronize for ``time_us`` (``blocked_autorange`` already syncs CUDA). The
+ CPU warm-up runs on accelerator runs too, because they still time CPU-only baselines.
+ """
+ torch.set_num_threads(args.threads)
+ cv2, _ = optional_import("cv2") if opencv else (None, None)
+ if cv2 is not None:
+ cv2.setNumThreads(args.threads)
+ warm_up_cpu()
+ torch.manual_seed(0)
+ random.seed(0)
+ try:
+ import numpy as np
+
+ np.random.seed(0) # noqa: NPY002 - albumentations samples from the legacy global RNG
+ except ImportError:
+ pass
+ device = torch.device(args.device)
+ return device, getattr(torch, args.dtype), (torch.mps.synchronize if device.type == "mps" else None)
+
+
+def kornia_provenance(module_file: Optional[str]) -> tuple[str, str]:
+ """``(console path, exported field)`` for the imported kornia package.
+
+ The console gets the resolved absolute path, which answers "which tree did I measure?". The
+ exported ``kornia_module`` field is checkout-relative (or ``"outside-checkout"``): a contributed
+ file is public, and the privacy rule keeps home directories out of it.
+ """
+ if module_file is None:
+ return "unknown", "outside-checkout"
+ resolved = Path(module_file).resolve()
+ if REPO_ROOT in resolved.parents:
+ return str(resolved), resolved.relative_to(REPO_ROOT).as_posix()
+ return str(resolved), "outside-checkout"
+
+
+def start_run(
+ title: str,
+ args: argparse.Namespace,
+ device: torch.device,
+ *,
+ units: str,
+ regimes: Sequence[str] = (),
+ missing: Sequence[tuple[str, Optional[str]]] = (),
+) -> dict[str, Any]:
+ """Print the shared run header and return the metadata to export.
+
+ Every suite prints the same header in the same order: title, commit and platform; the
+ software stack; the kornia source; the CUDA device; the run configuration with the throughput
+ unit; the regime of each backend; and one ``NOTE`` per unavailable library or eager-only op.
+ ``missing`` is ``(library, reason)`` for each baseline that could not be imported.
+ """
+ import kornia
+
+ meta = run_metadata(device)
+ meta["load"] = collect_load_metrics()
+ console_path, module_field = kornia_provenance(kornia.__file__)
+ meta["kornia_module"] = module_field
+ # The docs page and the llms digest label the throughput column from this key.
+ meta["units"] = units
+ if args.contribute:
+ print_preflight(meta["load"])
+ print(f"# {title} benchmark β€” commit {meta['git_commit']} β€” {platform.platform()}")
+ print(versions_line(meta))
+ print(f"# kornia source: {console_path}")
+ if module_field == "outside-checkout":
+ # git_commit() reports this checkout's HEAD, so a kornia from anywhere else means the
+ # numbers and the commit label describe different code.
+ print(f"# WARNING: kornia resolved outside {REPO_ROOT} - these numbers are NOT this checkout's.")
+ if device.type == "cuda":
+ print(f"# CUDA device: {meta['cuda_device']} (CUDA {meta['cuda_version']})")
+ size = f", size={args.size}" if getattr(args, "size", None) else ""
+ cv_threads = f" (opencv {meta['opencv_num_threads']})" if meta["opencv_num_threads"] is not None else ""
+ print(
+ f"# device={device}, dtype={args.dtype}, threads={torch.get_num_threads()}{cv_threads}{size}"
+ f" β€” throughput {units}"
+ )
+ if meta["opencv_num_threads"] not in (None, torch.get_num_threads()):
+ # macOS wheels build OpenCV on GCD, which ignores setNumThreads.
+ print(
+ f"# NOTE: OpenCV ignored --threads {torch.get_num_threads()} (its parallel backend does not honour "
+ f"setNumThreads) and runs on {meta['opencv_num_threads']} threads"
+ )
+ for line in regimes:
+ print(f"# {line}")
+ print("# '-' = skipped: backend unavailable, no counterpart, or compile failure (see the JSON 'error' field)")
+ for name, reason in missing:
+ print(f"# NOTE: {name} not available ({reason}) β€” its column is skipped")
+ if getattr(args, "skip_compile_ops", None):
+ print(f"# NOTE: --skip-compile-ops keeps eager-only: {', '.join(sorted(args.skip_compile_ops))}")
+ if getattr(args, "ops", None):
+ print(f"# selected rows: {', '.join(sorted(args.ops))}")
+ return meta
+
+
+def finish_run(args: argparse.Namespace, suite: str, meta: dict[str, Any], results: list[dict[str, Any]]) -> None:
+ """Write ``--json`` and ``--contribute`` outputs with the same messages for every suite."""
+ if args.json:
+ out = save_json(args.json, meta, results)
+ print(f"# results written to {out}")
+ if args.contribute:
+ contribute_result(args.contribute, suite, meta, results, slug_override=args.machine_slug)
+
+
+class KorniaRows:
+ """Build the ``kornia (eager)`` / ``kornia (compiled)`` cells of one config's op rows.
+
+ ``rows(label, target, *args)`` returns ``{"kornia (eager)": ..., "kornia (compiled)": ...}``
+ where eager calls ``target(*args)`` and compiled calls ``torch.compile(target)(*args)`` after
+ a warmup outside the timed region. A failed warmup leaves the compiled cell ``None`` and
+ records the exception name in ``compile_failures`` for ``run_batch_sweep`` to report.
+
+ ``step`` wraps both cells, e.g. to add a backward pass; the warmup runs the wrapped call, so
+ a backward graph also compiles outside the timed region.
+
+ ``reset_per_op`` resets dynamo before each op. The image suites need it: kornia's
+ augmentation classes share one ``forward`` code object, so a config with more ops than the
+ recompile limit would otherwise fall back to eager silently. A suite of distinct functions can
+ reset once per config instead (``feature/laf_ops.py``), which keeps every earlier op's
+ compiled graph valid until it is timed.
+ """
+
+ def __init__(
+ self,
+ device: torch.device,
+ do_compile: bool,
+ skip_compile: frozenset[str] = frozenset(),
+ reset_per_op: bool = True,
+ step: Optional[Callable[[Callable[[], object]], Callable[[], object]]] = None,
+ ) -> None:
+ self.device = device
+ self.step = step if step is not None else (lambda call: call)
+ self.do_compile = do_compile
+ self.skip_compile = skip_compile
+ self.reset_per_op = reset_per_op
+ self.compile_failures: dict[str, str] = {}
+ if do_compile and not reset_per_op:
+ torch._dynamo.reset()
+
+ def __call__(self, label: str, target: Callable[..., object], *args: Any) -> dict[str, Backend]:
+ row: dict[str, Backend] = {"kornia (eager)": self.step(lambda: target(*args))}
+ if not self.do_compile or label in self.skip_compile:
+ return row
+ if self.reset_per_op:
+ torch._dynamo.reset()
+ compiled = torch.compile(target)
+ compiled_call = self.step(lambda: compiled(*args))
+ try:
+ compiled_call() # warmup: compile + autotune before the timed region
+ if self.device.type == "cuda":
+ torch.cuda.synchronize() # surface async kernel faults HERE, not at the next op
+ row["kornia (compiled)"] = compiled_call
+ except Exception as e:
+ errors = str(e)
+ if self.device.type == "cuda":
+ try:
+ torch.cuda.synchronize() # a FAILED warmup may still have launched kernels
+ except Exception as sync_err:
+ errors += " | " + str(sync_err)
+ if "illegal memory access" in errors:
+ raise SystemExit(
+ f"FATAL: CUDA context poisoned during torch.compile warmup of '{label}' "
+ "(illegal memory access); no later measurement would be trustworthy. "
+ f"Rerun with --skip-compile-ops {label} to keep it eager-only, or without "
+ "--compile; CUDA_LAUNCH_BLOCKING=1 localizes the kernel."
+ ) from e
+ row["kornia (compiled)"] = None
+ self.compile_failures[label] = type(e).__name__
+ return row
+
+
+def image_batch(b: int, h: int, w: int, device: torch.device, dtype: torch.dtype) -> tuple[list[Any], torch.Tensor]:
+ """The shared seeded input: ``b`` uint8 HWC RGB images and the same batch as float BCHW in [0, 1]."""
+ import numpy as np
+
+ rng = np.random.default_rng(0)
+ imgs_u8 = [(rng.random((h, w, 3)) * 255).astype(np.uint8) for _ in range(b)]
+ batch_f = (
+ torch.stack([torch.from_numpy(im).permute(2, 0, 1) for im in imgs_u8]).to(device=device, dtype=dtype).div(255)
+ )
+ return imgs_u8, batch_f
+
+
+def image_row_fields(args: argparse.Namespace) -> Callable[[Any], dict[str, Any]]:
+ """Per-row config fields of an image suite: the square size and dtype."""
+ return lambda b: {"height": args.size, "width": args.size, "dtype": args.dtype}
+
+
+def batch_list(args: argparse.Namespace) -> list[int]:
+ return [int(x) for x in args.batches.split(",") if x.strip()]
diff --git a/benchmarks/common_test.py b/benchmarks/common_test.py
index 68e04ff92..9461e4c34 100644
--- a/benchmarks/common_test.py
+++ b/benchmarks/common_test.py
@@ -264,3 +264,183 @@ def test_machine_slug_override_is_slugified() -> None:
from common import machine_slug
assert machine_slug({"machine": "x86_64"}, override="My Box! #2") == "my-box-2"
+
+
+def _flagship_parser(**kwargs):
+ import argparse
+
+ parser = argparse.ArgumentParser()
+ common.add_flagship_args(parser, **kwargs)
+ return parser
+
+
+def test_add_flagship_args_shared_defaults() -> None:
+ args = _flagship_parser(ops=("a", "b")).parse_args([])
+ assert (args.batches, args.size, args.device, args.dtype, args.threads) == ("1,8,32", 256, "cpu", "float32", 4)
+ assert args.ops is None and args.skip_compile_ops == frozenset() and args.min_run_time == 1.0
+ assert args.json is None and args.contribute is None
+
+
+def test_add_flagship_args_rejects_unknown_ops(capsys) -> None:
+ import pytest
+
+ parser = _flagship_parser(ops=("a", "b"))
+ assert parser.parse_args(["--ops", "b, a"]).ops == frozenset({"a", "b"})
+ with pytest.raises(SystemExit):
+ parser.parse_args(["--ops", "a,nope"])
+ assert "unknown operation(s): nope" in capsys.readouterr().err
+
+
+def test_add_flagship_args_without_batches() -> None:
+ args = _flagship_parser(batches="").parse_args([])
+ assert not hasattr(args, "batches")
+
+
+def test_kornia_provenance_is_checkout_relative() -> None:
+ console, field = common.kornia_provenance(str(common.REPO_ROOT / "kornia" / "__init__.py"))
+ assert field == "kornia/__init__.py"
+ assert Path(console).is_absolute()
+ assert common.kornia_provenance("/elsewhere/site-packages/kornia/__init__.py")[1] == "outside-checkout"
+ assert common.kornia_provenance(None)[1] == "outside-checkout"
+
+
+def test_start_run_prints_shared_header_and_exports_units(capsys) -> None:
+ args = _flagship_parser().parse_args(["--skip-compile-ops", "opB"])
+ meta = common.start_run(
+ "flagship demo", args, torch.device("cpu"), units="img/s", regimes=["regime line"], missing=[("lib", "why")]
+ )
+ out = capsys.readouterr().out.splitlines()
+ assert out[0].startswith("# flagship demo benchmark β€” commit ")
+ assert out[1].startswith("# torch ")
+ assert out[2].startswith("# kornia source: ")
+ assert "throughput img/s" in out[3]
+ assert "# regime line" in out
+ assert "# NOTE: lib not available (why) β€” its column is skipped" in out
+ assert any("--skip-compile-ops keeps eager-only: opB" in line for line in out)
+ assert meta["units"] == "img/s"
+ assert not meta["kornia_module"].startswith("/") # privacy rule: never an absolute path
+ assert "load" in meta
+
+
+def test_finish_run_writes_json(tmp_path, capsys) -> None:
+ out = tmp_path / "run.json"
+ args = _flagship_parser().parse_args(["--json", str(out)])
+ common.finish_run(args, "demo", {"device": "cpu"}, [{"op": "a", "median_us": float("nan")}])
+ payload = json.loads(out.read_text())
+ assert payload["results"][0]["median_us"] is None
+ assert f"# results written to {out}" in capsys.readouterr().out
+
+
+def test_kornia_rows_eager_only_and_step() -> None:
+ calls: list[str] = []
+ rows = common.KorniaRows(torch.device("cpu"), do_compile=False, step=lambda call: lambda: calls.append(call()))
+ row = rows("op", lambda x: x + 1, 1)
+ assert set(row) == {"kornia (eager)"}
+ row["kornia (eager)"]()
+ assert calls == [2] # step wraps the eager call
+
+
+def test_kornia_rows_records_warmup_failure(monkeypatch) -> None: # 'compile' in a NAME gets deselected
+ def broken(fn):
+ def run(*args):
+ raise RuntimeError("boom")
+
+ return run
+
+ monkeypatch.setattr(torch, "compile", broken)
+ rows = common.KorniaRows(torch.device("cpu"), do_compile=True, skip_compile=frozenset({"kept"}))
+ row = rows("op", lambda x: x, 1)
+ assert row["kornia (compiled)"] is None
+ assert rows.compile_failures == {"op": "RuntimeError"}
+ assert "kornia (compiled)" not in rows("kept", lambda x: x, 1)
+
+
+def test_run_batch_sweep_records_raising_backend(capsys) -> None:
+ def boom():
+ raise ValueError("bad input")
+
+ def build(b):
+ return {"a_very_long_operation_name_here": {"ok": lambda: None, "bad": boom}}, {}
+
+ rows = run_batch_sweep([1], build, ["ok", "bad"], row_fields=lambda b: {}, min_run_time=0.05)
+ bad = next(r for r in rows if r["backend"] == "bad")
+ assert bad["error"] == "ValueError" and bad["median_us"] is None and bad["throughput_per_s"] is None
+ out = capsys.readouterr().out
+ assert "βœ—" in out and "a_very_long_operation_name_here/bad" in out
+ # the label column grows to fit the longest op name instead of running into the first cell
+ line = next(line for line in out.splitlines() if line.startswith("a_very_long_operation_name_here"))
+ assert line[len("a_very_long_operation_name_here")] == " "
+
+
+def test_run_batch_sweep_reports_the_timed_failure_without_calling_again() -> None:
+ calls: list[int] = []
+
+ def flaky():
+ calls.append(1)
+ raise (ValueError if len(calls) == 1 else TypeError)("differs per call")
+
+ rows = run_batch_sweep([1], lambda b: ({"op": {"flaky": flaky}}, {}), ["flaky"], row_fields=lambda b: {})
+ assert rows[0]["error"] == "ValueError" # the exception the timed call raised, not a re-run's
+ assert len(calls) == 1
+
+
+def test_setup_run_pins_opencv_threads_and_header_reports_them(monkeypatch, capsys) -> None:
+ import types
+
+ state = {"threads": 8}
+ fake_cv2 = types.ModuleType("cv2")
+ fake_cv2.setNumThreads = lambda n: state.update(threads=n)
+ fake_cv2.getNumThreads = lambda: state["threads"]
+ monkeypatch.setitem(sys.modules, "cv2", fake_cv2)
+ monkeypatch.setattr(common, "warm_up_cpu", lambda: None)
+ torch_threads = torch.get_num_threads()
+ try:
+ args = _flagship_parser().parse_args(["--threads", "3"])
+ common.setup_run(args)
+ assert state["threads"] == 3
+ meta = common.start_run("flagship demo", args, torch.device("cpu"), units="img/s")
+ finally:
+ torch.set_num_threads(torch_threads)
+ assert meta["opencv_num_threads"] == 3
+ assert "threads=3 (opencv 3)" in capsys.readouterr().out
+
+
+def test_start_run_notes_when_opencv_ignores_threads(monkeypatch, capsys) -> None:
+ import types
+
+ fake_cv2 = types.ModuleType("cv2")
+ fake_cv2.getNumThreads = lambda: 8 # GCD builds report every core whatever was requested
+ monkeypatch.setitem(sys.modules, "cv2", fake_cv2)
+ args = _flagship_parser().parse_args([])
+ common.start_run("flagship demo", args, torch.device("cpu"), units="img/s")
+ out = capsys.readouterr().out
+ assert f"OpenCV ignored --threads {torch.get_num_threads()}" in out and "runs on 8 threads" in out
+
+
+def test_setup_run_without_opencv_leaves_it_out(monkeypatch, capsys) -> None:
+ import types
+
+ # The version probe imports cv2 as a side effect; simulate that where OpenCV is not installed.
+ fake_cv2 = types.ModuleType("cv2")
+ fake_cv2.getNumThreads = lambda: 8
+ real_optional_version = common._optional_version
+
+ def optional_version(module: str):
+ if module == "cv2":
+ sys.modules["cv2"] = fake_cv2
+ return real_optional_version(module)
+
+ monkeypatch.delitem(sys.modules, "cv2", raising=False)
+ monkeypatch.setattr(common, "_optional_version", optional_version)
+ monkeypatch.setattr(common, "warm_up_cpu", lambda: None)
+ torch_threads = torch.get_num_threads()
+ try:
+ args = _flagship_parser().parse_args(["--threads", "3"])
+ common.setup_run(args, opencv=False)
+ meta = common.start_run("flagship demo", args, torch.device("cpu"), units="img/s")
+ finally:
+ torch.set_num_threads(torch_threads)
+ sys.modules.pop("cv2", None)
+ assert meta["opencv_num_threads"] is None
+ out = capsys.readouterr().out
+ assert "# device=cpu, dtype=float32, threads=3, size=" in out and "OpenCV ignored" not in out
diff --git a/benchmarks/contrib/flagship.py b/benchmarks/contrib/flagship.py
new file mode 100644
index 000000000..2ba4fc933
--- /dev/null
+++ b/benchmarks/contrib/flagship.py
@@ -0,0 +1,183 @@
+# LICENSE HEADER MANAGED BY add-license-header
+#
+# Copyright 2018 Kornia Team
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+
+"""Flagship contrib benchmark: kornia.contrib binary-image ops vs OpenCV, scikit-image and SciPy.
+
+``kornia.contrib`` mixes model wrappers (detectors, super-resolution, ViTs) that need downloaded
+weights with classic binary-image operations. This suite covers the latter; the dedicated
+``connected_components.py`` script compares the two labeling algorithms in depth.
+
+==================================== =================================== ==========================================
+kornia.contrib OpenCV (uint8 per-image loop) scikit-image / SciPy (per-image loop)
+==================================== =================================== ==========================================
+``connected_components_union_find`` ``connectedComponents(conn=8)`` ``measure.label(connectivity=2)``;
+ ``ndimage.label`` (3x3 structure)
+``distance_transform`` ``distanceTransform(DIST_L2, 5)`` ``ndimage.distance_transform_edt``
+==================================== =================================== ==========================================
+
+Regimes (see ``benchmarks/README.md``): kornia runs a batched float B1HW mask on CPU or GPU;
+OpenCV, scikit-image and SciPy run single masks on CPU in a Python loop, their native regime. The
+mask is thresholded Gaussian-blurred noise (about 30% foreground, blobs of varying size and
+shape), the same for every backend. Connected components are exact 8-connected labelings in all
+three columns; kornia's default ``connected_components`` is left out because its fixed pooling
+budget does not guarantee a correct partition (see ``connected_components.md``). The distance
+transforms differ in accuracy: kornia's is a cascaded-convolution approximation
+(``kernel_size=3``), OpenCV's a 5x5 chamfer approximation, and SciPy's exact. kornia measures the
+distance to the nearest foreground pixel, OpenCV and SciPy to the nearest zero, so the latter two
+receive the inverted mask and all three answer the same question. The labelers get the mask in
+their fastest input type, converted outside the timed call: ``uint8`` for OpenCV and ``bool`` for
+scikit-image and SciPy (scikit-image's ``label`` takes a much faster path on ``bool`` and returns
+the same labels). Throughput is img/s.
+
+Usage:
+ python benchmarks/contrib/flagship.py --batches 1,8,32 --size 256 --device cpu
+ python benchmarks/contrib/flagship.py --device cuda --compile --json contrib_cuda.json
+"""
+
+from __future__ import annotations
+
+import argparse
+import sys
+from pathlib import Path
+from types import ModuleType
+from typing import Optional
+
+import numpy as np
+import torch
+
+# Prefer this checkout to an installed wheel or another editable checkout.
+sys.path.insert(0, str(Path(__file__).resolve().parents[2]))
+sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
+from common import (
+ Backend,
+ KorniaRows,
+ add_flagship_args,
+ batch_list,
+ finish_run,
+ image_row_fields,
+ optional_import,
+ run_batch_sweep,
+ setup_run,
+ start_run,
+)
+
+import kornia.contrib as KC
+from kornia.filters import gaussian_blur2d
+
+OPS = ("connected_components_union_find", "distance_transform")
+
+
+def blob_masks(b: int, h: int, w: int) -> torch.Tensor:
+ """Seeded ``(B, 1, H, W)`` float {0, 1} masks: blurred noise above its 70th percentile."""
+ gen = torch.Generator().manual_seed(0)
+ smooth = gaussian_blur2d(torch.rand(b, 1, h, w, generator=gen), (13, 13), (3.0, 3.0))
+ threshold = smooth.flatten(1).quantile(0.7, dim=1).view(b, 1, 1, 1)
+ return (smooth > threshold).float()
+
+
+def build_ops(
+ b: int,
+ h: int,
+ w: int,
+ device: torch.device,
+ dtype: torch.dtype,
+ do_compile: bool,
+ cv2: Optional[ModuleType],
+ skmeasure: Optional[ModuleType],
+ ndimage: Optional[ModuleType],
+ skip_compile: frozenset[str] = frozenset(),
+ selected: Optional[frozenset[str]] = None,
+) -> tuple[dict[str, dict[str, Backend]], dict[str, str]]:
+ """Build {op: {backend: zero-arg callable}}; each callable processes the whole batch once."""
+ masks = blob_masks(b, h, w)
+ masks_f = masks.to(device=device, dtype=dtype)
+ masks_u8 = [m[0].numpy().astype(np.uint8) for m in masks]
+ masks_bool = [m.astype(bool) for m in masks_u8]
+ background_u8 = [1 - m for m in masks_u8]
+ connectivity8 = np.ones((3, 3), dtype=bool)
+
+ kornia_row = KorniaRows(device, do_compile, skip_compile)
+ ops: dict[str, dict[str, Backend]] = {}
+
+ def include(name: str) -> bool:
+ return selected is None or name in selected
+
+ if include("connected_components_union_find"):
+ row = kornia_row("connected_components_union_find", KC.connected_components_union_find, masks_f)
+ row["opencv"] = (lambda: [cv2.connectedComponents(m, connectivity=8) for m in masks_u8]) if cv2 else None
+ row["scikit-image"] = (lambda: [skmeasure.label(m, connectivity=2) for m in masks_bool]) if skmeasure else None
+ row["SciPy"] = (lambda: [ndimage.label(m, structure=connectivity8) for m in masks_bool]) if ndimage else None
+ ops["connected_components_union_find"] = row
+
+ if include("distance_transform"):
+ row = kornia_row("distance_transform", KC.distance_transform, masks_f)
+ row["opencv"] = (lambda: [cv2.distanceTransform(m, cv2.DIST_L2, 5) for m in background_u8]) if cv2 else None
+ row["SciPy"] = (lambda: [ndimage.distance_transform_edt(m) for m in background_u8]) if ndimage else None
+ ops["distance_transform"] = row
+
+ return ops, kornia_row.compile_failures
+
+
+def main() -> None:
+ parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
+ add_flagship_args(parser, ops=OPS)
+ args = parser.parse_args()
+ device, dtype, sync = setup_run(args)
+
+ cv2, cv2_error = optional_import("cv2")
+ skmeasure, skmeasure_error = optional_import("skimage.measure")
+ ndimage, ndimage_error = optional_import("scipy.ndimage")
+
+ libs = [(skmeasure, "scikit-image", skmeasure_error), (ndimage, "SciPy", ndimage_error), (cv2, "opencv", cv2_error)]
+ meta = start_run(
+ "flagship contrib",
+ args,
+ device,
+ units="img/s",
+ regimes=[
+ "kornia: batched float B1HW mask; opencv/scikit-image/SciPy: per-image loop (CPU), "
+ "uint8 masks except bool for scikit-image and SciPy labeling"
+ ],
+ missing=[(name, err) for lib, name, err in libs if lib is None],
+ )
+ backends = ["kornia (eager)", "kornia (compiled)", "scikit-image", "SciPy", "opencv"]
+ results = run_batch_sweep(
+ batch_list(args),
+ lambda b: build_ops(
+ b,
+ args.size,
+ args.size,
+ device,
+ dtype,
+ args.compile,
+ cv2,
+ skmeasure,
+ ndimage,
+ args.skip_compile_ops,
+ args.ops,
+ ),
+ backends,
+ row_fields=image_row_fields(args),
+ sync=sync,
+ units="img/s",
+ min_run_time=args.min_run_time,
+ )
+ finish_run(args, "contrib", meta, results)
+
+
+if __name__ == "__main__":
+ main()
diff --git a/benchmarks/enhance/flagship.py b/benchmarks/enhance/flagship.py
new file mode 100644
index 000000000..043419fbb
--- /dev/null
+++ b/benchmarks/enhance/flagship.py
@@ -0,0 +1,251 @@
+# LICENSE HEADER MANAGED BY add-license-header
+#
+# Copyright 2018 Kornia Team
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+
+"""Flagship enhance benchmark: kornia.enhance vs torchvision v2, albumentations, OpenCV, scikit-image and PIL.
+
+Covers one representative of each family the module exports β€” normalization, a pointwise tone
+curve, the two HSV-space adjustments, and global and local histogram equalization:
+
+===================== ===================== ============================ ===================================
+kornia.enhance torchvision v2 OpenCV / albumentations scikit-image / PIL
+===================== ===================== ============================ ===================================
+``normalize`` ``normalize`` albumentations ``Normalize`` β€”
+``adjust_gamma`` ``adjust_gamma`` ``cv2.LUT`` (uint8) ``exposure.adjust_gamma``
+ ``RandomGamma``
+``adjust_hue`` ``adjust_hue`` ``ColorJitter(hue=)`` β€”
+``adjust_saturation`` ``adjust_saturation`` ``ColorJitter(saturation=)`` PIL ``ImageEnhance.Color``
+``equalize`` ``equalize`` (uint8) ``cv2.equalizeHist``/channel ``equalize_hist``; PIL ``equalize``
+ ``Equalize``
+``equalize_clahe`` β€” ``cv2.createCLAHE``/channel ``exposure.equalize_adapthist``
+ ``CLAHE``
+===================== ===================== ============================ ===================================
+
+Regimes (see ``benchmarks/README.md``): kornia/torchvision run a batched float BCHW tensor on CPU
+or GPU and kornia is differentiable, except torchvision's ``equalize``, which runs the same batch
+as uint8 BCHW (its documented input); OpenCV, albumentations and PIL run single uint8 HWC images on
+CPU in a Python loop, their native regime; scikit-image runs normalized float HWC images per image.
+PIL receives ready-made ``Image`` objects, as kornia receives a ready-made tensor. OpenCV's
+per-channel ops split and merge with ``cv2.split``/``cv2.merge``. The albumentations transforms are
+pinned to the same fixed parameter (``gamma_limit``, ``saturation`` and ``hue`` as one-point
+ranges, the other ``ColorJitter`` factors at identity, which it skips). Parameters are matched:
+mean/std ImageNet normalization, gamma 2.2, a hue shift of 0.1 turn (``0.2 * pi`` radians in
+kornia, ``0.1`` in torchvision), saturation 1.5, and CLAHE with clip limit 40 on an 8x8 grid. The
+gamma LUT is the native uint8 implementation of a pointwise curve. CLAHE clip limits are not
+interchangeable across libraries: OpenCV and kornia use an absolute multiple of the uniform bin
+height, scikit-image a normalized fraction, here set to ``40 / 256`` β€” equal in spirit only.
+albumentations' ``CLAHE`` does less work on RGB input: it converts to Lab, equalizes only the L
+channel and converts back, while kornia, OpenCV and scikit-image equalize all three channels; its
+cell is the transform as users call it, not the same computation. scikit-image's ``adjust_gamma``
+runs on float here, the documented regime; on ``uint8`` it uses a lookup table and is several times
+faster, which the OpenCV LUT cell represents. ``adjust_saturation`` is not the same algorithm
+across columns: kornia scales S in HSV space and converts back, while torchvision and PIL blend
+with the grayscale image (kornia's ``adjust_saturation_with_gray_subtraction``); the row times each
+library's saturation adjustment as users call it. Throughput is img/s.
+
+Usage:
+ python benchmarks/enhance/flagship.py --batches 1,8,32 --size 256 --device cpu
+ python benchmarks/enhance/flagship.py --device cuda --compile --json enhance_cuda.json
+"""
+
+from __future__ import annotations
+
+import argparse
+import math
+import sys
+from pathlib import Path
+from types import ModuleType
+from typing import Callable, Optional
+
+import numpy as np
+import torch
+
+# Prefer this checkout to an installed wheel or another editable checkout.
+sys.path.insert(0, str(Path(__file__).resolve().parents[2]))
+sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
+from common import (
+ Backend,
+ KorniaRows,
+ add_flagship_args,
+ batch_list,
+ finish_run,
+ image_batch,
+ image_row_fields,
+ optional_import,
+ run_batch_sweep,
+ setup_run,
+ start_run,
+)
+
+import kornia.enhance as KE
+
+OPS = ("normalize", "adjust_gamma", "adjust_hue", "adjust_saturation", "equalize", "equalize_clahe")
+MEAN, STD = (0.485, 0.456, 0.406), (0.229, 0.224, 0.225)
+GAMMA, HUE_TURN, SATURATION, CLAHE_CLIP, CLAHE_GRID = 2.2, 0.1, 1.5, 40.0, (8, 8)
+
+
+def build_ops(
+ b: int,
+ h: int,
+ w: int,
+ device: torch.device,
+ dtype: torch.dtype,
+ do_compile: bool,
+ libs: dict[str, Optional[ModuleType]],
+ skip_compile: frozenset[str] = frozenset(),
+ selected: Optional[frozenset[str]] = None,
+) -> tuple[dict[str, dict[str, Backend]], dict[str, str]]:
+ """Build {op: {backend: zero-arg callable}}; each callable adjusts the whole batch once."""
+ cv2, tvf, A, ske, pil_enh, pil_ops, pil = (libs[k] for k in ("cv2", "tvf", "A", "ske", "pil_enh", "pil_ops", "pil"))
+ imgs_u8, batch_f = image_batch(b, h, w, device, dtype)
+ imgs_f = [im.astype(np.float32) / 255.0 for im in imgs_u8]
+ batch_u8 = (batch_f.float() * 255).round().to(torch.uint8)
+ pil_imgs = [pil.fromarray(im) for im in imgs_u8] if pil else []
+ mean = torch.tensor(MEAN, device=device, dtype=dtype)
+ std = torch.tensor(STD, device=device, dtype=dtype)
+
+ kornia_row = KorniaRows(device, do_compile, skip_compile)
+ ops: dict[str, dict[str, Backend]] = {}
+
+ def include(name: str) -> bool:
+ return selected is None or name in selected
+
+ def cv_per_channel(fn: Callable[[np.ndarray], np.ndarray]) -> Backend:
+ return lambda: [cv2.merge([fn(c) for c in cv2.split(im)]) for im in imgs_u8]
+
+ def sk_per_channel(fn: Callable[[np.ndarray], np.ndarray]) -> Backend:
+ return lambda: [np.stack([fn(im[..., c]) for c in range(im.shape[-1])], axis=-1) for im in imgs_f]
+
+ def alb(t: object) -> Backend:
+ return lambda: [t(image=im)["image"] for im in imgs_u8]
+
+ def color_jitter(**factor: tuple[float, float]) -> object:
+ identity = {"brightness": (1.0, 1.0), "contrast": (1.0, 1.0), "saturation": (1.0, 1.0), "hue": (0.0, 0.0)}
+ return A.ColorJitter(**{**identity, **factor}, p=1.0)
+
+ if include("normalize"):
+ row = kornia_row("normalize", KE.normalize, batch_f, mean, std)
+ row["torchvision v2"] = (lambda: tvf.normalize(batch_f, list(MEAN), list(STD))) if tvf else None
+ row["albumentations"] = alb(A.Normalize(mean=MEAN, std=STD, max_pixel_value=255.0, p=1.0)) if A else None
+ ops["normalize"] = row
+
+ if include("adjust_gamma"):
+ row = kornia_row("adjust_gamma", KE.adjust_gamma, batch_f, GAMMA)
+ row["torchvision v2"] = (lambda: tvf.adjust_gamma(batch_f, GAMMA)) if tvf else None
+ if cv2:
+ lut = np.clip(((np.arange(256) / 255.0) ** GAMMA) * 255.0 + 0.5, 0, 255).astype(np.uint8)
+ row["opencv"] = lambda: [cv2.LUT(im, lut) for im in imgs_u8]
+ row["albumentations"] = alb(A.RandomGamma(gamma_limit=(GAMMA * 100, GAMMA * 100), p=1.0)) if A else None
+ row["scikit-image"] = (lambda: [ske.adjust_gamma(im, GAMMA) for im in imgs_f]) if ske else None
+ ops["adjust_gamma"] = row
+
+ if include("adjust_hue"):
+ row = kornia_row("adjust_hue", KE.adjust_hue, batch_f, 2 * math.pi * HUE_TURN)
+ row["torchvision v2"] = (lambda: tvf.adjust_hue(batch_f, HUE_TURN)) if tvf else None
+ row["albumentations"] = alb(color_jitter(hue=(HUE_TURN, HUE_TURN))) if A else None
+ ops["adjust_hue"] = row
+
+ if include("adjust_saturation"):
+ row = kornia_row("adjust_saturation", KE.adjust_saturation, batch_f, SATURATION)
+ row["torchvision v2"] = (lambda: tvf.adjust_saturation(batch_f, SATURATION)) if tvf else None
+ row["albumentations"] = alb(color_jitter(saturation=(SATURATION, SATURATION))) if A else None
+ if pil and pil_enh:
+ row["PIL"] = lambda: [pil_enh.Color(im).enhance(SATURATION) for im in pil_imgs]
+ ops["adjust_saturation"] = row
+
+ if include("equalize"):
+ row = kornia_row("equalize", KE.equalize, batch_f)
+ row["torchvision v2"] = (lambda: tvf.equalize(batch_u8)) if tvf else None
+ row["albumentations"] = alb(A.Equalize(mode="cv", by_channels=True, p=1.0)) if A else None
+ row["opencv"] = cv_per_channel(cv2.equalizeHist) if cv2 else None
+ row["scikit-image"] = sk_per_channel(ske.equalize_hist) if ske else None
+ if pil and pil_ops:
+ row["PIL"] = lambda: [pil_ops.equalize(im) for im in pil_imgs]
+ ops["equalize"] = row
+
+ if include("equalize_clahe"):
+ row = kornia_row("equalize_clahe", KE.equalize_clahe, batch_f, CLAHE_CLIP, CLAHE_GRID)
+ if cv2:
+ clahe = cv2.createCLAHE(clipLimit=CLAHE_CLIP, tileGridSize=CLAHE_GRID)
+ row["opencv"] = cv_per_channel(clahe.apply)
+ row["albumentations"] = (
+ alb(A.CLAHE(clip_limit=(CLAHE_CLIP, CLAHE_CLIP), tile_grid_size=CLAHE_GRID, p=1.0)) if A else None
+ )
+ if ske:
+ kernel = (h // CLAHE_GRID[0], w // CLAHE_GRID[1])
+ row["scikit-image"] = lambda: [
+ ske.equalize_adapthist(im, kernel_size=kernel, clip_limit=CLAHE_CLIP / 256) for im in imgs_f
+ ]
+ ops["equalize_clahe"] = row
+
+ return ops, kornia_row.compile_failures
+
+
+def main() -> None:
+ parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
+ add_flagship_args(parser, ops=OPS)
+ args = parser.parse_args()
+ device, dtype, sync = setup_run(args)
+
+ names = {
+ "cv2": "cv2",
+ "tvf": "torchvision.transforms.v2.functional",
+ "A": "albumentations",
+ "ske": "skimage.exposure",
+ "pil": "PIL.Image",
+ "pil_enh": "PIL.ImageEnhance",
+ "pil_ops": "PIL.ImageOps",
+ }
+ imported = {key: optional_import(module) for key, module in names.items()}
+ libs = {key: mod for key, (mod, _) in imported.items()}
+ labels = {"cv2": "opencv", "tvf": "torchvision", "A": "albumentations", "ske": "scikit-image", "pil": "PIL"}
+ meta = start_run(
+ "flagship enhance",
+ args,
+ device,
+ units="img/s",
+ regimes=[
+ "kornia/torchvision: batched float BCHW (torchvision equalize: uint8 BCHW); "
+ "albumentations/opencv/PIL: uint8 HWC per-image loop (CPU); scikit-image: normalized float HWC loop",
+ "PIL: prebuilt Image objects; albumentations CLAHE equalizes only L in Lab, the others all 3 channels",
+ ],
+ missing=[(label, imported[key][1]) for key, label in labels.items() if libs[key] is None],
+ )
+ backends = [
+ "kornia (eager)",
+ "kornia (compiled)",
+ "torchvision v2",
+ "albumentations",
+ "scikit-image",
+ "opencv",
+ "PIL",
+ ]
+ results = run_batch_sweep(
+ batch_list(args),
+ lambda b: build_ops(
+ b, args.size, args.size, device, dtype, args.compile, libs, args.skip_compile_ops, args.ops
+ ),
+ backends,
+ row_fields=image_row_fields(args),
+ sync=sync,
+ units="img/s",
+ min_run_time=args.min_run_time,
+ )
+ finish_run(args, "enhance", meta, results)
+
+
+if __name__ == "__main__":
+ main()
diff --git a/benchmarks/feature/flagship.py b/benchmarks/feature/flagship.py
new file mode 100644
index 000000000..04e9c2fd5
--- /dev/null
+++ b/benchmarks/feature/flagship.py
@@ -0,0 +1,218 @@
+# LICENSE HEADER MANAGED BY add-license-header
+#
+# Copyright 2018 Kornia Team
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+
+"""Flagship feature benchmark: kornia.feature vs OpenCV and scikit-image.
+
+Covers the local-feature pipeline end to end β€” a corner response, a full detector + descriptor,
+and descriptor matching β€” rather than every detector and descriptor the module exports:
+
+=================== =================================================== ==============================
+kornia.feature OpenCV (per-image loop, CPU) scikit-image (per-image loop)
+=================== =================================================== ==============================
+``harris_response`` ``cv2.cornerHarris(blockSize=7, ksize=3, k=0.04)`` ``corner_harris(sigma=1)``
+``gftt_response`` ``cv2.cornerMinEigenVal(blockSize=7, ksize=3)`` ``corner_shi_tomasi(sigma=1)``
+``SIFTFeature`` ``cv2.SIFT_create(nfeatures=512).detectAndCompute`` β€”
+``match_snn`` ``BFMatcher(NORM_L2).knnMatch(k=2)`` + ratio test β€”
+=================== =================================================== ==============================
+
+Regimes (see ``benchmarks/README.md``): kornia runs a batched float B1HW tensor on CPU or GPU and
+is differentiable; OpenCV and scikit-image run single grayscale images on CPU in a Python loop,
+their native regime β€” float32 for the corner responses, uint8 for SIFT. The input is Gaussian-blurred
+noise rather than white noise, so detectors see blob structure instead of a response at every
+pixel. kornia's responses weight the structure tensor with a 7x7 Gaussian (sigma 1), which
+scikit-image matches; OpenCV sums a 7x7 box. kornia's ``SIFTFeature`` and OpenCV's SIFT both keep
+at most 512 features per image, but their scale spaces, thresholds and orientation handling differ;
+the row compares complete detect+describe calls, not identical keypoints. kornia's scale-space
+detector accepts one image per call, so its SIFT row loops over the batch like OpenCV's. For accuracy on real
+images use ``local_features.py`` and ``sift_scale_space.py``; learned detectors and descriptors
+(DISK, ALIKED, HardNet, ...) need downloaded weights and are measured there too.
+
+``match_snn`` matches 2048 128-d descriptors against 2048, with a 0.8 ratio test, one pair per
+batch element; neither library batches pairs, so both loop in Python. The OpenCV column includes
+the list comprehension that applies the ratio test to ``knnMatch``'s result, which is how the API
+is used. Throughput counts images for the first three rows and descriptor-set pairs for
+``match_snn``; the JSON ``units`` is therefore ``items/s``.
+
+Usage:
+ python benchmarks/feature/flagship.py --batches 1,8,32 --size 256 --device cpu
+ python benchmarks/feature/flagship.py --device cuda --compile --json feature_cuda.json
+"""
+
+from __future__ import annotations
+
+import argparse
+import sys
+from pathlib import Path
+from types import ModuleType
+from typing import Optional
+
+import numpy as np
+import torch
+
+# Prefer this checkout to an installed wheel or another editable checkout.
+sys.path.insert(0, str(Path(__file__).resolve().parents[2]))
+sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
+from common import (
+ Backend,
+ KorniaRows,
+ add_flagship_args,
+ batch_list,
+ finish_run,
+ image_row_fields,
+ optional_import,
+ run_batch_sweep,
+ setup_run,
+ start_run,
+)
+
+import kornia.feature as KF
+from kornia.filters import gaussian_blur2d
+
+OPS = ("harris_response", "gftt_response", "SIFTFeature", "match_snn")
+NUM_FEATURES, NUM_DESCRIPTORS, DESCRIPTOR_DIM, SNN_RATIO = 512, 2048, 128, 0.8
+
+
+def blob_images(b: int, h: int, w: int) -> torch.Tensor:
+ """Seeded Gaussian-blurred noise in [0, 1], ``(B, 1, H, W)`` float32 on CPU."""
+ gen = torch.Generator().manual_seed(0)
+ noise = torch.rand(b, 1, h, w, generator=gen)
+ blurred = gaussian_blur2d(noise, (13, 13), (3.0, 3.0))
+ lo = blurred.amin(dim=(-2, -1), keepdim=True)
+ hi = blurred.amax(dim=(-2, -1), keepdim=True)
+ return (blurred - lo) / (hi - lo)
+
+
+def descriptor_pairs(b: int) -> tuple[torch.Tensor, torch.Tensor]:
+ """``b`` pairs of unit descriptor sets; the second is a noisy permutation of the first, so matches exist."""
+ gen = torch.Generator().manual_seed(0)
+ d1 = torch.nn.functional.normalize(torch.randn(b, NUM_DESCRIPTORS, DESCRIPTOR_DIM, generator=gen), dim=-1)
+ perm = torch.randperm(NUM_DESCRIPTORS, generator=gen)
+ noisy = d1[:, perm] + 0.1 * torch.randn(b, NUM_DESCRIPTORS, DESCRIPTOR_DIM, generator=gen)
+ return d1, torch.nn.functional.normalize(noisy, dim=-1)
+
+
+def match_pairs(d1: torch.Tensor, d2: torch.Tensor) -> list[tuple[torch.Tensor, torch.Tensor]]:
+ return [KF.match_snn(d1[i], d2[i], SNN_RATIO) for i in range(d1.shape[0])]
+
+
+def build_ops(
+ b: int,
+ h: int,
+ w: int,
+ device: torch.device,
+ dtype: torch.dtype,
+ do_compile: bool,
+ cv2: Optional[ModuleType],
+ skf: Optional[ModuleType],
+ skip_compile: frozenset[str] = frozenset(),
+ selected: Optional[frozenset[str]] = None,
+) -> tuple[dict[str, dict[str, Backend]], dict[str, str]]:
+ """Build {op: {backend: zero-arg callable}}; each callable processes the whole batch once."""
+ gray = blob_images(b, h, w)
+ gray_f = gray.to(device=device, dtype=dtype)
+ imgs_f32 = [np.ascontiguousarray(g[0].numpy()) for g in gray]
+ imgs_u8 = [(im * 255).round().astype(np.uint8) for im in imgs_f32]
+ d1, d2 = descriptor_pairs(b)
+ d1_dev, d2_dev = d1.to(device=device, dtype=dtype), d2.to(device=device, dtype=dtype)
+ d1_np, d2_np = d1.numpy(), d2.numpy()
+
+ kornia_row = KorniaRows(device, do_compile, skip_compile)
+ ops: dict[str, dict[str, Backend]] = {}
+
+ def include(name: str) -> bool:
+ return selected is None or name in selected
+
+ if include("harris_response"):
+ row = kornia_row("harris_response", KF.harris_response, gray_f, 0.04)
+ row["opencv"] = (lambda: [cv2.cornerHarris(im, 7, 3, 0.04) for im in imgs_f32]) if cv2 else None
+ row["scikit-image"] = (
+ (lambda: [skf.corner_harris(im, method="k", k=0.04, sigma=1) for im in imgs_f32]) if skf else None
+ )
+ ops["harris_response"] = row
+
+ if include("gftt_response"):
+ row = kornia_row("gftt_response", KF.gftt_response, gray_f)
+ row["opencv"] = (lambda: [cv2.cornerMinEigenVal(im, 7, 3) for im in imgs_f32]) if cv2 else None
+ row["scikit-image"] = (lambda: [skf.corner_shi_tomasi(im, sigma=1) for im in imgs_f32]) if skf else None
+ ops["gftt_response"] = row
+
+ if include("SIFTFeature"):
+ sift = KF.SIFTFeature(num_features=NUM_FEATURES, device=device).to(dtype=dtype).eval()
+
+ @torch.no_grad()
+ def sift_each(images: torch.Tensor) -> list[tuple[torch.Tensor, torch.Tensor, torch.Tensor]]:
+ return [sift(images[i : i + 1]) for i in range(images.shape[0])]
+
+ row = kornia_row("SIFTFeature", sift_each, gray_f)
+ if cv2:
+ cv_sift = cv2.SIFT_create(nfeatures=NUM_FEATURES)
+ row["opencv"] = lambda: [cv_sift.detectAndCompute(im, None) for im in imgs_u8]
+ ops["SIFTFeature"] = row
+
+ if include("match_snn"):
+ row = kornia_row("match_snn", match_pairs, d1_dev, d2_dev)
+ if cv2:
+ matcher = cv2.BFMatcher(cv2.NORM_L2)
+
+ def cv_match(i: int) -> list[object]:
+ knn = matcher.knnMatch(d1_np[i], d2_np[i], k=2)
+ return [m for m, n in knn if m.distance < SNN_RATIO * n.distance]
+
+ row["opencv"] = lambda: [cv_match(i) for i in range(b)]
+ ops["match_snn"] = row
+
+ return ops, kornia_row.compile_failures
+
+
+def main() -> None:
+ parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
+ add_flagship_args(parser, ops=OPS)
+ args = parser.parse_args()
+ device, dtype, sync = setup_run(args)
+
+ cv2, cv2_error = optional_import("cv2")
+ skf, skf_error = optional_import("skimage.feature")
+
+ libs = [(skf, "scikit-image", skf_error), (cv2, "opencv", cv2_error)]
+ meta = start_run(
+ "flagship feature",
+ args,
+ device,
+ units="items/s",
+ regimes=[
+ "kornia: batched float B1HW; opencv/scikit-image: grayscale per-image loop (CPU); "
+ "items = images, except match_snn = descriptor-set pairs"
+ ],
+ missing=[(name, err) for lib, name, err in libs if lib is None],
+ )
+ backends = ["kornia (eager)", "kornia (compiled)", "scikit-image", "opencv"]
+ results = run_batch_sweep(
+ batch_list(args),
+ lambda b: build_ops(
+ b, args.size, args.size, device, dtype, args.compile, cv2, skf, args.skip_compile_ops, args.ops
+ ),
+ backends,
+ row_fields=image_row_fields(args),
+ sync=sync,
+ units="items/s",
+ min_run_time=args.min_run_time,
+ )
+ finish_run(args, "feature", meta, results)
+
+
+if __name__ == "__main__":
+ main()
diff --git a/benchmarks/feature/laf_ops.py b/benchmarks/feature/laf_ops.py
index fc9f89c70..fceca786b 100644
--- a/benchmarks/feature/laf_ops.py
+++ b/benchmarks/feature/laf_ops.py
@@ -27,22 +27,22 @@ editable finder can resolve ``kornia`` to the primary checkout while ``git_commi
worktree HEAD -- an A/B that silently measures one revision twice. This script therefore puts its
own checkout root ahead of everything else on ``sys.path`` before importing kornia, prints the
resolved module path, records its checkout-relative form in the exported metadata as
-``kornia_module``, and warns loudly if it still resolved outside this checkout. Read that line
-before trusting a comparison.
+``kornia_module``, and warns loudly if it still resolved outside this checkout (all suites share
+this via ``common.start_run``). Read that line before trusting a comparison.
Covered ops (all public ``kornia.feature`` API):
-=============================== =============================================================
-op why it is here
-=============================== =============================================================
-``laf_from_center_scale_ori`` LAF construction, runs once per detector forward
-``make_upright`` orientation reset, per detector forward
-``ellipse_to_laf`` Oxford-format import; :mod:`ellipse_to_laf` drills into it
-``laf_to_boundary_points`` visualization export; also drives ``laf_is_inside_image``
-``laf_is_inside_image`` border filtering, per detector forward
-``extract_patches_simple`` patch sampling; one folded ``grid_sample`` since #4128
-``extract_patches_from_pyramid`` patch sampling; one ``grid_sample`` over a packed atlas
-=============================== =============================================================
+================================ ==========================================================
+op why it is here
+================================ ==========================================================
+``laf_from_center_scale_ori`` LAF construction, runs once per detector forward
+``make_upright`` orientation reset, per detector forward
+``ellipse_to_laf`` Oxford-format import; :mod:`ellipse_to_laf` drills into it
+``laf_to_boundary_points`` visualization export; also drives ``laf_is_inside_image``
+``laf_is_inside_image`` border filtering, per detector forward
+``extract_patches_simple`` patch sampling; one folded ``grid_sample`` since #4128
+``extract_patches_from_pyramid`` patch sampling; one ``grid_sample`` over a packed atlas
+================================ ==========================================================
Throughput counts **LAFs per second** (``B*N`` per call) -- the README's "items" for LAF ops.
Patch extraction samples a ``(B, 1, size, size)`` float image; the pyramid variant's cost also
@@ -59,7 +59,7 @@ from __future__ import annotations
import argparse
import sys
from pathlib import Path
-from typing import Any, Callable, Optional
+from typing import Any, Callable
import torch
@@ -67,23 +67,20 @@ import torch
# kornia measured is the one this file lives in. `main` verifies that it actually won.
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
sys.path.insert(0, str(Path(__file__).resolve().parents[2]))
-from common import (
- add_contribute_args,
- collect_load_metrics,
- contribute_result,
- print_preflight,
- run_batch_sweep,
- run_metadata,
- save_json,
- versions_line,
-)
+from common import Backend, KorniaRows, add_flagship_args, finish_run, run_batch_sweep, setup_run, start_run
import kornia.feature as KF
-Backend = Optional[Callable[[], object]]
-
-REPO_ROOT = Path(__file__).resolve().parents[2]
PATCH_SIZE = 32
+OPS = (
+ "laf_from_center_scale_ori",
+ "make_upright",
+ "ellipse_to_laf",
+ "laf_to_boundary_points",
+ "laf_is_inside_image",
+ "extract_patches_simple",
+ "extract_patches_from_pyramid",
+)
def pyramid_levels(size: int, ps: int) -> int:
@@ -134,7 +131,13 @@ def make_ellipses(b: int, n: int, size: int, device: torch.device, dtype: torch.
def build_ops(
- config: tuple[int, int], size: int, device: torch.device, dtype: torch.dtype, do_compile: bool
+ config: tuple[int, int],
+ size: int,
+ device: torch.device,
+ dtype: torch.dtype,
+ do_compile: bool,
+ skip_compile: frozenset[str] = frozenset(),
+ selected: frozenset[str] | None = None,
) -> tuple[dict[str, dict[str, Backend]], dict[str, str]]:
"""Zero-arg callables per (op, backend) for one config, plus the compile-warmup failures."""
b, n = config
@@ -156,93 +159,50 @@ def build_ops(
("extract_patches_from_pyramid", KF.extract_patches_from_pyramid, (img, lafs, PATCH_SIZE)),
]
- ops: dict[str, dict[str, Backend]] = {}
- compile_failures: dict[str, str] = {}
- if do_compile:
- # Reset dynamo once per config so every op compiles a fresh static-shape graph here;
- # without it the first config is timed on a static graph and later ones on the
- # automatic-dynamic recompile. Mirrors ellipse_to_laf.py. The reset belongs outside the
- # op loop: it invalidates every compiled callable, so resetting per op would push the
- # earlier ops' recompiles into the timed region instead of this warmup.
- torch._dynamo.reset()
- for name, fn, args in cases:
- row: dict[str, Backend] = {"kornia (eager)": (lambda fn=fn, args=args: fn(*args))}
- if do_compile:
- try:
- cfn = torch.compile(fn)
- cfn(*args) # warmup: compilation happens on the first call
- row["kornia (compiled)"] = lambda cfn=cfn, args=args: cfn(*args)
- except Exception as exc:
- compile_failures[name] = type(exc).__name__
- row["kornia (compiled)"] = None
- ops[name] = row
- return ops, compile_failures
+ # Reset dynamo once per config so every op compiles a fresh static-shape graph here;
+ # without it the first config is timed on a static graph and later ones on the
+ # automatic-dynamic recompile. Mirrors ellipse_to_laf.py. The reset belongs outside the
+ # op loop: it invalidates every compiled callable, so resetting per op would push the
+ # earlier ops' recompiles into the timed region instead of this warmup. These are distinct
+ # functions, so the recompile limit that forces per-op resets on the image suites does not bite.
+ kornia_row = KorniaRows(device, do_compile, skip_compile, reset_per_op=False)
+ ops = {name: kornia_row(name, fn, *args) for name, fn, args in cases if selected is None or name in selected}
+ return ops, kornia_row.compile_failures
def main() -> None:
parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
- parser.add_argument("--device", default="cpu", help="cpu, cuda, or mps")
- parser.add_argument("--dtype", default="float32", choices=["float16", "bfloat16", "float32", "float64"])
+ add_flagship_args(parser, ops=OPS, batches="")
parser.add_argument("--configs", default="1x2000,1x20000,8x2000", help="comma-separated BxN pairs")
- parser.add_argument("--size", type=int, default=256, help="square image side for the patch-extraction ops")
- parser.add_argument("--compile", action="store_true", help="add a torch.compile column")
- parser.add_argument("--min-run-time", type=float, default=1.0, help="seconds of repeats per measurement")
- parser.add_argument("--json", type=str, default=None, help="write results to this path as JSON")
- add_contribute_args(parser)
args = parser.parse_args()
-
- device = torch.device(args.device)
- dtype = getattr(torch, args.dtype)
+ device, dtype, sync = setup_run(args, opencv=False)
configs = [(int(b), int(n)) for b, n in (c.split("x") for c in args.configs.split(","))]
- sync = torch.mps.synchronize if device.type == "mps" else None # blocked_autorange syncs CUDA itself
-
- meta = run_metadata(device)
- meta["load"] = collect_load_metrics()
- kornia_file = sys.modules["kornia"].__file__
- resolved = Path(kornia_file).resolve() if kornia_file is not None else None
- inside = resolved is not None and REPO_ROOT in resolved.parents
- print_preflight(meta["load"])
- print(f"# laf_ops | commit {meta['git_commit']} | {meta['platform']} | {device} | {args.dtype}")
- print(f"# kornia module: {kornia_file}")
- if not inside:
- # git_commit() reports this checkout's HEAD, so a kornia from anywhere else means the
- # numbers and the commit label describe different code.
- print(f"# WARNING: kornia resolved outside {REPO_ROOT} - these numbers are NOT this checkout's.")
- print(versions_line(meta))
+ meta = start_run(
+ "feature LAF ops",
+ args,
+ device,
+ units="LAFs/s",
+ regimes=["kornia only: no other library exposes LAFs; compare against another kornia revision"],
+ )
backends = ["kornia (eager)"] + (["kornia (compiled)"] if args.compile else [])
def row_fields(config: tuple[int, int]) -> dict[str, Any]:
b, n = config
- return {"batch": b, "n_lafs": n, "size": args.size, "dtype": args.dtype}
+ return {"batch": b, "n_lafs": n, "height": args.size, "width": args.size, "dtype": args.dtype}
results = run_batch_sweep(
configs,
- lambda config: build_ops(config, args.size, device, dtype, args.compile),
+ lambda config: build_ops(config, args.size, device, dtype, args.compile, args.skip_compile_ops, args.ops),
backends,
row_fields=row_fields,
sync=sync,
label_fn=lambda c: f"B={c[0]} N={c[1]}",
items_fn=lambda c: c[0] * c[1],
units="LAFs/s",
- label_width=30,
- col_width=16,
min_run_time=args.min_run_time,
)
-
- # The exported form is checkout-relative. The absolute path above answers "which tree?" on
- # the console, where it is needed; a contributed file is public, and README's privacy rule
- # keeps home directories and machine layout out of it. Relative or "outside-checkout" still
- # carries the only bit a reader of the file needs: did kornia resolve to the measured tree?
- module_field = resolved.relative_to(REPO_ROOT).as_posix() if inside else "outside-checkout"
- # The docs page and the llms digest label the throughput column from this key; without it a
- # committed run reads as "items/s", and the item here is a LAF, not an image.
- export_meta = {**meta, "kornia_module": module_field, "units": "LAFs/s"}
- if args.json:
- out = save_json(args.json, export_meta, results)
- print(f"# wrote {out}")
- if args.contribute:
- contribute_result(args.contribute, "feature-laf-ops", export_meta, results, args.machine_slug)
+ finish_run(args, "feature-laf-ops", meta, results)
if __name__ == "__main__":
diff --git a/benchmarks/filters/flagship.py b/benchmarks/filters/flagship.py
index ef28e4ffc..65af3e57f 100644
--- a/benchmarks/filters/flagship.py
+++ b/benchmarks/filters/flagship.py
@@ -92,8 +92,6 @@ Usage:
from __future__ import annotations
import argparse
-import importlib
-import platform
import sys
from pathlib import Path
from types import ModuleType
@@ -107,21 +105,21 @@ import torch
sys.path.insert(0, str(Path(__file__).resolve().parents[2]))
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
from common import (
- add_contribute_args,
- collect_load_metrics,
- contribute_result,
- print_preflight,
+ Backend,
+ KorniaRows,
+ add_flagship_args,
+ batch_list,
+ finish_run,
+ image_batch,
+ image_row_fields,
+ optional_import,
run_batch_sweep,
- run_metadata,
- save_json,
- versions_line,
- warm_up_cpu,
+ setup_run,
+ start_run,
)
import kornia.filters as KF
-Backend = Optional[Callable[[], object]]
-
AVAILABLE_OPS = (
"gaussian_blur2d",
"sobel",
@@ -139,24 +137,6 @@ AVAILABLE_OPS = (
)
-def optional_import(name: str) -> tuple[Optional[ModuleType], Optional[str]]:
- """Import an optional benchmark dependency and retain a concise failure reason."""
- try:
- return importlib.import_module(name), None
- except Exception as error:
- return None, f"{type(error).__name__}: {error}"
-
-
-def parse_ops(value: str) -> frozenset[str] | None:
- """Parse a comma-separated operation selection, validating benchmark row names."""
- selected = frozenset(name.strip() for name in value.split(",") if name.strip())
- unknown = selected.difference(AVAILABLE_OPS)
- if unknown:
- available = ", ".join(AVAILABLE_OPS)
- raise argparse.ArgumentTypeError(f"unknown operation(s): {', '.join(sorted(unknown))}. Available: {available}")
- return selected or None
-
-
def build_specialized_ops(
batch_f: torch.Tensor,
imgs_u8: list[np.ndarray],
@@ -296,44 +276,11 @@ def build_ops(
skr: Optional[ModuleType] = None,
) -> tuple[dict[str, dict[str, Backend]], dict[str, str]]:
"""Build {op: {backend: zero-arg callable}} with the documented per-backend regimes."""
- rng = np.random.default_rng(0)
- imgs_u8 = [(rng.random((h, w, 3)) * 255).astype(np.uint8) for _ in range(b)]
+ imgs_u8, batch_f = image_batch(b, h, w, device, dtype)
imgs_f = [im.astype(np.float32) / 255.0 for im in imgs_u8]
imgs_gray_f = [im.mean(axis=-1) for im in imgs_f]
imgs_gray_u8 = [np.rint(im.mean(axis=-1)).astype(np.uint8)[..., None] for im in imgs_u8]
- batch_f = (
- torch.stack([torch.from_numpy(im).permute(2, 0, 1) for im in imgs_u8]).to(device=device, dtype=dtype).div(255)
- )
-
- compile_failures: dict[str, str] = {}
-
- def kornia_row(label: str, fn: Callable[[], object]) -> dict[str, Backend]:
- row: dict[str, Backend] = {"kornia (eager)": fn}
- if do_compile and label not in skip_compile:
- torch._dynamo.reset()
- compiled = torch.compile(fn)
- try:
- compiled() # warmup: compile + autotune before the timed region
- if device.type == "cuda":
- torch.cuda.synchronize() # surface async kernel faults HERE, not at the next op
- row["kornia (compiled)"] = compiled
- except Exception as e:
- errors = str(e)
- if device.type == "cuda":
- try:
- torch.cuda.synchronize() # a FAILED warmup may still have launched kernels
- except Exception as sync_err:
- errors += " | " + str(sync_err)
- if "illegal memory access" in errors:
- raise SystemExit(
- f"FATAL: CUDA context poisoned during torch.compile warmup of '{label}' "
- "(illegal memory access); no later measurement would be trustworthy. "
- f"Rerun with --skip-compile-ops {label} to keep it eager-only, or without "
- "--compile; CUDA_LAUNCH_BLOCKING=1 localizes the kernel."
- ) from e
- row["kornia (compiled)"] = None
- compile_failures[label] = type(e).__name__
- return row
+ kornia_row = KorniaRows(device, do_compile, skip_compile)
def alb(t: object) -> Backend:
return lambda: [t(image=im)["image"] for im in imgs_u8]
@@ -458,40 +405,14 @@ def build_ops(
)
)
- return ops, compile_failures
+ return ops, kornia_row.compile_failures
def main() -> None:
parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
- parser.add_argument("--batches", type=str, default="1,8,32", help="comma-separated batch sizes to sweep")
- parser.add_argument("--size", type=int, default=256)
- parser.add_argument("--device", type=str, default="cpu")
- parser.add_argument("--dtype", type=str, default="float32", choices=["float32", "float16", "bfloat16"])
- parser.add_argument("--threads", type=int, default=4)
- parser.add_argument("--compile", action="store_true", help="also time torch.compile'd kornia")
- parser.add_argument(
- "--ops",
- type=parse_ops,
- default=None,
- help="comma-separated benchmark rows to run (default: all)",
- )
- parser.add_argument(
- "--skip-compile-ops",
- type=str,
- default="",
- help="comma-separated op names to keep eager-only (workaround for faulting compiled kernels)",
- )
- parser.add_argument("--json", type=str, default=None, help="write machine-readable results to this path")
- add_contribute_args(parser)
+ add_flagship_args(parser, ops=AVAILABLE_OPS)
args = parser.parse_args()
- skip_compile = frozenset(s.strip() for s in args.skip_compile_ops.split(",") if s.strip())
-
- torch.set_num_threads(args.threads)
- warm_up_cpu()
- torch.manual_seed(0)
- device = torch.device(args.device)
- dtype = getattr(torch, args.dtype)
- sync = torch.mps.synchronize if device.type == "mps" else None # Timer only syncs CUDA
+ device, dtype, sync = setup_run(args)
cv2, cv2_error = optional_import("cv2")
A, albumentations_error = optional_import("albumentations")
@@ -501,34 +422,28 @@ def main() -> None:
skf, skimage_filters_error = optional_import("skimage.filters")
skr, skimage_restoration_error = optional_import("skimage.restoration")
- meta = run_metadata(device)
- meta["load"] = collect_load_metrics()
- if args.contribute:
- print_preflight(meta["load"])
- print(f"# flagship filters benchmark β€” commit {meta['git_commit']} β€” {platform.platform()}")
- print(versions_line(meta))
- print(f"# kornia source: {Path(KF.__file__).resolve()}")
- if device.type == "cuda":
- print(f"# CUDA device: {meta['cuda_device']} (CUDA {meta['cuda_version']})")
- print(f"# device={device}, dtype={args.dtype}, threads={args.threads}, size={args.size} β€” throughput img/s")
- print(
- "# kornia/torchvision: batched float BCHW; "
- "albumentations/opencv/kornia-rs/PIL: uint8 HWC per-image loop (CPU), except kornia-rs Sobel float32; "
- "scikit-image: normalized float HWC per-image loop except uint8 rank mean"
- )
- unavailable = [
+ libs = [
(cv2, "opencv", cv2_error),
(A, "albumentations", albumentations_error),
(tvf, "torchvision", torchvision_error),
(pil if pilf is not None else None, "PIL", pil_error or pilf_error),
]
- for present, name, error in unavailable:
- if present is None:
- print(f"# NOTE: {name} not available ({error}) β€” its column is skipped")
+ missing = [(name, error) for present, name, error in libs if present is None]
if skf is None and skr is None:
- error = skimage_filters_error or skimage_restoration_error
- print(f"# NOTE: scikit-image not available ({error}) β€” its column is skipped")
- else:
+ missing.append(("scikit-image", skimage_filters_error or skimage_restoration_error))
+ meta = start_run(
+ "flagship filters",
+ args,
+ device,
+ units="img/s",
+ regimes=[
+ "kornia/torchvision: batched float BCHW; "
+ "albumentations/opencv/kornia-rs/PIL: uint8 HWC per-image loop (CPU), except kornia-rs Sobel float32; "
+ "scikit-image: normalized float HWC per-image loop except uint8 rank mean"
+ ],
+ missing=missing,
+ )
+ if skf is not None or skr is not None:
if skf is None:
print(f"# NOTE: scikit-image filters not available ({skimage_filters_error}) β€” affected rows are skipped")
if skr is None:
@@ -538,10 +453,6 @@ def main() -> None:
)
if krs_fn("gaussian_blur") is None:
print("# NOTE: kornia-rs filter APIs not available β€” its column is skipped")
- if skip_compile:
- print(f"# NOTE: --skip-compile-ops keeps eager-only: {', '.join(sorted(skip_compile))}")
- if args.ops:
- print(f"# selected rows: {', '.join(sorted(args.ops))}")
backends = [
"kornia (eager)",
@@ -554,7 +465,7 @@ def main() -> None:
"PIL",
]
results = run_batch_sweep(
- [int(x) for x in args.batches.split(",") if x.strip()],
+ batch_list(args),
lambda b: build_ops(
b,
args.size,
@@ -567,20 +478,18 @@ def main() -> None:
tvf,
pil,
pilf,
- skip_compile,
+ args.skip_compile_ops,
args.ops,
skf,
skr,
),
backends,
- row_fields=lambda b: {"height": args.size, "width": args.size, "dtype": args.dtype},
+ row_fields=image_row_fields(args),
sync=sync,
+ units="img/s",
+ min_run_time=args.min_run_time,
)
- if args.json:
- out = save_json(args.json, meta, results)
- print(f"# results written to {out}")
- if args.contribute:
- contribute_result(args.contribute, "filters", meta, results, slug_override=args.machine_slug)
+ finish_run(args, "filters", meta, results)
if __name__ == "__main__":
diff --git a/benchmarks/geometry/flagship.py b/benchmarks/geometry/flagship.py
index e587a1530..fcdf7e98c 100644
--- a/benchmarks/geometry/flagship.py
+++ b/benchmarks/geometry/flagship.py
@@ -19,15 +19,15 @@
Covers the differentiated-core ops named by the W3 benchmark plan:
-=========================== ============================================== ==================
-kornia (batched float BCHW) OpenCV (uint8 HWC, per-image Python loop) torchvision v2
-=========================== ============================================== ==================
-``warp_perspective`` ``cv2.warpPerspective`` β€”
-``warp_affine`` ``cv2.warpAffine`` β€”
-``rotate`` ``cv2.warpAffine(getRotationMatrix2D)`` ``tvf.rotate``
-``resize`` ``cv2.resize`` ``tvf.resize``
-``get_perspective_transform`` ``cv2.getPerspectiveTransform`` (per pair) β€”
-=========================== ============================================== ==================
+============================= ========================================== ==============
+kornia (batched float BCHW) OpenCV (uint8 HWC, per-image Python loop) torchvision v2
+============================= ========================================== ==============
+``warp_perspective`` ``cv2.warpPerspective`` β€”
+``warp_affine`` ``cv2.warpAffine`` β€”
+``rotate`` ``cv2.warpAffine(getRotationMatrix2D)`` ``tvf.rotate``
+``resize`` ``cv2.resize`` ``tvf.resize``
+``get_perspective_transform`` ``cv2.getPerspectiveTransform`` (per pair) β€”
+============================= ========================================== ==============
Regimes (same framing as ``benchmarks/augmentation``): kornia/torchvision run a batched float
tensor on CPU or GPU and kornia is differentiable; OpenCV runs single uint8 images on CPU in
@@ -44,30 +44,34 @@ Usage:
from __future__ import annotations
import argparse
-import platform
import sys
from pathlib import Path
from types import ModuleType
-from typing import Callable, Optional
+from typing import Optional
import numpy as np
import torch
+# Prefer this checkout to an installed wheel or another editable checkout.
+sys.path.insert(0, str(Path(__file__).resolve().parents[2]))
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
from common import (
- add_contribute_args,
- collect_load_metrics,
- contribute_result,
- print_preflight,
+ Backend,
+ KorniaRows,
+ add_flagship_args,
+ batch_list,
+ finish_run,
+ image_batch,
+ image_row_fields,
+ optional_import,
run_batch_sweep,
- run_metadata,
- save_json,
- versions_line,
+ setup_run,
+ start_run,
)
import kornia.geometry as KG
-Backend = Optional[Callable[[], object]]
+OPS = ("warp_perspective", "warp_affine", "rotate", "resize", "get_perspective_transform")
def build_ops(
@@ -80,17 +84,14 @@ def build_ops(
cv2: Optional[ModuleType],
tvf: Optional[ModuleType],
skip_compile: frozenset[str] = frozenset(),
+ selected: Optional[frozenset[str]] = None,
) -> tuple[dict[str, dict[str, Backend]], dict[str, str]]:
"""Build {op: {backend: zero-arg callable}} with identical transform params per backend.
Also returns {op: exception name} for ops whose ``torch.compile`` warmup failed, so the
caller can report them instead of leaving a silent skip cell.
"""
- rng = np.random.default_rng(0)
- imgs_u8 = [(rng.random((h, w, 3)) * 255).astype(np.uint8) for _ in range(b)]
- batch_f = (
- torch.stack([torch.from_numpy(im).permute(2, 0, 1) for im in imgs_u8]).to(device=device, dtype=dtype).div(255)
- )
+ imgs_u8, batch_f = image_batch(b, h, w, device, dtype)
angle_deg = 30.0
angle = torch.full((b,), angle_deg, device=device, dtype=dtype)
@@ -110,135 +111,80 @@ def build_ops(
h_np = h_mat.float().cpu().numpy().astype(np.float64)
src_np, dst_np = src_pts32.numpy(), dst_pts32.numpy()
- compile_failures: dict[str, str] = {}
-
- def kornia_row(label: str, fn: Callable[[], object]) -> dict[str, Backend]:
- row: dict[str, Backend] = {"kornia (eager)": fn}
- if do_compile and label not in skip_compile:
- torch._dynamo.reset()
- compiled = torch.compile(fn)
- try:
- compiled() # warmup: compile + autotune before the timed region
- if device.type == "cuda":
- torch.cuda.synchronize() # surface async kernel faults HERE, not at the next op
- row["kornia (compiled)"] = compiled
- except Exception as e:
- errors = str(e)
- if device.type == "cuda":
- try:
- torch.cuda.synchronize() # a FAILED warmup may still have launched kernels
- except Exception as sync_err:
- errors += " | " + str(sync_err)
- if "illegal memory access" in errors:
- raise SystemExit(
- f"FATAL: CUDA context poisoned during torch.compile warmup of '{label}' "
- "(illegal memory access); no later measurement would be trustworthy. "
- f"Rerun with --skip-compile-ops {label} to keep it eager-only, or without "
- "--compile; CUDA_LAUNCH_BLOCKING=1 localizes the kernel."
- ) from e
- row["kornia (compiled)"] = None
- compile_failures[label] = type(e).__name__
- return row
-
+ kornia_row = KorniaRows(device, do_compile, skip_compile)
ops: dict[str, dict[str, Backend]] = {}
- row = kornia_row("warp_perspective", lambda: KG.warp_perspective(batch_f, h_mat, (h, w)))
- row["opencv"] = (
- (lambda: [cv2.warpPerspective(im, h_np[i], (w, h)) for i, im in enumerate(imgs_u8)]) if cv2 else None
- )
- row["torchvision v2"] = None
- ops["warp_perspective"] = row
-
- row = kornia_row("warp_affine", lambda: KG.warp_affine(batch_f, m_affine, (h, w)))
- row["opencv"] = (lambda: [cv2.warpAffine(im, m_np[i], (w, h)) for i, im in enumerate(imgs_u8)]) if cv2 else None
- row["torchvision v2"] = None
- ops["warp_affine"] = row
-
- row = kornia_row("rotate", lambda: KG.rotate(batch_f, angle))
- if cv2:
- m_rot = cv2.getRotationMatrix2D((w / 2, h / 2), angle_deg, 1.0)
- row["opencv"] = lambda: [cv2.warpAffine(im, m_rot, (w, h)) for im in imgs_u8]
- else:
- row["opencv"] = None
- row["torchvision v2"] = (lambda: tvf.rotate(batch_f, angle_deg)) if tvf else None
- ops["rotate"] = row
-
- dst_size = (h // 2, w // 2)
- row = kornia_row("resize", lambda: KG.resize(batch_f, dst_size, interpolation="bilinear"))
- row["opencv"] = (lambda: [cv2.resize(im, (dst_size[1], dst_size[0])) for im in imgs_u8]) if cv2 else None
- row["torchvision v2"] = (lambda: tvf.resize(batch_f, list(dst_size), antialias=False)) if tvf else None
- ops["resize"] = row
-
- row = kornia_row("get_perspective_transform", lambda: KG.get_perspective_transform(src_pts, dst_pts))
- row["opencv"] = (lambda: [cv2.getPerspectiveTransform(src_np[i], dst_np[i]) for i in range(b)]) if cv2 else None
- row["torchvision v2"] = None
- ops["get_perspective_transform"] = row
- return ops, compile_failures
+ def include(name: str) -> bool:
+ return selected is None or name in selected
+
+ if include("warp_perspective"):
+ row = kornia_row("warp_perspective", lambda: KG.warp_perspective(batch_f, h_mat, (h, w)))
+ row["opencv"] = (
+ (lambda: [cv2.warpPerspective(im, h_np[i], (w, h)) for i, im in enumerate(imgs_u8)]) if cv2 else None
+ )
+ ops["warp_perspective"] = row
+
+ if include("warp_affine"):
+ row = kornia_row("warp_affine", lambda: KG.warp_affine(batch_f, m_affine, (h, w)))
+ row["opencv"] = (lambda: [cv2.warpAffine(im, m_np[i], (w, h)) for i, im in enumerate(imgs_u8)]) if cv2 else None
+ ops["warp_affine"] = row
+
+ if include("rotate"):
+ row = kornia_row("rotate", lambda: KG.rotate(batch_f, angle))
+ if cv2:
+ m_rot = cv2.getRotationMatrix2D((w / 2, h / 2), angle_deg, 1.0)
+ row["opencv"] = lambda: [cv2.warpAffine(im, m_rot, (w, h)) for im in imgs_u8]
+ row["torchvision v2"] = (lambda: tvf.rotate(batch_f, angle_deg)) if tvf else None
+ ops["rotate"] = row
+
+ if include("resize"):
+ dst_size = (h // 2, w // 2)
+ row = kornia_row("resize", lambda: KG.resize(batch_f, dst_size, interpolation="bilinear"))
+ row["opencv"] = (lambda: [cv2.resize(im, (dst_size[1], dst_size[0])) for im in imgs_u8]) if cv2 else None
+ row["torchvision v2"] = (lambda: tvf.resize(batch_f, list(dst_size), antialias=False)) if tvf else None
+ ops["resize"] = row
+
+ if include("get_perspective_transform"):
+ row = kornia_row("get_perspective_transform", lambda: KG.get_perspective_transform(src_pts, dst_pts))
+ row["opencv"] = (lambda: [cv2.getPerspectiveTransform(src_np[i], dst_np[i]) for i in range(b)]) if cv2 else None
+ ops["get_perspective_transform"] = row
+ return ops, kornia_row.compile_failures
def main() -> None:
parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
- parser.add_argument("--batches", type=str, default="1,8,32", help="comma-separated batch sizes to sweep")
- parser.add_argument("--size", type=int, default=256)
- parser.add_argument("--device", type=str, default="cpu")
- parser.add_argument("--dtype", type=str, default="float32", choices=["float32", "float16", "bfloat16"])
- parser.add_argument("--threads", type=int, default=4)
- parser.add_argument("--compile", action="store_true", help="also time torch.compile'd kornia")
- parser.add_argument(
- "--skip-compile-ops",
- type=str,
- default="",
- help="comma-separated op names to keep eager-only (workaround for faulting compiled kernels)",
- )
- parser.add_argument("--json", type=str, default=None, help="write machine-readable results to this path")
- add_contribute_args(parser)
+ add_flagship_args(parser, ops=OPS)
args = parser.parse_args()
- skip_compile = frozenset(s.strip() for s in args.skip_compile_ops.split(",") if s.strip())
-
- torch.set_num_threads(args.threads)
- torch.manual_seed(0)
- device = torch.device(args.device)
- dtype = getattr(torch, args.dtype)
- sync = torch.mps.synchronize if device.type == "mps" else None # Timer only syncs CUDA
-
- try:
- import cv2
- except Exception:
- cv2 = None
- try:
- import torchvision.transforms.v2.functional as tvf
- except Exception:
- tvf = None
-
- meta = run_metadata(device)
- meta["load"] = collect_load_metrics()
- if args.contribute:
- print_preflight(meta["load"])
- print(f"# flagship geometry benchmark β€” commit {meta['git_commit']} β€” {platform.platform()}")
- print(versions_line(meta))
- if device.type == "cuda":
- print(f"# CUDA device: {meta['cuda_device']} (CUDA {meta['cuda_version']})")
- print(f"# device={device}, dtype={args.dtype}, threads={args.threads}, size={args.size} β€” throughput items/s")
- print("# kornia/torchvision: batched float BCHW; opencv: uint8 HWC per-image loop (CPU); '-' = skipped")
- for lib, name in [(cv2, "opencv"), (tvf, "torchvision")]:
- if lib is None:
- print(f"# NOTE: {name} not installed β€” its column is skipped")
- if skip_compile:
- print(f"# NOTE: --skip-compile-ops keeps eager-only: {', '.join(sorted(skip_compile))}")
-
+ device, dtype, sync = setup_run(args)
+
+ cv2, cv2_error = optional_import("cv2")
+ tvf, tvf_error = optional_import("torchvision.transforms.v2.functional")
+
+ meta = start_run(
+ "flagship geometry",
+ args,
+ device,
+ units="items/s",
+ regimes=["kornia/torchvision: batched float BCHW; opencv: uint8 HWC per-image loop (CPU)"],
+ missing=[
+ (name, err)
+ for lib, name, err in [(cv2, "opencv", cv2_error), (tvf, "torchvision", tvf_error)]
+ if lib is None
+ ],
+ )
backends = ["kornia (eager)", "kornia (compiled)", "torchvision v2", "opencv"]
results = run_batch_sweep(
- [int(x) for x in args.batches.split(",") if x.strip()],
- lambda b: build_ops(b, args.size, args.size, device, dtype, args.compile, cv2, tvf, skip_compile),
+ batch_list(args),
+ lambda b: build_ops(
+ b, args.size, args.size, device, dtype, args.compile, cv2, tvf, args.skip_compile_ops, args.ops
+ ),
backends,
- row_fields=lambda b: {"height": args.size, "width": args.size, "dtype": args.dtype},
+ row_fields=image_row_fields(args),
sync=sync,
+ units="items/s",
+ min_run_time=args.min_run_time,
)
- if args.json:
- out = save_json(args.json, meta, results)
- print(f"# results written to {out}")
- if args.contribute:
- contribute_result(args.contribute, "geometry", meta, results, slug_override=args.machine_slug)
+ finish_run(args, "geometry", meta, results)
if __name__ == "__main__":
diff --git a/benchmarks/io/flagship.py b/benchmarks/io/flagship.py
new file mode 100644
index 000000000..c89f90cda
--- /dev/null
+++ b/benchmarks/io/flagship.py
@@ -0,0 +1,188 @@
+# LICENSE HEADER MANAGED BY add-license-header
+#
+# Copyright 2018 Kornia Team
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+
+"""Flagship io benchmark: kornia.io image decoding vs OpenCV, torchvision and PIL.
+
+Times what a data loader pays per image: read an encoded file from disk and decode it to an RGB
+``uint8`` array or tensor. One row per common format:
+
+============= ============================ ==================================== =============================
+kornia.io OpenCV torchvision.io PIL
+============= ============================ ==================================== =============================
+``load_jpeg`` ``imread(IMREAD_COLOR_RGB)`` ``decode_jpeg([read_file(p), ...])`` ``np.asarray(Image.open(p))``
+``load_png`` ``imread(IMREAD_COLOR_RGB)`` ``decode_image(read_file(p))`` ``np.asarray(Image.open(p))``
+============= ============================ ==================================== =============================
+
+kornia calls ``load_image(path, ImageLoadType.RGB8, device)``, which decodes with kornia-rs and
+returns a ``(3, H, W)`` uint8 tensor on the selected device; torchvision's tensor is moved to the
+same device, so on an accelerator both columns include the host-to-device copy and the device sync.
+OpenCV and PIL return host arrays, their native result, and never touch the accelerator. Every
+column produces RGB: OpenCV decodes straight to RGB with ``IMREAD_COLOR_RGB`` (OpenCV 4.10 and
+later; older versions time ``imread`` plus a ``cvtColor``), and PIL converts only when the file is
+not already RGB. PIL's cell includes ``np.asarray``, which forces the lazy decode, and closes each
+file. torchvision decodes the JPEG row with one batched ``decode_jpeg`` call over the file bytes,
+its fastest CPU path; ``decode_image`` takes one image at a time, so the PNG row loops. Each call
+loads ``batch`` distinct files, so the throughput is decoded images per second. The files are
+``--size`` square RGB images of Gaussian-blurred noise β€” compressible like a photograph rather than
+like white noise β€” written once per config to a temporary directory (JPEG quality 90 via PIL, PNG
+default compression) and read back through the OS page cache, so the rows measure decoding, not
+storage. There is no ``torch.compile`` column: file I/O and the kornia-rs decoder are outside what
+it compiles, so ``--compile`` is ignored.
+
+Usage:
+ python benchmarks/io/flagship.py --batches 1,8,32 --size 256 --device cpu
+ python benchmarks/io/flagship.py --device cuda --json io_cuda.json
+"""
+
+from __future__ import annotations
+
+import argparse
+import sys
+import tempfile
+from pathlib import Path
+from types import ModuleType
+from typing import Optional
+
+import numpy as np
+import torch
+
+# Prefer this checkout to an installed wheel or another editable checkout.
+sys.path.insert(0, str(Path(__file__).resolve().parents[2]))
+sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
+from common import (
+ Backend,
+ add_flagship_args,
+ batch_list,
+ finish_run,
+ image_row_fields,
+ optional_import,
+ run_batch_sweep,
+ setup_run,
+ start_run,
+)
+
+from kornia.filters import gaussian_blur2d
+from kornia.io import ImageLoadType, load_image
+
+OPS = ("load_jpeg", "load_png")
+FORMATS = {"load_jpeg": ("jpg", {"quality": 90}), "load_png": ("png", {})}
+
+
+def write_images(root: Path, b: int, size: int, pil: ModuleType) -> dict[str, list[str]]:
+ """Write ``b`` seeded smooth RGB images per format; returns ``{op: [paths]}``."""
+ gen = torch.Generator().manual_seed(0)
+ noise = torch.rand(b, 3, size, size, generator=gen)
+ smooth = gaussian_blur2d(noise, (13, 13), (3.0, 3.0))
+ lo, hi = smooth.amin(dim=(-2, -1), keepdim=True), smooth.amax(dim=(-2, -1), keepdim=True)
+ arrays = ((smooth - lo) / (hi - lo) * 255).round().to(torch.uint8).permute(0, 2, 3, 1).numpy()
+ paths: dict[str, list[str]] = {}
+ for op, (ext, options) in FORMATS.items():
+ paths[op] = []
+ for i, arr in enumerate(arrays):
+ path = root / f"b{b}_{i}.{ext}"
+ pil.fromarray(arr).save(path, **options)
+ paths[op].append(str(path))
+ return paths
+
+
+def pil_rgb(pil: ModuleType, path: str) -> np.ndarray:
+ """Decode ``path`` to an RGB ``uint8`` array and close the file."""
+ with pil.open(path) as im:
+ return np.asarray(im if im.mode == "RGB" else im.convert("RGB"))
+
+
+def build_ops(
+ b: int,
+ size: int,
+ root: Path,
+ device: torch.device,
+ cv2: Optional[ModuleType],
+ tvio: Optional[ModuleType],
+ pil: ModuleType,
+ selected: Optional[frozenset[str]] = None,
+) -> tuple[dict[str, dict[str, Backend]], dict[str, str]]:
+ """Build {op: {backend: zero-arg callable}}; each callable loads ``b`` files once."""
+ paths = write_images(root, b, size, pil)
+ ops: dict[str, dict[str, Backend]] = {}
+ for op in OPS:
+ if selected is not None and op not in selected:
+ continue
+ files = paths[op]
+ row: dict[str, Backend] = {
+ "kornia (eager)": lambda files=files: [load_image(p, ImageLoadType.RGB8, device) for p in files]
+ }
+ if tvio and op == "load_jpeg":
+ row["torchvision"] = lambda files=files: [
+ im.to(device)
+ for im in tvio.decode_jpeg([tvio.read_file(p) for p in files], mode=tvio.ImageReadMode.RGB)
+ ]
+ elif tvio:
+ row["torchvision"] = lambda files=files: [
+ tvio.decode_image(tvio.read_file(p), mode=tvio.ImageReadMode.RGB).to(device) for p in files
+ ]
+ if cv2 and hasattr(cv2, "IMREAD_COLOR_RGB"):
+ row["opencv"] = lambda files=files: [cv2.imread(p, cv2.IMREAD_COLOR_RGB) for p in files]
+ elif cv2:
+ row["opencv"] = lambda files=files: [
+ cv2.cvtColor(cv2.imread(p, cv2.IMREAD_COLOR), cv2.COLOR_BGR2RGB) for p in files
+ ]
+ row["PIL"] = lambda files=files: [pil_rgb(pil, p) for p in files]
+ ops[op] = row
+ return ops, {}
+
+
+def main() -> None:
+ parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
+ add_flagship_args(parser, ops=OPS)
+ args = parser.parse_args()
+ device, _, sync = setup_run(args)
+ args.dtype = "uint8" # every decoder returns uint8; the header and the rows say so
+
+ cv2, cv2_error = optional_import("cv2")
+ tvio, tvio_error = optional_import("torchvision.io")
+ pil, pil_error = optional_import("PIL.Image")
+ if pil is None:
+ raise SystemExit(f"PIL is required to write the benchmark's input files ({pil_error})")
+
+ libs = [(tvio, "torchvision", tvio_error), (cv2, "opencv", cv2_error)]
+ meta = start_run(
+ "flagship io",
+ args,
+ device,
+ units="img/s",
+ regimes=[
+ "kornia/torchvision: file -> uint8 CHW tensor on the device; opencv/PIL: file -> uint8 HWC host array",
+ "--dtype does not apply (decoders return uint8); no torch.compile column",
+ ],
+ missing=[(name, err) for lib, name, err in libs if lib is None],
+ )
+ backends = ["kornia (eager)", "torchvision", "opencv", "PIL"]
+ with tempfile.TemporaryDirectory(prefix="kornia-io-bench-") as tmp:
+ results = run_batch_sweep(
+ batch_list(args),
+ lambda b: build_ops(b, args.size, Path(tmp), device, cv2, tvio, pil, args.ops),
+ backends,
+ row_fields=image_row_fields(args),
+ sync=sync,
+ units="img/s",
+ min_run_time=args.min_run_time,
+ )
+ finish_run(args, "io", meta, results)
+
+
+if __name__ == "__main__":
+ main()
diff --git a/benchmarks/losses/flagship.py b/benchmarks/losses/flagship.py
new file mode 100644
index 000000000..1661d885a
--- /dev/null
+++ b/benchmarks/losses/flagship.py
@@ -0,0 +1,185 @@
+# LICENSE HEADER MANAGED BY add-license-header
+#
+# Copyright 2018 Kornia Team
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+
+"""Flagship losses benchmark: kornia.losses forward + backward, vs torchvision where it has one.
+
+Losses run inside training steps, so every row times a forward **and** the backward pass to the
+prediction (``torch.autograd.grad``), not the forward alone. One representative per family:
+
+================================= ====================================== ============================
+kornia.losses torchvision task
+================================= ====================================== ============================
+``binary_focal_loss_with_logits`` ``ops.sigmoid_focal_loss`` dense binary detection
+``focal_loss`` β€” 21-class segmentation
+``dice_loss`` β€” 21-class segmentation
+``ssim_loss`` β€” image reconstruction
+``total_variation`` β€” image regularization
+================================= ====================================== ============================
+
+Regime (see ``benchmarks/README.md``): everything runs as batched float tensors on the selected
+device, so every column is the same regime. Classification losses score ``(B, 21, H, W)`` logits
+against ``(B, H, W)`` labels; the binary focal loss scores ``(B, 1, H, W)`` logits against
+``{0, 1}`` targets with ``alpha=0.25, gamma=2`` and mean reduction in both libraries. ``ssim_loss``
+uses an 11x11 window; ``total_variation`` sums over each image and the batch is summed before the
+backward. ``--compile`` compiles the loss function; the backward then runs through AOTAutograd,
+and both are compiled during the untimed warmup. Other libraries' losses are thin wrappers over the
+same PyTorch ops and are left out rather than timed as look-alikes. Throughput is img/s.
+
+Usage:
+ python benchmarks/losses/flagship.py --batches 1,8,32 --size 256 --device cpu
+ python benchmarks/losses/flagship.py --device cuda --compile --json losses_cuda.json
+"""
+
+from __future__ import annotations
+
+import argparse
+import sys
+from pathlib import Path
+from types import ModuleType
+from typing import Callable, Optional
+
+import torch
+
+# Prefer this checkout to an installed wheel or another editable checkout.
+sys.path.insert(0, str(Path(__file__).resolve().parents[2]))
+sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
+from common import (
+ Backend,
+ KorniaRows,
+ add_flagship_args,
+ batch_list,
+ finish_run,
+ image_batch,
+ image_row_fields,
+ optional_import,
+ run_batch_sweep,
+ setup_run,
+ start_run,
+)
+
+import kornia.losses as KL
+
+OPS = ("binary_focal_loss_with_logits", "focal_loss", "dice_loss", "ssim_loss", "total_variation")
+NUM_CLASSES, ALPHA, GAMMA, WINDOW = 21, 0.25, 2.0, 11
+
+
+def build_ops(
+ b: int,
+ h: int,
+ w: int,
+ device: torch.device,
+ dtype: torch.dtype,
+ do_compile: bool,
+ tvops: Optional[ModuleType],
+ skip_compile: frozenset[str] = frozenset(),
+ selected: Optional[frozenset[str]] = None,
+) -> tuple[dict[str, dict[str, Backend]], dict[str, str]]:
+ """Build {op: {backend: zero-arg callable}}; each callable runs one forward + backward on the batch."""
+ gen = torch.Generator().manual_seed(0)
+ _, batch_f = image_batch(b, h, w, device, dtype)
+ logits = torch.randn(b, NUM_CLASSES, h, w, generator=gen).to(device=device, dtype=dtype).requires_grad_()
+ labels = torch.randint(0, NUM_CLASSES, (b, h, w), generator=gen).to(device)
+ bin_logits = torch.randn(b, 1, h, w, generator=gen).to(device=device, dtype=dtype).requires_grad_()
+ bin_target = (torch.rand(b, 1, h, w, generator=gen) < 0.1).to(device=device, dtype=dtype)
+ recon = (batch_f + 0.05 * torch.randn(batch_f.shape, generator=gen).to(device=device, dtype=dtype)).clamp(0, 1)
+ recon = recon.detach().requires_grad_()
+
+ def backward_to(pred: torch.Tensor) -> Callable[[Callable[[], object]], Callable[[], object]]:
+ return lambda loss: lambda: torch.autograd.grad(loss(), pred)
+
+ ops: dict[str, dict[str, Backend]] = {}
+ failures: dict[str, str] = {}
+
+ def include(name: str) -> bool:
+ return selected is None or name in selected
+
+ def kornia_row(label: str, pred: torch.Tensor, target: Callable[..., object], *args: object) -> dict[str, Backend]:
+ rows = KorniaRows(device, do_compile, skip_compile, step=backward_to(pred))
+ row = rows(label, target, *args)
+ failures.update(rows.compile_failures)
+ return row
+
+ if include("binary_focal_loss_with_logits"):
+ row = kornia_row(
+ "binary_focal_loss_with_logits",
+ bin_logits,
+ KL.binary_focal_loss_with_logits,
+ bin_logits,
+ bin_target,
+ ALPHA,
+ GAMMA,
+ "mean",
+ )
+ if tvops:
+ row["torchvision"] = backward_to(bin_logits)(
+ lambda: tvops.sigmoid_focal_loss(bin_logits, bin_target, alpha=ALPHA, gamma=GAMMA, reduction="mean")
+ )
+ ops["binary_focal_loss_with_logits"] = row
+
+ if include("focal_loss"):
+ ops["focal_loss"] = kornia_row("focal_loss", logits, KL.focal_loss, logits, labels, ALPHA, GAMMA, "mean")
+
+ if include("dice_loss"):
+ ops["dice_loss"] = kornia_row("dice_loss", logits, KL.dice_loss, logits, labels)
+
+ if include("ssim_loss"):
+ ops["ssim_loss"] = kornia_row("ssim_loss", recon, KL.ssim_loss, recon, batch_f, WINDOW)
+
+ if include("total_variation"):
+
+ def tv_sum(img: torch.Tensor) -> torch.Tensor:
+ return KL.total_variation(img).sum()
+
+ ops["total_variation"] = kornia_row("total_variation", recon, tv_sum, recon)
+
+ return ops, failures
+
+
+def main() -> None:
+ parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
+ add_flagship_args(parser, ops=OPS)
+ args = parser.parse_args()
+ device, dtype, sync = setup_run(args, opencv=False)
+
+ tvops, tvops_error = optional_import("torchvision.ops")
+
+ meta = start_run(
+ "flagship losses",
+ args,
+ device,
+ units="img/s",
+ regimes=["all backends: batched float tensors on the device; timed region = forward + backward"],
+ missing=[("torchvision", tvops_error)] if tvops is None else [],
+ )
+ backends = ["kornia (eager)", "kornia (compiled)", "torchvision"]
+ results = run_batch_sweep(
+ batch_list(args),
+ lambda b: build_ops(
+ b, args.size, args.size, device, dtype, args.compile, tvops, args.skip_compile_ops, args.ops
+ ),
+ backends,
+ row_fields=image_row_fields(args),
+ sync=sync,
+ torch_backends=("kornia (", "torchvision"),
+ units="img/s",
+ min_run_time=args.min_run_time,
+ )
+ finish_run(args, "losses", meta, results)
+
+
+if __name__ == "__main__":
+ main()
diff --git a/benchmarks/metrics/flagship.py b/benchmarks/metrics/flagship.py
new file mode 100644
index 000000000..9e05be1a1
--- /dev/null
+++ b/benchmarks/metrics/flagship.py
@@ -0,0 +1,191 @@
+# LICENSE HEADER MANAGED BY add-license-header
+#
+# Copyright 2018 Kornia Team
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+
+"""Flagship metrics benchmark: kornia.metrics vs scikit-image and OpenCV.
+
+Covers the two image-quality metrics and the segmentation metric an evaluation loop computes
+most often:
+
+============ ============================================================= ======================
+kornia scikit-image / OpenCV (float HWC per-image loop) notes
+============ ============================================================= ======================
+``psnr`` ``metrics.peak_signal_noise_ratio(data_range=1)``; β€”
+ ``cv2.PSNR(ref, test, 1.0)``
+``ssim`` ``metrics.structural_similarity`` (Gaussian 11x11, sigma 1.5) kornia returns the map
+``mean_iou`` β€” 21 classes
+============ ============================================================= ======================
+
+Regimes (see ``benchmarks/README.md``): kornia runs batched float BCHW tensors on CPU or GPU and
+is differentiable; scikit-image and OpenCV run single normalized float32 HWC images on CPU in a
+Python loop, contiguous and built outside the timed call. OpenCV has no SSIM function.
+The image pair is the shared seeded batch and a copy with clipped Gaussian noise (sigma 0.05).
+SSIM parameters are the Wang et al. defaults in both: an 11x11 Gaussian window with sigma 1.5 and
+population covariance (``gaussian_weights=True, use_sample_covariance=False``). kornia's ``ssim``
+returns the per-pixel map and scikit-image the mean, which costs one reduction more on kornia's
+side if the caller wants a scalar. ``mean_iou`` scores ``(B, H, W)`` label maps over 21 classes;
+neither library has a counterpart. Throughput is image pairs per second (``img/s``).
+
+Usage:
+ python benchmarks/metrics/flagship.py --batches 1,8,32 --size 256 --device cpu
+ python benchmarks/metrics/flagship.py --device cuda --compile --json metrics_cuda.json
+"""
+
+from __future__ import annotations
+
+import argparse
+import sys
+from pathlib import Path
+from types import ModuleType
+from typing import Optional
+
+import numpy as np
+import torch
+
+# Prefer this checkout to an installed wheel or another editable checkout.
+sys.path.insert(0, str(Path(__file__).resolve().parents[2]))
+sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
+from common import (
+ Backend,
+ KorniaRows,
+ add_flagship_args,
+ batch_list,
+ finish_run,
+ image_batch,
+ image_row_fields,
+ optional_import,
+ run_batch_sweep,
+ setup_run,
+ start_run,
+)
+
+import kornia.metrics as KMt
+
+OPS = ("psnr", "ssim", "mean_iou")
+WINDOW, SIGMA, NUM_CLASSES = 11, 1.5, 21
+
+
+def build_ops(
+ b: int,
+ h: int,
+ w: int,
+ device: torch.device,
+ dtype: torch.dtype,
+ do_compile: bool,
+ skm: Optional[ModuleType],
+ cv2: Optional[ModuleType],
+ skip_compile: frozenset[str] = frozenset(),
+ selected: Optional[frozenset[str]] = None,
+) -> tuple[dict[str, dict[str, Backend]], dict[str, str]]:
+ """Build {op: {backend: zero-arg callable}}; each callable scores the whole batch once."""
+ _, batch_f = image_batch(b, h, w, device, dtype)
+ gen = torch.Generator().manual_seed(0)
+ noisy = (batch_f.cpu().float() + 0.05 * torch.randn(batch_f.shape, generator=gen)).clamp(0, 1)
+ noisy_f = noisy.to(device=device, dtype=dtype)
+ refs_np = [im.permute(1, 2, 0).numpy() for im in batch_f.cpu().float()]
+ tests_np = [im.permute(1, 2, 0).numpy() for im in noisy]
+ refs_c = [np.ascontiguousarray(im) for im in refs_np]
+ tests_c = [np.ascontiguousarray(im) for im in tests_np]
+ labels_true = torch.randint(0, NUM_CLASSES, (b, h, w), generator=gen)
+ # 80% of the predicted labels agree with the target, so every class has a non-trivial IoU.
+ keep = torch.rand(b, h, w, generator=gen) < 0.8
+ labels_pred = torch.where(keep, labels_true, torch.randint(0, NUM_CLASSES, (b, h, w), generator=gen))
+
+ kornia_row = KorniaRows(device, do_compile, skip_compile)
+ ops: dict[str, dict[str, Backend]] = {}
+
+ def include(name: str) -> bool:
+ return selected is None or name in selected
+
+ if include("psnr"):
+ row = kornia_row("psnr", KMt.psnr, noisy_f, batch_f, 1.0)
+ row["scikit-image"] = (
+ (lambda: [skm.peak_signal_noise_ratio(r, t, data_range=1.0) for r, t in zip(refs_np, tests_np)])
+ if skm
+ else None
+ )
+ row["opencv"] = (lambda: [cv2.PSNR(r, t, 1.0) for r, t in zip(refs_c, tests_c)]) if cv2 else None
+ ops["psnr"] = row
+
+ if include("ssim"):
+ row = kornia_row("ssim", KMt.ssim, noisy_f, batch_f, WINDOW)
+ row["scikit-image"] = (
+ (
+ lambda: [
+ skm.structural_similarity(
+ r,
+ t,
+ data_range=1.0,
+ channel_axis=-1,
+ gaussian_weights=True,
+ sigma=SIGMA,
+ use_sample_covariance=False,
+ )
+ for r, t in zip(refs_np, tests_np)
+ ]
+ )
+ if skm
+ else None
+ )
+ ops["ssim"] = row
+
+ if include("mean_iou"):
+ pred, target = labels_pred.to(device), labels_true.to(device)
+ ops["mean_iou"] = kornia_row("mean_iou", KMt.mean_iou, pred, target, NUM_CLASSES)
+
+ return ops, kornia_row.compile_failures
+
+
+def main() -> None:
+ parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
+ add_flagship_args(parser, ops=OPS)
+ args = parser.parse_args()
+ device, dtype, sync = setup_run(args)
+
+ skm, skm_error = optional_import("skimage.metrics")
+ cv2, cv2_error = optional_import("cv2")
+
+ meta = start_run(
+ "flagship metrics",
+ args,
+ device,
+ units="img/s",
+ regimes=[
+ "kornia: batched float BCHW; scikit-image/opencv: float32 HWC per-image loop (CPU); img/s = image pairs/s"
+ ],
+ missing=[
+ (name, err)
+ for lib, name, err in [(skm, "scikit-image", skm_error), (cv2, "opencv", cv2_error)]
+ if lib is None
+ ],
+ )
+ backends = ["kornia (eager)", "kornia (compiled)", "scikit-image", "opencv"]
+ results = run_batch_sweep(
+ batch_list(args),
+ lambda b: build_ops(
+ b, args.size, args.size, device, dtype, args.compile, skm, cv2, args.skip_compile_ops, args.ops
+ ),
+ backends,
+ row_fields=image_row_fields(args),
+ sync=sync,
+ units="img/s",
+ min_run_time=args.min_run_time,
+ )
+ finish_run(args, "metrics", meta, results)
+
+
+if __name__ == "__main__":
+ main()
diff --git a/benchmarks/morphology/flagship.py b/benchmarks/morphology/flagship.py
new file mode 100644
index 000000000..45a7eb0cf
--- /dev/null
+++ b/benchmarks/morphology/flagship.py
@@ -0,0 +1,217 @@
+# LICENSE HEADER MANAGED BY add-license-header
+#
+# Copyright 2018 Kornia Team
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+
+"""Flagship morphology benchmark: kornia.morphology vs torchmorph, OpenCV, albumentations and scikit-image.
+
+Covers the two primitives and the two most used compound operators, all with a 5x5 square
+structuring element:
+
+======== ========================== ================================ ============== ==========================
+kornia torchmorph (CUDA only) OpenCV (per-image loop) albumentations scikit-image (per channel)
+======== ========================== ================================ ============== ==========================
+dilation ``grey_dilation`` ``cv2.dilate`` ``"dilation"`` ``morphology.dilation``
+erosion ``grey_erosion`` ``cv2.erode`` ``"erosion"`` ``morphology.erosion``
+opening ``grey_opening`` ``morphologyEx(MORPH_OPEN)`` β€” ``morphology.opening``
+gradient ``morphological_gradient`` ``morphologyEx(MORPH_GRADIENT)`` β€” ``dilation - erosion``
+======== ========================== ================================ ============== ==========================
+
+The kornia column names ``kornia.morphology`` functions and the albumentations column the
+``operation`` of its ``Morphological`` transform.
+
+Regimes (see ``benchmarks/README.md``): kornia runs a batched float BCHW tensor on CPU or GPU with
+its default ``unfold`` engine and is differentiable; `torchmorph <https://github.com/intcomp/torchmorph>`_
+runs the same batched BCHW tensor through its custom CUDA kernels, which exist only for CUDA, so its
+column is skipped on every other device; it computes in float32 (a float16 or bfloat16 input is
+upcast inside the call) and is not differentiable. OpenCV runs single uint8 HWC images on CPU in
+a Python loop, its native regime, and filters all channels in one call; albumentations'
+``Morphological`` runs the same loop through its transform call, with its elliptical element
+replaced by the 5x5 square (albumentations offers only dilation and erosion); scikit-image runs the
+same uint8 images one channel at a time, because its grayscale morphology is 2-D. Borders are each
+library's default: kornia's ``geodesic`` border and OpenCV's default border value both leave
+out-of-image pixels out of the max/min; torchmorph and scikit-image follow SciPy and reflect at the
+border (``mode="reflect"``). torchmorph's flat ``size=5`` element is the same 5x5 square.
+scikit-image has no gradient operator, so its row is ``dilation - erosion`` in int16, which is the
+definition. Throughput is img/s.
+
+Usage:
+ python benchmarks/morphology/flagship.py --batches 1,8,32 --size 256 --device cpu
+ python benchmarks/morphology/flagship.py --device cuda --compile --json morphology_cuda.json
+"""
+
+from __future__ import annotations
+
+import argparse
+import sys
+from pathlib import Path
+from types import ModuleType
+from typing import Callable, Optional
+
+import numpy as np
+import torch
+
+# Prefer this checkout to an installed wheel or another editable checkout.
+sys.path.insert(0, str(Path(__file__).resolve().parents[2]))
+sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
+from common import (
+ Backend,
+ KorniaRows,
+ add_flagship_args,
+ batch_list,
+ finish_run,
+ image_batch,
+ image_row_fields,
+ optional_import,
+ run_batch_sweep,
+ setup_run,
+ start_run,
+)
+
+import kornia.morphology as KM
+
+OPS = ("dilation", "erosion", "opening", "gradient")
+KERNEL_SIZE = 5
+
+
+def square_morphological(A: ModuleType, operation: str, element: np.ndarray) -> object:
+ """albumentations' ``Morphological`` with a fixed element; its own draws an ellipse of size ``scale``."""
+
+ class SquareMorphological(A.Morphological):
+ def get_params(self) -> dict[str, np.ndarray]:
+ return {"kernel": element}
+
+ return SquareMorphological(operation=operation, p=1.0)
+
+
+def build_ops(
+ b: int,
+ h: int,
+ w: int,
+ device: torch.device,
+ dtype: torch.dtype,
+ do_compile: bool,
+ cv2: Optional[ModuleType],
+ skm: Optional[ModuleType],
+ A: Optional[ModuleType],
+ tm: Optional[ModuleType],
+ skip_compile: frozenset[str] = frozenset(),
+ selected: Optional[frozenset[str]] = None,
+) -> tuple[dict[str, dict[str, Backend]], dict[str, str]]:
+ """Build {op: {backend: zero-arg callable}}; each callable filters the whole batch once."""
+ imgs_u8, batch_f = image_batch(b, h, w, device, dtype)
+ kernel = torch.ones(KERNEL_SIZE, KERNEL_SIZE, device=device, dtype=dtype)
+ kernel_np = np.ones((KERNEL_SIZE, KERNEL_SIZE), dtype=np.uint8)
+ footprint = np.ones((KERNEL_SIZE, KERNEL_SIZE), dtype=bool)
+
+ kornia_row = KorniaRows(device, do_compile, skip_compile)
+ ops: dict[str, dict[str, Backend]] = {}
+
+ def include(name: str) -> bool:
+ return selected is None or name in selected
+
+ def per_channel(fn: Callable[[np.ndarray], np.ndarray]) -> Backend:
+ return lambda: [np.stack([fn(im[..., c]) for c in range(im.shape[-1])], axis=-1) for im in imgs_u8]
+
+ def sk_gradient(channel: np.ndarray) -> np.ndarray:
+ dilated = skm.dilation(channel, footprint).astype(np.int16)
+ return dilated - skm.erosion(channel, footprint).astype(np.int16)
+
+ cv_ops = {
+ "dilation": (lambda im: cv2.dilate(im, kernel_np)) if cv2 else None,
+ "erosion": (lambda im: cv2.erode(im, kernel_np)) if cv2 else None,
+ "opening": (lambda im: cv2.morphologyEx(im, cv2.MORPH_OPEN, kernel_np)) if cv2 else None,
+ "gradient": (lambda im: cv2.morphologyEx(im, cv2.MORPH_GRADIENT, kernel_np)) if cv2 else None,
+ }
+ sk_ops = {
+ "dilation": (lambda ch: skm.dilation(ch, footprint)) if skm else None,
+ "erosion": (lambda ch: skm.erosion(ch, footprint)) if skm else None,
+ "opening": (lambda ch: skm.opening(ch, footprint)) if skm else None,
+ "gradient": sk_gradient if skm else None,
+ }
+ tm_ops = (
+ {
+ "dilation": tm.grey_dilation,
+ "erosion": tm.grey_erosion,
+ "opening": tm.grey_opening,
+ "gradient": tm.morphological_gradient,
+ }
+ if tm
+ else {}
+ )
+ alb_ops = {name: square_morphological(A, name, kernel_np) for name in ("dilation", "erosion")} if A else {}
+ for name in OPS:
+ if not include(name):
+ continue
+ row = kornia_row(name, getattr(KM, name), batch_f, kernel)
+ cv_fn, sk_fn, tm_fn = cv_ops[name], sk_ops[name], tm_ops.get(name)
+ row["torchmorph"] = (lambda tm_fn=tm_fn: tm_fn(batch_f, size=KERNEL_SIZE)) if tm_fn else None
+ row["opencv"] = (lambda cv_fn=cv_fn: [cv_fn(im) for im in imgs_u8]) if cv_fn else None
+ alb_t = alb_ops.get(name)
+ row["albumentations"] = (lambda alb_t=alb_t: [alb_t(image=im)["image"] for im in imgs_u8]) if alb_t else None
+ row["scikit-image"] = per_channel(sk_fn) if sk_fn else None
+ ops[name] = row
+
+ return ops, kornia_row.compile_failures
+
+
+def main() -> None:
+ parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
+ add_flagship_args(parser, ops=OPS)
+ args = parser.parse_args()
+ device, dtype, sync = setup_run(args)
+
+ cv2, cv2_error = optional_import("cv2")
+ skm, skm_error = optional_import("skimage.morphology")
+ A, a_error = optional_import("albumentations")
+ # torchmorph ships CUDA kernels only and rejects any other tensor, so it is not even imported off CUDA.
+ tm, tm_error = optional_import("torchmorph") if device.type == "cuda" else (None, "CUDA only")
+
+ libs = [
+ (tm, "torchmorph", tm_error),
+ (skm, "scikit-image", skm_error),
+ (cv2, "opencv", cv2_error),
+ (A, "albumentations", a_error),
+ ]
+ meta = start_run(
+ "flagship morphology",
+ args,
+ device,
+ units="img/s",
+ regimes=[
+ f"{KERNEL_SIZE}x{KERNEL_SIZE} square element; kornia: batched float BCHW; "
+ "torchmorph: batched float32 BCHW (CUDA only); "
+ "opencv/albumentations: uint8 HWC per-image loop (CPU); scikit-image: uint8 per-image, per-channel loop"
+ ],
+ missing=[(name, err) for lib, name, err in libs if lib is None],
+ )
+ backends = ["kornia (eager)", "kornia (compiled)", "torchmorph", "albumentations", "scikit-image", "opencv"]
+ results = run_batch_sweep(
+ batch_list(args),
+ lambda b: build_ops(
+ b, args.size, args.size, device, dtype, args.compile, cv2, skm, A, tm, args.skip_compile_ops, args.ops
+ ),
+ backends,
+ torch_backends=("kornia (", "torchmorph"),
+ row_fields=image_row_fields(args),
+ sync=sync,
+ units="img/s",
+ min_run_time=args.min_run_time,
+ )
+ finish_run(args, "morphology", meta, results)
+
+
+if __name__ == "__main__":
+ main()
diff --git a/tests/test_benchmark_timing.py b/tests/test_benchmark_timing.py
index 17ebea20d..ff894ceac 100644
--- a/tests/test_benchmark_timing.py
+++ b/tests/test_benchmark_timing.py
@@ -19,6 +19,7 @@
import argparse
import importlib.util
+import re
import subprocess
import sys
import time
@@ -96,11 +97,20 @@ def test_benchmark_imports_its_checkout(tmp_path, suite):
@pytest.mark.device_agnostic
def test_filter_benchmark_operation_selection():
flagship = _load_filter_flagship()
+ parser = argparse.ArgumentParser()
+ flagship.add_flagship_args(parser, ops=flagship.AVAILABLE_OPS)
- assert flagship.parse_ops("motion_blur, otsu_threshold") == frozenset({"motion_blur", "otsu_threshold"})
- assert flagship.parse_ops("") is None
- with pytest.raises(argparse.ArgumentTypeError, match=r"unknown operation.*Available:.*otsu_threshold"):
- flagship.parse_ops("not_a_filter")
+ selected = parser.parse_args(["--ops", "motion_blur, otsu_threshold"]).ops
+ assert selected == frozenset({"motion_blur", "otsu_threshold"})
+ assert parser.parse_args(["--ops", ""]).ops is None
+
+ # The script's own main() must register its op names, or an unknown name would run zero rows.
+ script = Path(__file__).resolve().parents[1] / "benchmarks/filters/flagship.py"
+ result = subprocess.run( # noqa: S603 - fixed script and interpreter; no shell or external input.
+ [sys.executable, str(script), "--ops", "not_a_filter"], capture_output=True, text=True, check=False
+ )
+ assert result.returncode == 2
+ assert re.search(r"unknown operation.*not_a_filter.*Available:.*otsu_threshold", result.stderr)
@pytest.mark.device_agnostic