π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
bench: shared methodology utils + flagship geometry benchmark with JSON export (#3906)
Dmytro Mishkinddec12d62d5b
diff --git a/benchmarks/README.md b/benchmarks/README.mdnew file mode 100644index 000000000..3027c739f--- /dev/null+++ b/benchmarks/README.md@@ -0,0 +1,162 @@+# Kornia benchmarks++Reproducible speed/quality benchmarks for the public kornia API, with honest cross-library+baselines. Goal: current, citable numbers with disclosed methodology β where kornia wins+**and** where it loses β replacing stale performance anecdotes.++## Directory map++| Directory | Contents |+| --- | --- |+| [`augmentation/`](augmentation/) | Cross-library augmentation throughput; see its [README](augmentation/README.md). |+| [`geometry/`](geometry/) | [`flagship.py`](geometry/flagship.py): core geometry ops vs OpenCV/torchvision v2. |+| [`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. |++## Methodology contract++Every benchmark here must follow the same rules (utilities in [`common.py`](common.py)):++- **Warmup + repeats:** time with `common.time_us(fn)` β it wraps+ `torch.utils.benchmark.Timer.blocked_autorange`, which warms up, runs many repeats, and+ reports **median** wall clock; `time_us` additionally returns the **IQR** as the spread.+ Never time a single call.+- **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.+- **Pinned seeds:** seed every RNG (`torch.manual_seed`, `np.random.default_rng(0)`) so runs+ are reproducible bit-for-bit on the same software stack.+- **Recorded metadata:** embed `common.run_metadata(device)` in every result file β date, git+ commit, platform, Python/torch/kornia versions, device (CUDA name + version when+ applicable), thread count, and baseline-library versions.+- **Machine-readable export:** support `--json PATH` and write via `common.save_json` β+ strict-valid JSON (`NaN` β `null`), shape `{"metadata": {...}, "results": [...]}`.+- **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.+- **Public API only:** benchmark `kornia.*` as users call it β no private helpers, no+ reimplementations inside the script.++## JSON schema++One file per run:++```json+{+ "metadata": {+ "timestamp_utc": "2026-08-07T17:58:12+00:00",+ "git_commit": "407b6dce",+ "platform": "macOS-26.5.1-arm64-arm-64bit",+ "machine": "arm64",+ "python": "3.11.14",+ "torch": "2.9.1",+ "kornia": "0.9.0rc1",+ "device": "cpu",+ "torch_num_threads": 4,+ "opencv": "4.11.0",+ "torchvision": null,+ "numpy": "2.4.0"+ },+ "results": [+ {+ "op": "warp_perspective",+ "backend": "kornia (eager)",+ "batch": 8,+ "height": 256,+ "width": 256,+ "dtype": "float32",+ "median_us": 1983.4,+ "iqr_us": 12.1,+ "throughput_per_s": 4033.5+ }+ ]+}+```++`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).++## 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)`.+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.+5. Document the regimes in the module docstring; keep the honest framing.++## Sample results β geometry flagship ops++Directional numbers only β reproduce on your own hardware for anything you cite. Measured+2026-08-07, commit `5eaa7a10`, Apple Silicon (macOS 26.5, arm64), Python 3.11, torch 2.9.1,+kornia 0.9.0rc1, OpenCV 4.11.0, float32, 256Γ256, 4 threads. Throughput in items/s (higher is+better); kornia runs a batched float BCHW tensor, OpenCV a per-image uint8 loop on CPU.++`--device cpu --compile`:++| batch=32 | kornia (eager) | kornia (compiled) | opencv |+| --- | --: | --: | --: |+| warp_perspective | 785 | 1079 | 2680 |+| warp_affine | 841 | 1389 | 3073 |+| rotate | 909 | 1400 | 3195 |+| resize | 3044 | 21834 | 32443 |+| get_perspective_transform | 242759 | **808428** | 753415 |++`--device mps --compile`:++| batch=32 | kornia (eager) | kornia (compiled) | opencv (CPU) |+| --- | --: | --: | --: |+| warp_perspective | 2072 | **4503** | 2861 |+| warp_affine | 2433 | **6662** | 3385 |+| rotate | 2019 | **4418** | 3443 |+| resize | 25576 | 26561 | 34531 |+| get_perspective_transform | 16336 | 69578 | 784576 |++### CUDA (batch=32, fp32, 256Γ256, throughput items/s)++Measured 2026-08-07 on commits `b317c16d`/`f4cb83eb`, torch 2.x, full tables in+[PR #3906](https://github.com/kornia/kornia/pull/3906). OpenCV column is the same box's CPU+uint8 per-image loop.++NVIDIA L4 (Intel Cascade Lake host):++| op | kornia (eager) | kornia (compiled) | torchvision v2 | opencv (CPU) |+| --- | --: | --: | --: | --: |+| warp_perspective | 24897 | **56552** | - | 1246 |+| warp_affine | 27747 | **53575** | - | 1946 |+| rotate | 14230 | 44547 | **74258** | 2002 |+| resize | **1021334** | 322329 | 838383 | 25742 |+| get_perspective_transform | 26723 | **139442** | - | 388340 |++NVIDIA RTX PRO 6000 Blackwell (AMD Turin host):++| op | kornia (eager) | kornia (compiled) | torchvision v2 | opencv (CPU) |+| --- | --: | --: | --: | --: |+| warp_perspective | 96022 | **232170** | - | 3223 |+| warp_affine | 120089 | **217083** | - | 5747 |+| rotate | 58357 | 159196 | **298016** | 5742 |+| resize | 625142 | **1204817** | 625100 | 60394 |+| get_perspective_transform | 78071 | **431034** | - | 272523 |++### The honest reading (across Apple Silicon, L4, RTX PRO 6000, RTX 4090/WSL2)++- **Batched GPU is kornia's regime and the margin is large:** compiled `warp_perspective` at+ batch 32 beats OpenCV's per-image CPU loop by ~45Γ (L4) to ~72Γ (RTX PRO 6000); eager alone+ is ~20β30Γ.+- **`rotate` is a found weak spot:** torchvision v2 beats kornia on every GPU tested+ (~1.7β2Γ, up to ~4Γ vs eager where compile was unavailable). First data-driven optimization+ target for the Stage-3 iteration.+- **`resize`:** kornia eager matches torchvision almost exactly (same underlying kernel);+ `torch.compile` is a large win at big batches on newer GPUs (3.6M img/s at batch 128 on+ Blackwell) but *regressed* resize on L4 at batch β€ 32 β compile is not a free win, measure+ per shape.+- **Batched `get_perspective_transform` beats OpenCV's per-pair solver even on CPU** once+ batched: crossover by batch β 32, up to ~13Γ at batch 128 on an AMD Turin CPU+ (3.5M solves/s compiled).+- **CPU per-image warps remain OpenCV's win everywhere**, as expected and published.+- **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.diff --git a/benchmarks/common.py b/benchmarks/common.pynew file mode 100644index 000000000..441fd6617--- /dev/null+++ b/benchmarks/common.py@@ -0,0 +1,114 @@+# 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.+#++"""Shared methodology utilities for kornia benchmarks.++Non-negotiable methodology (W3 of the agent-era plan): warmup, device sync inside timed+regions, multiple repeats with median + spread, pinned seeds, and recorded hardware/software+metadata. ``torch.utils.benchmark.Timer.blocked_autorange`` supplies warmup, repeats and CUDA+sync; this module adds spread reporting, MPS sync support, metadata capture, and+machine-readable JSON export so every run is comparable and citable.+"""++from __future__ import annotations++import json+import math+import platform+import subprocess+import sys+from datetime import UTC, datetime+from pathlib import Path+from typing import Any, Callable, Optional++import torch+import torch.utils.benchmark as bench+++def time_us(+ fn: Callable[[], object], min_run_time: float = 1.0, sync: Optional[Callable[[], None]] = None+) -> tuple[float, float]:+ """Median and interquartile-range wall clock of ``fn`` in microseconds.++ ``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.+ """+ stmt = "fn(); sync()" if sync is not None else "fn()"+ try:+ m = bench.Timer(stmt=stmt, globals={"fn": fn, "sync": sync}).blocked_autorange(min_run_time=min_run_time)+ return m.median * 1e6, m.iqr * 1e6+ except Exception:+ return float("nan"), float("nan")+++def git_commit() -> str:+ """Short hash of HEAD, or 'unknown' outside a git checkout."""+ try:+ return subprocess.check_output(["git", "rev-parse", "--short", "HEAD"], text=True).strip() # noqa: S607+ except Exception:+ return "unknown"+++def _optional_version(module: str) -> Optional[str]:+ try:+ return __import__(module).__version__+ except Exception:+ return None+++def run_metadata(device: torch.device) -> dict[str, Any]:+ """Hardware/software metadata embedded in every result file (W3: date, hardware, versions)."""+ import kornia++ meta: dict[str, Any] = {+ "timestamp_utc": datetime.now(UTC).isoformat(timespec="seconds"),+ "git_commit": git_commit(),+ "platform": platform.platform(),+ "machine": platform.machine(),+ "python": sys.version.split()[0],+ "torch": torch.__version__,+ "kornia": kornia.__version__,+ "device": str(device),+ "torch_num_threads": torch.get_num_threads(),+ "opencv": _optional_version("cv2"),+ "torchvision": _optional_version("torchvision"),+ "numpy": _optional_version("numpy"),+ }+ if device.type == "cuda":+ meta["cuda_device"] = torch.cuda.get_device_name(device)+ meta["cuda_version"] = torch.version.cuda+ return meta+++def _sanitize(obj: Any) -> Any:+ if isinstance(obj, float) and not math.isfinite(obj):+ return None+ if isinstance(obj, dict):+ return {k: _sanitize(v) for k, v in obj.items()}+ if isinstance(obj, (list, tuple)):+ return [_sanitize(v) for v in obj]+ return obj+++def save_json(path: str | Path, metadata: dict[str, Any], results: list[dict[str, Any]]) -> Path:+ """Write one run as strict-valid JSON ``{"metadata": ..., "results": [...]}`` (non-finite β null)."""+ out = Path(path)+ out.parent.mkdir(parents=True, exist_ok=True)+ payload = _sanitize({"metadata": metadata, "results": results})+ out.write_text(json.dumps(payload, indent=2, allow_nan=False) + "\n")+ return outdiff --git a/benchmarks/common_test.py b/benchmarks/common_test.pynew file mode 100644index 000000000..df9630812--- /dev/null+++ b/benchmarks/common_test.py@@ -0,0 +1,77 @@+# 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.+#++"""Unit tests for the shared benchmark methodology utilities."""++from __future__ import annotations++import json+import math+import sys+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+++def test_time_us_returns_median_and_spread():+ median, iqr = time_us(lambda: sum(range(100)), min_run_time=0.05)+ assert median > 0 and not math.isnan(median)+ assert iqr >= 0+++def test_time_us_failure_is_nan():+ def boom():+ raise RuntimeError("expected")++ median, iqr = time_us(boom, min_run_time=0.05)+ assert math.isnan(median) and math.isnan(iqr)+++def test_time_us_accepts_sync_callable():+ calls = []+ median, _ = time_us(lambda: None, min_run_time=0.05, sync=lambda: calls.append(1))+ assert not math.isnan(median)+ assert calls # sync ran inside the timed region+++def test_run_metadata_records_environment():+ meta = run_metadata(torch.device("cpu"))+ assert meta["torch"] == torch.__version__+ assert meta["git_commit"]+ for key in ("timestamp_utc", "platform", "python", "kornia", "torch_num_threads", "device"):+ assert key in meta+++def test_git_commit_is_short_hash():+ assert len(git_commit()) >= 7+++def test_save_json_round_trip_sanitizes_non_finite(tmp_path):+ rows = [{"op": "x", "median_us": float("nan"), "throughput_per_s": float("inf"), "iqr_us": float("-inf")}]+ path = save_json(tmp_path / "run.json", {"a": 1}, rows)++ def reject_constant(name):+ raise AssertionError(f"non-strict JSON token in output: {name}")++ payload = json.loads(path.read_text(), parse_constant=reject_constant)+ assert payload["metadata"] == {"a": 1}+ assert payload["results"][0]["median_us"] is None+ assert payload["results"][0]["throughput_per_s"] is None+ assert payload["results"][0]["iqr_us"] is Nonediff --git a/benchmarks/geometry/flagship.py b/benchmarks/geometry/flagship.pynew file mode 100644index 000000000..d8f188182--- /dev/null+++ b/benchmarks/geometry/flagship.py@@ -0,0 +1,236 @@+# 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 geometry-op benchmark: kornia vs OpenCV vs torchvision v2.++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) β+=========================== ============================================== ==================++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+a Python loop β its native regime. Columns are regime comparisons, not apples-to-apples.++Equal footing: bilinear interpolation, no antialiasing anywhere (torchvision gets an explicit+``antialias=False``), identical transform parameters across backends, pinned seeds.++Usage:+ python benchmarks/geometry/flagship.py --batches 1,8,32 --size 256 --device cpu+ python benchmarks/geometry/flagship.py --device cuda --compile --json flagship_cuda.json+"""++from __future__ import annotations++import argparse+import math+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_metadata, save_json, time_us++import kornia.geometry as KG++Backend = Optional[Callable[[], object]]+++def build_ops(+ b: int,+ h: int,+ w: int,+ device: torch.device,+ dtype: torch.dtype,+ do_compile: bool,+ cv2: Optional[ModuleType],+ tvf: Optional[ModuleType],+) -> 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)+ )++ angle_deg = 30.0+ angle = torch.full((b,), angle_deg, device=device, dtype=dtype)+ center = torch.tensor([[w / 2, h / 2]], dtype=torch.float32).expand(b, 2).to(device=device, dtype=dtype)+ scale = torch.ones(b, 2, device=device, dtype=dtype)+ m_affine = KG.get_rotation_matrix2d(center, angle, scale) # (B, 2, 3)++ quad = torch.tensor([[[0.0, 0.0], [w - 1.0, 0.0], [w - 1.0, h - 1.0], [0.0, h - 1.0]]], dtype=torch.float32)+ src_pts32 = quad.expand(b, 4, 2).contiguous()+ gen = torch.Generator().manual_seed(0)+ dst_pts32 = src_pts32 + 8.0 * torch.randn(b, 4, 2, generator=gen)+ src_pts = src_pts32.to(device=device, dtype=dtype)+ dst_pts = dst_pts32.to(device=device, dtype=dtype)+ h_mat = KG.get_perspective_transform(src_pts, dst_pts) # (B, 3, 3)++ m_np = m_affine.float().cpu().numpy()+ 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:+ torch._dynamo.reset()+ compiled = torch.compile(fn)+ try:+ compiled() # warmup: compile + autotune before the timed region+ row["kornia (compiled)"] = compiled+ except Exception as e:+ row["kornia (compiled)"] = None+ compile_failures[label] = type(e).__name__+ return row++ 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 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("--json", type=str, default=None, help="write machine-readable results to this path")+ args = parser.parse_args()++ 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 ImportError:+ cv2 = None+ try:+ import torchvision.transforms.v2.functional as tvf+ except ImportError:+ tvf = None++ meta = run_metadata(device)+ print(f"# flagship geometry benchmark β commit {meta['git_commit']} β {platform.platform()}")+ if device.type == "cuda":+ print(f"# CUDA device: {meta['cuda_device']}")+ 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")++ 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))+ if args.json:+ out = save_json(args.json, meta, results)+ print(f"# results written to {out}")+++if __name__ == "__main__":+ main()diff --git a/docs/source/_extra/llms-full.txt b/docs/source/_extra/llms-full.txtindex fa461d49e..47a04c0ef 100644--- a/docs/source/_extra/llms-full.txt+++ b/docs/source/_extra/llms-full.txt@@ -156,6 +156,16 @@ img = img[None] # most ops want (B, C, H, W)13. Expecting hue in `[0, 360]` or `[0, 1]` β `rgb_to_hsv` returns radians `[0, 2Ο)`.14. Wrong `data_keys` box format β `"bbox"` means 4-corner `(B, 4, 2)`; coordinate formats are `"bbox_xyxy"` / `"bbox_xywh"`.+## Performance (measured 2026-08-07)++From the in-repo benchmark harness (`benchmarks/` in the GitHub repo β warmup + repeats, median wall clock, device sync, recorded hardware metadata; see `benchmarks/README.md`). Guidance for choosing a backend, not marketing; numbers vary by hardware β reproduce with `python benchmarks/geometry/flagship.py --json out.json` before citing:++- Kornia's regime is batched float tensors on an accelerator, differentiable end-to-end. At batch 32, 256Γ256 fp32, `warp_perspective` under `torch.compile` reached ~57k img/s on an NVIDIA L4 and ~232k img/s on an RTX PRO 6000 β roughly 45β72Γ OpenCV's per-image uint8 CPU loop on the same hosts.+- OpenCV wins the CPU single-image uint8 regime on image warps and resize β use OpenCV or kornia-rs for per-image CPU data loading; use Kornia for batched / GPU / differentiable pipelines.+- Batched `get_perspective_transform` beats OpenCV's per-pair solver even on CPU once batched: crossover around batch 32, ~13Γ (3.5M solves/s, compiled) at batch 128 on an AMD Turin CPU.+- Known weak spot (as of 2026-08): `rotate` on GPU trails torchvision v2 by ~1.7β2Γ.+- `torch.compile` speeds most of these ops 1.3β7Γ, but regressed `resize` at batch β€ 32 on L4 β measure your own shapes before assuming compile helps.+## Links- Docs: <https://kornia.readthedocs.io/en/latest/>diff --git a/docs/source/_extra/llms.txt b/docs/source/_extra/llms.txtindex beb41ce5d..18c687591 100644--- a/docs/source/_extra/llms.txt+++ b/docs/source/_extra/llms.txt@@ -39,6 +39,7 @@ For the full self-contained reference with runnable examples, fetch [llms-full.t- [Applications](https://kornia.readthedocs.io/en/latest/applications/intro.html): face detection, image matching, stitching, registration, denoising walkthroughs- [Models](https://kornia.readthedocs.io/en/latest/models.html): pre-trained model wrappers (SAM, RT-DETR, YuNet, ...)+- [Benchmarks](https://github.com/kornia/kornia/tree/main/benchmarks): reproducible cross-library performance harness with current, honest numbers (where Kornia wins and loses)- [GitHub repository](https://github.com/kornia/kornia): source, issue tracker- [Contributing guide](https://github.com/kornia/kornia/blob/main/CONTRIBUTING.md): contribution protocol- [AI usage policy](https://github.com/kornia/kornia/blob/main/AI_POLICY.md): rules for AI-assisted contributions