π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
bench(augmentation): full cross-library benchmark + documented baseline (#3812)
Edgar Riba909e649710b7
diff --git a/benchmarks/augmentation/README.md b/benchmarks/augmentation/README.mdnew file mode 100644index 000000000..40df84bba--- /dev/null+++ b/benchmarks/augmentation/README.md@@ -0,0 +1,128 @@+# Augmentation benchmarks++Reproducible throughput benchmarks for kornia's augmentation stack, measured against every+common image-augmentation library. The goal is an **honest, durable baseline** β one that makes+each performance regime measurable and gives future work a concrete target to improve against.++## Scripts++| Script | What it measures |+| --- | --- |+| [`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). |++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+```++Each script prints the git commit, platform, and (on CUDA) the device name, per the benchmark+guidelines in the root `CLAUDE.md`. Optional libraries that are not installed are reported as a+skip line rather than failing the run.++## The regimes β why the numbers are not apples-to-apples++The libraries do not solve the same problem, and reading a single column as "the winner" is+misleading. What each one operates on:++| Library | Data | Batch | Device | Differentiable |+| --- | --- | --- | --- | --- |+| **kornia** | `float` `BCHW` tensor | β batched | CPU **or GPU** | β yes |+| **torchvision v2** | `float` `BCHW` tensor | β batched | CPU or GPU | β no |+| **albumentations** | `uint8` `HWC` numpy | β per-image loop | CPU only | β no |+| **OpenCV** (`cv2`) | `uint8` `HWC` numpy | β per-image loop | CPU only | β no |+| **PIL** (Pillow) | `uint8` `HWC` image | β per-image loop | CPU only | β no |+| **kornia-rs** | `uint8` `HWC` numpy | β per-image | CPU only (native Rust) | β no |++Two distinct races follow:++- **CPU / `uint8` / single-image** β albumentations, OpenCV, PIL and kornia-rs live here. This is+ the classic data-loader regime, and the SIMD/native backends win it. kornia's `float` path is+ *not* built for this and should not be expected to lead.+- **GPU / `float` / batched / differentiable** β kornia's home turf. torchvision v2 competes on+ 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++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**+(higher is better):++| op | kornia (eager) | kornia (compiled) | torchvision v2 | albumentations | OpenCV | PIL | kornia-rs |+| --- | --: | --: | --: | --: | --: | --: | --: |+| HorizontalFlip | 12269 | 30262 | 37147 | 4498 | **156846** | 18174 | 65304 |+| VerticalFlip | 14088 | 27319 | 46584 | 4497 | **145922** | 20634 | 72195 |+| Resize (Β½) | 2079 | 3961 | 5892 | 2840 | 45657 | 3812 | **75643** |+| GaussianBlur | 978 | 194 | 912 | 1875 | 15266 | β | **62848** |+| Brightness | 8275 | 25746 | 26425 | 2657 | 22872 | β | **173588** |+| Grayscale | 7655 | 32267 | 31502 | 3497 | **67327** | 16789 | 15492 |++What this particular slice shows (CPU):++- **kornia-rs is the fastest CPU/`uint8` backend on most ops** β it beats OpenCV on Resize,+ GaussianBlur and Brightness, and only trails it on the two ops that are a single memory pass+ (flips) or a fused color reduction (grayscale). This is the evidence behind the planned+ **opt-in `kornia-rs` augmentation backend** (roadmap): kornia already ships the fastest CPU+ kernels via its Rust sibling β the work is API integration, not raw speed.+- **`torch.compile` is kornia's CPU lever for pointwise ops** β Brightness 8.3k β 25.7k (3.1Γ),+ Grayscale 7.7k β 32.3k (4.2Γ), closing or beating the torchvision gap. It does **not** help+ conv-bound ops on CPU (GaussianBlur regresses β the compile/launch overhead exceeds the tiny+ kernel).+GPU (NVIDIA Jetson Orin, torch 2.10, `--device cuda`, batch 32, 256Γ256, img/s). The `uint8`+single-image backends are CPU-only and repeated for reference:++| op | kornia (eager) | kornia (compiled) | torchvision v2 | OpenCV | kornia-rs |+| --- | --: | --: | --: | --: | --: |+| HorizontalFlip | 11458 | β | **52120** | 22134 | 32284 |+| VerticalFlip | 10599 | β | **50601** | 22683 | 29592 |+| Resize (Β½) | β nan | β | 26149 | 21145 | **40773** |+| GaussianBlur | 474 | 1042 | **6904** | 8342 | 19336 |+| Brightness | 6538 | 12284 | **29785** | 4044 | 9621 |+| Grayscale | 19062 | 24777 | **42555** | 18211 | 4698 |++What the GPU rows show β **read the Jetson caveats, do not treat them as a datacenter result**:++- `β` in the compiled column is a **Jetson-wheel limitation**, not a kornia bug: `torch.compile`+ on the Orin's torch 2.10 CUDA build errors (`CUDA driver error: invalid argument`) for several+ ops, so the compiled row is unavailable. `Resize`'s eager `nan` is the same story β the Orin+ wheel's `cusolver` is broken, so the `get_perspective_transform` linear solve fails on-device.+ On a normal (datacenter) CUDA wheel both work; the Orin simply *understates* kornia here.+- Where compile **is** available on-device (Brightness, GaussianBlur, Grayscale) it gives the+ expected 2β4Γ over eager, and torchvision v2 leads the batched float throughput β consistent+ with the wrapper-overhead finding (β78% of a cheap-op GPU forward is base-class orchestration,+ not the kernel; see the improvement list below).+- **This box's Orin is the standard GPU-bench target for this project** β run all GPU numbers+ here with `--device cuda`, and report the two caveats above rather than omitting the rows.++## Known improvement opportunities (the "improve later" list)++Concrete, measured levers, roughly in leverage order. Each is a place this baseline can move.++1. **Wrapper overhead on cheap ops (GPU).** Profiling shows ~78% of a GPU `RandomHorizontalFlip`+ forward is per-call orchestration in the augmentation base (transform-matrix construction, the+ `where`-blend, dtype/shape bookkeeping) β not the kernel. The lever is a leaner, fully+ `torch.compile`-able base `forward` plus CUDA-graph capture, not faster kernels. Partially+ addressed (the `p == 1` transform-matrix fast path); CUDA-graph capture is the next step.+2. **A `kornia-rs` CPU/`uint8` backend.** The table above shows kornia-rs already leads the CPU+ race. An opt-in `backend="rust"` selector that routes non-differentiable CPU `uint8`+ augmentation through `kornia_rs.imgproc` would make kornia the fastest option in the data-loader+ regime too β an API-integration problem, not a kernel one.+3. **Triton kernels for the kernel-bound minority.** For ops `inductor` cannot fuse β the fused+ warp sampler (`warp_affine` / `grid_sample` / `remap`, which every geometric aug routes+ through), `median_blur`, `equalize`/histogram, bilateral/guided filters, morphology. Pointwise+ ops stay on `inductor`; a Triton rewrite there only re-derives what the compiler emits. (Note:+ kornia's dependency policy is PyTorch-only, so a core Triton kernel is a deliberate+ optional-dependency decision, not a drop-in.)+4. **A `uint8` fast path in the float pipeline** to cut the `float`β`uint8` conversions that make+ the batched path lose to the native `uint8` backends on cheap ops.+5. **Compiled end-to-end pipelines.** `pipeline.py` already shows a compiled kornia pipeline+ beating torchvision v2 and reaching albumentations parity on CPU; the remaining win is keeping+ the whole pipeline (including parameter generation) fullgraph so it captures into a CUDA graph.++When you improve one of these, re-run the relevant script, drop the new numbers in the PR+description, and β if the change is durable β update the sample table above with fresh hardware.diff --git a/benchmarks/augmentation/all_libraries.py b/benchmarks/augmentation/all_libraries.pynew file mode 100644index 000000000..449c3e1f8--- /dev/null+++ b/benchmarks/augmentation/all_libraries.py@@ -0,0 +1,240 @@+# 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()