π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
perf(morphology): pick the engine by device with engine="auto" (#4728)
Dmytro Mishkin8b03a8085960
diff --git a/benchmarks/README.md b/benchmarks/README.mdindex ca041b3a1..330dddf73 100644--- a/benchmarks/README.md+++ b/benchmarks/README.md@@ -36,6 +36,7 @@ Deeper, single-topic scripts:| --- | --- || [`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. |+| [`morphology/`](morphology/) | [`flagship.py`](morphology/flagship.py): representative morphology ops vs torchmorph, albumentations, scikit-image and OpenCV. [`engines.py`](morphology/engines.py): dilation engine comparison across explicit public engines. || [`filters/`](filters/) | [`flagship.py`](filters/flagship.py): core filters vs OpenCV/albumentations/torchvision v2/kornia-rs/PIL/scikit-image. [`gaussian_cpu.py`](filters/gaussian_cpu.py): Gaussian blur and scale-pyramid base/branch timing and numerical comparisons; [report](filters/gaussian_cpu.md). || [`color/`](color/) | pytest-benchmark microbenchmarks for color conversions (`*_test.py`). || [`contrib/`](contrib/) | [`connected_components.py`](contrib/connected_components.py): union-find vs pooling labeling, validated against SciPy; [report](contrib/connected_components.md). |diff --git a/benchmarks/morphology/engines.py b/benchmarks/morphology/engines.pynew file mode 100644index 000000000..ee40e5a57--- /dev/null+++ b/benchmarks/morphology/engines.py@@ -0,0 +1,361 @@+# 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.+#++"""Compare the three ``kornia.morphology`` engines, ``unfold``, ``convolution`` and ``shift``, on one device.++For each dtype, kernel size and batch it times ``dilation`` with each explicit public engine,+reports the fastest successful timing, and checks that the engines agree. ``conv-unfold`` and+``shift-unfold`` are the largest absolute differences from the ``unfold`` output. The engines+compute the same max-plus expression, so a non-zero value is backend rounding: ``convolution``+inherits the precision of ``conv2d``, and ``shift`` takes the same max or min sequentially in the+same order, which should always give 0. On CUDA the TF32 column repeats the ``convolution`` comparison+with ``torch.backends.cudnn.allow_tf32`` (PyTorch's default ``True``) switched on, which rounds+float32 convolution inputs to a 10-bit mantissa on Ampere and newer GPUs; every other column runs+with the flag left as the process found it.++``--backward`` times forward + backward of ``dilation(x).sum()`` instead of the forward alone.+``--compile`` adds a ``torch.compile(fullgraph=True)`` timing of each engine and the wall clock of+its first (compiling) call: inductor fuses the ``unfold`` window reduction and the ``shift`` loop,+so the ranking under compile can differ from the eager one, and ``shift``'s compile time grows+with the kernel area. ``--engines`` restricts the sweep, e.g. to skip ``convolution`` in CPU half+precision, which runs for minutes at large kernels.++Usage:+ python benchmarks/morphology/engines.py --device cpu+ python benchmarks/morphology/engines.py --device cuda --dtypes float32,float16,bfloat16 --json engines_cuda.json+ python benchmarks/morphology/engines.py --device mps --kernels 3,7 --batches 1,32 --size 512+"""++from __future__ import annotations++import argparse+import math+import sys+import time+from pathlib import Path+from typing import Any, Callable, Optional++import torch++# Prefer this checkout to an installed wheel or another editable checkout.+sys.path.insert(0, str(Path(__file__).resolve().parents[2]))+sys.path.insert(0, str(Path(__file__).resolve().parents[1]))+from common import add_contribute_args, finish_run, parse_names, start_run, time_us_or_error, warm_up_cpu++import kornia.morphology as KM++ENGINES = ("unfold", "convolution", "shift")+SHORT = {"unfold": "unfold", "convolution": "conv", "shift": "shift"}+++def parse_selected_names(value: str, *, kind: str, choices: tuple[str, ...]) -> frozenset[str]:+ """Parse a non-empty comma-separated subset and make invalid names an argparse error."""+ selected = parse_names(value)+ unknown = selected.difference(choices)+ if unknown:+ raise argparse.ArgumentTypeError(+ f"unknown {kind}(s): {', '.join(sorted(unknown))}. Available: {', '.join(choices)}"+ )+ if not selected:+ raise argparse.ArgumentTypeError(f"at least one {kind} is required. Available: {', '.join(choices)}")+ return selected+++def max_abs_diff(x: torch.Tensor, kernel: torch.Tensor, engine: str, tf32: Optional[bool]) -> float:+ """Largest absolute difference between ``engine`` and ``unfold``, optionally with cuDNN TF32 forced."""+ previous = torch.backends.cudnn.allow_tf32+ if tf32 is not None:+ torch.backends.cudnn.allow_tf32 = tf32+ try:+ out = KM.dilation(x, kernel, engine=engine)+ finally:+ torch.backends.cudnn.allow_tf32 = previous+ ref = KM.dilation(x, kernel, engine="unfold")+ return (out.cpu().double() - ref.cpu().double()).abs().max().item()+++def bench_fn(+ x: torch.Tensor, kernel: torch.Tensor, engine: str, backward: bool, compiled: bool = False+) -> Callable[[], object]:+ def op(t: torch.Tensor, k: torch.Tensor) -> torch.Tensor:+ return KM.dilation(t, k, engine=engine)++ if compiled:+ # Every config compiles its own graph; without a reset the sweep hits dynamo's recompile limit.+ torch._dynamo.reset()+ fn = torch.compile(op, fullgraph=True) if compiled else op+ if not backward:+ return lambda: fn(x, kernel)+ xg = x.detach().clone().requires_grad_(True)++ def step() -> None:+ xg.grad = None+ fn(xg, kernel).sum().backward()++ return step+++def display_timing(value: float) -> str:+ """Render a failed timing as a visible table marker instead of a plausible number."""+ return f"{value:.3f}" if math.isfinite(value) else "-"+++def display_difference(value: float) -> str:+ """Render a failed numerical comparison as visibly unavailable."""+ return f"{value:.2e}" if math.isfinite(value) else "-"+++def abort_if_cuda_context_poisoned(+ device: torch.device, *, context: str, error_text: str = "", cause: Optional[BaseException] = None+) -> None:+ """Abort rather than publish later timings after an illegal CUDA memory access."""+ if device.type != "cuda":+ return+ try:+ torch.cuda.synchronize(device)+ except Exception as sync_error:+ error_text = f"{error_text} | {sync_error}"+ if "illegal memory access" in error_text.lower():+ raise SystemExit(+ f"FATAL: CUDA context poisoned during {context} (illegal memory access); "+ "no later measurement or contributed result would be trustworthy. "+ "Rerun without the failing configuration; CUDA_LAUNCH_BLOCKING=1 localizes the kernel."+ ) from cause+++def time_us_checked(+ fn: Callable[[], None], min_run_time: float, sync: Optional[Callable[[], None]], device: torch.device, context: str+) -> tuple[float, float, Optional[str]]:+ """Time a call and ensure a reported CUDA failure did not poison the context."""+ median, iqr, error = time_us_or_error(fn, min_run_time, sync)+ if error is not None:+ abort_if_cuda_context_poisoned(device, context=context)+ return median, iqr, error+++def result_row(+ *, dtype: str, batch: int, kernel: int, backend: str, median_us: float, iqr_us: float, error: Optional[str]+) -> dict[str, Any]:+ """Return one schema-valid long-form timing row."""+ valid = error is None and math.isfinite(median_us) and median_us > 0+ row: dict[str, Any] = {+ "op": "dilation",+ "backend": backend,+ "batch": batch,+ "dtype": dtype,+ "kernel": kernel,+ "median_us": median_us if valid else None,+ "iqr_us": iqr_us if valid and math.isfinite(iqr_us) else None,+ "throughput_per_s": batch * 1e6 / median_us if valid else None,+ }+ if not valid:+ row["error"] = error or "non-finite timing"+ return row+++def main() -> None:+ parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)+ parser.add_argument("--device", type=str, default="cpu", help="cpu, cuda, or mps")+ parser.add_argument(+ "--engines",+ type=lambda value: parse_selected_names(value, kind="engine", choices=ENGINES),+ default=frozenset(ENGINES),+ help="comma-separated engines (default: all)",+ )+ dtype_names = ("float32", "float16", "bfloat16", "float64")+ parser.add_argument(+ "--dtypes",+ type=lambda value: parse_selected_names(value, kind="dtype", choices=dtype_names),+ default=frozenset({"float32", "float16"}),+ help="comma-separated dtypes (default: float32,float16)",+ )+ parser.add_argument("--kernels", type=str, default="3,5,7,15", help="comma-separated square kernel sizes")+ parser.add_argument("--batches", type=str, default="1,8", help="comma-separated batch sizes")+ parser.add_argument("--channels", type=int, default=3)+ parser.add_argument("--size", type=int, default=256, help="square image side")+ parser.add_argument("--threads", type=int, default=4, help="torch intra-op threads")+ parser.add_argument("--backward", action="store_true", help="time forward + backward")+ parser.add_argument("--compile", action="store_true", help="also time torch.compile(fullgraph=True) engines")+ parser.add_argument("--min-run-time", type=float, default=0.5, help="seconds of repeats per measurement")+ parser.add_argument("--json", type=str, default=None, help="write machine-readable results to this path")+ add_contribute_args(parser)+ args = parser.parse_args()++ torch.set_num_threads(args.threads)+ warm_up_cpu()+ torch.manual_seed(0)+ device = torch.device(args.device)+ sync = torch.mps.synchronize if device.type == "mps" else None+ dtypes = [d for d in dtype_names if d in args.dtypes]+ args.dtype = ",".join(dtypes) # start_run prints it+ meta = start_run(+ "morphology engines",+ args,+ device,+ units="img/s",+ regimes=[+ f"dilation, square kernel, B x {args.channels} x {args.size} x {args.size} float input"+ + (", forward + backward" if args.backward else ", forward only"),+ ],+ )+ if device.type == "cuda":+ meta["cudnn_allow_tf32"] = torch.backends.cudnn.allow_tf32+ print(f"# cudnn.allow_tf32={torch.backends.cudnn.allow_tf32}")+ if device.type == "cpu":+ meta["cpu_capability"] = torch.backends.cpu.get_cpu_capability()+ print(f"# cpu capability: {meta['cpu_capability']}")++ engines = [e for e in ENGINES if e in args.engines]+ diffs = [e for e in engines if e != "unfold"] if "unfold" in engines else []+ tf32_col = device.type == "cuda" and "convolution" in diffs+ header = f"{'dtype':9} {'B':>3} {'k':>3}" + "".join(f" {SHORT[e] + ' ms':>11}" for e in engines)+ header += f" {'fastest':>12}" + "".join(f" {SHORT[e] + '-unfold':>13}" for e in diffs)+ header += f" {'conv TF32 on':>13}" if tf32_col else ""+ if args.compile:+ header += "".join(f" {'compiled ' + SHORT[e] + ' ms':>18} {'compile s':>9}" for e in engines)+ print(header)+ results: list[dict[str, Any]] = []+ for dtype_name in dtypes:+ dtype = getattr(torch, dtype_name)+ for b in (int(v) for v in args.batches.split(",")):+ for k in (int(v) for v in args.kernels.split(",")):+ x = torch.rand(b, args.channels, args.size, args.size, device=device, dtype=dtype)+ kernel = torch.ones(k, k, device=device, dtype=dtype)+ row: dict[str, Any] = {+ "dtype": dtype_name,+ "batch": b,+ "kernel": k,+ }+ result_by_engine: dict[str, dict[str, Any]] = {}+ for engine in engines:+ median, iqr, error = time_us_checked(+ bench_fn(x, kernel, engine, args.backward),+ args.min_run_time,+ sync,+ device,+ f"eager {engine} timing (dtype={dtype_name}, batch={b}, kernel={k})",+ )+ row[f"{engine}_ms"] = median / 1e3+ row[f"{engine}_iqr_ms"] = iqr / 1e3+ row[f"{engine}_error"] = error+ engine_result = result_row(+ dtype=dtype_name,+ batch=b,+ kernel=k,+ backend=f"kornia (engine={engine})",+ median_us=median,+ iqr_us=iqr,+ error=error,+ )+ results.append(engine_result)+ result_by_engine[engine] = engine_result+ successful = [e for e in engines if row[f"{e}_error"] is None and math.isfinite(row[f"{e}_ms"])]+ row["fastest"] = min(successful, key=lambda e: row[f"{e}_ms"]) if successful else "-"+ if args.compile:+ for engine in engines:+ try:+ fn = bench_fn(x, kernel, engine, args.backward, compiled=True)+ start = time.perf_counter()+ fn() # compile outside the timed region+ if sync is not None:+ sync()+ elif device.type == "cuda":+ torch.cuda.synchronize(device)+ row[f"compile_{engine}_s"] = time.perf_counter() - start+ median, iqr, error = time_us_checked(+ fn,+ args.min_run_time,+ sync,+ device,+ f"compiled {engine} timing (dtype={dtype_name}, batch={b}, kernel={k})",+ )+ except Exception as exc:+ abort_if_cuda_context_poisoned(+ device,+ context=f"compiled {engine} warmup (dtype={dtype_name}, batch={b}, kernel={k})",+ error_text=str(exc),+ cause=exc,+ )+ row[f"compile_{engine}_s"] = float("nan")+ median, iqr, error = float("nan"), float("nan"), type(exc).__name__+ row[f"compiled_{engine}_ms"] = median / 1e3+ row[f"compiled_{engine}_iqr_ms"] = iqr / 1e3+ row[f"compiled_{engine}_error"] = error+ compiled_result = result_row(+ dtype=dtype_name,+ batch=b,+ kernel=k,+ backend=f"kornia (engine={engine}, compiled)",+ median_us=median,+ iqr_us=iqr,+ error=error,+ )+ compiled_result["compile_s"] = (+ row[f"compile_{engine}_s"] if math.isfinite(row[f"compile_{engine}_s"]) else None+ )+ results.append(compiled_result)+ for engine in diffs:+ try:+ difference = max_abs_diff(x, kernel, engine, None)+ except Exception as exc:+ abort_if_cuda_context_poisoned(+ device,+ context=f"{engine}-unfold comparison (dtype={dtype_name}, batch={b}, kernel={k})",+ error_text=str(exc),+ cause=exc,+ )+ difference = float("nan")+ result_by_engine[engine]["comparison_error"] = type(exc).__name__+ row[f"max_abs_diff_{engine}"] = difference+ result_by_engine[engine]["max_abs_diff_from_unfold"] = (+ difference if math.isfinite(difference) else None+ )+ if tf32_col:+ try:+ tf32_difference = max_abs_diff(x, kernel, "convolution", True)+ except Exception as exc:+ abort_if_cuda_context_poisoned(+ device,+ context=f"convolution TF32 comparison (dtype={dtype_name}, batch={b}, kernel={k})",+ error_text=str(exc),+ cause=exc,+ )+ tf32_difference = float("nan")+ result_by_engine["convolution"]["tf32_comparison_error"] = type(exc).__name__+ row["max_abs_diff_convolution_tf32"] = tf32_difference+ result_by_engine["convolution"]["max_abs_diff_from_unfold_tf32"] = (+ tf32_difference if math.isfinite(tf32_difference) else None+ )+ line = f"{dtype_name:9} {b:>3} {k:>3}" + "".join(+ f" {display_timing(row[e + '_ms']):>11}" for e in engines+ )+ line += f" {row['fastest']:>12}"+ line += "".join(f" {display_difference(row['max_abs_diff_' + e]):>13}" for e in diffs)+ if tf32_col:+ line += f" {display_difference(row['max_abs_diff_convolution_tf32']):>13}"+ if args.compile:+ line += "".join(+ f" {display_timing(row['compiled_' + e + '_ms']):>18} "+ f"{display_timing(row['compile_' + e + '_s']):>9}"+ for e in engines+ )+ print(line, flush=True)+ finish_run(args, "morphology-engines", meta, results)+++if __name__ == "__main__":+ main()diff --git a/benchmarks/morphology/flagship.py b/benchmarks/morphology/flagship.pyindex 45a7eb0cf..c1bf20a22 100644--- a/benchmarks/morphology/flagship.py+++ b/benchmarks/morphology/flagship.py@@ -33,7 +33,10 @@ The kornia column names ``kornia.morphology`` functions and the albumentations c``operation`` of its ``Morphological`` transform.Regimes (see ``benchmarks/README.md``): kornia runs a batched float BCHW tensor on CPU or GPU with-its default ``unfold`` engine and is differentiable; `torchmorph <https://github.com/intcomp/torchmorph>`_+its default ``engine="auto"`` and is differentiable. ``auto`` picks ``unfold`` on CUDA and the exact+``shift`` engine elsewhere, except for a float32 or float64 CPU call that records a backward graph,+which keeps ``unfold``; this suite times the forward alone, so it measures ``unfold`` on CUDA and+``shift`` on CPU and MPS. `torchmorph <https://github.com/intcomp/torchmorph>`_runs the same batched BCHW tensor through its custom CUDA kernels, which exist only for CUDA, so itscolumn is skipped on every other device; it computes in float32 (a float16 or bfloat16 input isupcast inside the call) and is not differentiable. OpenCV runs single uint8 HWC images on CPU indiff --git a/changelog.d/4728.added.md b/changelog.d/4728.added.mdnew file mode 100644index 000000000..b7f6ab560--- /dev/null+++ b/changelog.d/4728.added.md@@ -0,0 +1 @@+`kornia.morphology` gains `engine="shift"`: a running max or min over the shifted views of the padded image. For finite inputs its output equals `engine="unfold"` (`torch.equal`; only the sign of a zero can differ), `torch.compile` fuses it into a single kernel, and forward-only its peak memory is flat in the kernel area instead of growing with it (24 MiB against 1627 MiB for a 15x15 kernel on 8x3x256x256 float32). Under autograd it saves two output-sized intermediates per kernel position, so `engine="auto"` keeps `"unfold"` for the float32/float64 CPU backward path.diff --git a/changelog.d/4728.breaking.md b/changelog.d/4728.breaking.mdnew file mode 100644index 000000000..317cc328b--- /dev/null+++ b/changelog.d/4728.breaking.md@@ -0,0 +1 @@+The `kornia.morphology` functions (`dilation`, `erosion`, `opening`, `closing`, `gradient`, `top_hat`, `bottom_hat`) now default to `engine="auto"` instead of `"unfold"`. `"auto"` runs `"unfold"` on CUDA; off CUDA it runs the exact `"shift"` engine, except that a CPU call which computes in float32 or float64 (the image dtype, or the wider dtype a kernel or structuring element promotes it to) and records a backward graph keeps `"unfold"`. For finite inputs the forward output remains equal to `"unfold"` (`torch.equal`), including mixed-dtype kernels and non-flat structuring elements; only the sign of a zero can differ, because a backend's `max`/`min` may return either tied operand. Gradients change only where `"shift"` is now selected: CPU float16/bfloat16, MPS, and forward-mode AD (`torch.func.jvp`) off CUDA, which records no backward graph. Previously a window with tied maxima sent its whole gradient to one argmax; `"shift"` splits it along its traversal order: half goes to the last tied position it visits, a quarter to the one before, and so on, so pixels that received exactly zero can now receive a fraction (the total is unchanged, and in a large flat window the earliest positions' share underflows to zero). Pass `engine="unfold"` to keep the previous gradient behaviour.diff --git a/kornia/morphology/morphology.py b/kornia/morphology/morphology.pyindex 5c101ffea..f98904f39 100644--- a/kornia/morphology/morphology.py+++ b/kornia/morphology/morphology.py@@ -29,6 +29,99 @@ def _neight2channels_like_kernel(kernel: torch.Tensor) -> torch.Tensor:return kernel.view(h * w, 1, h, w)+def _shift_reduce(padded: torch.Tensor, offsets: torch.Tensor, height: int, width: int, dilate: bool) -> torch.Tensor:+ """Running max (``dilate``) or min over the ``k_h * k_w`` shifted views of ``padded`` plus their offsets.++ The ``shift`` engine: output pixel ``(y, x)`` reduces ``padded[y + i, x + j] + offsets[i, j]`` over the+ kernel positions, the same max-plus expression ``unfold`` evaluates, without materialising the window+ tensor. ``torch.compile`` fuses the loop.++ Forward-only this holds one output-sized intermediate whatever the kernel area, so peak memory is flat+ in ``k_h k_w`` where ``unfold`` and ``convolution`` grow with it (24 MiB against 1627 MiB at 15 x 15,+ B=8 x 3 x 256^2 float32 on CUDA). Under autograd the opposite is true: every ``torch.maximum`` saves+ both operands, so ``2 (k_h k_w - 1)`` output-sized tensors stay alive until backward (2717 MiB+ against 1627 MiB in that same cell). :func:`_resolve_engine` accounts for both regimes.+ """+ kh, kw = offsets.shape+ # Keep each offset two-dimensional so PyTorch applies tensor-tensor dtype promotion. Indexing+ # down to a scalar would instead apply wrapped-scalar rules and silently keep ``padded.dtype``.+ output = padded[..., 0:height, 0:width] + offsets[0:1, 0:1]+ # ``unfold`` reduces the kernel-height dimension first and then kernel width; keep that traversal so+ # tied values are met in the same order. Which of two tied operands a backend's ``max``/``min``+ # returns is its own choice (CPU keeps the first, MPS the second), so the sign of a zero result is+ # not preserved between engines or devices; the value is.+ for j in range(kw):+ for i in range(kh):+ if i == 0 and j == 0:+ continue+ shifted = padded[..., i : i + height, j : j + width] + offsets[i : i + 1, j : j + 1]+ output = torch.maximum(output, shifted) if dilate else torch.minimum(output, shifted)+ return output+++def _resolve_engine(+ engine: str, tensor: torch.Tensor, recording_grad: bool = False, dtype: Optional[torch.dtype] = None+) -> str:+ """Map ``engine="auto"`` to the preferred engine for ``tensor``; leave other values unchanged.++ ``recording_grad`` says whether this call will build a backward graph, which changes the ranking.+ ``dtype`` is the dtype the max-plus terms are computed in; it defaults to ``tensor.dtype`` and is+ wider when the kernel or the structuring element promotes the computation, which is what the+ dtype rule below has to see. For finite inputs, the two engines selected by ``auto`` (``unfold``+ and ``shift``) return equal forward output, so switching between them never changes a value; only+ the sign of a zero can differ, because a backend's ``max``/``min`` may return either tied operand.++ Benchmarks in :mod:`benchmarks.morphology.engines` (x86 CPU, an RTX 4090 and an Apple M1,+ ``dilation``, B x 3 x 256 x 256) give three CPU/CUDA regimes:++ - CUDA: ``unfold`` is the broadly faster engine forward (23 of 24 cells) and forward + backward+ (21 of 24), so it is always the CUDA choice.+ - CPU without a backward graph: ``shift`` wins every cell, by 4-13x in float32 and 12-20x in half+ precision, and its peak memory is flat in the kernel area instead of growing with it.+ - CPU with a backward graph: the running max saves ``2 (k_h k_w - 1)`` intermediates, so ``shift``+ loses to ``unfold`` in float32 (up to 2.5x at 15 x 15) and float64 (up to 3.4x), while still+ winning 11 of 12 half-precision cells.++ MPS keeps ``shift`` in both cases, measured on an Apple M1: ``unfold`` is not the fastest engine+ in any of the 16 forward + backward cells, and ``shift`` beats it there by 2.6-10x, so the CPU+ float32 grad branch deliberately does not extend to Metal. ``convolution`` is faster than+ ``shift`` at small kernels on MPS but collapses at 15 x 15 (2854 ms against 354 ms at B=8), which+ is why it is not the choice either.++ The grad branch is a backward-pass speed rule, not a derivative-preserving one: forward-mode AD+ (``torch.func.jvp``, ``torch.autograd.forward_ad``) records no backward graph, so it takes+ ``shift`` off CUDA like any forward-only call, and its tangent at tied maxima is the ``shift``+ one.+ """+ if engine == "auto":+ if tensor.device.type == "cuda":+ return "unfold"+ if dtype is None:+ dtype = tensor.dtype+ is_float32_or_64 = dtype in (torch.float32, torch.float64)+ if tensor.device.type == "cpu" and recording_grad and is_float32_or_64:+ return "unfold"+ return "shift"+ return engine+++def _records_grad(tensor: torch.Tensor, structuring_element: Optional[torch.Tensor]) -> bool:+ """Whether an op over these inputs will build a backward graph.++ ``torch.no_grad()`` leaves ``requires_grad`` set on the inputs but records nothing, so grad mode has+ to be checked too: inference on a tensor that happens to require grad should take the forward-only+ engine. The structuring element counts because ``dilation`` and ``erosion`` differentiate through+ the neighborhood they build from it. The kernel does not: it enters only through the ``kernel == 0``+ mask, so a kernel that requires grad still produces an output that does not. Forward-mode AD+ (``torch.func.jvp``) is invisible here by design; see :func:`_resolve_engine`.+ """+ if not torch.is_grad_enabled():+ return False+ if tensor.requires_grad:+ return True+ return structuring_element is not None and structuring_element.requires_grad++def dilation(tensor: torch.Tensor,kernel: torch.Tensor,@@ -37,7 +130,7 @@ def dilation(border_type: str = "geodesic",border_value: float = 0.0,max_val: float = 1e4,- engine: str = "unfold",+ engine: str = "auto",) -> torch.Tensor:r"""Return the dilated image applying the same kernel in each channel.@@ -59,7 +152,20 @@ def dilation(outside the image when applying the operation.border_value: Value to fill past edges of input if ``border_type`` is ``constant``.max_val: The value of the infinite elements in the kernel.- engine: convolution is faster and less memory hungry, and unfold is more stable numerically+ engine: ``"unfold"``, ``"convolution"``, ``"shift"`` or ``"auto"`` (default). The ``"unfold"``+ and ``"shift"`` engines compute the same max-plus expression and, for finite inputs, return equal+ output; only the sign of a zero can differ, because a backend's ``max``/``min`` may return either+ tied operand.+ ``"auto"`` picks ``"unfold"`` on CUDA, and off CUDA the exact ``"shift"`` engine, except that a CPU call+ which computes in float32 or float64 (the image dtype, or the wider dtype the kernel promotes it+ to) and records a backward graph takes ``"unfold"``, where ``"shift"`` is up to 3.4x slower. The+ measurements behind that rule are recorded in the ``_resolve_engine`` source.+ ``"convolution"`` runs through the backend's ``conv2d`` and inherits its precision: a float32+ convolution that computes in reduced precision (macOS CPU, CUDA with TF32 enabled) rounds the+ output. ``"shift"`` takes a running max or min over the :math:`k_h k_w` shifted views of the+ padded image. It is exact, and forward-only it needs no :math:`k_h k_w`-sized intermediate;+ under autograd it instead saves :math:`2 (k_h k_w - 1)` output-sized tensors for the backward+ pass, which is more memory than ``"unfold"``, not less.Returns:Dilated image with shape :math:`(B, C, H, W)`.@@ -105,6 +211,10 @@ def dilation(neighborhood = structuring_element.clone()neighborhood[kernel == 0] = -max_val+ # The max-plus terms compute in the promoted dtype, which the dtype rule of ``auto`` has to see: a+ # float16 image with a float32 kernel computes, and differentiates, in float32.+ compute_dtype = torch.promote_types(tensor.dtype, neighborhood.dtype)+ engine = _resolve_engine(engine, tensor, _records_grad(tensor, structuring_element), compute_dtype)if engine == "unfold":output = output.unfold(2, se_h, 1).unfold(3, se_w, 1)output, _ = torch.max(output + neighborhood.flip((0, 1)), 4)@@ -120,8 +230,10 @@ def dilation(bias=neighborhood.view(-1).flip(0).to(dtype=output.dtype),).max(dim=1)output = output.view(B, C, H, W)+ elif engine == "shift":+ output = _shift_reduce(output, neighborhood.flip((0, 1)), tensor.shape[-2], tensor.shape[-1], True)else:- raise NotImplementedError(f"engine {engine} is unknown, use 'convolution' or 'unfold'")+ raise NotImplementedError(f"engine {engine} is unknown, use 'auto', 'convolution', 'shift' or 'unfold'")return output.view_as(tensor)@@ -133,7 +245,7 @@ def erosion(border_type: str = "geodesic",border_value: float = 0.0,max_val: float = 1e4,- engine: str = "unfold",+ engine: str = "auto",) -> torch.Tensor:r"""Return the eroded image applying the same kernel in each channel.@@ -155,7 +267,20 @@ def erosion(outside the image when applying the operation.border_value: Value to fill past edges of input if border_type is ``constant``.max_val: The value of the infinite elements in the kernel.- engine: ``convolution`` is faster and less memory hungry, and ``unfold`` is more stable numerically+ engine: ``"unfold"``, ``"convolution"``, ``"shift"`` or ``"auto"`` (default). The ``"unfold"``+ and ``"shift"`` engines compute the same max-plus expression and, for finite inputs, return equal+ output; only the sign of a zero can differ, because a backend's ``max``/``min`` may return either+ tied operand.+ ``"auto"`` picks ``"unfold"`` on CUDA, and off CUDA the exact ``"shift"`` engine, except that a CPU call+ which computes in float32 or float64 (the image dtype, or the wider dtype the kernel promotes it+ to) and records a backward graph takes ``"unfold"``, where ``"shift"`` is up to 3.4x slower. The+ measurements behind that rule are recorded in the ``_resolve_engine`` source.+ ``"convolution"`` runs through the backend's ``conv2d`` and inherits its precision: a float32+ convolution that computes in reduced precision (macOS CPU, CUDA with TF32 enabled) rounds the+ output. ``"shift"`` takes a running max or min over the :math:`k_h k_w` shifted views of the+ padded image. It is exact, and forward-only it needs no :math:`k_h k_w`-sized intermediate;+ under autograd it instead saves :math:`2 (k_h k_w - 1)` output-sized tensors for the backward+ pass, which is more memory than ``"unfold"``, not less.Returns:Eroded image with shape :math:`(B, C, H, W)`.@@ -201,6 +326,10 @@ def erosion(neighborhood = structuring_element.clone()neighborhood[kernel == 0] = -max_val+ # The max-plus terms compute in the promoted dtype, which the dtype rule of ``auto`` has to see: a+ # float16 image with a float32 kernel computes, and differentiates, in float32.+ compute_dtype = torch.promote_types(tensor.dtype, neighborhood.dtype)+ engine = _resolve_engine(engine, tensor, _records_grad(tensor, structuring_element), compute_dtype)if engine == "unfold":output = output.unfold(2, se_h, 1).unfold(3, se_w, 1)output, _ = torch.min(output - neighborhood, 4)@@ -216,8 +345,10 @@ def erosion(bias=-neighborhood.view(-1).to(dtype=output.dtype),).min(dim=1)output = output.view(B, C, H, W)+ elif engine == "shift":+ output = _shift_reduce(output, -neighborhood, tensor.shape[-2], tensor.shape[-1], False)else:- raise NotImplementedError(f"engine {engine} is unknown, use 'convolution' or 'unfold'")+ raise NotImplementedError(f"engine {engine} is unknown, use 'auto', 'convolution', 'shift' or 'unfold'")return output@@ -230,7 +361,7 @@ def opening(border_type: str = "geodesic",border_value: float = 0.0,max_val: float = 1e4,- engine: str = "unfold",+ engine: str = "auto",) -> torch.Tensor:r"""Return the opened image, (that means, dilation after an erosion) applying the same kernel in each channel.@@ -252,7 +383,20 @@ def opening(outside the image when applying the operation.border_value: Value to fill past edges of input if ``border_type`` is ``constant``.max_val: The value of the infinite elements in the kernel.- engine: convolution is faster and less memory hungry, and unfold is more stable numerically+ engine: ``"unfold"``, ``"convolution"``, ``"shift"`` or ``"auto"`` (default). The ``"unfold"``+ and ``"shift"`` engines compute the same max-plus expression and, for finite inputs, return equal+ output; only the sign of a zero can differ, because a backend's ``max``/``min`` may return either+ tied operand.+ ``"auto"`` picks ``"unfold"`` on CUDA, and off CUDA the exact ``"shift"`` engine, except that a CPU call+ which computes in float32 or float64 (the image dtype, or the wider dtype the kernel promotes it+ to) and records a backward graph takes ``"unfold"``, where ``"shift"`` is up to 3.4x slower. The+ measurements behind that rule are recorded in the ``_resolve_engine`` source.+ ``"convolution"`` runs through the backend's ``conv2d`` and inherits its precision: a float32+ convolution that computes in reduced precision (macOS CPU, CUDA with TF32 enabled) rounds the+ output. ``"shift"`` takes a running max or min over the :math:`k_h k_w` shifted views of the+ padded image. It is exact, and forward-only it needs no :math:`k_h k_w`-sized intermediate;+ under autograd it instead saves :math:`2 (k_h k_w - 1)` output-sized tensors for the backward+ pass, which is more memory than ``"unfold"``, not less.Returns:torch.Tensor: Opened image with shape :math:`(B, C, H, W)`.@@ -307,7 +451,7 @@ def closing(border_type: str = "geodesic",border_value: float = 0.0,max_val: float = 1e4,- engine: str = "unfold",+ engine: str = "auto",) -> torch.Tensor:r"""Return the closed image, (that means, erosion after a dilation) applying the same kernel in each channel.@@ -329,7 +473,20 @@ def closing(outside the image when applying the operation.border_value: Value to fill past edges of input if ``border_type`` is ``constant``.max_val: The value of the infinite elements in the kernel.- engine: convolution is faster and less memory hungry, and unfold is more stable numerically+ engine: ``"unfold"``, ``"convolution"``, ``"shift"`` or ``"auto"`` (default). The ``"unfold"``+ and ``"shift"`` engines compute the same max-plus expression and, for finite inputs, return equal+ output; only the sign of a zero can differ, because a backend's ``max``/``min`` may return either+ tied operand.+ ``"auto"`` picks ``"unfold"`` on CUDA, and off CUDA the exact ``"shift"`` engine, except that a CPU call+ which computes in float32 or float64 (the image dtype, or the wider dtype the kernel promotes it+ to) and records a backward graph takes ``"unfold"``, where ``"shift"`` is up to 3.4x slower. The+ measurements behind that rule are recorded in the ``_resolve_engine`` source.+ ``"convolution"`` runs through the backend's ``conv2d`` and inherits its precision: a float32+ convolution that computes in reduced precision (macOS CPU, CUDA with TF32 enabled) rounds the+ output. ``"shift"`` takes a running max or min over the :math:`k_h k_w` shifted views of the+ padded image. It is exact, and forward-only it needs no :math:`k_h k_w`-sized intermediate;+ under autograd it instead saves :math:`2 (k_h k_w - 1)` output-sized tensors for the backward+ pass, which is more memory than ``"unfold"``, not less.Returns:Closed image with shape :math:`(B, C, H, W)`.@@ -385,7 +542,7 @@ def gradient(border_type: str = "geodesic",border_value: float = 0.0,max_val: float = 1e4,- engine: str = "unfold",+ engine: str = "auto",) -> torch.Tensor:r"""Return the morphological gradient of an image.@@ -408,7 +565,20 @@ def gradient(outside the image when applying the operation.border_value: Value to fill past edges of input if ``border_type`` is ``constant``.max_val: The value of the infinite elements in the kernel.- engine: convolution is faster and less memory hungry, and unfold is more stable numerically+ engine: ``"unfold"``, ``"convolution"``, ``"shift"`` or ``"auto"`` (default). The ``"unfold"``+ and ``"shift"`` engines compute the same max-plus expression and, for finite inputs, return equal+ output; only the sign of a zero can differ, because a backend's ``max``/``min`` may return either+ tied operand.+ ``"auto"`` picks ``"unfold"`` on CUDA, and off CUDA the exact ``"shift"`` engine, except that a CPU call+ which computes in float32 or float64 (the image dtype, or the wider dtype the kernel promotes it+ to) and records a backward graph takes ``"unfold"``, where ``"shift"`` is up to 3.4x slower. The+ measurements behind that rule are recorded in the ``_resolve_engine`` source.+ ``"convolution"`` runs through the backend's ``conv2d`` and inherits its precision: a float32+ convolution that computes in reduced precision (macOS CPU, CUDA with TF32 enabled) rounds the+ output. ``"shift"`` takes a running max or min over the :math:`k_h k_w` shifted views of the+ padded image. It is exact, and forward-only it needs no :math:`k_h k_w`-sized intermediate;+ under autograd it instead saves :math:`2 (k_h k_w - 1)` output-sized tensors for the backward+ pass, which is more memory than ``"unfold"``, not less.Returns:Gradient image with shape :math:`(B, C, H, W)`.@@ -451,7 +621,7 @@ def top_hat(border_type: str = "geodesic",border_value: float = 0.0,max_val: float = 1e4,- engine: str = "unfold",+ engine: str = "auto",) -> torch.Tensor:r"""Return the top hat transformation of an image.@@ -476,7 +646,20 @@ def top_hat(outside the image when applying the operation.border_value: Value to fill past edges of input if ``border_type`` is ``constant``.max_val: The value of the infinite elements in the kernel.- engine: convolution is faster and less memory hungry, and unfold is more stable numerically+ engine: ``"unfold"``, ``"convolution"``, ``"shift"`` or ``"auto"`` (default). The ``"unfold"``+ and ``"shift"`` engines compute the same max-plus expression and, for finite inputs, return equal+ output; only the sign of a zero can differ, because a backend's ``max``/``min`` may return either+ tied operand.+ ``"auto"`` picks ``"unfold"`` on CUDA, and off CUDA the exact ``"shift"`` engine, except that a CPU call+ which computes in float32 or float64 (the image dtype, or the wider dtype the kernel promotes it+ to) and records a backward graph takes ``"unfold"``, where ``"shift"`` is up to 3.4x slower. The+ measurements behind that rule are recorded in the ``_resolve_engine`` source.+ ``"convolution"`` runs through the backend's ``conv2d`` and inherits its precision: a float32+ convolution that computes in reduced precision (macOS CPU, CUDA with TF32 enabled) rounds the+ output. ``"shift"`` takes a running max or min over the :math:`k_h k_w` shifted views of the+ padded image. It is exact, and forward-only it needs no :math:`k_h k_w`-sized intermediate;+ under autograd it instead saves :math:`2 (k_h k_w - 1)` output-sized tensors for the backward+ pass, which is more memory than ``"unfold"``, not less.Returns:Top hat transformed image with shape :math:`(B, C, H, W)`.@@ -522,7 +705,7 @@ def bottom_hat(border_type: str = "geodesic",border_value: float = 0.0,max_val: float = 1e4,- engine: str = "unfold",+ engine: str = "auto",) -> torch.Tensor:r"""Return the bottom hat transformation of an image.@@ -547,7 +730,20 @@ def bottom_hat(outside the image when applying the operation.border_value: Value to fill past edges of input if ``border_type`` is ``constant``.max_val: The value of the infinite elements in the kernel.- engine: convolution is faster and less memory hungry, and unfold is more stable numerically+ engine: ``"unfold"``, ``"convolution"``, ``"shift"`` or ``"auto"`` (default). The ``"unfold"``+ and ``"shift"`` engines compute the same max-plus expression and, for finite inputs, return equal+ output; only the sign of a zero can differ, because a backend's ``max``/``min`` may return either+ tied operand.+ ``"auto"`` picks ``"unfold"`` on CUDA, and off CUDA the exact ``"shift"`` engine, except that a CPU call+ which computes in float32 or float64 (the image dtype, or the wider dtype the kernel promotes it+ to) and records a backward graph takes ``"unfold"``, where ``"shift"`` is up to 3.4x slower. The+ measurements behind that rule are recorded in the ``_resolve_engine`` source.+ ``"convolution"`` runs through the backend's ``conv2d`` and inherits its precision: a float32+ convolution that computes in reduced precision (macOS CPU, CUDA with TF32 enabled) rounds the+ output. ``"shift"`` takes a running max or min over the :math:`k_h k_w` shifted views of the+ padded image. It is exact, and forward-only it needs no :math:`k_h k_w`-sized intermediate;+ under autograd it instead saves :math:`2 (k_h k_w - 1)` output-sized tensors for the backward+ pass, which is more memory than ``"unfold"``, not less.Returns:Top hat transformed image with shape :math:`(B, C, H, W)`.diff --git a/tests/morphology/test_dilation.py b/tests/morphology/test_dilation.pyindex 56aafedcf..534d2aa40 100644--- a/tests/morphology/test_dilation.py+++ b/tests/morphology/test_dilation.py@@ -19,8 +19,10 @@ import pytestimport torchfrom kornia.morphology import dilation+from kornia.morphology import morphology as morphology_module+from kornia.morphology.morphology import _records_grad, _resolve_engine-from testing.base import BaseTester, assert_close+from testing.base import BaseTester, assert_close, supports_reflect_padding, supports_replicate_paddingfrom testing.parametrized_tester import parametrized_test@@ -182,3 +184,201 @@ class TestDilate(BaseTester):assert result.dtype == dtypeself.assert_close(result, dilation(tensor, kernel.to(dtype), engine="convolution"))++ def test_auto_engine(self, device, dtype):+ # engine="auto", the default, runs "unfold" on CUDA and the exact "shift" engine everywhere+ # else (#4525). An explicit engine is passed through unchanged.+ tensor = torch.rand(2, 3, 9, 9, device=device, dtype=dtype)+ kernel = torch.ones(3, 5, device=device, dtype=dtype)+ kernel[0, 0] = 0.0+ expected_engine = "unfold" if device.type == "cuda" else "shift"++ assert _resolve_engine("auto", tensor) == expected_engine+ assert _resolve_engine("unfold", tensor) == "unfold"+ assert _resolve_engine("convolution", tensor) == "convolution"+ assert _resolve_engine("shift", tensor) == "shift"+ expected = dilation(tensor, kernel, engine=expected_engine)+ assert torch.equal(dilation(tensor, kernel), expected)+ assert torch.equal(dilation(tensor, kernel, engine="auto"), expected)++ def test_auto_engine_is_grad_aware(self, device, dtype):+ # A CPU call that records a backward graph takes "unfold" in float32/float64, where "shift"+ # is up to 3.4x slower; half precision and the forward-only path keep "shift". CUDA is+ # "unfold" either way, and MPS is "shift" either way -- the grad branch is CPU-only, so the+ # dtype does not enter off CPU. Equal forward output makes the switch value-preserving.+ tensor = torch.rand(2, 3, 9, 9, device=device, dtype=dtype)+ kernel = torch.ones(3, 5, device=device, dtype=dtype)+ wide = dtype in (torch.float32, torch.float64)+ grad_engine = "unfold" if device.type == "cuda" or (device.type == "cpu" and wide) else "shift"+ plain_engine = "unfold" if device.type == "cuda" else "shift"++ assert _resolve_engine("auto", tensor, True) == grad_engine+ assert _resolve_engine("auto", tensor, False) == plain_engine+ assert _resolve_engine("shift", tensor, True) == "shift"+ assert torch.equal(dilation(tensor, kernel), dilation(tensor, kernel, engine=plain_engine))++ grad_tensor = tensor.clone().requires_grad_(True)+ assert torch.equal(dilation(grad_tensor, kernel), dilation(grad_tensor, kernel, engine=grad_engine))+ # torch.no_grad() leaves requires_grad set but records nothing, so the forward-only engine wins.+ with torch.no_grad():+ assert torch.equal(dilation(grad_tensor, kernel), dilation(grad_tensor, kernel, engine=plain_engine))++ def test_auto_engine_follows_structuring_element_grad(self, device, dtype, monkeypatch):+ # The neighborhood is built from the structuring element, so grad on it records a backward+ # graph even when the image does not require grad. The kernel enters only through the+ # ``kernel == 0`` mask, so a kernel that requires grad records nothing and must not push a+ # forward-only call onto the slower grad-mode engine (#4525).+ tensor = torch.rand(2, 3, 9, 9, device=device, dtype=dtype)+ kernel = torch.ones(3, 5, device=device, dtype=dtype)+ se = torch.rand(3, 5, device=device, dtype=dtype)+ seen = []+ resolve = morphology_module._resolve_engine+ monkeypatch.setattr(+ morphology_module,+ "_resolve_engine",+ lambda engine, t, recording_grad=False, dtype=None: (+ seen.append(recording_grad) or resolve(engine, t, recording_grad, dtype)+ ),+ )++ assert _records_grad(tensor, None) is False+ assert _records_grad(tensor, se) is False+ assert _records_grad(tensor, se.clone().requires_grad_(True)) is True++ dilation(tensor, kernel.clone().requires_grad_(True), engine="shift")+ dilation(tensor, kernel, se.clone().requires_grad_(True), engine="shift")+ dilation(tensor.clone().requires_grad_(True), kernel, engine="shift")+ with torch.no_grad():+ dilation(tensor.clone().requires_grad_(True), kernel, engine="shift")+ assert seen == [False, True, True, False]+ assert not dilation(tensor, kernel.clone().requires_grad_(True)).requires_grad++ def test_auto_engine_resolves_from_promoted_dtype(self, device, monkeypatch):+ # A float16 image with a float32 kernel computes, and differentiates, in float32, so the+ # float32/float64 grad rule of "auto" must see the promoted dtype rather than the image's.+ # On CPU that is the difference between "unfold" and a "shift" backward that is ~5x slower.+ tensor = torch.rand(2, 3, 9, 9, device=device, dtype=torch.float16).requires_grad_(True)+ kernel = torch.ones(3, 5, device=device, dtype=torch.float32)+ grad_engine = "unfold" if device.type in ("cuda", "cpu") else "shift"+ seen = []+ resolve = morphology_module._resolve_engine++ def recording_resolve(engine, t, recording_grad=False, dtype=None):+ seen.append((dtype, resolve(engine, t, recording_grad, dtype)))+ return seen[-1][1]++ monkeypatch.setattr(morphology_module, "_resolve_engine", recording_resolve)+ assert _resolve_engine("auto", tensor, True, torch.float32) == grad_engine+ assert _resolve_engine("auto", tensor, True) == ("unfold" if device.type == "cuda" else "shift")++ actual = dilation(tensor, kernel)+ expected = dilation(tensor, kernel, engine=grad_engine)+ assert seen[0] == (torch.float32, grad_engine)+ assert actual.dtype == torch.float32+ assert torch.equal(actual, expected)+ # The same call without a backward graph keeps the forward-only engine off CUDA.+ with torch.no_grad():+ dilation(tensor, kernel)+ assert seen[-1] == (torch.float32, "unfold" if device.type == "cuda" else "shift")++ def test_auto_engine_forward_ad_takes_forward_engine(self, device):+ # Forward-mode AD records no backward graph, so off CUDA "auto" takes "shift" and the tangent+ # at tied maxima is the "shift" one: torch.maximum averages the tied tangents where+ # torch.max(dim=) (the "unfold" engine) forwards one argmax's tangent. The all-ones input makes+ # every window a tie, so the two engines' tangents differ and the pin can fail.+ tensor = torch.ones(1, 1, 2, 2, device=device)+ tangent = torch.tensor([[[[1.0, 2.0], [4.0, 8.0]]]], device=device)+ kernel = torch.ones(2, 2, device=device)+ expected_engine = "unfold" if device.type == "cuda" else "shift"++ def run(engine):+ return torch.func.jvp(lambda t: dilation(t, kernel, origin=[0, 0], engine=engine), (tensor,), (tangent,))[1]++ assert not torch.equal(run("unfold"), run("shift"))+ assert torch.equal(run("auto"), run(expected_engine))++ @pytest.mark.parametrize("kernel_shape", [(1, 1), (3, 3), (3, 5), (4, 2)])+ @pytest.mark.parametrize("origin", ["center", "first", "last"])+ @pytest.mark.parametrize("border_type", ["geodesic", "constant", "reflect", "replicate"])+ @pytest.mark.parametrize("non_flat", [False, True])+ def test_shift_engine_matches_unfold(self, device, dtype, kernel_shape, origin, border_type, non_flat):+ # engine="shift" reduces the same finite max-plus terms as engine="unfold" in the same order,+ # so the outputs are equal (#4729).+ if border_type == "reflect" and not supports_reflect_padding(device, dtype):+ pytest.skip("reflection_pad2d is unavailable for this device/dtype")+ if border_type == "replicate" and not supports_replicate_padding(device, dtype):+ pytest.skip("replication_pad2d is unavailable for this device/dtype")+ kh, kw = kernel_shape+ origin_yx = {"center": None, "first": [0, 0], "last": [kh - 1, kw - 1]}[origin]+ anchor = origin_yx if origin_yx is not None else [kh // 2, kw // 2]+ tensor = torch.rand(2, 3, 6, 7, device=device, dtype=dtype) * 10 - 5+ kernel = (torch.rand(kh, kw, device=device) > 0.3).to(dtype)+ kernel[anchor[0], anchor[1]] = 1.0+ structuring_element = (torch.rand(kh, kw, device=device) * 2 - 1).to(dtype) if non_flat else None+ border_value = 0.5 if border_type == "constant" else 0.0+ kwargs = {+ "structuring_element": structuring_element,+ "origin": origin_yx,+ "border_type": border_type,+ "border_value": border_value,+ }++ expected = dilation(tensor, kernel, engine="unfold", **kwargs)+ actual = dilation(tensor, kernel, engine="shift", **kwargs)++ assert actual.dtype == tensor.dtype+ assert torch.equal(actual, expected)++ def test_shift_engine_mixed_dtype_non_flat(self, device):+ tensor = torch.zeros(1, 1, 2, 2, device=device, dtype=torch.float16)+ kernel = torch.ones(2, 2, device=device, dtype=torch.float32)+ structuring_element = torch.tensor(+ [[0.1234567, 0.2345678], [0.3456789, 0.4567890]], device=device, dtype=torch.float32+ )+ kwargs = {"structuring_element": structuring_element, "origin": [0, 0]}++ expected = dilation(tensor, kernel, engine="unfold", **kwargs)+ actual = dilation(tensor, kernel, engine="shift", **kwargs)++ assert expected.dtype == torch.float32+ assert actual.dtype == expected.dtype+ assert torch.equal(actual, expected)+ assert torch.equal(dilation(tensor, kernel, **kwargs), expected)++ def test_shift_engine_signed_zero_is_equal_value(self, device):+ # Windows that tie between +0 and -0 give an equal value on every engine; which zero comes out+ # is the backend's tie choice for max/min (CPU keeps the first operand, MPS the second) and is+ # deliberately not pinned, on either engine.+ tensor = torch.tensor([[[[-1.0, -0.0], [0.0, -0.0]]]], device=device)+ kernel = torch.ones(2, 2, device=device)++ expected = dilation(tensor, kernel, origin=[0, 0], engine="unfold")+ actual = dilation(tensor, kernel, origin=[0, 0], engine="shift")++ assert torch.equal(actual, expected)+ assert torch.equal(actual, torch.zeros_like(actual))++ def test_shift_engine_gradcheck(self, device):+ tensor = torch.rand(2, 3, 5, 5, device=device, dtype=torch.float64)+ kernel = torch.ones(3, 3, device=device, dtype=torch.float64)+ kernel[0, 2] = 0.0+ self.gradcheck(lambda t: dilation(t, kernel, engine="shift"), (tensor,))++ @pytest.mark.parametrize("requires_grad", [False, True])+ def test_dynamo(self, device, dtype, torch_optimizer, requires_grad):+ # engine="auto" reads grad mode, ``requires_grad`` and the promoted dtype when the graph is traced,+ # so both engines it can select on this device (``shift`` forward-only, ``unfold`` for a CPU+ # float32/float64 backward graph) have to compile to the eager result.+ tensor = torch.rand(2, 3, 9, 9, device=device, dtype=dtype).requires_grad_(requires_grad)+ kernel = torch.ones(3, 5, device=device, dtype=dtype)+ kernel[0, 0] = 0.0+ op_optimized = torch_optimizer(dilation)++ self.assert_close(dilation(tensor, kernel), op_optimized(tensor, kernel))++ def test_shift_engine_jit(self, device, dtype):+ op_script = torch.jit.script(dilation)+ tensor = torch.rand(1, 2, 7, 7, device=device, dtype=dtype)+ kernel = torch.ones(3, 3, device=device, dtype=dtype)++ assert torch.equal(op_script(tensor, kernel, engine="shift"), dilation(tensor, kernel, engine="shift"))diff --git a/tests/morphology/test_erosion.py b/tests/morphology/test_erosion.pyindex d0013c09d..273f63445 100644--- a/tests/morphology/test_erosion.py+++ b/tests/morphology/test_erosion.py@@ -19,8 +19,10 @@ import pytestimport torchfrom kornia.morphology import erosion+from kornia.morphology import morphology as morphology_module+from kornia.morphology.morphology import _records_grad, _resolve_engine-from testing.base import BaseTester, assert_close+from testing.base import BaseTester, assert_close, supports_reflect_padding, supports_replicate_paddingfrom testing.parametrized_tester import parametrized_test@@ -169,3 +171,201 @@ class TestErode(BaseTester):assert result.dtype == dtypeself.assert_close(result, erosion(tensor, kernel.to(dtype), engine="convolution"))++ def test_auto_engine(self, device, dtype):+ # engine="auto", the default, runs "unfold" on CUDA and the exact "shift" engine everywhere+ # else (#4525). An explicit engine is passed through unchanged.+ tensor = torch.rand(2, 3, 9, 9, device=device, dtype=dtype)+ kernel = torch.ones(3, 5, device=device, dtype=dtype)+ kernel[0, 0] = 0.0+ expected_engine = "unfold" if device.type == "cuda" else "shift"++ assert _resolve_engine("auto", tensor) == expected_engine+ assert _resolve_engine("unfold", tensor) == "unfold"+ assert _resolve_engine("convolution", tensor) == "convolution"+ assert _resolve_engine("shift", tensor) == "shift"+ expected = erosion(tensor, kernel, engine=expected_engine)+ assert torch.equal(erosion(tensor, kernel), expected)+ assert torch.equal(erosion(tensor, kernel, engine="auto"), expected)++ def test_auto_engine_is_grad_aware(self, device, dtype):+ # A CPU call that records a backward graph takes "unfold" in float32/float64, where "shift"+ # is up to 3.4x slower; half precision and the forward-only path keep "shift". CUDA is+ # "unfold" either way, and MPS is "shift" either way -- the grad branch is CPU-only, so the+ # dtype does not enter off CPU. Equal forward output makes the switch value-preserving.+ tensor = torch.rand(2, 3, 9, 9, device=device, dtype=dtype)+ kernel = torch.ones(3, 5, device=device, dtype=dtype)+ wide = dtype in (torch.float32, torch.float64)+ grad_engine = "unfold" if device.type == "cuda" or (device.type == "cpu" and wide) else "shift"+ plain_engine = "unfold" if device.type == "cuda" else "shift"++ assert _resolve_engine("auto", tensor, True) == grad_engine+ assert _resolve_engine("auto", tensor, False) == plain_engine+ assert _resolve_engine("shift", tensor, True) == "shift"+ assert torch.equal(erosion(tensor, kernel), erosion(tensor, kernel, engine=plain_engine))++ grad_tensor = tensor.clone().requires_grad_(True)+ assert torch.equal(erosion(grad_tensor, kernel), erosion(grad_tensor, kernel, engine=grad_engine))+ # torch.no_grad() leaves requires_grad set but records nothing, so the forward-only engine wins.+ with torch.no_grad():+ assert torch.equal(erosion(grad_tensor, kernel), erosion(grad_tensor, kernel, engine=plain_engine))++ def test_auto_engine_follows_structuring_element_grad(self, device, dtype, monkeypatch):+ # The neighborhood is built from the structuring element, so grad on it records a backward+ # graph even when the image does not require grad. The kernel enters only through the+ # ``kernel == 0`` mask, so a kernel that requires grad records nothing and must not push a+ # forward-only call onto the slower grad-mode engine (#4525).+ tensor = torch.rand(2, 3, 9, 9, device=device, dtype=dtype)+ kernel = torch.ones(3, 5, device=device, dtype=dtype)+ se = torch.rand(3, 5, device=device, dtype=dtype)+ seen = []+ resolve = morphology_module._resolve_engine+ monkeypatch.setattr(+ morphology_module,+ "_resolve_engine",+ lambda engine, t, recording_grad=False, dtype=None: (+ seen.append(recording_grad) or resolve(engine, t, recording_grad, dtype)+ ),+ )++ assert _records_grad(tensor, None) is False+ assert _records_grad(tensor, se) is False+ assert _records_grad(tensor, se.clone().requires_grad_(True)) is True++ erosion(tensor, kernel.clone().requires_grad_(True), engine="shift")+ erosion(tensor, kernel, se.clone().requires_grad_(True), engine="shift")+ erosion(tensor.clone().requires_grad_(True), kernel, engine="shift")+ with torch.no_grad():+ erosion(tensor.clone().requires_grad_(True), kernel, engine="shift")+ assert seen == [False, True, True, False]+ assert not erosion(tensor, kernel.clone().requires_grad_(True)).requires_grad++ def test_auto_engine_resolves_from_promoted_dtype(self, device, monkeypatch):+ # A float16 image with a float32 kernel computes, and differentiates, in float32, so the+ # float32/float64 grad rule of "auto" must see the promoted dtype rather than the image's.+ # On CPU that is the difference between "unfold" and a "shift" backward that is ~5x slower.+ tensor = torch.rand(2, 3, 9, 9, device=device, dtype=torch.float16).requires_grad_(True)+ kernel = torch.ones(3, 5, device=device, dtype=torch.float32)+ grad_engine = "unfold" if device.type in ("cuda", "cpu") else "shift"+ seen = []+ resolve = morphology_module._resolve_engine++ def recording_resolve(engine, t, recording_grad=False, dtype=None):+ seen.append((dtype, resolve(engine, t, recording_grad, dtype)))+ return seen[-1][1]++ monkeypatch.setattr(morphology_module, "_resolve_engine", recording_resolve)+ assert _resolve_engine("auto", tensor, True, torch.float32) == grad_engine+ assert _resolve_engine("auto", tensor, True) == ("unfold" if device.type == "cuda" else "shift")++ actual = erosion(tensor, kernel)+ expected = erosion(tensor, kernel, engine=grad_engine)+ assert seen[0] == (torch.float32, grad_engine)+ assert actual.dtype == torch.float32+ assert torch.equal(actual, expected)+ # The same call without a backward graph keeps the forward-only engine off CUDA.+ with torch.no_grad():+ erosion(tensor, kernel)+ assert seen[-1] == (torch.float32, "unfold" if device.type == "cuda" else "shift")++ def test_auto_engine_forward_ad_takes_forward_engine(self, device):+ # Forward-mode AD records no backward graph, so off CUDA "auto" takes "shift" and the tangent+ # at tied maxima is the "shift" one: torch.maximum averages the tied tangents where+ # torch.max(dim=) (the "unfold" engine) forwards one argmax's tangent. The all-ones input makes+ # every window a tie, so the two engines' tangents differ and the pin can fail.+ tensor = torch.ones(1, 1, 2, 2, device=device)+ tangent = torch.tensor([[[[1.0, 2.0], [4.0, 8.0]]]], device=device)+ kernel = torch.ones(2, 2, device=device)+ expected_engine = "unfold" if device.type == "cuda" else "shift"++ def run(engine):+ return torch.func.jvp(lambda t: erosion(t, kernel, origin=[0, 0], engine=engine), (tensor,), (tangent,))[1]++ assert not torch.equal(run("unfold"), run("shift"))+ assert torch.equal(run("auto"), run(expected_engine))++ @pytest.mark.parametrize("kernel_shape", [(1, 1), (3, 3), (3, 5), (4, 2)])+ @pytest.mark.parametrize("origin", ["center", "first", "last"])+ @pytest.mark.parametrize("border_type", ["geodesic", "constant", "reflect", "replicate"])+ @pytest.mark.parametrize("non_flat", [False, True])+ def test_shift_engine_matches_unfold(self, device, dtype, kernel_shape, origin, border_type, non_flat):+ # engine="shift" reduces the same finite max-plus terms as engine="unfold" in the same order,+ # so the outputs are equal (#4729).+ if border_type == "reflect" and not supports_reflect_padding(device, dtype):+ pytest.skip("reflection_pad2d is unavailable for this device/dtype")+ if border_type == "replicate" and not supports_replicate_padding(device, dtype):+ pytest.skip("replication_pad2d is unavailable for this device/dtype")+ kh, kw = kernel_shape+ origin_yx = {"center": None, "first": [0, 0], "last": [kh - 1, kw - 1]}[origin]+ anchor = origin_yx if origin_yx is not None else [kh // 2, kw // 2]+ tensor = torch.rand(2, 3, 6, 7, device=device, dtype=dtype) * 10 - 5+ kernel = (torch.rand(kh, kw, device=device) > 0.3).to(dtype)+ kernel[anchor[0], anchor[1]] = 1.0+ structuring_element = (torch.rand(kh, kw, device=device) * 2 - 1).to(dtype) if non_flat else None+ border_value = 0.5 if border_type == "constant" else 0.0+ kwargs = {+ "structuring_element": structuring_element,+ "origin": origin_yx,+ "border_type": border_type,+ "border_value": border_value,+ }++ expected = erosion(tensor, kernel, engine="unfold", **kwargs)+ actual = erosion(tensor, kernel, engine="shift", **kwargs)++ assert actual.dtype == tensor.dtype+ assert torch.equal(actual, expected)++ def test_shift_engine_mixed_dtype_non_flat(self, device):+ tensor = torch.zeros(1, 1, 2, 2, device=device, dtype=torch.float16)+ kernel = torch.ones(2, 2, device=device, dtype=torch.float32)+ structuring_element = torch.tensor(+ [[0.1234567, 0.2345678], [0.3456789, 0.4567890]], device=device, dtype=torch.float32+ )+ kwargs = {"structuring_element": structuring_element, "origin": [0, 0]}++ expected = erosion(tensor, kernel, engine="unfold", **kwargs)+ actual = erosion(tensor, kernel, engine="shift", **kwargs)++ assert expected.dtype == torch.float32+ assert actual.dtype == expected.dtype+ assert torch.equal(actual, expected)+ assert torch.equal(erosion(tensor, kernel, **kwargs), expected)++ def test_shift_engine_signed_zero_is_equal_value(self, device):+ # Windows that tie between +0 and -0 give an equal value on every engine; which zero comes out+ # is the backend's tie choice for max/min (CPU keeps the first operand, MPS the second) and is+ # deliberately not pinned, on either engine.+ tensor = torch.tensor([[[[1.0, -0.0], [0.0, -0.0]]]], device=device)+ kernel = torch.ones(2, 2, device=device)++ expected = erosion(tensor, kernel, origin=[0, 0], engine="unfold")+ actual = erosion(tensor, kernel, origin=[0, 0], engine="shift")++ assert torch.equal(actual, expected)+ assert torch.equal(actual, torch.zeros_like(actual))++ def test_shift_engine_gradcheck(self, device):+ tensor = torch.rand(2, 3, 5, 5, device=device, dtype=torch.float64)+ kernel = torch.ones(3, 3, device=device, dtype=torch.float64)+ kernel[0, 2] = 0.0+ self.gradcheck(lambda t: erosion(t, kernel, engine="shift"), (tensor,))++ @pytest.mark.parametrize("requires_grad", [False, True])+ def test_dynamo(self, device, dtype, torch_optimizer, requires_grad):+ # engine="auto" reads grad mode, ``requires_grad`` and the promoted dtype when the graph is traced,+ # so both engines it can select on this device (``shift`` forward-only, ``unfold`` for a CPU+ # float32/float64 backward graph) have to compile to the eager result.+ tensor = torch.rand(2, 3, 9, 9, device=device, dtype=dtype).requires_grad_(requires_grad)+ kernel = torch.ones(3, 5, device=device, dtype=dtype)+ kernel[0, 0] = 0.0+ op_optimized = torch_optimizer(erosion)++ self.assert_close(erosion(tensor, kernel), op_optimized(tensor, kernel))++ def test_shift_engine_jit(self, device, dtype):+ op_script = torch.jit.script(erosion)+ tensor = torch.rand(1, 2, 7, 7, device=device, dtype=dtype)+ kernel = torch.ones(3, 3, device=device, dtype=dtype)++ assert torch.equal(op_script(tensor, kernel, engine="shift"), erosion(tensor, kernel, engine="shift"))