Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

bench: augmentation class-API + filters flagship suites with albumentations/PIL baselines (#3912)

Dmytro Mishkind44abd15d95b
diff --git a/.claude/skills/kornia-developer/SKILL.md b/.claude/skills/kornia-developer/SKILL.md
index b5342b4df..c0fb44bb7 100644
--- a/.claude/skills/kornia-developer/SKILL.md
+++ b/.claude/skills/kornia-developer/SKILL.md
@@ -61,7 +61,7 @@ The fix must run the **same code path** in eager and compile.
- **Realistic shape + batch** (e.g. `(32,3,256,256)` for augmentation) β€” a `(1,3,8,8)` toy inflates Python overhead and hides kernel cost. Record **hardware, torch version, commit, date** with the numbers (edge silicon like Jetson is *directional*; headline GPU-leadership claims need a datacenter GPU).
- Confirm the rewrite didn't **regress eager** (branchless "compute both branches" and deleted early-exits add eager work β€” measure it). Put the before/after table in the PR.
- **Benchmark against every other library β€” kornia's numbers are meaningless in isolation.** Use the harnesses, don't hand-roll: `benchmarks/augmentation/all_libraries.py` (kornia eager+compiled vs torchvision v2, albumentations, OpenCV, PIL, **kornia-rs**), `cross_library.py` (focused three-way), `pipeline.py` (end-to-end). Read `benchmarks/augmentation/README.md` first β€” it documents the regimes and the standing improvement list, and it is where durable results and the honest interpretation live (update it when you move a number). Read the columns honestly and state the regime: **OpenCV / kornia-rs win CPU/uint8/single-image**, **torchvision v2 wins raw float-tensor throughput**, **kornia's regime is GPU-batched + differentiable + compiled** β€” the only one where differentiable, on-device augmentation exists at all.
+ **Benchmark against every other library β€” kornia's numbers are meaningless in isolation.** Use the harnesses, don't hand-roll: `benchmarks/augmentation/flagship.py` (each library's random-transform class API, parameter sampling included: kornia eager+compiled vs torchvision v2, albumentations, OpenCV, PIL; `--json` export), `cross_library.py` (focused three-way), `pipeline.py` (end-to-end), plus `benchmarks/filters/flagship.py` and `benchmarks/geometry/flagship.py` for the functional ops. Read `benchmarks/augmentation/README.md` first β€” it documents the regimes and the standing improvement list, and it is where durable results and the honest interpretation live (update it when you move a number). Read the columns honestly and state the regime: **OpenCV / kornia-rs win CPU/uint8/single-image**, **torchvision v2 wins raw float-tensor throughput**, **kornia's regime is GPU-batched + differentiable + compiled** β€” the only one where differentiable, on-device augmentation exists at all.
**The moonshot is 10Γ— vs albumentations** for the augmentation package β€” frame every perf fix against that target. Today kornia trails on CPU; the levers that close then invert the gap: (a) `torch.compile` (the fix you just made β€” ~2–3Γ—), (b) a **uint8 fast path** (albumentations' whole edge is uint8 + OpenCV; kornia upcasts to float32), (c) pushing the hot op into **`kornia-rs`** (the Rust backend albumentations can't match). A compile fix that only reaches parity is a step toward 10Γ—, not the destination β€” say in the PR which lever is still on the table.
diff --git a/ROADMAP.md b/ROADMAP.md
index 73c86cbf2..b9a1805c4 100644
--- a/ROADMAP.md
+++ b/ROADMAP.md
@@ -73,9 +73,9 @@ classical-CV gaps and hardening the model zoo.
public API, and widen the dynamo job beyond the core once model/feature paths are vetted.
- **Augmentation performance.** Introduce a `uint8` fast path and begin moving the hottest
ops (warps, blurs, color conversions) toward native `kornia-rs` kernels. *The cross-library
- benchmark harness has landed* β€” `benchmarks/augmentation/{cross_library,pipeline,all_libraries}.py`
+ benchmark harness has landed* β€” `benchmarks/augmentation/{flagship,cross_library,pipeline}.py`
plus a documented `README.md` measure kornia (eager + compiled) against torchvision v2,
- albumentations, OpenCV, PIL and kornia-rs on CPU and GPU, with an honest per-regime reading
+ albumentations, OpenCV, and PIL on CPU and GPU, with an honest per-regime reading
and a standing improvement list. Early findings: `torch.compile` gives kornia 2–4Γ— on pointwise
ops and a compiled pipeline already beats torchvision v2 / reaches albumentations parity on CPU;
kornia-rs is the fastest CPU/`uint8` backend on most ops (motivating the backend item below).
diff --git a/benchmarks/README.md b/benchmarks/README.md
index 3027c739f..3b5181873 100644
--- a/benchmarks/README.md
+++ b/benchmarks/README.md
@@ -8,8 +8,9 @@ baselines. Goal: current, citable numbers with disclosed methodology β€” where k
| Directory | Contents |
| --- | --- |
-| [`augmentation/`](augmentation/) | Cross-library augmentation throughput; see its [README](augmentation/README.md). |
+| [`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. |
| [`color/`](color/) | pytest-benchmark microbenchmarks for color conversions. |
| [`feature/`](feature/) | Local-feature detector benchmarks incl. quality (matching) metrics. |
| [`common.py`](common.py) | Shared methodology utilities β€” use these in every new benchmark. |
@@ -160,3 +161,100 @@ NVIDIA RTX PRO 6000 Blackwell (AMD Turin host):
- **WSL2 + RTX 4090: inductor failed for all ops** (`InductorError`, reported by the harness's
compile-failure NOTE rather than silently skipped); eager still led OpenCV by ~23Γ— on
batch-128 warp_perspective.
+
+## Sample results β€” augmentation flagship (class API)
+
+Directional numbers only β€” reproduce on your own hardware for anything you cite. Measured
+2026-08-08, commit `c97b0f9a`, Apple Silicon (macOS 26.5, arm64), Python 3.11, torch 2.9.1,
+torchvision 0.24.1, albumentations 2.0.8, OpenCV 4.11.0, Pillow 12.3, float32, 256Γ—256,
+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.
+
+`--device cpu --compile`:
+
+| op | kornia (eager) | kornia (compiled) | torchvision v2 | albumentations | opencv | PIL |
+| --- | --: | --: | --: | --: | --: | --: |
+| RandomHorizontalFlip | 10488 | 16754 | 10481 | 33421 | **37019** | 9813 |
+| RandomAffine | 899 | 1939 | 1373 | **5162** | - | - |
+| RandomPerspective | 843 | 1396 | 1086 | **5890** | - | - |
+| RandomResizedCrop | 3653 | βœ— | 3975 | **20241** | - | - |
+| ColorJiggle | 105 | βœ— | 269 | **2060** | - | - |
+| RandomGaussianBlur | 1103 | 75 | 993 | **5008** | - | - |
+| RandomBrightness | 6457 | **15590** | 9156 | 13846 | - | - |
+| RandomGrayscale | 5615 | 12592 | 22666 | 23614 | **49286** | 14373 |
+
+`--device mps --compile` (uint8 loop backends are CPU, repeated for reference):
+
+| op | kornia (eager) | kornia (compiled) | torchvision v2 | albumentations | opencv | PIL |
+| --- | --: | --: | --: | --: | --: | --: |
+| RandomHorizontalFlip | 16651 | 21301 | 20428 | 62662 | **77361** | 13492 |
+| RandomAffine | 1605 | 2701 | 2600 | **6508** | - | - |
+| RandomPerspective | 1611 | βœ— | 2071 | **7481** | - | - |
+| RandomResizedCrop | 3680 | βœ— | 17471 | **26307** | - | - |
+| ColorJiggle | 48 | βœ— | 538 | **2548** | - | - |
+| RandomGaussianBlur | 2968 | 4315 | 3616 | **6026** | - | - |
+| RandomBrightness | 4018 | 13510 | 7692 | **24982** | - | - |
+| RandomGrayscale | 5306 | 17504 | 10569 | 39590 | **92889** | 18483 |
+
+The honest reading (this box only β€” an integrated GPU is not the datacenter regime):
+
+- **albumentations owns the CPU single-image race here**, winning almost every row at batch ≀ 32
+ β€” published as-is; kornia's regime is large-batch discrete-GPU + differentiable.
+- **Found weak spot: `ColorJiggle`** β€” ~20Γ— behind albumentations and ~2.5Γ— behind torchvision's
+ `ColorJitter` on CPU, worse on MPS (48 img/s), and `torch.compile` fails on it
+ (`InductorError` on this stack). On MPS its path hits a `torch._assert_async` CPU fallback in
+ `kornia/enhance/adjust.py` (MPS does not support the op), which forces device sync per call.
+- **Found weak spot: compile coverage** β€” `RandomResizedCrop` fails to compile
+ (`GuardOnDataDependentSymNode` from data-dependent crop parameters) on both devices;
+ `RandomPerspective` additionally fails on MPS β€” and on an NVIDIA L4 its *compiled* warmup goes
+ further and triggers a **CUDA illegal memory access** (inductor emits an out-of-bounds indexing
+ kernel for the data-dependent parameter graph; the harness names the op and exits, and
+ `--skip-compile-ops RandomPerspective` keeps the rest of the compiled column measurable).
+ Direct input for the S5 compile-cleanliness work.
+- **`RandomGaussianBlur` compiled regresses ~15Γ— on CPU** (conv-bound; compile overhead exceeds
+ the kernel) β€” consistent with the historical all-libraries finding; don't compile blindly.
+- Where compile works on pointwise ops it delivers: `RandomBrightness` 6.5k β†’ 15.6k (CPU),
+ 4k β†’ 13.5k (MPS); `RandomGrayscale` 2.2Γ— (CPU) / 3.3Γ— (MPS).
+
+## Sample results β€” filters flagship
+
+Same machine, stack, and caveats as above; batch 32, 256Γ—256, float32, throughput img/s.
+kornia-rs 0.1.10 (this wheel) ships no filter functions β€” its column is skipped and reported.
+PIL matches exactly on box (`BoxBlur(2)`) and median (`MedianFilter(5)`); its Gaussian is a
+box-approximation with radius = sigma (matched in spirit).
+
+`--device cpu --compile`:
+
+| op | kornia (eager) | kornia (compiled) | torchvision v2 | albumentations | opencv | PIL |
+| --- | --: | --: | --: | --: | --: | --: |
+| gaussian_blur2d | 423 | 391 | 672 | 5345 | **9253** | 844 |
+| sobel | 826 | 1183 | - | - | **2907** | - |
+| laplacian | 674 | 618 | - | - | **2593** | - |
+| median_blur | 13 | 13 | - | 7552 | **7990** | 21 |
+| box_blur | 676 | 625 | - | 15116 | **16646** | 1940 |
+| canny | 37 | 74 | - | - | **2568** | - |
+
+`--device mps --compile` (uint8 loop backends are CPU, repeated for reference):
+
+| op | kornia (eager) | kornia (compiled) | torchvision v2 | albumentations | opencv | PIL |
+| --- | --: | --: | --: | --: | --: | --: |
+| gaussian_blur2d | 2941 | 2592 | 3860 | 5988 | **12327** | 869 |
+| sobel | 2688 | **6673** | - | - | 3440 | - |
+| laplacian | **5891** | 4411 | - | - | 2905 | - |
+| median_blur | 1 | 1 | - | 6191 | **6473** | 20 |
+| box_blur | 7233 | 4493 | - | **14575** | 14226 | 1860 |
+| canny | 187 | 376 | - | - | **2406** | - |
+
+The honest reading:
+
+- **Found weak spot (worst in the whole harness so far): `median_blur`** β€” 13 img/s CPU and
+ **1 img/s MPS** vs ~8k for OpenCV/albumentations and 21 for PIL. The unfold-based kernel is
+ ~600Γ— off the native implementations; top Stage-3 candidate alongside `rotate`.
+- **Found weak spot: `canny`** β€” ~35–70Γ— behind OpenCV on CPU (37–74 vs 2568 img/s).
+- Even on an integrated GPU, batched MPS starts winning the derivative filters: `sobel`
+ (compiled) and `laplacian` beat the OpenCV loop, and `box_blur` closes to within 2Γ— of the
+ uint8 backends; the remaining blurs still lose to SIMD.
+- PIL is the slowest float-correct reference on most ops, as expected β€” but still ~1.6–3Γ— ahead
+ of kornia's CPU blurs at this scale, and ~60Γ— ahead on `median_blur`.
diff --git a/benchmarks/augmentation/README.md b/benchmarks/augmentation/README.md
index ac6465fa5..2c91723f2 100644
--- a/benchmarks/augmentation/README.md
+++ b/benchmarks/augmentation/README.md
@@ -8,17 +8,17 @@ each performance regime measurable and gives future work a concrete target to im
| Script | What it measures |
| --- | --- |
+| [`flagship.py`](flagship.py) | **The flagship suite** β€” augmentations benchmarked through each library's random-transform class API (parameter sampling included) vs torchvision v2, albumentations, and OpenCV/PIL where comparable; shared `common.py` methodology, `--json` export. Supersedes `all_libraries.py`. |
| [`vs_torchvision.py`](vs_torchvision.py) | Per-op kornia (eager + `torch.compile`) vs torchvision v2, with a `best/tv` ratio and win/lose verdict per op. |
-| [`all_libraries.py`](all_libraries.py) | Per-op throughput across **all** libraries (kornia eager + compiled, torchvision v2, albumentations, OpenCV, PIL, kornia-rs). |
| [`cross_library.py`](cross_library.py) | A focused per-op comparison of kornia vs torchvision v2 vs albumentations. |
| [`pipeline.py`](pipeline.py) | End-to-end **multi-op pipeline** throughput (the shape a training loop runs); supports `--compile` and `--half` (fp16/AMP). |
Run:
```bash
-python benchmarks/augmentation/all_libraries.py --batch 32 --size 256 --device cpu --compile
-python benchmarks/augmentation/all_libraries.py --batch 32 --size 256 --device cuda --compile
-python benchmarks/augmentation/pipeline.py --batch 32 --size 224 --device cuda --compile
+python benchmarks/augmentation/flagship.py --batches 1,8,32 --size 256 --device cpu --compile
+python benchmarks/augmentation/flagship.py --batches 1,8,32 --size 256 --device cuda --compile --json aug_cuda.json
+python benchmarks/augmentation/pipeline.py --batch 32 --size 224 --device cuda --compile
```
Each script prints the git commit, platform, and (on CUDA) the device name, per the benchmark
@@ -48,7 +48,12 @@ Two distinct races follow:
raw speed but is not differentiable; nothing else runs here at all. This is the regime kornia
is designed to lead, and where `torch.compile` fusion pays off.
-## Sample results
+## Historical sample results (all_libraries.py, superseded 2026-08-08)
+
+The tables below were measured with the superseded per-op script `all_libraries.py` (deterministic
+parameters, albumentations transforms constructed inside the timed loop, PIL/kornia-rs columns);
+it predates the shared `common.py` methodology and JSON export. Fresh flagship numbers live in the
+root [`benchmarks/README.md`](../README.md); the script itself remains in git history.
Directional numbers only β€” reproduce on your own hardware for anything you cite. Measured on an
NVIDIA Jetson Orin (aarch64), torch 2.10, **CPU**, batch 8, 128Γ—128, throughput in **img/s**
diff --git a/benchmarks/augmentation/all_libraries.py b/benchmarks/augmentation/all_libraries.py
deleted file mode 100644
index 449c3e1f8..000000000
--- a/benchmarks/augmentation/all_libraries.py
+++ /dev/null
@@ -1,240 +0,0 @@
-# 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.
-#
-
-"""Comprehensive per-op image-augmentation throughput benchmark across every common library.
-
-Compares, for a set of representative ops, the throughput of:
-
-- **kornia** (eager) β€” float ``BCHW`` batch, CPU or GPU, differentiable
-- **kornia** (compiled) β€” the same under ``torch.compile``
-- **torchvision v2** β€” float ``BCHW`` batch, CPU or GPU
-- **albumentations** β€” ``uint8`` HWC, per-image Python loop (CPU, OpenCV backend)
-- **opencv** (cv2) β€” ``uint8`` HWC, per-image Python loop (CPU)
-- **PIL** (Pillow) β€” ``uint8`` HWC, per-image Python loop (CPU)
-- **kornia-rs** β€” ``uint8`` HWC, per-image, native Rust (CPU)
-
-Read the numbers with the regimes in mind β€” they are **not** apples-to-apples, and that is the
-point of showing them together:
-
-- albumentations / opencv / PIL / kornia-rs operate on a **single ``uint8`` image** at a time
- (a batch is a Python loop). This is the CPU/integer/single-image regime, and it is where the
- OpenCV-backed libraries and the native ``kornia-rs`` win.
-- kornia and torchvision v2 operate on a **batched float tensor**, and on the **GPU**.
-- Only **kornia** is differentiable end-to-end.
-
-So: expect albumentations/opencv/kornia-rs to lead the CPU/uint8 rows, and kornia (compiled,
-GPU-batched) to lead the throughput that matters for on-device differentiable training. The
-purpose of this script is to make each regime measurable and honest, and to give a durable
-baseline to improve against. See ``README.md`` in this directory for methodology and the list
-of known improvement opportunities.
-
-Usage:
- python benchmarks/augmentation/all_libraries.py [--batch 32] [--size 256] [--device cpu]
- python benchmarks/augmentation/all_libraries.py --device cuda --compile
-"""
-
-from __future__ import annotations
-
-import argparse
-import math
-import platform
-import subprocess
-from typing import Callable, Optional
-
-import numpy as np
-import torch
-import torch.utils.benchmark as bench
-
-
-def _us(fn: Callable[[], object], min_run_time: float = 1.5) -> float:
- """Median wall-clock of ``fn`` in microseconds (CUDA-synced by torch.utils.benchmark)."""
- try:
- return bench.Timer(stmt="fn()", globals={"fn": fn}).blocked_autorange(min_run_time=min_run_time).median * 1e6
- except Exception:
- return float("nan")
-
-
-def _git_commit() -> str:
- try:
- return subprocess.check_output(["git", "rev-parse", "--short", "HEAD"], text=True).strip() # noqa: S607
- except Exception:
- return "unknown"
-
-
-def main() -> None:
- parser = argparse.ArgumentParser(description=__doc__)
- parser.add_argument("--batch", type=int, default=32)
- parser.add_argument("--size", type=int, default=256)
- parser.add_argument("--device", type=str, default="cpu")
- parser.add_argument("--threads", type=int, default=4)
- parser.add_argument("--compile", action="store_true", help="also time torch.compile'd kornia")
- args = parser.parse_args()
-
- torch.set_num_threads(args.threads)
- device = torch.device(args.device)
- b, h, w = args.batch, args.size, args.size
-
- # Two views of the same random data: a batched float tensor (kornia/torchvision) and a list
- # of single uint8 HWC images (albumentations/opencv/PIL/kornia-rs).
- 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).float().div(255) for im in imgs_u8]).to(device)
-
- # Lazily import the optional libraries; missing ones are simply reported as skipped.
- libs: dict[str, object] = {}
- for name, mod in [("cv2", "cv2"), ("PIL", "PIL.Image"), ("albumentations", "albumentations")]:
- try:
- libs[name] = __import__(mod, fromlist=["x"]) if "." in mod else __import__(mod)
- except Exception:
- libs[name] = None
- try:
- import torchvision.transforms.v2.functional as tvf
-
- libs["tv"] = tvf
- except Exception:
- libs["tv"] = None
- try:
- import kornia_rs
-
- libs["krs"] = kornia_rs
- except Exception:
- libs["krs"] = None
-
- import kornia
-
- def thr(t: float) -> float:
- return b / (t / 1e6) if t and not math.isnan(t) else float("nan")
-
- # Each op: name -> dict of {backend: zero-arg callable that applies it to the whole batch}.
- # `None` for a backend means "not benchmarked for this op".
- cv2 = libs["cv2"]
- pil = libs["PIL"]
- A = libs["albumentations"]
- tvf = libs["tv"]
- krs = libs["krs"]
-
- def kornia_run(op_eager: torch.nn.Module) -> dict[str, Optional[Callable[[], object]]]:
- op_eager = op_eager.to(device)
- out: dict[str, Optional[Callable[[], object]]] = {"kornia (eager)": lambda: op_eager(batch_f)}
- if args.compile:
- torch._dynamo.reset()
- compiled = torch.compile(op_eager)
- try:
- compiled(batch_f) # warmup / compile
- out["kornia (compiled)"] = lambda: compiled(batch_f)
- except Exception:
- out["kornia (compiled)"] = None
- return out
-
- ops: dict[str, dict[str, Optional[Callable[[], object]]]] = {}
-
- # kornia-rs operates on single uint8 HWC numpy images (float input is unsupported).
- krs_ip = krs.imgproc if krs is not None else None
-
- # --- Horizontal flip -------------------------------------------------------------------
- row = kornia_run(kornia.augmentation.RandomHorizontalFlip(p=1.0))
- row["torchvision v2"] = (lambda: tvf.horizontal_flip(batch_f)) if tvf else None
- row["albumentations"] = (lambda: [A.HorizontalFlip(p=1.0)(image=im)["image"] for im in imgs_u8]) 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.FLIP_LEFT_RIGHT) for im in imgs_u8]) if pil else None
- row["kornia-rs"] = (lambda: [krs_ip.horizontal_flip(im) for im in imgs_u8]) if krs_ip else None
- ops["HorizontalFlip"] = row
-
- # --- Vertical flip ---------------------------------------------------------------------
- row = kornia_run(kornia.augmentation.RandomVerticalFlip(p=1.0))
- row["torchvision v2"] = (lambda: tvf.vertical_flip(batch_f)) if tvf else None
- row["albumentations"] = (lambda: [A.VerticalFlip(p=1.0)(image=im)["image"] for im in imgs_u8]) if A else None
- row["opencv"] = (lambda: [cv2.flip(im, 0) for im in imgs_u8]) if cv2 else None
- row["PIL"] = (lambda: [pil.fromarray(im).transpose(pil.FLIP_TOP_BOTTOM) for im in imgs_u8]) if pil else None
- row["kornia-rs"] = (lambda: [krs_ip.vertical_flip(im) for im in imgs_u8]) if krs_ip else None
- ops["VerticalFlip"] = row
-
- # --- Resize (downscale to half) --------------------------------------------------------
- dst = (h // 2, w // 2)
- row = kornia_run(kornia.augmentation.Resize(dst))
- row["torchvision v2"] = (lambda: tvf.resize(batch_f, list(dst), antialias=True)) if tvf else None
- row["albumentations"] = (lambda: [A.Resize(dst[0], dst[1])(image=im)["image"] for im in imgs_u8]) if A else None
- row["opencv"] = (lambda: [cv2.resize(im, (dst[1], dst[0])) for im in imgs_u8]) if cv2 else None
- row["PIL"] = (lambda: [pil.fromarray(im).resize((dst[1], dst[0])) for im in imgs_u8]) if pil else None
- row["kornia-rs"] = (lambda: [krs_ip.resize(im, dst, "bilinear") for im in imgs_u8]) if krs_ip else None
- ops["Resize"] = row
-
- # --- Gaussian blur ---------------------------------------------------------------------
- row = kornia_run(kornia.augmentation.RandomGaussianBlur((5, 5), (1.0, 1.0), p=1.0))
- row["torchvision v2"] = (lambda: tvf.gaussian_blur(batch_f, [5, 5], [1.0, 1.0])) if tvf else None
- row["albumentations"] = (
- (lambda: [A.GaussianBlur((5, 5), (1.0, 1.0), p=1.0)(image=im)["image"] for im in imgs_u8]) if A else None
- )
- row["opencv"] = (lambda: [cv2.GaussianBlur(im, (5, 5), 1.0) for im in imgs_u8]) if cv2 else None
- row["kornia-rs"] = (lambda: [krs_ip.gaussian_blur(im, (5, 5), (1.0, 1.0)) for im in imgs_u8]) if krs_ip else None
- ops["GaussianBlur"] = row
-
- # --- Brightness ------------------------------------------------------------------------
- row = kornia_run(kornia.augmentation.RandomBrightness((1.3, 1.3), p=1.0))
- row["torchvision v2"] = (lambda: tvf.adjust_brightness(batch_f, 1.3)) if tvf else None
- row["albumentations"] = (
- (lambda: [A.RandomBrightnessContrast(0.3, 0, p=1.0)(image=im)["image"] for im in imgs_u8]) if A else None
- )
- row["opencv"] = (lambda: [cv2.convertScaleAbs(im, alpha=1.3, beta=0) for im in imgs_u8]) if cv2 else None
- row["kornia-rs"] = (lambda: [krs_ip.adjust_brightness(im, 1.3) for im in imgs_u8]) if krs_ip else None
- ops["Brightness"] = row
-
- # --- Grayscale -------------------------------------------------------------------------
- row = kornia_run(kornia.augmentation.RandomGrayscale(p=1.0))
- row["torchvision v2"] = (lambda: tvf.rgb_to_grayscale(batch_f, num_output_channels=3)) if tvf else None
- row["albumentations"] = (lambda: [A.ToGray(p=1.0)(image=im)["image"] for im in imgs_u8]) 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
- row["kornia-rs"] = (lambda: [krs_ip.gray_from_rgb(im) for im in imgs_u8]) if krs_ip else None
- ops["Grayscale"] = row
-
- # ---------------------------------------------------------------------------------------
- backends = [
- "kornia (eager)",
- "kornia (compiled)",
- "torchvision v2",
- "albumentations",
- "opencv",
- "PIL",
- "kornia-rs",
- ]
-
- print(f"# all-library augmentation benchmark β€” commit {_git_commit()} β€” {platform.platform()}")
- if device.type == "cuda":
- print(f"# CUDA device: {torch.cuda.get_device_name(0)}")
- print(
- f"# batch={b}, {h}x{w}, device={device}, threads={args.threads} β€” throughput img/s (higher is better)\n"
- f"# kornia/torchvision: float BCHW batch{' on ' + device.type if device.type == 'cuda' else ''}; "
- f"albumentations/opencv/PIL/kornia-rs: uint8 HWC single-image loop (CPU)"
- )
- col_w = 13
- header = f"{'op':<15}" + "".join(f"{n[:col_w]:>{col_w + 1}}" for n in backends)
- print("-" * len(header))
- print(header)
- print("-" * len(header))
- for op_name, row in ops.items():
- cells = []
- for backend in backends:
- fn = row.get(backend)
- cells.append(f"{thr(_us(fn)):>{col_w + 1}.0f}" if fn is not None else f"{'-':>{col_w + 1}}")
- print(f"{op_name:<15}" + "".join(cells))
- print("-" * len(header))
- print("# '-' = op not benchmarked for that backend (unsupported or not mapped).")
-
-
-if __name__ == "__main__":
- main()
diff --git a/benchmarks/augmentation/flagship.py b/benchmarks/augmentation/flagship.py
new file mode 100644
index 000000000..c65323362
--- /dev/null
+++ b/benchmarks/augmentation/flagship.py
@@ -0,0 +1,268 @@
+# 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 augmentation benchmark: each library's augmentation API, parameter sampling included.
+
+Benchmarks augmentations **as augmentations** β€” through the user-facing random-transform classes
+(kornia's ``forward_parameters`` + apply, torchvision v2 transform objects, albumentations
+transforms), not the underlying deterministic functionals. Transform objects are constructed once,
+outside the timed region; the timed region is parameter sampling + application, per call.
+
+===================== ========================== ========================= ================ ==================
+kornia.augmentation torchvision.transforms.v2 albumentations opencv PIL
+===================== ========================== ========================= ================ ==================
+RandomHorizontalFlip RandomHorizontalFlip HorizontalFlip ``cv2.flip`` ``Image.transpose``
+RandomAffine RandomAffine Affine β€” β€”
+RandomPerspective RandomPerspective Perspective β€” β€”
+RandomResizedCrop RandomResizedCrop RandomResizedCrop β€” β€”
+ColorJiggle ColorJitter ColorJitter β€” β€”
+RandomGaussianBlur GaussianBlur GaussianBlur β€” β€”
+RandomBrightness ColorJitter(brightness=) RandomBrightnessContrast β€” β€”
+RandomGrayscale RandomGrayscale ToGray ``cv2.cvtColor`` ``convert("L")``
+===================== ========================== ========================= ================ ==================
+
+Regimes (see ``benchmarks/README.md``): kornia/torchvision run a batched float BCHW tensor on
+CPU or GPU and kornia is differentiable; albumentations/OpenCV/PIL run single uint8 HWC images on
+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.
+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;
+throughput is img/s of input images.
+
+Usage:
+ python benchmarks/augmentation/flagship.py --batches 1,8,32 --size 256 --device cpu
+ python benchmarks/augmentation/flagship.py --device cuda --compile --json aug_cuda.json
+"""
+
+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
+
+import numpy as np
+import torch
+
+sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
+from common import run_batch_sweep, run_metadata, save_json, versions_line
+
+import kornia.augmentation as KA
+
+Backend = Optional[Callable[[], object]]
+
+
+def build_ops(
+ b: int,
+ h: int,
+ w: int,
+ device: torch.device,
+ dtype: torch.dtype,
+ do_compile: bool,
+ T2: Optional[ModuleType],
+ A: Optional[ModuleType],
+ cv2: Optional[ModuleType],
+ pil: Optional[ModuleType],
+ skip_compile: frozenset[str] = frozenset(),
+) -> 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)
+ )
+
+ compile_failures: dict[str, str] = {}
+
+ 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
+
+ def tv(t: object) -> Backend:
+ return lambda: t(batch_f)
+
+ def alb(t: object) -> Backend:
+ return lambda: [t(image=im)["image"] for im in imgs_u8]
+
+ 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
+
+
+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")
+ 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)
+ 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)
+ print(f"# flagship augmentation 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 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"
+ )
+ 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),
+ backends,
+ row_fields=lambda b: {"height": args.size, "width": args.size, "dtype": args.dtype},
+ sync=sync,
+ )
+ if args.json:
+ out = save_json(args.json, meta, results)
+ print(f"# results written to {out}")
+
+
+if __name__ == "__main__":
+ main()
diff --git a/benchmarks/common.py b/benchmarks/common.py
index 441fd6617..467ffa30c 100644
--- a/benchmarks/common.py
+++ b/benchmarks/common.py
@@ -88,6 +88,9 @@ def run_metadata(device: torch.device) -> dict[str, Any]:
"opencv": _optional_version("cv2"),
"torchvision": _optional_version("torchvision"),
"numpy": _optional_version("numpy"),
+ "albumentations": _optional_version("albumentations"),
+ "kornia_rs": _optional_version("kornia_rs"),
+ "pillow": _optional_version("PIL"),
}
if device.type == "cuda":
meta["cuda_device"] = torch.cuda.get_device_name(device)
@@ -112,3 +115,67 @@ def save_json(path: str | Path, metadata: dict[str, Any], results: list[dict[str
payload = _sanitize({"metadata": metadata, "results": results})
out.write_text(json.dumps(payload, indent=2, allow_nan=False) + "\n")
return out
+
+
+def versions_line(meta: dict[str, Any]) -> str:
+ """One-line software-stack summary for printed table headers (the JSON carries the same data)."""
+ keys = ("torch", "kornia", "python", "opencv", "torchvision", "albumentations", "pillow", "kornia_rs")
+ return "# " + ", ".join(f"{k} {meta.get(k) or '-'}" for k in keys)
+
+
+def run_batch_sweep(
+ batches: list[int],
+ build_ops: Callable[[int], tuple[dict[str, dict[str, Optional[Callable[[], object]]]], dict[str, str]]],
+ backends: list[str],
+ row_fields: Callable[[int], dict[str, Any]],
+ sync: Optional[Callable[[], None]] = None,
+ torch_backends: tuple[str, ...] = ("kornia (", "torchvision"),
+ label_width: int = 26,
+ col_width: int = 14,
+ min_run_time: float = 1.0,
+) -> list[dict[str, Any]]:
+ """Sweep batch sizes, print one throughput table per batch, and return JSON-ready rows.
+
+ ``build_ops(batch)`` returns ``({op: {backend: zero-arg callable | None}}, {op: exc_name})``;
+ the second dict names ops whose ``torch.compile`` warmup failed, reported as a NOTE instead
+ of a silent skip cell. ``sync`` lands inside the timed region only for backends whose name
+ starts with one of ``torch_backends`` β€” uint8 CPU-loop baselines are timed without it (the
+ default prefix is ``"kornia ("`` so the CPU-only ``"kornia-rs"`` backend never matches).
+ """
+ results: list[dict[str, Any]] = []
+ 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"{'batch=' + str(b):<{label_width}}" + "".join(f"{n[:col_width]:>{col_width + 1}}" for n in backends)
+ print("-" * len(header))
+ print(header)
+ print("-" * len(header))
+ for op_name, row in ops.items():
+ cells = []
+ for backend in backends:
+ fn = row.get(backend)
+ if fn is None:
+ 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 = b / (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,
+ }
+ )
+ cells.append(f"{thr:>{col_width + 1}.0f}")
+ print(f"{op_name:<{label_width}}" + "".join(cells))
+ if header:
+ print("-" * len(header))
+ return results
diff --git a/benchmarks/common_test.py b/benchmarks/common_test.py
index df9630812..9ac3f16fa 100644
--- a/benchmarks/common_test.py
+++ b/benchmarks/common_test.py
@@ -27,7 +27,7 @@ from pathlib import Path
import torch
sys.path.insert(0, str(Path(__file__).resolve().parent))
-from common import git_commit, run_metadata, save_json, time_us
+from common import git_commit, run_batch_sweep, run_metadata, save_json, time_us, versions_line
def test_time_us_returns_median_and_spread():
@@ -75,3 +75,62 @@ def test_save_json_round_trip_sanitizes_non_finite(tmp_path):
assert payload["results"][0]["median_us"] is None
assert payload["results"][0]["throughput_per_s"] is None
assert payload["results"][0]["iqr_us"] is None
+
+
+def test_run_metadata_records_optional_baseline_versions():
+ meta = run_metadata(torch.device("cpu"))
+ for key in ("opencv", "torchvision", "albumentations", "kornia_rs", "pillow"):
+ assert key in meta # None when not installed β€” key must still be present
+
+
+def test_run_batch_sweep_rows_and_skip_cells(capsys):
+ def build(b):
+ return {"opA": {"fast": lambda: None, "missing": None}}, {}
+
+ rows = run_batch_sweep([1, 2], build, ["fast", "missing"], row_fields=lambda b: {"size": 8}, min_run_time=0.05)
+ assert [r["batch"] for r in rows] == [1, 2] # only 'fast' produces rows
+ assert rows[0]["op"] == "opA" and rows[0]["backend"] == "fast" and rows[0]["size"] == 8
+ assert rows[0]["median_us"] > 0 and rows[0]["throughput_per_s"] > 0
+ out = capsys.readouterr().out
+ assert "batch=1" in out and "batch=2" in out
+ assert "-" in out # the skip cell
+
+
+def test_versions_line_reports_stack_and_gaps():
+ line = versions_line({"torch": "2.9.1", "kornia": "0.9.0", "torchvision": None})
+ assert line.startswith("#")
+ assert "torch 2.9.1" in line and "kornia 0.9.0" in line
+ assert "torchvision -" in line # missing libs shown as '-', never dropped
+
+
+def test_run_batch_sweep_syncs_torch_backends_only():
+ synced_during: list[str] = []
+ current = {"name": ""}
+
+ def build(b):
+ def make(name):
+ def fn():
+ current["name"] = name
+
+ return fn
+
+ return {"opA": {"kornia (eager)": make("kornia (eager)"), "kornia-rs": make("kornia-rs")}}, {}
+
+ run_batch_sweep(
+ [1],
+ build,
+ ["kornia (eager)", "kornia-rs"],
+ row_fields=lambda b: {},
+ sync=lambda: synced_during.append(current["name"]),
+ min_run_time=0.05,
+ )
+ assert "kornia (eager)" in synced_during # torch backend gets the device sync
+ assert "kornia-rs" not in synced_during # CPU-only backend must not be synced
+
+
+def test_run_batch_sweep_reports_warmup_failures(capsys): # 'compile' in a test NAME gets deselected by conftest
+ def build(b):
+ return {"opA": {"fast": lambda: None}}, {"opA": "RuntimeError"}
+
+ run_batch_sweep([1], build, ["fast"], row_fields=lambda b: {}, min_run_time=0.05)
+ assert "torch.compile warmup failed" in capsys.readouterr().out
diff --git a/benchmarks/filters/flagship.py b/benchmarks/filters/flagship.py
new file mode 100644
index 000000000..1f8767ca6
--- /dev/null
+++ b/benchmarks/filters/flagship.py
@@ -0,0 +1,276 @@
+# 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 filters benchmark: kornia.filters vs OpenCV, albumentations, torchvision v2, kornia-rs.
+
+Covers the core image filters with fixed, identical parameters across backends (equal footing;
+5x5 kernels, sigma 1.5 where applicable):
+
+================ =============================================== ===================================
+kornia.filters OpenCV (uint8 HWC, per-image Python loop) others
+================ =============================================== ===================================
+gaussian_blur2d ``cv2.GaussianBlur`` albumentations, tvf, kornia-rs, PIL
+sobel ``cv2.magnitude(Sobel(dx), Sobel(dy))`` β€”
+laplacian ``cv2.Laplacian`` β€”
+median_blur ``cv2.medianBlur`` albumentations, PIL
+box_blur ``cv2.blur`` albumentations, PIL
+canny ``cv2.Canny`` (on grayscale) β€”
+================ =============================================== ===================================
+
+Regimes (see ``benchmarks/README.md``): kornia/torchvision run a batched float BCHW tensor on CPU
+or GPU and kornia is differentiable; OpenCV/albumentations/kornia-rs/PIL run single uint8 HWC
+images on CPU in a Python loop β€” their native regime. albumentations wraps OpenCV in its
+transform-class API (constructed once, called with fixed parameters). PIL β€” usually the slowest,
+but the signal-processing-correct reference β€” matches exactly on ``BoxBlur(2)`` (5x5 box) and
+``MedianFilter(5)``; its ``GaussianBlur(radius=1.5)`` approximates a true Gaussian with repeated
+box passes, so the sigma is matched in spirit only. Canny thresholds are each library's standard
+defaults β€” kornia 0.1/0.2 on normalized float gradients, OpenCV 100/200 on uint8 gradients β€” the
+domains differ, so that row compares regimes, not identical outputs. kornia's canny converts to
+grayscale internally per its definition; the OpenCV canny loop therefore includes ``cv2.cvtColor``
+(sobel runs per-channel in both). Throughput is img/s.
+
+Usage:
+ python benchmarks/filters/flagship.py --batches 1,8,32 --size 256 --device cpu
+ python benchmarks/filters/flagship.py --device cuda --compile --json filters_cuda.json
+"""
+
+from __future__ import annotations
+
+import argparse
+import platform
+import sys
+from pathlib import Path
+from types import ModuleType
+from typing import Callable, Optional
+
+import numpy as np
+import torch
+
+sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
+from common import run_batch_sweep, run_metadata, save_json, versions_line
+
+import kornia.filters as KF
+
+Backend = Optional[Callable[[], object]]
+
+
+def krs_fn(name: str) -> Optional[Callable[..., object]]:
+ """Resolve a kornia-rs function across wheel layouts (imgproc submodule vs top-level)."""
+ try:
+ import kornia_rs
+ except Exception:
+ return None
+ ns = getattr(kornia_rs, "imgproc", kornia_rs)
+ return getattr(ns, name, getattr(kornia_rs, name, None))
+
+
+def build_ops(
+ b: int,
+ h: int,
+ w: int,
+ device: torch.device,
+ dtype: torch.dtype,
+ do_compile: bool,
+ cv2: Optional[ModuleType],
+ A: Optional[ModuleType],
+ tvf: Optional[ModuleType],
+ pil: Optional[ModuleType],
+ pilf: Optional[ModuleType],
+ skip_compile: frozenset[str] = frozenset(),
+) -> tuple[dict[str, dict[str, Backend]], dict[str, str]]:
+ """Build {op: {backend: zero-arg callable}} with identical filter parameters per backend."""
+ 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)
+ )
+
+ 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
+
+ def alb(t: object) -> Backend:
+ return lambda: [t(image=im)["image"] for im in imgs_u8]
+
+ ops: dict[str, dict[str, Backend]] = {}
+
+ krs_gaussian = krs_fn("gaussian_blur")
+ row = kornia_row("gaussian_blur2d", lambda: KF.gaussian_blur2d(batch_f, (5, 5), (1.5, 1.5)))
+ row["opencv"] = (lambda: [cv2.GaussianBlur(im, (5, 5), 1.5) for im in imgs_u8]) if cv2 else None
+ row["albumentations"] = alb(A.GaussianBlur(blur_limit=(5, 5), sigma_limit=(1.5, 1.5), p=1.0)) if A else None
+ row["torchvision v2"] = (lambda: tvf.gaussian_blur(batch_f, [5, 5], [1.5, 1.5])) if tvf else None
+ row["kornia-rs"] = (lambda: [krs_gaussian(im, (5, 5), (1.5, 1.5)) for im in imgs_u8]) if krs_gaussian else None
+ row["PIL"] = (lambda: [pil.fromarray(im).filter(pilf.GaussianBlur(radius=1.5)) for im in imgs_u8]) if pil else None
+ ops["gaussian_blur2d"] = row
+
+ row = kornia_row("sobel", lambda: KF.sobel(batch_f))
+ if cv2:
+
+ def cv_sobel_mag(im: np.ndarray) -> np.ndarray:
+ dx = cv2.Sobel(im, cv2.CV_32F, 1, 0, ksize=3)
+ dy = cv2.Sobel(im, cv2.CV_32F, 0, 1, ksize=3)
+ return cv2.magnitude(dx, dy)
+
+ row["opencv"] = lambda: [cv_sobel_mag(im) for im in imgs_u8]
+ else:
+ row["opencv"] = None
+ row["albumentations"] = None
+ row["torchvision v2"] = None
+ row["kornia-rs"] = None
+ ops["sobel"] = row
+
+ row = kornia_row("laplacian", lambda: KF.laplacian(batch_f, 5))
+ row["opencv"] = (lambda: [cv2.Laplacian(im, cv2.CV_32F, ksize=5) for im in imgs_u8]) if cv2 else None
+ row["albumentations"] = None
+ row["torchvision v2"] = None
+ row["kornia-rs"] = None
+ ops["laplacian"] = row
+
+ row = kornia_row("median_blur", lambda: KF.median_blur(batch_f, (5, 5)))
+ row["opencv"] = (lambda: [cv2.medianBlur(im, 5) for im in imgs_u8]) if cv2 else None
+ row["albumentations"] = alb(A.MedianBlur(blur_limit=(5, 5), p=1.0)) if A else None
+ row["torchvision v2"] = None
+ row["kornia-rs"] = None
+ row["PIL"] = (lambda: [pil.fromarray(im).filter(pilf.MedianFilter(5)) for im in imgs_u8]) if pil else None
+ ops["median_blur"] = row
+
+ row = kornia_row("box_blur", lambda: KF.box_blur(batch_f, (5, 5)))
+ row["opencv"] = (lambda: [cv2.blur(im, (5, 5)) for im in imgs_u8]) if cv2 else None
+ row["albumentations"] = alb(A.Blur(blur_limit=(5, 5), p=1.0)) if A else None
+ row["torchvision v2"] = None
+ row["kornia-rs"] = None
+ row["PIL"] = (lambda: [pil.fromarray(im).filter(pilf.BoxBlur(2)) for im in imgs_u8]) if pil else None
+ ops["box_blur"] = row
+
+ row = kornia_row("canny", lambda: KF.canny(batch_f))
+ row["opencv"] = (
+ (lambda: [cv2.Canny(cv2.cvtColor(im, cv2.COLOR_RGB2GRAY), 100, 200) for im in imgs_u8]) if cv2 else None
+ )
+ row["albumentations"] = None
+ row["torchvision v2"] = None
+ row["kornia-rs"] = None
+ ops["canny"] = row
+
+ return ops, 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")
+ 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 albumentations as A
+ except Exception:
+ A = None
+ try:
+ import torchvision.transforms.v2.functional as tvf
+ except Exception:
+ tvf = None
+ try:
+ from PIL import Image as pil
+ from PIL import ImageFilter as pilf
+ except Exception:
+ pil = None
+ pilf = None
+
+ meta = run_metadata(device)
+ print(f"# flagship filters 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 img/s")
+ print(
+ "# kornia/torchvision: batched float BCHW; albumentations/opencv/kornia-rs/PIL: uint8 HWC per-image loop (CPU)"
+ )
+ skips = [
+ (cv2, "opencv"),
+ (A, "albumentations"),
+ (tvf, "torchvision"),
+ (krs_fn("gaussian_blur"), "kornia-rs filters"),
+ (pil, "PIL"),
+ ]
+ for present, name in skips:
+ if present is None:
+ print(f"# NOTE: {name} not available β€” 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", "kornia-rs", "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, cv2, A, tvf, pil, pilf, skip_compile),
+ backends,
+ row_fields=lambda b: {"height": args.size, "width": args.size, "dtype": args.dtype},
+ sync=sync,
+ )
+ if args.json:
+ out = save_json(args.json, meta, results)
+ print(f"# results written to {out}")
+
+
+if __name__ == "__main__":
+ main()
diff --git a/benchmarks/geometry/flagship.py b/benchmarks/geometry/flagship.py
index d8f188182..e70da8dcd 100644
--- a/benchmarks/geometry/flagship.py
+++ b/benchmarks/geometry/flagship.py
@@ -44,7 +44,6 @@ Usage:
from __future__ import annotations
import argparse
-import math
import platform
import sys
from pathlib import Path
@@ -55,7 +54,7 @@ import numpy as np
import torch
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
-from common import run_metadata, save_json, time_us
+from common import run_batch_sweep, run_metadata, save_json, versions_line
import kornia.geometry as KG
@@ -71,6 +70,7 @@ def build_ops(
do_compile: bool,
cv2: Optional[ModuleType],
tvf: Optional[ModuleType],
+ skip_compile: frozenset[str] = frozenset(),
) -> tuple[dict[str, dict[str, Backend]], dict[str, str]]:
"""Build {op: {backend: zero-arg callable}} with identical transform params per backend.
@@ -105,13 +105,28 @@ def build_ops(
def kornia_row(label: str, fn: Callable[[], object]) -> dict[str, Backend]:
row: dict[str, Backend] = {"kornia (eager)": fn}
- if do_compile:
+ 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
@@ -160,8 +175,15 @@ def main() -> None:
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")
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)
@@ -171,62 +193,34 @@ def main() -> None:
try:
import cv2
- except ImportError:
+ except Exception:
cv2 = None
try:
import torchvision.transforms.v2.functional as tvf
- except ImportError:
+ except Exception:
tvf = None
meta = run_metadata(device)
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']}")
+ 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))}")
backends = ["kornia (eager)", "kornia (compiled)", "torchvision v2", "opencv"]
- results: list[dict[str, object]] = []
- col_w = 14
- header = ""
- for b in [int(x) for x in args.batches.split(",")]:
- ops, compile_failures = build_ops(b, args.size, args.size, device, dtype, args.compile, cv2, tvf)
- 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"{'batch=' + str(b):<26}" + "".join(f"{n[:col_w]:>{col_w + 1}}" for n in backends)
- print("-" * len(header))
- print(header)
- print("-" * len(header))
- for op_name, row in ops.items():
- cells = []
- for backend in backends:
- fn = row.get(backend)
- if fn is None:
- cells.append(f"{'-':>{col_w + 1}}")
- continue
- is_torch_backend = backend.startswith(("kornia", "torchvision"))
- median, iqr = time_us(fn, sync=sync if is_torch_backend else None)
- thr = b / (median * 1e-6) if not math.isnan(median) else float("nan")
- results.append(
- {
- "op": op_name,
- "backend": backend,
- "batch": b,
- "height": args.size,
- "width": args.size,
- "dtype": args.dtype,
- "median_us": median,
- "iqr_us": iqr,
- "throughput_per_s": thr,
- }
- )
- cells.append(f"{thr:>{col_w + 1}.0f}")
- print(f"{op_name:<26}" + "".join(cells))
- print("-" * len(header))
+ 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),
+ backends,
+ row_fields=lambda b: {"height": args.size, "width": args.size, "dtype": args.dtype},
+ sync=sync,
+ )
if args.json:
out = save_json(args.json, meta, results)
print(f"# results written to {out}")
diff --git a/docs/source/augmentation.rst b/docs/source/augmentation.rst
index 2fc7feeb8..f79ac9ac5 100644
--- a/docs/source/augmentation.rst
+++ b/docs/source/augmentation.rst
@@ -49,7 +49,9 @@ print their git commit, platform, and device so results are auditable:
- ``vs_torchvision.py`` β€” per-op kornia (eager / ``torch.compile``) vs torchvision v2, with a
``best/tv`` ratio and verdict per op.
-- ``all_libraries.py`` β€” per-op across kornia, torchvision, albumentations, OpenCV, PIL, kornia-rs.
+- ``flagship.py`` β€” the flagship suite: augmentations through each library's random-transform
+ class API (parameter sampling included) vs torchvision v2, albumentations, OpenCV, and PIL,
+ with machine-readable JSON export.
- ``pipeline.py`` β€” end-to-end multi-op pipeline throughput (the shape a training loop runs),
including a compiled and an ``--half`` (fp16/AMP) path.