Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

fix(core): check sizes without specializing them under torch.compile (#6063)

Dmytro Mishkin2686f63c99eb
diff --git a/AGENTS.md b/AGENTS.md
index 19ccfd4e7..5f9b0f83c 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -114,6 +114,7 @@ when more than one virtualenv is in play: name the interpreter explicitly rather
- Search for an existing `kornia` operation before building the same operation from raw PyTorch.
- Follow nearby batching, broadcasting, shape-validation, dtype, and device conventions.
+- A `KORNIA_CHECK` message that formats a tensor size or an `int` argument specializes it under a dynamic-shape `torch.compile`, which then compiles a graph per value. Compare sizes with `KORNIA_CHECK_SAME_SIZE`, `KORNIA_CHECK_SIZES` or `KORNIA_CHECK_SHAPE`, or pass the message as `lambda: f"..."`. TorchScript rejects a `lambda`, so a function it compiles formats whole shapes instead, such as `{x.shape}`, which do not specialize. `tests/core/test_check_message_call_sites.py` enforces both and lists the functions TorchScript compiles.
- Use `BaseTester` from `testing.base`, injected `device`/`dtype` fixtures, and `self.assert_close()` for tensor comparisons. Its dtype-specific tolerances are intentional.
- Follow [TESTING.md](TESTING.md) for test mechanisms. Use `self.gradcheck()` for gradient checks and the injected `torch_optimizer` fixture for `torch.compile` coverage. Include smoke, exception, shape/cardinality, numerical, gradient, and compile tests when they apply; not every change needs every kind.
- Keep numerical correctness tests self-contained. For expected values produced by an optional reference library, prefer a hardcoded literal plus the small generation snippet and source. Optional-dependency integration tests, including ONNX tests, may still use `pytest.importorskip`.
diff --git a/changelog.d/6063.added.md b/changelog.d/6063.added.md
new file mode 100644
index 000000000..965d41457
--- /dev/null
+++ b/changelog.d/6063.added.md
@@ -0,0 +1 @@
+`KORNIA_CHECK_SAME_SIZE` checks that two tensors have the same size along a dimension, optionally accepting a size of 1 for the first, and `KORNIA_CHECK_SIZES` checks a tensor against sizes computed at run time, with `None` for a dimension of any size. Both build their error message only on failure. The `msg` of every `KORNIA_CHECK*` helper can also be a function without arguments, called only when the check fails: `KORNIA_CHECK(condition, lambda: f"...")`.
diff --git a/changelog.d/6063.fixed.md b/changelog.d/6063.fixed.md
new file mode 100644
index 000000000..5e740b2e8
--- /dev/null
+++ b/changelog.d/6063.fixed.md
@@ -0,0 +1 @@
+Input checks no longer make a dynamic-shape `torch.compile` recompile for each new input size: their messages formatted tensor sizes or `int` arguments on every call, which specialized them. Over three sizes, `get_motion_kernel2d`, `motion_blur`, `fft_conv` with `padding="valid"`, `gaussian_blur2d` with a varying `kernel_size` and DeDoDe's `PatchEmbed` now compile one graph instead of three, `solve_pnp_dlt` two instead of four, `jpeg_codec_differentiable` four instead of eight (its quality-range message also read the tensor twice per call, which broke the graph and synchronized with the device in eager mode), and `ScaleSpaceDetector` 10 instead of 15. Size checks now raise `ShapeError` with both sizes, and the messages are no longer built on every call in eager mode.
diff --git a/docs/source/core.rst b/docs/source/core.rst
index bca269aa5..f7a49336b 100644
--- a/docs/source/core.rst
+++ b/docs/source/core.rst
@@ -45,6 +45,27 @@ callable that lets the download half reject a truncated cache entry.
.. autofunction:: check_safetensors
+Validation
+----------
+
+.. currentmodule:: kornia.core.check
+
+The ``KORNIA_CHECK*`` helpers validate inputs and raise the errors below. A check on sizes compares them with
+:func:`KORNIA_CHECK_SAME_SIZE`, :func:`KORNIA_CHECK_SIZES` or :func:`KORNIA_CHECK_SHAPE`, which build their message only
+when the check fails. Any other message that formats a tensor size or an ``int`` argument is passed as a function,
+``KORNIA_CHECK(condition, lambda: f"...")``: an f-string argument is built on every call, and under a dynamic-shape
+``torch.compile`` that specializes the value, so each new value would compile a new graph.
+
+.. autofunction:: KORNIA_CHECK
+
+.. autofunction:: KORNIA_CHECK_SHAPE
+
+.. autofunction:: KORNIA_CHECK_SAME_SHAPE
+
+.. autofunction:: KORNIA_CHECK_SAME_SIZE
+
+.. autofunction:: KORNIA_CHECK_SIZES
+
Exceptions
----------
diff --git a/kornia/augmentation/_2d/intensity/grayscale.py b/kornia/augmentation/_2d/intensity/grayscale.py
index 71e21f62a..53c55a4ce 100644
--- a/kornia/augmentation/_2d/intensity/grayscale.py
+++ b/kornia/augmentation/_2d/intensity/grayscale.py
@@ -112,7 +112,7 @@ class RandomGrayscale(IntensityAugmentationBase2D):
else:
KORNIA_CHECK(
weights.numel() == num_channels,
- f"rgb_weights needs one weight per channel: got {weights.numel()} for {num_channels}.",
+ lambda: f"rgb_weights needs one weight per channel: got {weights.numel()} for {num_channels}.",
)
weights = weights.to(input)
gray = (input * weights.view(*lead, num_channels, 1, 1)).sum(-3, keepdim=True)
diff --git a/kornia/augmentation/_2d/mix/transplantation.py b/kornia/augmentation/_2d/mix/transplantation.py
index cb8f5e198..63131419f 100644
--- a/kornia/augmentation/_2d/mix/transplantation.py
+++ b/kornia/augmentation/_2d/mix/transplantation.py
@@ -371,8 +371,10 @@ class RandomTransplantation(MixAugmentationBaseV2):
)
KORNIA_CHECK(
len(selected_labels) <= len(params["acceptor_indices"]),
- f"There cannot be more selected labels ({len(selected_labels)}) than images where this "
- f"augmentation should be applied ({len(params['acceptor_indices'])}).",
+ lambda: (
+ f"There cannot be more selected labels ({len(selected_labels)}) than images where this "
+ f"augmentation should be applied ({len(params['acceptor_indices'])})."
+ ),
)
for d, selected_label in zip(range(len(params["donor_indices"])), selected_labels):
diff --git a/kornia/contrib/distance_transform.py b/kornia/contrib/distance_transform.py
index 2208c8112..5e6e4fe2a 100644
--- a/kornia/contrib/distance_transform.py
+++ b/kornia/contrib/distance_transform.py
@@ -48,9 +48,11 @@ def _check_h_range(kernel_size: int, h: float, dtype: torch.dtype, ndim: int) ->
farthest_tap = math.exp(-math.sqrt(ndim) * k_half / h)
KORNIA_CHECK(
farthest_tap >= torch.finfo(dtype).tiny,
- f"h={h} is too small for kernel_size={kernel_size} at working precision {dtype}: the corner kernel tap "
- f"exp(-sqrt({ndim})*{k_half}/h) falls below the smallest normal number of that precision and the result "
- "would be wrong. Increase h or decrease kernel_size.",
+ lambda: (
+ f"h={h} is too small for kernel_size={kernel_size} at working precision {dtype}: the corner kernel tap "
+ f"exp(-sqrt({ndim})*{k_half}/h) falls below the smallest normal number of that precision and the result "
+ "would be wrong. Increase h or decrease kernel_size."
+ ),
)
# A pixel counts as reached when -h*log(sum of its window's taps over reached pixels) > 0, i.e. when that sum is
# below 1; a source pixel fails the test through its own centre tap, and that is how sources stay at 0. If the
@@ -64,9 +66,11 @@ def _check_h_range(kernel_size: int, h: float, dtype: torch.dtype, ndim: int) ->
off_centre = _off_centre_tap_sum(kernel_size, h, ndim)
KORNIA_CHECK(
off_centre < 1.0 - margin,
- f"h={h} is too large for kernel_size={kernel_size} in {ndim}-D: the kernel's off-centre taps sum to "
- f"{off_centre:.7f}, not below 1 by the rounding margin {margin:.1e} of the {dtype} working precision, so a "
- "pixel surrounded by reached pixels could read as foreground (distance 0). Decrease h.",
+ lambda: (
+ f"h={h} is too large for kernel_size={kernel_size} in {ndim}-D: the kernel's off-centre taps sum to "
+ f"{off_centre:.7f}, not below 1 by the rounding margin {margin:.1e} of the {dtype} working precision, so a "
+ "pixel surrounded by reached pixels could read as foreground (distance 0). Decrease h."
+ ),
)
diff --git a/kornia/contrib/kmeans.py b/kornia/contrib/kmeans.py
index 1368922a7..678a5f959 100644
--- a/kornia/contrib/kmeans.py
+++ b/kornia/contrib/kmeans.py
@@ -21,7 +21,7 @@ from __future__ import annotations
import torch
-from kornia.core.check import KORNIA_CHECK, KORNIA_CHECK_SHAPE
+from kornia.core.check import KORNIA_CHECK, KORNIA_CHECK_SAME_SIZE, KORNIA_CHECK_SHAPE
from kornia.geometry.linalg import euclidean_distance
@@ -205,10 +205,11 @@ class KMeans:
current_centers = self._initialise_cluster_centers(X, self.num_clusters)
else:
# X and cluster_centers should have same number of columns
- KORNIA_CHECK(
- X.shape[1] == self._initial_cluster_centers.shape[1],
- f"Dimensions at position 1 of X and cluster_centers do not match. \
- {X.shape[1]} != {self._initial_cluster_centers.shape[1]}",
+ KORNIA_CHECK_SAME_SIZE(
+ X,
+ self._initial_cluster_centers,
+ dim=1,
+ msg="X and cluster_centers must have the same number of columns.",
)
current_centers = self._initial_cluster_centers
@@ -289,10 +290,8 @@ class KMeans:
"""
KORNIA_CHECK_SHAPE(x, ["N", "D"])
# x and cluster_centers should have same number of columns
- KORNIA_CHECK(
- x.shape[1] == self.cluster_centers.shape[1],
- f"Dimensions at position 1 of x and cluster_centers do not match. \
- {x.shape[1]} != {self.cluster_centers.shape[1]}",
+ KORNIA_CHECK_SAME_SIZE(
+ x, self.cluster_centers, dim=1, msg="x and cluster_centers must have the same number of columns."
)
work_dtype = self._work_dtype(x, self.cluster_centers)
diff --git a/kornia/contrib/visual_prompter.py b/kornia/contrib/visual_prompter.py
index 0188c84a5..062626641 100644
--- a/kornia/contrib/visual_prompter.py
+++ b/kornia/contrib/visual_prompter.py
@@ -209,9 +209,10 @@ class VisualPrompter:
image = image.unsqueeze(0)
else:
KORNIA_CHECK_SHAPE(image, ["B", "3", "H", "W"])
- KORNIA_CHECK(
- image.shape[0] == 1,
- f"VisualPrompter takes one image, (3, H, W) or (1, 3, H, W); got a batch of {image.shape[0]}. "
+ KORNIA_CHECK_SHAPE(
+ image,
+ ["1", "3", "H", "W"],
+ "VisualPrompter takes one image, (3, H, W) or (1, 3, H, W). "
"Use `Sam.forward` to segment a batch of images with per-image prompts.",
)
@@ -235,9 +236,11 @@ class VisualPrompter:
encoder_size = self.model.image_encoder.img_size
KORNIA_CHECK(
max(height, width) <= encoder_size,
- f"VisualPrompter.transforms resizes the image to {height} x {width}, larger than the image encoder's input "
- f"size {encoder_size}: the padding to {encoder_size} would crop the image while the prompts are scaled "
- "for all of it.",
+ lambda: (
+ f"VisualPrompter.transforms resizes the image to {height} x {width}, larger than the image "
+ f"encoder's input size {encoder_size}: the padding to {encoder_size} would crop the image while the "
+ "prompts are scaled for all of it."
+ ),
)
prompt_dtype = torch.promote_types(self.model.prompt_encoder.point_embeddings[0].weight.dtype, torch.float32)
self._prompt_scale = torch.tensor(
@@ -291,8 +294,10 @@ class VisualPrompter:
KORNIA_CHECK(
images == 1,
- f"VisualPrompter takes the boxes of its one image, (K, 4) or (1, K, 4); got boxes for {images} images. "
- "Use `Sam.forward` to prompt a batch of images.",
+ lambda: (
+ f"VisualPrompter takes the boxes of its one image, (K, 4) or (1, K, 4); got boxes for {images} "
+ "images. Use `Sam.forward` to prompt a batch of images."
+ ),
)
return xyxy.reshape(-1, 4)
diff --git a/kornia/core/check.py b/kornia/core/check.py
index 0eade5ebd..32c2d8f9f 100644
--- a/kornia/core/check.py
+++ b/kornia/core/check.py
@@ -20,7 +20,7 @@
from __future__ import annotations
import os
-from typing import Any, Optional, Sequence, TypeVar, cast
+from typing import TYPE_CHECKING, Any, Callable, Optional, Sequence, TypeVar, Union, cast
import torch
from torch import float16, float32, float64
@@ -45,7 +45,9 @@ __all__ = [
"KORNIA_CHECK_LAF",
"KORNIA_CHECK_SAME_DEVICE",
"KORNIA_CHECK_SAME_DEVICES",
+ "KORNIA_CHECK_SAME_SIZE",
"KORNIA_CHECK_SHAPE",
+ "KORNIA_CHECK_SIZES",
"KORNIA_CHECK_TYPE",
"KORNIA_UNWRAP",
"BaseError",
@@ -82,6 +84,22 @@ def _should_enable_checks() -> bool:
# Module-level flag - evaluated once at import time, but can be changed at runtime
_KORNIA_CHECKS_ENABLED: bool = _should_enable_checks()
+if TYPE_CHECKING:
+ # A check message is a string, or a function without arguments that builds it; see ``KORNIA_CHECK``.
+ CheckMessage = Union[str, Callable[[], str]]
+else:
+ # TorchScript resolves the annotations at run time and has no type for a Python function, so it sees ``str``. A
+ # message function is Python-only, and ``_resolve_msg`` calls it under a bare ``is_scripting()`` guard.
+ CheckMessage = str
+
+
+def _resolve_msg(msg: Optional[CheckMessage]) -> Optional[str]:
+ """Return the message of a failed check, calling it first if it is a function."""
+ if not torch.jit.is_scripting(): # noqa: SIM102 - TorchScript only skips a bare is_scripting() guard
+ if callable(msg):
+ return msg()
+ return msg
+
def are_checks_enabled() -> bool:
"""Check if validation is currently enabled.
@@ -128,7 +146,9 @@ def enable_checks() -> None:
# Logger api
-def KORNIA_CHECK_SHAPE(x: torch.Tensor, shape: list[str], msg: Optional[str] = None, raises: bool = True) -> bool:
+def KORNIA_CHECK_SHAPE(
+ x: torch.Tensor, shape: list[str], msg: Optional[CheckMessage] = None, raises: bool = True
+) -> bool:
"""Check whether a tensor has a specified shape.
The shape can be specified with a implicit or explicit list of strings.
@@ -138,7 +158,8 @@ def KORNIA_CHECK_SHAPE(x: torch.Tensor, shape: list[str], msg: Optional[str] = N
x: the tensor to evaluate.
shape: a list with strings with the expected shape. A leading or trailing ``"*"`` matches any number
of dimensions; ``["*"]`` accepts any shape, and an empty list accepts only a scalar tensor.
- msg: optional custom message to append to error.
+ msg: optional custom message to append to error, or a function that returns it; see
+ :func:`KORNIA_CHECK`.
raises: bool indicating whether an exception should be raised upon failure.
Raises:
@@ -178,6 +199,7 @@ def KORNIA_CHECK_SHAPE(x: torch.Tensor, shape: list[str], msg: Optional[str] = N
if len(x_shape_to_check) != len(shape_to_check):
if raises:
+ msg = _resolve_msg(msg)
expected_dims = len(shape_to_check)
actual_dims = len(x_shape_to_check)
error_msg = f"Shape dimension mismatch: expected {expected_dims} dimensions, got {actual_dims}.\n"
@@ -202,6 +224,7 @@ def KORNIA_CHECK_SHAPE(x: torch.Tensor, shape: list[str], msg: Optional[str] = N
dim = int(dim_)
if x_shape_to_check[i] != dim:
if raises:
+ msg = _resolve_msg(msg)
error_msg = (
f"Shape mismatch at dimension {i + dimension_offset}: expected {dim}, got {x_shape_to_check[i]}.\n"
)
@@ -219,12 +242,18 @@ def KORNIA_CHECK_SHAPE(x: torch.Tensor, shape: list[str], msg: Optional[str] = N
return True
-def KORNIA_CHECK(condition: bool, msg: Optional[str] = None, raises: bool = True) -> bool:
+def KORNIA_CHECK(condition: bool, msg: Optional[CheckMessage] = None, raises: bool = True) -> bool:
"""Check any arbitrary boolean condition.
Args:
condition: the condition to evaluate.
- msg: message to show in the exception.
+ msg: message to show in the exception, or a function without arguments that returns it. A function is
+ called only when the check fails. Python builds an f-string argument on every call, and under a
+ dynamic-shape ``torch.compile`` formatting a tensor size or an ``int`` argument specializes it, so each
+ new value would compile a new graph. A check on sizes therefore compares them with
+ :func:`KORNIA_CHECK_SAME_SIZE`, :func:`KORNIA_CHECK_SIZES` or :func:`KORNIA_CHECK_SHAPE`, which format
+ only on failure, and any other message that formats such a value is a function, as in
+ ``lambda: f"got {n}"``. TorchScript takes only a string.
raises: bool indicating whether an exception should be raised upon failure.
Raises:
@@ -240,6 +269,8 @@ def KORNIA_CHECK(condition: bool, msg: Optional[str] = None, raises: bool = True
>>> x = torch.rand(2, 3, 3)
>>> KORNIA_CHECK(x.shape[-2:] == (3, 3), "Invalid homography")
True
+ >>> KORNIA_CHECK(x.shape[0] == 2, lambda: f"Expected a batch of 2, got {x.shape[0]}")
+ True
"""
if not torch.jit.is_scripting(): # noqa: SIM102 - TorchScript only skips a bare is_scripting() guard
@@ -248,6 +279,7 @@ def KORNIA_CHECK(condition: bool, msg: Optional[str] = None, raises: bool = True
if not condition:
if raises:
+ msg = _resolve_msg(msg)
error_msg = "Validation condition failed" if msg is None else msg
raise BaseError(error_msg)
return False
@@ -269,13 +301,15 @@ def KORNIA_UNWRAP(maybe_obj: Any, typ: Any) -> Any:
_T = TypeVar("_T", bound=type)
-def KORNIA_CHECK_TYPE(x: Any, typ: _T | tuple[_T, ...], msg: Optional[str] = None, raises: bool = True) -> bool:
+def KORNIA_CHECK_TYPE(
+ x: Any, typ: _T | tuple[_T, ...], msg: Optional[CheckMessage] = None, raises: bool = True
+) -> bool:
"""Check the type of an arbitrary variable.
Args:
x: any input variable.
typ: the expected type of the variable.
- msg: message to show in the exception.
+ msg: message to show in the exception, or a function that returns it; see :func:`KORNIA_CHECK`.
raises: bool indicating whether an exception should be raised upon failure.
Raises:
@@ -298,6 +332,7 @@ def KORNIA_CHECK_TYPE(x: Any, typ: _T | tuple[_T, ...], msg: Optional[str] = Non
if not isinstance(x, typ):
if raises:
+ msg = _resolve_msg(msg)
# JIT doesn't support try-except or type introspection, so use simple message
if torch.jit.is_scripting():
error_msg = "Type mismatch."
@@ -324,12 +359,12 @@ def KORNIA_CHECK_TYPE(x: Any, typ: _T | tuple[_T, ...], msg: Optional[str] = Non
return True
-def KORNIA_CHECK_IS_TENSOR(x: Any, msg: Optional[str] = None, raises: bool = True) -> bool:
+def KORNIA_CHECK_IS_TENSOR(x: Any, msg: Optional[CheckMessage] = None, raises: bool = True) -> bool:
"""Check the input variable is a Tensor.
Args:
x: any input variable.
- msg: message to show in the exception.
+ msg: message to show in the exception, or a function that returns it; see :func:`KORNIA_CHECK`.
raises: bool indicating whether an exception should be raised upon failure.
Raises:
@@ -353,6 +388,7 @@ def KORNIA_CHECK_IS_TENSOR(x: Any, msg: Optional[str] = None, raises: bool = Tru
if not isinstance(x, torch.Tensor):
if raises:
+ msg = _resolve_msg(msg)
# JIT doesn't support try-except or type introspection, so use simple message
if torch.jit.is_scripting():
error_msg = "Type mismatch: expected Tensor."
@@ -464,12 +500,14 @@ def KORNIA_CHECK_SAME_DEVICE(x: torch.Tensor, y: torch.Tensor, raises: bool = Tr
return True
-def KORNIA_CHECK_SAME_DEVICES(tensors: list[torch.Tensor], msg: Optional[str] = None, raises: bool = True) -> bool:
+def KORNIA_CHECK_SAME_DEVICES(
+ tensors: list[torch.Tensor], msg: Optional[CheckMessage] = None, raises: bool = True
+) -> bool:
"""Check whether a non-empty list of tensors live on the same device.
Args:
tensors: a non-empty list of tensors.
- msg: message to show in the exception.
+ msg: message to show in the exception, or a function that returns it; see :func:`KORNIA_CHECK`.
raises: bool indicating whether an exception should be raised upon failure.
Raises:
@@ -495,6 +533,7 @@ def KORNIA_CHECK_SAME_DEVICES(tensors: list[torch.Tensor], msg: Optional[str] =
if not (isinstance(tensors, list) and len(tensors) > 0 and all(isinstance(x, torch.Tensor) for x in tensors)):
if raises:
+ msg = _resolve_msg(msg)
prefix = "Expected a non-empty list of tensors, got"
suffix = "" if msg is None else f"\n {msg}"
if not isinstance(tensors, list):
@@ -513,6 +552,7 @@ def KORNIA_CHECK_SAME_DEVICES(tensors: list[torch.Tensor], msg: Optional[str] =
return False
if not all(tensors[0].device == x.device for x in tensors):
if raises:
+ msg = _resolve_msg(msg)
devices = [x.device for x in tensors]
error_msg = "Device mismatch: all tensors must be on the same device.\n"
error_msg += f" Expected device: {tensors[0].device}\n"
@@ -572,12 +612,142 @@ def KORNIA_CHECK_SAME_SHAPE(x: torch.Tensor, y: torch.Tensor, raises: bool = Tru
return True
-def KORNIA_CHECK_IS_COLOR(x: torch.Tensor, msg: Optional[str] = None, raises: bool = True) -> bool:
+def KORNIA_CHECK_SAME_SIZE(
+ x: torch.Tensor,
+ y: torch.Tensor,
+ dim: int = 0,
+ allow_one: bool = False,
+ msg: Optional[CheckMessage] = None,
+ raises: bool = True,
+) -> bool:
+ """Check whether two tensors have the same size along a dimension.
+
+ The sizes are compared as they are and the error message is built only on failure, so under a dynamic-shape
+ ``torch.compile`` the check relates the two sizes without specializing either of them.
+
+ Args:
+ x: the tensor to evaluate.
+ y: the reference tensor.
+ dim: the dimension to compare; negative values count from the end.
+ allow_one: also accept a size of 1 for ``x``, such as a kernel or a parameter shared by the whole batch.
+ msg: message to append to the error, or a function that returns it; see :func:`KORNIA_CHECK`.
+ raises: bool indicating whether an exception should be raised upon failure.
+
+ Raises:
+ ShapeError: if a tensor has no dimension ``dim``, or the sizes differ (and that of ``x`` is not 1 with
+ ``allow_one``), and raises is True.
+
+ Note:
+ Checks can be disabled in Python mode using `disable_checks()` or the KORNIA_CHECKS
+ environment variable. In TorchScript-compiled code, checks always run (TorchScript
+ cannot access module-level globals, but the validation logic is fast). When running
+ with `python -O`, Python's optimizer may eliminate some checks.
+
+ Example:
+ >>> image = torch.rand(4, 3, 8, 8)
+ >>> sigma = torch.rand(1, 2)
+ >>> KORNIA_CHECK_SAME_SIZE(sigma, image, allow_one=True)
+ True
+ >>> KORNIA_CHECK_SAME_SIZE(torch.rand(2, 2), image, raises=False)
+ False
+
+ """
+ if not torch.jit.is_scripting(): # noqa: SIM102 - TorchScript only skips a bare is_scripting() guard
+ if not _KORNIA_CHECKS_ENABLED:
+ return True
+
+ # every ``.shape`` builds a new ``torch.Size``, so each is read once
+ x_shape, y_shape = x.shape, y.shape
+ x_ndim, y_ndim = len(x_shape), len(y_shape)
+ in_range = -x_ndim <= dim < x_ndim and -y_ndim <= dim < y_ndim
+ if not in_range or not (x_shape[dim] == y_shape[dim] or (allow_one and x_shape[dim] == 1)):
+ if raises:
+ msg = _resolve_msg(msg)
+ x_shape_list = list(x_shape)
+ y_shape_list = list(y_shape)
+ if not in_range:
+ error_msg = f"Size mismatch: the tensors have no dimension {dim}.\n"
+ else:
+ expected = f"{y_shape[dim]} or 1" if allow_one and y_shape[dim] != 1 else f"{y_shape[dim]}"
+ error_msg = f"Size mismatch at dimension {dim}: expected {expected}, got {x_shape[dim]}.\n"
+ error_msg += f" First tensor shape: {x_shape_list}\n"
+ error_msg += f" Second tensor shape: {y_shape_list}"
+ if msg is not None:
+ error_msg += f"\n {msg}"
+ raise ShapeError(error_msg, actual_shape=x_shape_list, expected_shape=y_shape_list)
+ return False
+ return True
+
+
+def KORNIA_CHECK_SIZES(
+ x: torch.Tensor, sizes: list[Optional[int]], msg: Optional[CheckMessage] = None, raises: bool = True
+) -> bool:
+ """Check whether a tensor has the given sizes, which may be computed at run time.
+
+ It is the counterpart of :func:`KORNIA_CHECK_SHAPE` for sizes that are numbers rather than fixed strings, such as
+ the number of classes of a prediction or the batch of another tensor. The sizes are compared as they are and the
+ error message is built only on failure, so under a dynamic-shape ``torch.compile`` the check relates the sizes
+ without specializing them.
+
+ Args:
+ x: the tensor to evaluate.
+ sizes: the expected size of every dimension, or ``None`` for a dimension of any size.
+ msg: message to append to the error, or a function that returns it; see :func:`KORNIA_CHECK`.
+ raises: bool indicating whether an exception should be raised upon failure.
+
+ Raises:
+ ShapeError: if the tensor does not have ``len(sizes)`` dimensions, or one of them differs from a given size,
+ and raises is True.
+
+ Note:
+ Checks can be disabled in Python mode using `disable_checks()` or the KORNIA_CHECKS
+ environment variable. In TorchScript-compiled code, checks always run (TorchScript
+ cannot access module-level globals, but the validation logic is fast). When running
+ with `python -O`, Python's optimizer may eliminate some checks.
+
+ Example:
+ >>> pred = torch.rand(2, 5, 4, 4)
+ >>> weight = torch.rand(5)
+ >>> KORNIA_CHECK_SIZES(weight, [pred.shape[1]])
+ True
+ >>> KORNIA_CHECK_SIZES(pred, [2, None, 4, 4])
+ True
+
+ """
+ if not torch.jit.is_scripting(): # noqa: SIM102 - TorchScript only skips a bare is_scripting() guard
+ if not _KORNIA_CHECKS_ENABLED:
+ return True
+
+ x_shape = x.shape
+ matches = len(x_shape) == len(sizes)
+ if matches:
+ for i in range(len(sizes)):
+ size = sizes[i]
+ if size is not None and x_shape[i] != size:
+ matches = False
+ break
+ if not matches:
+ if raises:
+ msg = _resolve_msg(msg)
+ expected: list[str] = []
+ for size in sizes:
+ expected.append("*" if size is None else str(size))
+ x_shape_list = list(x.shape)
+ expected_str = ", ".join(expected) + ("," if len(expected) == 1 else "")
+ error_msg = f"Shape mismatch: expected ({expected_str}), got {x_shape_list}."
+ if msg is not None:
+ error_msg += f"\n {msg}"
+ raise ShapeError(error_msg, actual_shape=x_shape_list, expected_shape=expected)
+ return False
+ return True
+
+
+def KORNIA_CHECK_IS_COLOR(x: torch.Tensor, msg: Optional[CheckMessage] = None, raises: bool = True) -> bool:
"""Check whether an image tensor is a color images.
Args:
x: image tensor to evaluate.
- msg: message to show in the exception.
+ msg: message to show in the exception, or a function that returns it; see :func:`KORNIA_CHECK`.
raises: bool indicating whether an exception should be raised upon failure.
Raises:
@@ -601,6 +771,7 @@ def KORNIA_CHECK_IS_COLOR(x: torch.Tensor, msg: Optional[str] = None, raises: bo
if len(x.shape) < 3 or x.shape[-3] != 3:
if raises:
+ msg = _resolve_msg(msg)
error_msg = f"Not a color tensor. Got shape {list(x.shape)}."
if msg is not None:
error_msg += f"\n{msg}"
@@ -609,12 +780,12 @@ def KORNIA_CHECK_IS_COLOR(x: torch.Tensor, msg: Optional[str] = None, raises: bo
return True
-def KORNIA_CHECK_IS_GRAY(x: torch.Tensor, msg: Optional[str] = None, raises: bool = True) -> bool:
+def KORNIA_CHECK_IS_GRAY(x: torch.Tensor, msg: Optional[CheckMessage] = None, raises: bool = True) -> bool:
"""Check whether an image tensor is grayscale.
Args:
x: image tensor to evaluate.
- msg: message to show in the exception.
+ msg: message to show in the exception, or a function that returns it; see :func:`KORNIA_CHECK`.
raises: bool indicating whether an exception should be raised upon failure.
Raises:
@@ -638,6 +809,7 @@ def KORNIA_CHECK_IS_GRAY(x: torch.Tensor, msg: Optional[str] = None, raises: boo
if len(x.shape) < 2 or (len(x.shape) >= 3 and x.shape[-3] != 1):
if raises:
+ msg = _resolve_msg(msg)
error_msg = f"Not a gray tensor. Got shape {list(x.shape)}."
if msg is not None:
error_msg += f"\n{msg}"
@@ -646,12 +818,12 @@ def KORNIA_CHECK_IS_GRAY(x: torch.Tensor, msg: Optional[str] = None, raises: boo
return True
-def KORNIA_CHECK_IS_COLOR_OR_GRAY(x: torch.Tensor, msg: Optional[str] = None, raises: bool = True) -> bool:
+def KORNIA_CHECK_IS_COLOR_OR_GRAY(x: torch.Tensor, msg: Optional[CheckMessage] = None, raises: bool = True) -> bool:
"""Check whether an image tensor is grayscale or color.
Args:
x: image tensor to evaluate.
- msg: message to show in the exception.
+ msg: message to show in the exception, or a function that returns it; see :func:`KORNIA_CHECK`.
raises: bool indicating whether an exception should be raised upon failure.
Raises:
@@ -675,6 +847,7 @@ def KORNIA_CHECK_IS_COLOR_OR_GRAY(x: torch.Tensor, msg: Optional[str] = None, ra
if len(x.shape) < 3 or x.shape[-3] not in [1, 3]:
if raises:
+ msg = _resolve_msg(msg)
error_msg = f"Not a color or gray tensor. Got shape {list(x.shape)}."
if msg is not None:
error_msg += f"\n{msg}"
@@ -687,7 +860,9 @@ def KORNIA_CHECK_IS_COLOR_OR_GRAY(x: torch.Tensor, msg: Optional[str] = None, ra
_UNSIGNED_AS_SIGNED = {torch.uint16: torch.int16, torch.uint32: torch.int32, torch.uint64: torch.int64}
-def KORNIA_CHECK_IS_IMAGE(x: torch.Tensor, msg: Optional[str] = None, raises: bool = True, bits: int = 8) -> bool:
+def KORNIA_CHECK_IS_IMAGE(
+ x: torch.Tensor, msg: Optional[CheckMessage] = None, raises: bool = True, bits: int = 8
+) -> bool:
"""Check whether a tensor is a color or gray image with values in [0, 1] for float or [0, 2 ** bits - 1] for int.
The shape must be :math:`(*, 3, H, W)` or :math:`(*, 1, H, W)`. A NaN value fails the range check, and an empty
@@ -695,7 +870,7 @@ def KORNIA_CHECK_IS_IMAGE(x: torch.Tensor, msg: Optional[str] = None, raises: bo
Args:
x: image tensor to evaluate.
- msg: message to show in the exception.
+ msg: message to show in the exception, or a function that returns it; see :func:`KORNIA_CHECK`.
raises: bool indicating whether an exception should be raised upon failure.
bits: the image bits. The default checks if given integer input image is an
8-bit image (0-255) or not.
@@ -842,14 +1017,15 @@ def KORNIA_CHECK_LAF(laf: torch.Tensor, raises: bool = True) -> bool:
def _handle_invalid_range(
- msg: Optional[str], raises: bool, min_val: float, max_val: float, expected_range: tuple[float, float]
+ msg: Optional[CheckMessage], raises: bool, min_val: float, max_val: float, expected_range: tuple[float, float]
) -> bool:
"""Handle invalid range cases."""
- low, high = (f"{b:g}" if isinstance(b, float) else f"{b}" for b in expected_range)
- err_msg = f"Value range mismatch: expected [{low}, {high}], got [{min_val}, {max_val}]."
- if msg is not None:
- err_msg += f"\n {msg}"
if raises:
+ low, high = (f"{b:g}" if isinstance(b, float) else f"{b}" for b in expected_range)
+ err_msg = f"Value range mismatch: expected [{low}, {high}], got [{min_val}, {max_val}]."
+ msg = _resolve_msg(msg)
+ if msg is not None:
+ err_msg += f"\n {msg}"
raise ValueCheckError(
err_msg,
actual_value=(min_val, max_val),
diff --git a/kornia/core/utils.py b/kornia/core/utils.py
index e9253697a..a5a2b3af0 100644
--- a/kornia/core/utils.py
+++ b/kornia/core/utils.py
@@ -858,7 +858,7 @@ def batched_forward(
True
"""
- KORNIA_CHECK(batch_size > 0, f"batch_size must be positive, got {batch_size}")
+ KORNIA_CHECK(batch_size > 0, lambda: f"batch_size must be positive, got {batch_size}")
model_dev = model.to(device)
B: int = len(data)
bs: int = batch_size
diff --git a/kornia/enhance/jpeg.py b/kornia/enhance/jpeg.py
index 4b783b4d2..c7aa39336 100644
--- a/kornia/enhance/jpeg.py
+++ b/kornia/enhance/jpeg.py
@@ -25,11 +25,7 @@ import torch.nn.functional as F
from torch import nn
from kornia.color import rgb_to_ycbcr, ycbcr_to_rgb
-from kornia.core.check import (
- KORNIA_CHECK,
- KORNIA_CHECK_IS_TENSOR,
- KORNIA_CHECK_SHAPE,
-)
+from kornia.core.check import KORNIA_CHECK, KORNIA_CHECK_IS_TENSOR, KORNIA_CHECK_SAME_SIZE, KORNIA_CHECK_SHAPE
from kornia.core.utils import is_compiling, is_exporting
from kornia.enhance.adjust import _check_floating_image
from kornia.geometry.transform.affwarp import rescale
@@ -604,31 +600,31 @@ def jpeg_codec_differentiable(
if not is_exporting():
KORNIA_CHECK(
(jpeg_quality.amin().item() >= 0.0) and (jpeg_quality.amax().item() <= 100.0),
- f"JPEG quality is out of range. Expected range is [0, 100], "
- f"got [{jpeg_quality.amin().item()}, {jpeg_quality.amax().item()}]. Consider clipping jpeg_quality.",
+ lambda: (
+ "JPEG quality is out of range. Expected range is [0, 100], "
+ f"got [{jpeg_quality.amin().item()}, {jpeg_quality.amax().item()}]. Consider clipping jpeg_quality."
+ ),
)
# Pad the image to a shape dividable by 16
input, h_pad, w_pad = _perform_padding(input)
# Get height and shape
H, W = input.shape[-2:]
# Check matching batch dimensions
- if quantization_table_y.shape[0] != 1:
- KORNIA_CHECK(
- quantization_table_y.shape[0] == input.shape[0],
- f"Batch dimensions do not match. "
- f"Got {input.shape[0]} images and {quantization_table_y.shape[0]} quantization tables (Y).",
- )
- if quantization_table_c.shape[0] != 1:
- KORNIA_CHECK(
- quantization_table_c.shape[0] == input.shape[0],
- f"Batch dimensions do not match. "
- f"Got {input.shape[0]} images and {quantization_table_c.shape[0]} quantization tables (C).",
- )
- if jpeg_quality.shape[0] != 1:
- KORNIA_CHECK(
- jpeg_quality.shape[0] == input.shape[0],
- f"Batch dimensions do not match. Got {input.shape[0]} images and {jpeg_quality.shape[0]} JPEG qualities.",
- )
+ KORNIA_CHECK_SAME_SIZE(
+ quantization_table_y,
+ input,
+ allow_one=True,
+ msg="quantization_table_y needs one table per image, or one for all.",
+ )
+ KORNIA_CHECK_SAME_SIZE(
+ quantization_table_c,
+ input,
+ allow_one=True,
+ msg="quantization_table_c needs one table per image, or one for all.",
+ )
+ KORNIA_CHECK_SAME_SIZE(
+ jpeg_quality, input, allow_one=True, msg="jpeg_quality needs one quality per image, or one for all."
+ )
# keep jpeg_quality same device as input torch.Tensor
jpeg_quality = jpeg_quality.to(device, dtype)
# Quantization tables to same device and dtype as input image
diff --git a/kornia/enhance/threshold.py b/kornia/enhance/threshold.py
index b89959b2c..9d37dd709 100644
--- a/kornia/enhance/threshold.py
+++ b/kornia/enhance/threshold.py
@@ -119,7 +119,7 @@ def threshold(
KORNIA_CHECK(
t in {int(x) for x in ThresholdType if x != ThresholdType.THRESH_OTSU},
- f"Unsupported threshold type: {type}. Supported: BINARY, BINARY_INV, TRUNC, TOZERO, TOZERO_INV.",
+ lambda: f"Unsupported threshold type: {type}. Supported: BINARY, BINARY_INV, TRUNC, TOZERO, TOZERO_INV.",
)
# Make thresh/maxval tensors on same device/dtype for safe broadcasting
diff --git a/kornia/feature/dedode/transformer/layers/patch_embed.py b/kornia/feature/dedode/transformer/layers/patch_embed.py
index cbd18ceaa..bd149e003 100644
--- a/kornia/feature/dedode/transformer/layers/patch_embed.py
+++ b/kornia/feature/dedode/transformer/layers/patch_embed.py
@@ -98,8 +98,8 @@ class PatchEmbed(nn.Module):
"""
_, _, H, W = x.shape
patch_H, patch_W = self.patch_size
- KORNIA_CHECK(H % patch_H == 0, f"Input image height {H} is not a multiple of patch height {patch_H}")
- KORNIA_CHECK(W % patch_W == 0, f"Input image width {W} is not a multiple of patch width: {patch_W}")
+ KORNIA_CHECK(H % patch_H == 0, f"Input image height is not a multiple of patch height {patch_H}: {x.shape}")
+ KORNIA_CHECK(W % patch_W == 0, f"Input image width is not a multiple of patch width {patch_W}: {x.shape}")
x = self.proj(x) # B C H W
H, W = x.size(2), x.size(3)
diff --git a/kornia/feature/scale_space_detector.py b/kornia/feature/scale_space_detector.py
index a73420604..d97cd0627 100644
--- a/kornia/feature/scale_space_detector.py
+++ b/kornia/feature/scale_space_detector.py
@@ -23,7 +23,7 @@ import torch
import torch.nn.functional as F
from torch import nn
-from kornia.core.check import KORNIA_CHECK, KORNIA_CHECK_SHAPE
+from kornia.core.check import KORNIA_CHECK, KORNIA_CHECK_SAME_SIZE, KORNIA_CHECK_SHAPE, KORNIA_CHECK_SIZES
from kornia.geometry.subpix import (
AdaptiveQuadInterp3d,
ConvQuadInterp3d,
@@ -156,10 +156,7 @@ def _check_mask(mask: torch.Tensor, img: torch.Tensor) -> None:
"""
KORNIA_CHECK(mask.dim() == 4 and mask.shape[1] == 1, f"mask must be (1 or B, 1, H, W). Got {tuple(mask.shape)}")
KORNIA_CHECK(mask.device == img.device, f"mask device {mask.device} must match the image device {img.device}")
- KORNIA_CHECK(
- mask.shape[0] in (1, img.shape[0]),
- f"mask batch {mask.shape[0]} must be 1 or match the image batch {img.shape[0]}",
- )
+ KORNIA_CHECK_SAME_SIZE(mask, img, allow_one=True, msg="The mask batch must be 1 or match the image batch.")
KORNIA_CHECK(
mask.shape[-2:] == img.shape[-2:],
f"mask spatial size {tuple(mask.shape[-2:])} must match the image {tuple(img.shape[-2:])}",
@@ -424,22 +421,17 @@ class ScaleSpaceDetector(nn.Module):
else:
with self._dynamo_config_patch(("resp",)):
level_resp = self.resp(octave.permute(0, 2, 1, 3, 4).reshape(B * L, CH, H, W), sigmas_oct.reshape(-1))
- KORNIA_CHECK(
- level_resp.dim() == 4
- and level_resp.shape[0] == B * L
- and level_resp.shape[1] == 1
- and level_resp.shape[-2:] == (H, W),
- "resp_module must return one response map per image with shape "
- f"({B * L}, 1, {H}, {W}). Got {tuple(level_resp.shape)}",
+ KORNIA_CHECK_SIZES(
+ level_resp, [B * L, 1, H, W], "resp_module must return one response map per image, (B * L, 1, H, W)."
)
oct_resp = level_resp.view(B, L, 1, H, W)
# Reorder to (B, CH, L, H, W) for scale-space NMS
oct_resp = oct_resp.permute(0, 2, 1, 3, 4)
- KORNIA_CHECK(
- oct_resp.dim() == 5 and oct_resp.shape[0] == B and oct_resp.shape[1] == 1 and oct_resp.shape[-2:] == (H, W),
- "resp_module must return one scale-space response channel with shape "
- f"({B}, 1, L, {H}, {W}). Got {tuple(oct_resp.shape)}. For a multi-channel image, convert it to "
- "grayscale first or use a response function that reduces the channels to one.",
+ KORNIA_CHECK_SIZES(
+ oct_resp,
+ [B, 1, None, H, W],
+ "resp_module must return one scale-space response channel, (B, 1, L, H, W). For a multi-channel image, "
+ "convert it to grayscale first or use a response function that reduces the channels to one.",
)
# Iterative sub-pixel modules flatten the full response volume internally. The
# level/channel permutation above is contiguous when CH == 1 (the common path), but
diff --git a/kornia/feature/siftdesc.py b/kornia/feature/siftdesc.py
index 15404736d..76af4d5d1 100644
--- a/kornia/feature/siftdesc.py
+++ b/kornia/feature/siftdesc.py
@@ -428,7 +428,9 @@ def convert_sift_descriptor_layout(
size = num_ang_bins * num_spatial_bins * num_spatial_bins
KORNIA_CHECK(
descriptors.shape[-1] == size,
- f"Expected descriptors of size num_ang_bins * num_spatial_bins**2 = {size}, got {descriptors.shape[-1]}",
+ lambda: (
+ f"Expected descriptors of size num_ang_bins * num_spatial_bins**2 = {size}, got {descriptors.shape[-1]}"
+ ),
)
if source == target:
order = list(range(size))
diff --git a/kornia/filters/bilateral.py b/kornia/filters/bilateral.py
index aa2e66ead..01adf4ca5 100644
--- a/kornia/filters/bilateral.py
+++ b/kornia/filters/bilateral.py
@@ -23,7 +23,7 @@ import torch
import torch.nn.functional as F
from torch import nn
-from kornia.core.check import KORNIA_CHECK, KORNIA_CHECK_IS_TENSOR, KORNIA_CHECK_SHAPE
+from kornia.core.check import KORNIA_CHECK, KORNIA_CHECK_IS_TENSOR, KORNIA_CHECK_SAME_SIZE, KORNIA_CHECK_SHAPE
from kornia.core.utils import is_compiling
from .filter import _to_floating
@@ -33,14 +33,7 @@ from .median import _compute_zero_padding
def _check_sigma_batch(name: str, sigma: torch.Tensor, input: torch.Tensor) -> None:
"""Check that a tensor sigma has a batch of 1, shared by the input, or the input batch."""
- # Format the sizes only on failure: an f-string evaluated on every call makes Dynamo specialize the batch size,
- # so a dynamic-shape torch.compile would recompile for each new batch.
- if sigma.shape[0] not in (1, input.shape[0]):
- KORNIA_CHECK(
- False,
- f"{name} must have a batch of 1 or the input batch. "
- f"Got a {name} batch of {sigma.shape[0]} for an input batch of {input.shape[0]}",
- )
+ KORNIA_CHECK_SAME_SIZE(sigma, input, allow_one=True, msg=f"{name} must have a batch of 1 or the input batch.")
def _bilateral_blur(
diff --git a/kornia/filters/blur.py b/kornia/filters/blur.py
index 8510bc0c1..b96385ca8 100644
--- a/kornia/filters/blur.py
+++ b/kornia/filters/blur.py
@@ -83,7 +83,7 @@ def _box_blur_pool(
"""Average local windows without constructing kernels or expanding them over channels."""
KORNIA_CHECK_SHAPE(input, ["B", "C", "H", "W"])
ky, kx = _unpack_2d_ks(kernel_size)
- KORNIA_CHECK(ky > 0 and kx > 0, f"Kernel dimensions must be positive. Got {kernel_size}")
+ KORNIA_CHECK(ky > 0 and kx > 0, lambda: f"Kernel dimensions must be positive. Got {kernel_size}")
KORNIA_CHECK(
str(border_type).lower() in {"constant", "reflect", "replicate", "circular"},
f"Invalid border, {border_type}. Expected one of constant, reflect, replicate, circular",
diff --git a/kornia/filters/canny.py b/kornia/filters/canny.py
index 0daad201e..769812992 100644
--- a/kornia/filters/canny.py
+++ b/kornia/filters/canny.py
@@ -193,7 +193,7 @@ def canny(
"""
KORNIA_CHECK_IS_TENSOR(input)
KORNIA_CHECK_SHAPE(input, ["B", "C", "H", "W"])
- KORNIA_CHECK_IS_COLOR_OR_GRAY(input, f"canny expects 1 or 3 channels. Got: {input.shape[1]}")
+ KORNIA_CHECK_IS_COLOR_OR_GRAY(input, "canny expects 1 or 3 channels.")
_check_thresholds(low_threshold, high_threshold)
# an integer image is processed in float32, so both outputs are float32 (#5155); promoting before the grayscale
diff --git a/kornia/filters/filter.py b/kornia/filters/filter.py
index 4cb7cdf89..53a944fdc 100644
--- a/kornia/filters/filter.py
+++ b/kornia/filters/filter.py
@@ -20,7 +20,7 @@ from __future__ import annotations
import torch
import torch.nn.functional as F
-from kornia.core.check import KORNIA_CHECK, KORNIA_CHECK_IS_TENSOR, KORNIA_CHECK_SHAPE
+from kornia.core.check import KORNIA_CHECK, KORNIA_CHECK_IS_TENSOR, KORNIA_CHECK_SAME_SIZE, KORNIA_CHECK_SHAPE
from kornia.filters.kernels import normalize_kernel2d
_VALID_BORDERS = {"constant", "reflect", "replicate", "circular"}
@@ -64,14 +64,7 @@ def _to_floating(input: torch.Tensor) -> torch.Tensor:
def _check_kernel_batch(input: torch.Tensor, kernel: torch.Tensor) -> None:
"""Check that the kernel batch is 1 or the input batch."""
- # Format the sizes only on failure: an f-string evaluated on every call makes Dynamo specialize the batch size,
- # so a dynamic-shape torch.compile would recompile for each new batch.
- if kernel.shape[0] not in (1, input.shape[0]):
- KORNIA_CHECK(
- False,
- "The kernel batch must be 1 or the input batch. "
- f"Got a kernel batch of {kernel.shape[0]} for an input batch of {input.shape[0]}",
- )
+ KORNIA_CHECK_SAME_SIZE(kernel, input, allow_one=True, msg="The kernel batch must be 1 or the input batch.")
def filter2d(
@@ -509,8 +502,10 @@ def fft_conv(
# without padding the kernel has to fit inside the input, as F.conv2d requires in filter2d
KORNIA_CHECK(
padding == "same" or (kh <= h and kw <= w),
- f"With padding='valid' the kernel must not be larger than the input. Got a {kh} x {kw} kernel for a {h} x {w}"
- " input",
+ lambda: (
+ f"With padding='valid' the kernel must not be larger than the input. Got a {kh} x {kw} kernel for a "
+ f"{h} x {w} input"
+ ),
)
if behaviour == "conv":
diff --git a/kornia/filters/gaussian.py b/kornia/filters/gaussian.py
index 4ffd582e3..9feba6054 100644
--- a/kornia/filters/gaussian.py
+++ b/kornia/filters/gaussian.py
@@ -21,7 +21,7 @@ import torch
import torch.nn.functional as F
from torch import nn
-from kornia.core.check import KORNIA_CHECK, KORNIA_CHECK_IS_TENSOR, KORNIA_CHECK_SHAPE
+from kornia.core.check import KORNIA_CHECK, KORNIA_CHECK_IS_TENSOR, KORNIA_CHECK_SAME_SIZE, KORNIA_CHECK_SHAPE
from kornia.core.utils import is_autocast_enabled, is_compiling
from .filter import _to_floating, filter2d, filter2d_separable
@@ -165,13 +165,7 @@ def gaussian_blur2d(
sigma = sigma.to(device=input.device, dtype=input.dtype)
KORNIA_CHECK_SHAPE(sigma, ["B", "2"])
- # Format the sizes only on failure: an f-string evaluated on every call makes Dynamo specialize the batch size.
- if sigma.shape[0] not in (1, input.shape[0]):
- KORNIA_CHECK(
- False,
- "sigma must have a batch of 1 or the input batch. "
- f"Got a sigma batch of {sigma.shape[0]} for an input batch of {input.shape[0]}",
- )
+ KORNIA_CHECK_SAME_SIZE(sigma, input, allow_one=True, msg="sigma must have a batch of 1 or the input batch.")
# `bool()` on a tensor is untraceable by dynamo; skip the data-dependent check under compile.
if not is_compiling():
# Only interpolate `sigma` into the message when the check actually fails: a plain
diff --git a/kornia/filters/guided.py b/kornia/filters/guided.py
index 6c99ecbf6..e4fb4d3c9 100644
--- a/kornia/filters/guided.py
+++ b/kornia/filters/guided.py
@@ -31,8 +31,10 @@ from .kernels import _unpack_2d_ks
def _check_subsample(subsample: int) -> None:
- msg = f"`subsample` must be a positive integer. Got: {subsample!r}"
- KORNIA_CHECK_TYPE(subsample, Integral, f"{msg} ({type(subsample).__name__})")
+ def msg() -> str:
+ return f"`subsample` must be a positive integer. Got: {subsample!r}"
+
+ KORNIA_CHECK_TYPE(subsample, Integral, lambda: f"{msg()} ({type(subsample).__name__})")
# ``bool`` is an ``int``, and ``subsample=True`` would otherwise run as 1.
KORNIA_CHECK(not isinstance(subsample, bool) and subsample >= 1, msg)
diff --git a/kornia/filters/kernels.py b/kornia/filters/kernels.py
index 0a2caf537..f76ed94dc 100644
--- a/kornia/filters/kernels.py
+++ b/kornia/filters/kernels.py
@@ -30,11 +30,15 @@ def _check_kernel_size(kernel_size: tuple[int, ...] | int, min_value: int = 0, a
kernel_size = (kernel_size,)
fmt = "even or odd" if allow_even else "odd"
- for size in kernel_size:
- KORNIA_CHECK(
- isinstance(size, int) and (((size % 2 == 1) or allow_even) and size > min_value),
- f"Kernel size must be an {fmt} integer bigger than {min_value}. Got {size} on {kernel_size}",
- )
+ invalid = [
+ size
+ for size in kernel_size
+ if not (isinstance(size, int) and (((size % 2 == 1) or allow_even) and size > min_value))
+ ]
+ KORNIA_CHECK(
+ not invalid,
+ lambda: f"Kernel size must be an {fmt} integer bigger than {min_value}. Got {invalid[0]} on {kernel_size}",
+ )
def _check_laplacian_kernel_size(kernel_size: tuple[int, ...] | int) -> None:
@@ -46,7 +50,10 @@ def _check_laplacian_kernel_size(kernel_size: tuple[int, ...] | int) -> None:
KORNIA_CHECK(
any(size != 1 for size in sizes),
- f"A Laplacian kernel needs a size of at least 3 along one axis: a single tap is all zeros. Got {kernel_size}",
+ lambda: (
+ "A Laplacian kernel needs a size of at least 3 along one axis: a single tap is all zeros. Got "
+ f"{kernel_size}"
+ ),
)
@@ -57,13 +64,17 @@ def _check_kernel_dtype(dtype: Optional[torch.dtype], name: str, taps: Optional[
return
KORNIA_CHECK(
taps is not None,
- f"{name} has fractional taps, which an integer dtype cannot hold. Got dtype={dtype}; use a floating dtype.",
+ lambda: (
+ f"{name} has fractional taps, which an integer dtype cannot hold. Got dtype={dtype}; use a floating dtype."
+ ),
)
low, high = (0, 1) if dtype == torch.bool else (torch.iinfo(dtype).min, torch.iinfo(dtype).max)
KORNIA_CHECK(
low <= taps[0] and taps[1] <= high,
- f"{name} has taps from {taps[0]} to {taps[1]}, which dtype={dtype} cannot hold. Use a signed integer dtype "
- "wide enough for them, or a floating one.",
+ lambda: (
+ f"{name} has taps from {taps[0]} to {taps[1]}, which dtype={dtype} cannot hold. Use a signed integer "
+ "dtype wide enough for them, or a floating one."
+ ),
)
@@ -379,7 +390,7 @@ def gaussian_discrete(
KORNIA_CHECK_SHAPE(sigma, ["B", "1"])
# The discrete Gaussian is defined at the integer offsets of the taps from the centre tap, so there is no even
# window: the window must be odd, and holds the offsets 0 .. window_size // 2 on either side of the centre.
- KORNIA_CHECK(window_size % 2 == 1, f"The discrete Gaussian kernel needs an odd window. Got {window_size}")
+ KORNIA_CHECK(window_size % 2 == 1, lambda: f"The discrete Gaussian kernel needs an odd window. Got {window_size}")
output_dtype = sigma.dtype
if not (sigma.dtype.is_floating_point or sigma.dtype.is_complex):
@@ -703,7 +714,7 @@ def get_spatial_gradient_kernel2d(
"""
KORNIA_CHECK(mode.lower() in {"sobel", "diff"}, f"Mode should be `sobel` or `diff`. Got {mode}")
- KORNIA_CHECK(order in {1, 2}, f"Order should be 1 or 2. Got {order}")
+ KORNIA_CHECK(order in {1, 2}, lambda: f"Order should be 1 or 2. Got {order}")
# the check is case-insensitive, so dispatch on the lower-case spelling as well
mode = mode.lower()
@@ -750,7 +761,7 @@ def get_spatial_gradient_kernel3d(
"""
KORNIA_CHECK(mode.lower() in {"sobel", "diff"}, f"Mode should be `sobel` or `diff`. Got {mode}")
- KORNIA_CHECK(order in {1, 2}, f"Order should be 1 or 2. Got {order}")
+ KORNIA_CHECK(order in {1, 2}, lambda: f"Order should be 1 or 2. Got {order}")
# the check is case-insensitive, so dispatch on the lower-case spelling as well
mode = mode.lower()
diff --git a/kornia/filters/kernels_geometry.py b/kornia/filters/kernels_geometry.py
index 894453a4b..7b7b8e8f4 100644
--- a/kornia/filters/kernels_geometry.py
+++ b/kornia/filters/kernels_geometry.py
@@ -20,7 +20,7 @@ from __future__ import annotations
import torch
import torch.nn.functional as F
-from kornia.core.check import KORNIA_CHECK, KORNIA_CHECK_SHAPE
+from kornia.core.check import KORNIA_CHECK, KORNIA_CHECK_SAME_SIZE, KORNIA_CHECK_SHAPE
from kornia.core.utils import _extract_device_dtype
from kornia.geometry.conversions import axis_angle_to_rotation_matrix
from kornia.geometry.transform import rotate, rotate3d
@@ -103,10 +103,7 @@ def get_motion_kernel2d(
direction = direction[None]
KORNIA_CHECK_SHAPE(direction, ["B"])
- KORNIA_CHECK(
- direction.size(0) == angle.size(0),
- f"direction and angle must have the same length. Got {direction.size(0)} and {angle.size(0)}.",
- )
+ KORNIA_CHECK_SAME_SIZE(direction, angle, msg="direction and angle must have the same length.")
# direction from [-1, 1] to [0, 1] range
direction = (torch.clamp(direction, -1.0, 1.0) + 1.0) / 2.0
@@ -247,10 +244,7 @@ def get_motion_kernel3d(
direction = direction[None]
KORNIA_CHECK_SHAPE(direction, ["B"])
- KORNIA_CHECK(
- direction.size(0) == angle.size(0),
- f"direction and angle must have the same batch size. Got {direction.shape} and {angle.shape}.",
- )
+ KORNIA_CHECK_SAME_SIZE(direction, angle, msg="direction and angle must have the same batch size.")
# direction from [-1, 1] to [0, 1] range
direction = (torch.clamp(direction, -1.0, 1.0) + 1.0) / 2.0
diff --git a/kornia/geometry/calibration/pnp.py b/kornia/geometry/calibration/pnp.py
index 03a79d8db..1bd85c590 100644
--- a/kornia/geometry/calibration/pnp.py
+++ b/kornia/geometry/calibration/pnp.py
@@ -178,7 +178,7 @@ def solve_pnp_dlt(
KORNIA_CHECK_SAME_SHAPE(world_points[:, :, 0], img_points[:, :, 0])
KORNIA_CHECK(
world_points.shape[1] >= 6,
- f"world_points must hold at least 6 points (N >= 6), got N = {world_points.shape[1]}.",
+ lambda: f"world_points must hold at least 6 points (N >= 6), got N = {world_points.shape[1]}.",
)
if weights is not None:
KORNIA_CHECK_IS_TENSOR(weights)
diff --git a/kornia/geometry/transform/pyramid.py b/kornia/geometry/transform/pyramid.py
index 389b60b54..5177ce005 100644
--- a/kornia/geometry/transform/pyramid.py
+++ b/kornia/geometry/transform/pyramid.py
@@ -539,7 +539,7 @@ def build_pyramid(
KORNIA_CHECK_SHAPE(input, ["B", "C", "H", "W"])
KORNIA_CHECK(
isinstance(max_level, int) and not isinstance(max_level, bool) and max_level > 0,
- f"Invalid max_level, it must be a positive integer. Got: {max_level}",
+ lambda: f"Invalid max_level, it must be a positive integer. Got: {max_level}",
)
# create empty list and append the original image
@@ -611,7 +611,7 @@ def build_laplacian_pyramid(
KORNIA_CHECK_SHAPE(input, ["B", "C", "H", "W"])
KORNIA_CHECK(
isinstance(max_level, int) and not isinstance(max_level, bool) and max_level > 0,
- f"Invalid max_level, it must be a positive integer. Got: {max_level}",
+ lambda: f"Invalid max_level, it must be a positive integer. Got: {max_level}",
)
h = input.size()[2]
diff --git a/kornia/image/base.py b/kornia/image/base.py
index 2a7d6e1ba..48e74ecdc 100644
--- a/kornia/image/base.py
+++ b/kornia/image/base.py
@@ -22,7 +22,7 @@ from enum import Enum
import torch
-from kornia.core.check import KORNIA_CHECK_SHAPE
+from kornia.core.check import KORNIA_CHECK_SHAPE, CheckMessage
@dataclass(frozen=True)
@@ -134,7 +134,7 @@ class ImageLayout:
def KORNIA_CHECK_IMAGE_LAYOUT(
x: torch.Tensor,
layout: ImageLayout,
- msg: str | None = None,
+ msg: CheckMessage | None = None,
raises: bool = True,
) -> bool:
"""Check tensor shape matches the expected ImageLayout.
@@ -142,7 +142,7 @@ def KORNIA_CHECK_IMAGE_LAYOUT(
Args:
x: tensor to validate.
layout: expected image layout.
- msg: custom error message.
+ msg: custom error message, or a function that returns it; see :func:`~kornia.core.check.KORNIA_CHECK`.
raises: if True, raise ShapeError on mismatch.
Returns:
diff --git a/kornia/losses/dice.py b/kornia/losses/dice.py
index 65d0a94ce..4611736e5 100644
--- a/kornia/losses/dice.py
+++ b/kornia/losses/dice.py
@@ -148,7 +148,8 @@ def dice_loss(
KORNIA_CHECK_IS_TENSOR(weight, "weight must be torch.Tensor or None.")
KORNIA_CHECK(
(weight.shape[0] == num_of_classes and weight.numel() == num_of_classes),
- f"weight shape must be (num_of_classes,): ({num_of_classes},), got {weight.shape}",
+ f"weight must hold one value per class of pred: got weight of shape {weight.shape} for pred of shape "
+ f"{pred.shape}",
)
KORNIA_CHECK(
weight.device == pred.device,
diff --git a/kornia/losses/focal.py b/kornia/losses/focal.py
index 72e2f7ccf..07b059edd 100644
--- a/kornia/losses/focal.py
+++ b/kornia/losses/focal.py
@@ -123,7 +123,7 @@ def focal_loss(
target_one_hot: Optional[torch.Tensor] = None
if reduced:
KORNIA_CHECK(target.dtype == torch.int64, f"labels must be of dtype torch.int64. Got: {target.dtype}")
- KORNIA_CHECK(pred.shape[1] >= 1, f"The number of classes must be >= 1. Got: {pred.shape[1]}")
+ KORNIA_CHECK(pred.shape[1] >= 1, f"The number of classes must be >= 1. Got pred of shape {pred.shape}")
else:
target_one_hot = one_hot(target, num_classes=pred.shape[1], device=pred.device, dtype=pred.dtype)
@@ -172,7 +172,8 @@ def focal_loss(
KORNIA_CHECK_IS_TENSOR(weight, "weight must be torch.Tensor or None.")
KORNIA_CHECK(
(weight.shape[0] == num_of_classes and weight.numel() == num_of_classes),
- f"weight shape must be (num_of_classes,): ({num_of_classes},), got {weight.shape}",
+ f"weight must hold one value per class of pred: got weight of shape {weight.shape} for pred of shape "
+ f"{pred.shape}",
)
KORNIA_CHECK(
weight.device == pred.device,
@@ -371,7 +372,8 @@ def binary_focal_loss_with_logits(
KORNIA_CHECK_IS_TENSOR(pos_weight, "pos_weight must be torch.Tensor or None.")
KORNIA_CHECK(
(pos_weight.shape[0] == num_of_classes and pos_weight.numel() == num_of_classes),
- f"pos_weight shape must be (num_of_classes,): ({num_of_classes},), got {pos_weight.shape}",
+ f"pos_weight must hold one value per class of pred: got pos_weight of shape {pos_weight.shape} for pred "
+ f"of shape {pred.shape}",
)
KORNIA_CHECK(
pos_weight.device == pred.device,
@@ -386,7 +388,8 @@ def binary_focal_loss_with_logits(
KORNIA_CHECK_IS_TENSOR(weight, "weight must be torch.Tensor or None.")
KORNIA_CHECK(
(weight.shape[0] == num_of_classes and weight.numel() == num_of_classes),
- f"weight shape must be (num_of_classes,): ({num_of_classes},), got {weight.shape}",
+ f"weight must hold one value per class of pred: got weight of shape {weight.shape} for pred of shape "
+ f"{pred.shape}",
)
KORNIA_CHECK(
weight.device == pred.device,
diff --git a/kornia/losses/lovasz_softmax.py b/kornia/losses/lovasz_softmax.py
index acb1b9f62..24922ff36 100644
--- a/kornia/losses/lovasz_softmax.py
+++ b/kornia/losses/lovasz_softmax.py
@@ -106,7 +106,8 @@ def lovasz_softmax_loss(pred: Tensor, target: Tensor, weight: Optional[Tensor] =
KORNIA_CHECK_IS_TENSOR(weight, "weight must be Tensor or None.")
KORNIA_CHECK(
(weight.shape[0] == num_of_classes and weight.numel() == num_of_classes),
- f"weight shape must be (num_of_classes,): ({num_of_classes},), got {weight.shape}",
+ f"weight must hold one value per class of pred: got weight of shape {weight.shape} for pred of shape "
+ f"{pred.shape}",
)
KORNIA_CHECK(
weight.device == pred.device,
diff --git a/kornia/metrics/confusion_matrix.py b/kornia/metrics/confusion_matrix.py
index 96d7fe4c3..f0d1ecc9b 100644
--- a/kornia/metrics/confusion_matrix.py
+++ b/kornia/metrics/confusion_matrix.py
@@ -37,7 +37,7 @@ def _check_label_range(name: str, labels: torch.Tensor, num_classes: int) -> Non
low, high = int(labels.min()), int(labels.max())
KORNIA_CHECK(
0 <= low and high < num_classes,
- f"Input {name} must contain values in [0, {num_classes}). Got values in [{low}, {high}]",
+ lambda: f"Input {name} must contain values in [0, {num_classes}). Got values in [{low}, {high}]",
)
diff --git a/kornia/metrics/mean_average_precision.py b/kornia/metrics/mean_average_precision.py
index c4ec07f98..f5485d496 100644
--- a/kornia/metrics/mean_average_precision.py
+++ b/kornia/metrics/mean_average_precision.py
@@ -19,7 +19,7 @@ from typing import Dict, List, Tuple
import torch
-from kornia.core.check import KORNIA_CHECK
+from kornia.core.check import KORNIA_CHECK, KORNIA_CHECK_SAME_SIZE
from .mean_iou import mean_iou_bbox
@@ -91,10 +91,8 @@ def mean_average_precision(
# The counts are checked per image: totals that agree can still pair the rows of one image with another's.
gt_images = []
for i, (boxes, labels) in enumerate(zip(gt_boxes, gt_labels)):
- KORNIA_CHECK(
- boxes.size(0) == labels.size(0),
- f"gt_boxes and gt_labels must have one row per object in every image. Got image {i}: {boxes.size(0)} "
- f"boxes and {labels.size(0)} labels",
+ KORNIA_CHECK_SAME_SIZE(
+ boxes, labels, msg=f"gt_boxes and gt_labels must have one row per object in every image (image {i})."
)
gt_images.extend([i] * labels.size(0))
# (n_objects), n_objects is the total no. of objects across all images
@@ -105,11 +103,10 @@ def mean_average_precision(
# Store all detections in a single continuous torch.Tensor while keeping track of the image it is from
pred_images = []
for i, (boxes, labels, scores) in enumerate(zip(pred_boxes, pred_labels, pred_scores)):
- KORNIA_CHECK(
- boxes.size(0) == labels.size(0) == scores.size(0),
- f"pred_boxes, pred_labels and pred_scores must have one row per detection in every image. Got image {i}: "
- f"{boxes.size(0)} boxes, {labels.size(0)} labels and {scores.size(0)} scores",
- )
+ for name, other in (("pred_labels", labels), ("pred_scores", scores)):
+ KORNIA_CHECK_SAME_SIZE(
+ boxes, other, msg=f"pred_boxes and {name} must have one row per detection in every image (image {i})."
+ )
pred_images.extend([i] * labels.size(0))
_pred_boxes = torch.cat(pred_boxes, 0) # (n_detections, 4)
_pred_labels = torch.cat(pred_labels, 0) # (n_detections)
@@ -123,10 +120,11 @@ def mean_average_precision(
_gt_boxes.dtype if _gt_boxes.is_floating_point() else torch.float32,
)
+ # These data-dependent checks break the compiled graph; in a helper function they would also break it at each call.
for name, labels in (("pred_labels", _pred_labels), ("gt_labels", _gt_labels)):
KORNIA_CHECK(
bool(((labels >= 0) & (labels < n_classes)).all()),
- f"{name} must satisfy 0 <= label < n_classes ({n_classes}).",
+ lambda: f"{name} must satisfy 0 <= label < n_classes ({n_classes}).", # noqa: B023 - called at once
)
if labels.is_floating_point():
KORNIA_CHECK(bool((labels == labels.round()).all()), f"{name} must contain integer-valued labels.")
diff --git a/kornia/models/processors/naflex.py b/kornia/models/processors/naflex.py
index 1aea6d70d..b981a2576 100644
--- a/kornia/models/processors/naflex.py
+++ b/kornia/models/processors/naflex.py
@@ -170,16 +170,20 @@ class NaFlex(nn.Module):
h_grid, w_grid = height // patch_h, width // patch_w
KORNIA_CHECK(
h_grid * w_grid == num_patches,
- f"NaFlex reads the grid of a (B, N, C) patch output from patch_size={self.patch_size}: a {height} x "
- f"{width} image has a {h_grid} x {w_grid} grid of {h_grid * w_grid} patches, but the patch embedding "
- f"returned {num_patches}.",
+ lambda: (
+ f"NaFlex reads the grid of a (B, N, C) patch output from patch_size={self.patch_size}: a "
+ f"{height} x {width} image has a {h_grid} x {w_grid} grid of {h_grid * w_grid} patches, but the "
+ f"patch embedding returned {num_patches}."
+ ),
)
return h_grid, w_grid
side = math.isqrt(num_patches)
KORNIA_CHECK(
side * side == num_patches,
- f"NaFlex reads a (B, N, C) patch output without patch_size as a square grid, but {num_patches} patch "
- "embeddings are not a square number. Pass patch_size to NaFlex, or make the patch embedding return "
- "(B, C, h, w).",
+ lambda: (
+ f"NaFlex reads a (B, N, C) patch output without patch_size as a square grid, but {num_patches} "
+ "patch embeddings are not a square number. Pass patch_size to NaFlex, or make the patch embedding "
+ "return (B, C, h, w)."
+ ),
)
return side, side
diff --git a/kornia/models/siglip2/model.py b/kornia/models/siglip2/model.py
index 1a9ebb977..c37708774 100644
--- a/kornia/models/siglip2/model.py
+++ b/kornia/models/siglip2/model.py
@@ -27,7 +27,7 @@ import torch
import torch.nn.functional as F
from torch import nn
-from kornia.core.check import KORNIA_CHECK
+from kornia.core.check import KORNIA_CHECK_SAME_SIZE
from .config import SigLip2Config
from .text_encoder import SigLip2TextModel
@@ -242,10 +242,10 @@ class SigLip2Model(nn.Module):
# pairwise sigmoid loss (SigLIP paper, eq. 1; transformers' SiglipModel): every image-text pair enters,
# the matching pairs on the diagonal labelled +1 and every other pair -1
if return_loss:
- KORNIA_CHECK(
- image_embeds.shape[0] == text_embeds.shape[0],
- "return_loss pairs the i-th image with the i-th text, so it needs as many images as texts; got "
- f"{image_embeds.shape[0]} images and {text_embeds.shape[0]} texts.",
+ KORNIA_CHECK_SAME_SIZE(
+ image_embeds,
+ text_embeds,
+ msg="return_loss pairs the i-th image with the i-th text, so it needs as many images as texts.",
)
eye = torch.eye(logits_per_text.shape[0], device=logits_per_text.device, dtype=logits_per_text.dtype)
loss = -F.logsigmoid((2 * eye - 1) * logits_per_text).sum(-1).mean()
diff --git a/kornia/models/tiny_vit.py b/kornia/models/tiny_vit.py
index bfe9b7f3c..0d3523b7b 100644
--- a/kornia/models/tiny_vit.py
+++ b/kornia/models/tiny_vit.py
@@ -28,7 +28,7 @@ import torch.nn.functional as F
from torch import nn
from torch.utils import checkpoint
-from kornia.core.check import KORNIA_CHECK
+from kornia.core.check import KORNIA_CHECK, KORNIA_CHECK_SAME_SIZE
from kornia.core.download import hf_url, load_state_dict_from_url
from kornia.models.common import DropPath, LayerNorm2d, window_partition, window_unpartition
@@ -711,7 +711,9 @@ def _load_pretrained(model: TinyViT, url: str | list[str]) -> TinyViT:
for k in ab_keys:
n_heads1, L1 = state_dict[k].shape
n_heads2, L2 = model_state_dict[k].shape
- KORNIA_CHECK(n_heads1 == n_heads2, f"Fail to load {k}. Pre-trained checkpoint should have num_heads={n_heads1}")
+ KORNIA_CHECK_SAME_SIZE(
+ state_dict[k], model_state_dict[k], msg=f"Fail to load {k}: the checkpoint has a different number of heads."
+ )
if L1 != L2:
S1 = int(L1**0.5)
diff --git a/testing/half_precision_eager_rng.py b/testing/half_precision_eager_rng.py
index ae7986c1d..1c1e65306 100644
--- a/testing/half_precision_eager_rng.py
+++ b/testing/half_precision_eager_rng.py
@@ -172,7 +172,7 @@ AUDITED_EAGER_RNG_CALLS = tuple(
(f"tests/core/test_check.py::TestCheckShape::{test_name}",),
"value-independent",
)
- for test_name, lines in (("test_valid", range(73, 77)), ("test_invalid", range(85, 89)))
+ for test_name, lines in (("test_valid", range(75, 79)), ("test_invalid", range(87, 91)))
for line in lines
),
*(
diff --git a/tests/api_surface.json b/tests/api_surface.json
index 6223d9ef5..954f0eca3 100644
--- a/tests/api_surface.json
+++ b/tests/api_surface.json
@@ -259,7 +259,9 @@
"KORNIA_CHECK_LAF",
"KORNIA_CHECK_SAME_DEVICE",
"KORNIA_CHECK_SAME_DEVICES",
+ "KORNIA_CHECK_SAME_SIZE",
"KORNIA_CHECK_SHAPE",
+ "KORNIA_CHECK_SIZES",
"KORNIA_CHECK_TYPE",
"KORNIA_UNWRAP",
"ShapeError",
diff --git a/tests/contrib/test_kmeans.py b/tests/contrib/test_kmeans.py
index 45ffc024f..0d9f070fd 100644
--- a/tests/contrib/test_kmeans.py
+++ b/tests/contrib/test_kmeans.py
@@ -132,7 +132,7 @@ class TestKMeans(BaseTester):
kmeans.fit(torch.rand((1000, 5), dtype=dtype))
with pytest.raises(Exception) as errinfo:
kmeans.predict(torch.rand((10, 7), dtype=dtype))
- assert "7 != 5" in str(errinfo)
+ assert "dimension 1: expected 5, got 7" in str(errinfo.value)
# case: num_clusters does not match the number of rows in an explicit cluster_centers
starting_centers = torch.rand((5, 2), device=device, dtype=dtype)
diff --git a/tests/core/test_check.py b/tests/core/test_check.py
index a68fb0fcc..0096652ab 100644
--- a/tests/core/test_check.py
+++ b/tests/core/test_check.py
@@ -31,7 +31,9 @@ from kornia.core.check import (
KORNIA_CHECK_SAME_DEVICE,
KORNIA_CHECK_SAME_DEVICES,
KORNIA_CHECK_SAME_SHAPE,
+ KORNIA_CHECK_SAME_SIZE,
KORNIA_CHECK_SHAPE,
+ KORNIA_CHECK_SIZES,
KORNIA_CHECK_TYPE,
are_checks_enabled,
disable_checks,
@@ -598,3 +600,267 @@ class TestChecksEnableDisable:
monkeypatch.setenv("KORNIA_CHECKS", "false")
assert _should_enable_checks() is False
+
+
+class TestCheckSameSize:
+ @pytest.mark.parametrize(
+ "x_shape, y_shape, dim, allow_one",
+ [
+ ((2, 3), (2, 5), 0, False),
+ ((2, 3), (4, 3), 1, False),
+ ((2, 3), (4, 3), -1, False),
+ ((1, 3), (4, 3), 0, True),
+ ],
+ )
+ def test_valid(self, x_shape, y_shape, dim, allow_one):
+ assert KORNIA_CHECK_SAME_SIZE(torch.rand(x_shape), torch.rand(y_shape), dim, allow_one) is True
+
+ def test_invalid_reports_both_sizes(self):
+ with pytest.raises(
+ ShapeError, match=r"dimension 0: expected 4, got 3\.\n.*\[3, 2\]\n.*\[4, 2\]\n a note"
+ ) as e:
+ KORNIA_CHECK_SAME_SIZE(torch.rand(3, 2), torch.rand(4, 2), msg="a note")
+ assert e.value.actual_shape == [3, 2]
+ assert e.value.expected_shape == [4, 2]
+
+ def test_allow_one_is_for_the_first_tensor_only(self):
+ assert KORNIA_CHECK_SAME_SIZE(torch.rand(1, 2), torch.rand(4, 2), allow_one=True) is True
+ with pytest.raises(ShapeError, match="expected 1, got 4"):
+ KORNIA_CHECK_SAME_SIZE(torch.rand(4, 2), torch.rand(1, 2), allow_one=True)
+ with pytest.raises(ShapeError, match="expected 4 or 1, got 3"):
+ KORNIA_CHECK_SAME_SIZE(torch.rand(3, 2), torch.rand(4, 2), allow_one=True)
+
+ @pytest.mark.parametrize("dim", [2, -3])
+ def test_dimension_out_of_range(self, dim):
+ with pytest.raises(ShapeError, match=f"no dimension {dim}"):
+ KORNIA_CHECK_SAME_SIZE(torch.rand(3, 2), torch.rand(3, 2), dim)
+
+ def test_invalid_raises_false(self):
+ assert KORNIA_CHECK_SAME_SIZE(torch.rand(3, 2), torch.rand(4, 2), raises=False) is False
+
+ def test_jit(self):
+ op_jit = torch.jit.script(KORNIA_CHECK_SAME_SIZE)
+ assert op_jit(torch.rand(1, 2), torch.rand(4, 2), 0, True) is True
+ with pytest.raises(Exception, match="expected 4, got 3"):
+ op_jit(torch.rand(3, 2), torch.rand(4, 2))
+
+ def test_dynamo_relates_the_sizes_without_specializing(self, torch_optimizer, optimizer_backend):
+ from torch._dynamo.testing import CompileCounter
+
+ if optimizer_backend == "jit":
+ pytest.skip("counts the graphs of torch.compile, which torch.jit.script does not build")
+
+ def op(x: torch.Tensor, y: torch.Tensor) -> torch.Tensor:
+ KORNIA_CHECK_SAME_SIZE(x, y, allow_one=True)
+ return x + y
+
+ counter = CompileCounter()
+ compiled = torch_optimizer(op, backend=counter, fullgraph=True, dynamic=True)
+ for batch in (2, 4, 6):
+ x, y = torch.rand(batch, batch + 3), torch.rand(batch, batch + 3)
+ assert torch.equal(compiled(x, y), x + y)
+ assert counter.frame_count == 1
+
+
+class TestCheckSizes:
+ @pytest.mark.parametrize("shape, sizes", [((5,), [5]), ((2, 3), [None, 3]), ((2, 3, 4), [2, None, None]), ((), [])])
+ def test_valid(self, shape, sizes):
+ assert KORNIA_CHECK_SIZES(torch.rand(shape), sizes) is True
+
+ @pytest.mark.parametrize(
+ "shape, sizes, expected",
+ [
+ ((4,), [5], r"\(5,\), got \[4\]"),
+ ((5, 1), [5], r"\(5,\), got \[5, 1\]"),
+ ((2, 3), [None, 4], r"\(\*, 4\), got \[2, 3\]"),
+ ],
+ )
+ def test_invalid_reports_the_shapes(self, shape, sizes, expected):
+ with pytest.raises(ShapeError, match=f"Shape mismatch: expected {expected}") as e:
+ KORNIA_CHECK_SIZES(torch.rand(shape), sizes)
+ assert e.value.actual_shape == list(shape)
+
+ def test_invalid_raises_false(self):
+ assert KORNIA_CHECK_SIZES(torch.rand(4), [5], raises=False) is False
+
+ def test_jit(self):
+ op_jit = torch.jit.script(KORNIA_CHECK_SIZES)
+ assert op_jit(torch.rand(2, 3), [None, 3]) is True
+ with pytest.raises(Exception, match=r"expected \(\*, 4\)"):
+ op_jit(torch.rand(2, 3), [None, 4])
+
+ def test_dynamo_relates_the_sizes_without_specializing(self, torch_optimizer, optimizer_backend):
+ from torch._dynamo.testing import CompileCounter
+
+ if optimizer_backend == "jit":
+ pytest.skip("counts the graphs of torch.compile, which torch.jit.script does not build")
+
+ def op(pred: torch.Tensor, weight: torch.Tensor) -> torch.Tensor:
+ KORNIA_CHECK_SIZES(weight, [pred.shape[1]])
+ KORNIA_CHECK_SIZES(pred, [None, weight.shape[0], None])
+ return pred * weight[:, None]
+
+ counter = CompileCounter()
+ compiled = torch_optimizer(op, backend=counter, fullgraph=True, dynamic=True)
+ for classes in (3, 5, 7):
+ pred, weight = torch.rand(2, classes, classes + 4), torch.rand(classes)
+ assert torch.equal(compiled(pred, weight), pred * weight[:, None])
+ assert counter.frame_count == 1
+
+
+class _Message:
+ """A message function that counts its calls."""
+
+ def __init__(self) -> None:
+ self.calls = 0
+
+ def __call__(self) -> str:
+ self.calls += 1
+ return "deferred message text"
+
+
+# helper -> (a call that passes, a call that fails), each taking (msg, raises); a helper with two failure paths has
+# one case per path
+_DEFERRED_CASES = {
+ "KORNIA_CHECK": (
+ lambda msg, raises: KORNIA_CHECK(True, msg, raises),
+ lambda msg, raises: KORNIA_CHECK(False, msg, raises),
+ ),
+ "KORNIA_CHECK_SHAPE-ndim": (
+ lambda msg, raises: KORNIA_CHECK_SHAPE(torch.rand(2, 3), ["B", "N"], msg, raises),
+ lambda msg, raises: KORNIA_CHECK_SHAPE(torch.rand(2, 3), ["B", "N", "D"], msg, raises),
+ ),
+ "KORNIA_CHECK_SHAPE-size": (
+ lambda msg, raises: KORNIA_CHECK_SHAPE(torch.rand(2, 3), ["B", "3"], msg, raises),
+ lambda msg, raises: KORNIA_CHECK_SHAPE(torch.rand(2, 3), ["B", "4"], msg, raises),
+ ),
+ "KORNIA_CHECK_SAME_SIZE-size": (
+ lambda msg, raises: KORNIA_CHECK_SAME_SIZE(torch.rand(2, 3), torch.rand(2, 5), 0, False, msg, raises),
+ lambda msg, raises: KORNIA_CHECK_SAME_SIZE(torch.rand(3, 3), torch.rand(2, 5), 0, False, msg, raises),
+ ),
+ "KORNIA_CHECK_SAME_SIZE-dim": (
+ lambda msg, raises: KORNIA_CHECK_SAME_SIZE(torch.rand(2, 3), torch.rand(2, 5), -2, False, msg, raises),
+ lambda msg, raises: KORNIA_CHECK_SAME_SIZE(torch.rand(2), torch.rand(2, 5), 1, False, msg, raises),
+ ),
+ "KORNIA_CHECK_SIZES-ndim": (
+ lambda msg, raises: KORNIA_CHECK_SIZES(torch.rand(2, 3), [2, None], msg, raises),
+ lambda msg, raises: KORNIA_CHECK_SIZES(torch.rand(2, 3), [2], msg, raises),
+ ),
+ "KORNIA_CHECK_SIZES-size": (
+ lambda msg, raises: KORNIA_CHECK_SIZES(torch.rand(2, 3), [None, 3], msg, raises),
+ lambda msg, raises: KORNIA_CHECK_SIZES(torch.rand(2, 3), [None, 4], msg, raises),
+ ),
+ "KORNIA_CHECK_TYPE": (
+ lambda msg, raises: KORNIA_CHECK_TYPE(1, int, msg, raises),
+ lambda msg, raises: KORNIA_CHECK_TYPE("1", int, msg, raises),
+ ),
+ "KORNIA_CHECK_IS_TENSOR": (
+ lambda msg, raises: KORNIA_CHECK_IS_TENSOR(torch.rand(2), msg, raises),
+ lambda msg, raises: KORNIA_CHECK_IS_TENSOR([1.0], msg, raises),
+ ),
+ "KORNIA_CHECK_SAME_DEVICES": (
+ lambda msg, raises: KORNIA_CHECK_SAME_DEVICES([torch.rand(2)], msg, raises),
+ lambda msg, raises: KORNIA_CHECK_SAME_DEVICES([], msg, raises),
+ ),
+ "KORNIA_CHECK_IS_COLOR": (
+ lambda msg, raises: KORNIA_CHECK_IS_COLOR(torch.rand(3, 4, 4), msg, raises),
+ lambda msg, raises: KORNIA_CHECK_IS_COLOR(torch.rand(1, 4, 4), msg, raises),
+ ),
+ "KORNIA_CHECK_IS_GRAY": (
+ lambda msg, raises: KORNIA_CHECK_IS_GRAY(torch.rand(1, 4, 4), msg, raises),
+ lambda msg, raises: KORNIA_CHECK_IS_GRAY(torch.rand(3, 4, 4), msg, raises),
+ ),
+ "KORNIA_CHECK_IS_COLOR_OR_GRAY": (
+ lambda msg, raises: KORNIA_CHECK_IS_COLOR_OR_GRAY(torch.rand(3, 4, 4), msg, raises),
+ lambda msg, raises: KORNIA_CHECK_IS_COLOR_OR_GRAY(torch.rand(2, 4, 4), msg, raises),
+ ),
+ "KORNIA_CHECK_IS_IMAGE-shape": (
+ lambda msg, raises: KORNIA_CHECK_IS_IMAGE(torch.rand(3, 4, 4), msg, raises),
+ lambda msg, raises: KORNIA_CHECK_IS_IMAGE(torch.rand(2, 4, 4), msg, raises),
+ ),
+ "KORNIA_CHECK_IS_IMAGE-range": (
+ lambda msg, raises: KORNIA_CHECK_IS_IMAGE(torch.rand(3, 4, 4), msg, raises),
+ lambda msg, raises: KORNIA_CHECK_IS_IMAGE(torch.full((3, 4, 4), 2.0), msg, raises),
+ ),
+}
+
+
+class TestDeferredMessage:
+ """Every helper that takes ``msg`` accepts a function for it and calls it only to raise."""
+
+ def teardown_method(self):
+ enable_checks()
+
+ @pytest.mark.parametrize("case", sorted(_DEFERRED_CASES))
+ def test_not_called_when_the_check_passes(self, case):
+ passes, _ = _DEFERRED_CASES[case]
+ msg = _Message()
+ assert passes(msg, True) is True
+ assert msg.calls == 0
+
+ @pytest.mark.parametrize("case", sorted(_DEFERRED_CASES))
+ def test_called_once_and_reported_when_the_check_fails(self, case):
+ _, fails = _DEFERRED_CASES[case]
+ msg = _Message()
+ with pytest.raises(BaseError, match="deferred message text"):
+ fails(msg, True)
+ assert msg.calls == 1
+
+ @pytest.mark.parametrize("case", sorted(_DEFERRED_CASES))
+ def test_not_called_when_the_check_does_not_raise(self, case):
+ _, fails = _DEFERRED_CASES[case]
+ msg = _Message()
+ assert fails(msg, False) is False
+ assert msg.calls == 0
+
+ @pytest.mark.parametrize("case", sorted(_DEFERRED_CASES))
+ def test_not_called_when_checks_are_disabled(self, case):
+ _, fails = _DEFERRED_CASES[case]
+ msg = _Message()
+ disable_checks()
+ assert fails(msg, True) is True
+ assert msg.calls == 0
+
+ def test_image_layout_takes_a_deferred_message(self):
+ from kornia.image.base import KORNIA_CHECK_IMAGE_LAYOUT, ChannelsOrder, ImageLayout, ImageSize
+
+ layout = ImageLayout(ImageSize(4, 5), 3, ChannelsOrder.CHANNELS_FIRST)
+ msg = _Message()
+ assert KORNIA_CHECK_IMAGE_LAYOUT(torch.rand(3, 4, 5), layout, msg) is True
+ assert msg.calls == 0
+ with pytest.raises(ShapeError, match="deferred message text"):
+ KORNIA_CHECK_IMAGE_LAYOUT(torch.rand(3, 4, 6), layout, msg)
+ assert msg.calls == 1
+
+ def test_jit_still_takes_a_string_message(self):
+ def op(x: torch.Tensor) -> torch.Tensor:
+ KORNIA_CHECK(x.shape[0] == 2, "a scripted message")
+ KORNIA_CHECK_SHAPE(x, ["2", "N"], "a scripted shape message")
+ return x * 2
+
+ scripted = torch.jit.script(op)
+ assert scripted(torch.ones(2, 3)).sum() == 12
+ with pytest.raises(Exception, match="a scripted message"):
+ scripted(torch.ones(3, 3))
+
+ @pytest.mark.parametrize("helper", ["KORNIA_CHECK", "KORNIA_CHECK_SHAPE"])
+ def test_dynamo_deferred_size_message_compiles_one_graph(self, helper, torch_optimizer, optimizer_backend):
+ """Formatting a size inside the message function does not specialize it."""
+ from torch._dynamo.testing import CompileCounter
+
+ if optimizer_backend == "jit":
+ pytest.skip("counts the graphs of torch.compile, which torch.jit.script does not build")
+
+ def op(x: torch.Tensor) -> torch.Tensor:
+ if helper == "KORNIA_CHECK":
+ KORNIA_CHECK(x.shape[0] >= 1, lambda: f"Expected a batch, got {x.shape[0]} rows of {x.shape[1]}")
+ else:
+ KORNIA_CHECK_SHAPE(x, ["B", "N"], lambda: f"Expected (B, N), got {x.shape[0]} x {x.shape[1]}")
+ return x * 2
+
+ counter = CompileCounter()
+ compiled = torch_optimizer(op, backend=counter, fullgraph=True, dynamic=True)
+ for batch in (2, 4, 6):
+ x = torch.rand(batch, batch + 3)
+ assert torch.equal(compiled(x), x * 2)
+ assert counter.frame_count == 1
diff --git a/tests/core/test_check_message_call_sites.py b/tests/core/test_check_message_call_sites.py
new file mode 100644
index 000000000..f753ca32e
--- /dev/null
+++ b/tests/core/test_check_message_call_sites.py
@@ -0,0 +1,514 @@
+# 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.
+#
+
+"""No ``KORNIA_CHECK*`` message in ``kornia/`` formats a value that ``torch.compile`` can treat as symbolic.
+
+Python evaluates the arguments of ``KORNIA_CHECK(condition, f"... {x.shape[0]} ...")`` on every
+call, so the message is formatted even when the check passes. Under a dynamic-shape
+``torch.compile``, formatting a symbolic integer makes Dynamo specialize it, so every new value
+compiles a new graph (and after ``torch._dynamo.config.recompile_limit`` graphs the function runs
+eagerly); ``str()`` of one does not trace at all. Such a value is a single tensor size --
+``x.shape[i]``, ``x.size(i)``, ``x.numel()`` -- or an ``int`` argument of the compiled function, and
+anything computed from them. A value read from tensor data (``.item()``, ``.tolist()``) is worse:
+it breaks the graph, and in eager mode it synchronizes with the device on every call. Whole shapes
+(``x.shape``, ``tuple(x.shape)``, slices), dtypes, devices and strings do not specialize, so their
+messages stay as they are.
+
+Such a check uses a helper that compares the sizes itself and formats them only on failure
+(``KORNIA_CHECK_SAME_SIZE``, ``KORNIA_CHECK_SIZES``, ``KORNIA_CHECK_SHAPE``), or passes the message
+as a function, ``KORNIA_CHECK(condition, lambda: f"...")``, which the check calls only on failure.
+
+The rules, for every call to a function named ``KORNIA_CHECK*`` that has a ``msg`` parameter, outside
+constructors (``torch.compile`` compiles ``forward``, not module construction):
+
+* a message that is not a ``lambda`` formats no single size, no ``int``-annotated argument of the
+ function, no local assigned from those, nothing computed from them, and no ``.item()`` or
+ ``.tolist()``;
+* except in ``_TORCHSCRIPT_FUNCTIONS``, which TorchScript compiles: TorchScript rejects a ``lambda``
+ anywhere in their source, so a message there may format such a value but may not be a ``lambda``.
+ It formats whole shapes where it can, which neither specializes nor needs deferring. Every entry
+ must exist and hold a formatted message.
+
+A message assigned to a local first counts as formatting what that assignment formats.
+"""
+
+from __future__ import annotations
+
+import ast
+from pathlib import Path
+
+import pytest
+import torch
+
+import kornia
+
+_KORNIA_ROOT = Path(kornia.__file__).resolve().parent
+_SIZE_METHODS = {"size", "numel"}
+_DATA_METHODS = {"item", "tolist"}
+_PASSTHROUGH = {"int", "min", "max", "abs"}
+
+# Functions with formatted check messages that TorchScript compiles: those that ``torch.jit.script`` compiles directly
+# or through a caller in the tests, with or without ``KORNIA_TEST_OPTIMIZER=jit``. TorchScript rejects a ``lambda``
+# anywhere in a scripted function, even under ``if not torch.jit.is_scripting()``. Their messages that format a
+# single size or an ``int`` stay eager: measured under ``torch.compile(dynamic=True)`` on torch 2.5.1 and 2.14, only
+# ``_check_n``'s ``{n}`` adds graphs, when ``n`` is itself an input of the compiled function (``one_hot`` specializes
+# ``num_classes`` regardless, and ``reconstruction`` breaks the graph on its data-dependent loop).
+_TORCHSCRIPT_FUNCTIONS = {
+ "color/raw.py::raw_to_rgb_2x2_downscaled",
+ "core/ops.py::_check_n",
+ "core/ops.py::eye_like",
+ "core/ops.py::vec_like",
+ "enhance/shift_rgb.py::shift_rgb",
+ "feature/dedode/transformer/layers/patch_embed.py::PatchEmbed.forward",
+ "geometry/depth.py::warp_frame_depth",
+ "losses/focal.py::binary_focal_loss_with_logits",
+ "losses/focal.py::focal_loss",
+ "losses/lovasz_softmax.py::lovasz_softmax_loss",
+ "losses/one_hot.py::one_hot",
+ "morphology/morphology.py::reconstruction",
+}
+
+
+def _int_params(func: ast.FunctionDef | ast.AsyncFunctionDef) -> set[str]:
+ """Return the parameters annotated with an ``int`` type, alone or in a union, tuple or ``Optional``."""
+ names = set()
+ for arg in func.args.posonlyargs + func.args.args + func.args.kwonlyargs:
+ if arg.annotation is not None and any(
+ isinstance(n, ast.Name) and n.id == "int" for n in ast.walk(arg.annotation)
+ ):
+ names.add(arg.arg)
+ return names
+
+
+def _is_symbolic(node: ast.AST, names: set[str]) -> bool:
+ """Return whether ``node`` is a value that Dynamo can treat as symbolic, or one read from tensor data."""
+ if isinstance(node, ast.Subscript):
+ if isinstance(node.slice, ast.Slice):
+ return False
+ value = node.value
+ if isinstance(value, ast.Attribute) and value.attr == "shape":
+ return True
+ if (
+ isinstance(value, ast.Call)
+ and isinstance(value.func, ast.Attribute)
+ and value.func.attr == "size"
+ and not value.args
+ and not value.keywords
+ ):
+ return True
+ return isinstance(value, ast.Name) and value.id in names
+ if isinstance(node, ast.Call):
+ func = node.func
+ if isinstance(func, ast.Attribute) and func.attr in _DATA_METHODS:
+ return True
+ if isinstance(func, ast.Attribute) and func.attr in _SIZE_METHODS:
+ return func.attr == "numel" or bool(node.args)
+ if isinstance(func, ast.Name) and func.id in _PASSTHROUGH:
+ return any(_is_symbolic(a, names) for a in node.args)
+ return False
+ if isinstance(node, ast.Name):
+ return node.id in names
+ if isinstance(node, ast.BinOp):
+ return _is_symbolic(node.left, names) or _is_symbolic(node.right, names)
+ if isinstance(node, ast.UnaryOp):
+ return _is_symbolic(node.operand, names)
+ if isinstance(node, ast.IfExp):
+ return _is_symbolic(node.body, names) or _is_symbolic(node.orelse, names)
+ return False
+
+
+def _is_shape(node: ast.AST) -> bool:
+ """Return whether ``node`` is a whole or sliced shape, whose unpacking gives sizes."""
+ if isinstance(node, ast.Subscript) and isinstance(node.slice, ast.Slice):
+ node = node.value
+ if isinstance(node, ast.Call) and isinstance(node.func, ast.Attribute) and node.func.attr == "size":
+ return not node.args
+ return isinstance(node, ast.Attribute) and node.attr == "shape"
+
+
+def _local_names(func: ast.FunctionDef | ast.AsyncFunctionDef) -> tuple[set[str], set[str]]:
+ """Return symbolic values/eager messages and lambda aliases separately; lambda bodies are deferred."""
+ names = _int_params(func)
+ lambda_names: set[str] = set()
+ changed = True
+ while changed:
+ changed = False
+ for node in ast.walk(func):
+ if isinstance(node, ast.Assign):
+ targets, value = node.targets, node.value
+ elif isinstance(node, ast.AnnAssign) and node.value is not None:
+ targets, value = [node.target], node.value
+ else:
+ continue
+ for target in targets:
+ if isinstance(target, ast.Name) and (
+ isinstance(value, ast.Lambda) or (isinstance(value, ast.Name) and value.id in lambda_names)
+ ):
+ if target.id not in lambda_names:
+ lambda_names.add(target.id)
+ changed = True
+ if isinstance(value, ast.Lambda):
+ continue
+ # a size, or a message built from one
+ if isinstance(target, ast.Name) and (
+ _is_symbolic(value, names) or any(_is_symbolic(v, names) for v in _formatted_values(value))
+ ):
+ new = {target.id}
+ elif isinstance(target, ast.Tuple) and (
+ _is_shape(value)
+ or (isinstance(value, ast.Tuple) and any(_is_symbolic(v, names) for v in value.elts))
+ ):
+ new = {t.id for t in target.elts if isinstance(t, ast.Name)}
+ else:
+ continue
+ if not new <= names:
+ names |= new
+ changed = True
+ return names, lambda_names
+
+
+def _formatted_values(msg: ast.AST) -> list[ast.AST]:
+ """Return the values an eagerly built message formats: f-string fields, ``str.format``, ``%`` and ``str()``."""
+ values: list[ast.AST] = []
+ for node in ast.walk(msg):
+ if isinstance(node, ast.FormattedValue):
+ values.append(node.value)
+ elif isinstance(node, ast.Call) and isinstance(node.func, ast.Attribute) and node.func.attr == "format":
+ values += list(node.args) + [k.value for k in node.keywords]
+ elif isinstance(node, ast.Call) and isinstance(node.func, ast.Name) and node.func.id in {"str", "repr"}:
+ values += list(node.args)
+ elif isinstance(node, ast.BinOp) and isinstance(node.op, ast.Mod):
+ right = node.right
+ values += list(right.elts) if isinstance(right, ast.Tuple) else [right]
+ return values
+
+
+def _msg_positions(trees: dict[str, ast.Module]) -> dict[str, int]:
+ """Map each ``KORNIA_CHECK*`` function defined in ``kornia/`` to the position of its ``msg`` parameter."""
+ positions: dict[str, int] = {}
+ for tree in trees.values():
+ for node in ast.walk(tree):
+ if isinstance(node, ast.FunctionDef) and node.name.startswith("KORNIA_CHECK"):
+ params = [a.arg for a in node.args.posonlyargs + node.args.args]
+ if "msg" in params:
+ positions[node.name] = params.index("msg")
+ return positions
+
+
+def _qualified_names(tree: ast.Module) -> dict[ast.AST, str]:
+ """Map every function of a module to its name, as ``Class.method`` inside a class."""
+ names: dict[ast.AST, str] = {}
+
+ def visit(node: ast.AST, prefix: str) -> None:
+ for child in ast.iter_child_nodes(node):
+ if isinstance(child, ast.ClassDef):
+ visit(child, f"{prefix}{child.name}.")
+ elif isinstance(child, (ast.FunctionDef, ast.AsyncFunctionDef)):
+ names[child] = f"{prefix}{child.name}"
+ visit(child, f"{prefix}{child.name}.")
+ else:
+ visit(child, prefix)
+
+ visit(tree, "")
+ return names
+
+
+def _violations(
+ rel: str, tree: ast.Module, positions: dict[str, int], torchscript: set[str]
+) -> tuple[int, list[str], set[str], set[str]]:
+ """Return ``(checked calls, violations, functions defined, TorchScript functions with a formatted message)``."""
+ qualified = _qualified_names(tree)
+ defined = {f"{rel}::{name}" for name in qualified.values()}
+ n_calls = 0
+ violations: list[str] = []
+ formatted_in: set[str] = set()
+ seen: set[int] = set()
+ # outer functions start before the functions nested in them; in reverse order, each call is judged in the
+ # innermost function that contains it
+ for func in sorted(qualified, key=lambda f: (f.lineno, f.col_offset), reverse=True):
+ key = f"{rel}::{qualified[func]}"
+ names, lambda_names = _local_names(func)
+ for node in ast.walk(func):
+ if not isinstance(node, ast.Call) or id(node) in seen:
+ continue
+ callee = node.func
+ name = callee.id if isinstance(callee, ast.Name) else getattr(callee, "attr", "")
+ if name not in positions:
+ continue
+ seen.add(id(node))
+ n_calls += 1
+ if func.name == "__init__":
+ continue
+ pos = positions[name]
+ msg = node.args[pos] if len(node.args) > pos else None
+ msg = next((k.value for k in node.keywords if k.arg == "msg"), msg)
+ if msg is None:
+ continue
+ # A name can have both eager and lambda assignments. Do not hide its eager paths in Python mode.
+ if isinstance(msg, ast.Lambda) or (
+ isinstance(msg, ast.Name) and msg.id in lambda_names and (key in torchscript or msg.id not in names)
+ ):
+ if key in torchscript:
+ violations.append(f"{rel}:{node.lineno} {name} has a lambda message, which TorchScript rejects")
+ continue
+ values = _formatted_values(msg)
+ symbolic = [ast.unparse(v) for v in values if _is_symbolic(v, names)]
+ if isinstance(msg, ast.Name) and msg.id in names:
+ symbolic.append(msg.id)
+ if key in torchscript:
+ if values or symbolic:
+ formatted_in.add(key)
+ elif symbolic:
+ violations.append(f"{rel}:{node.lineno} {name} formats {', '.join(symbolic)}")
+ return n_calls, violations, defined, formatted_in
+
+
+def _scan() -> tuple[int, list[str], set[str], set[str]]:
+ """Return ``(checked calls, violations, functions defined, exempt functions used)`` over ``kornia/``."""
+ trees = {
+ path.relative_to(_KORNIA_ROOT).as_posix(): ast.parse(path.read_text(encoding="utf-8"), filename=str(path))
+ for path in sorted(_KORNIA_ROOT.rglob("*.py"))
+ }
+ positions = _msg_positions(trees)
+ n_calls = 0
+ violations: list[str] = []
+ defined: set[str] = set()
+ exempt_used: set[str] = set()
+ for rel, tree in trees.items():
+ n, found, names, used = _violations(rel, tree, positions, _TORCHSCRIPT_FUNCTIONS)
+ n_calls += n
+ violations += found
+ defined |= names
+ exempt_used |= used
+ return n_calls, sorted(violations), defined, exempt_used
+
+
+class TestCheckMessageCallSites:
+ def test_no_message_formats_a_symbolic_value(self) -> None:
+ n_calls, violations, _, _ = _scan()
+ assert n_calls > 500, f"the scan found only {n_calls} KORNIA_CHECK calls; is it reading kornia/?"
+ assert not violations, (
+ "These KORNIA_CHECK messages format a tensor size or an int argument on every call. Under a "
+ "dynamic-shape torch.compile that specializes the value, so each new value compiles a new graph. Compare "
+ "sizes with KORNIA_CHECK_SAME_SIZE / KORNIA_CHECK_SIZES / KORNIA_CHECK_SHAPE, or pass the message as a "
+ "function, which the check calls only on failure: `KORNIA_CHECK(condition, lambda: f'...')`.\n"
+ + "\n".join(violations)
+ )
+
+ def test_torchscript_functions_are_current(self) -> None:
+ """Every listed function exists and holds a formatted message, so the list cannot outgrow its reason."""
+ _, _, defined, formatted_in = _scan()
+ assert _TORCHSCRIPT_FUNCTIONS <= defined, f"no such function: {sorted(_TORCHSCRIPT_FUNCTIONS - defined)}"
+ assert formatted_in == _TORCHSCRIPT_FUNCTIONS, (
+ f"no formatted message left, drop it from the list: {sorted(_TORCHSCRIPT_FUNCTIONS - formatted_in)}"
+ )
+
+ def test_scan_flags_symbolic_values_only(self) -> None:
+ """The scanner flags every form of a symbolic value, and leaves whole shapes, dtypes and strings alone."""
+ source = """
+def KORNIA_CHECK(condition, msg=None, raises=True): ...
+def KORNIA_CHECK_SHAPE(x, shape, msg=None, raises=True): ...
+
+def f(x, y, n: int, k: tuple[int, int] | int, name: str, h: float):
+ B, C, H, W = x.shape
+ rows = x.shape[0] * 2
+ side = int(max(H, W))
+ KORNIA_CHECK(x.dim() == 4, f"got {x.shape[0]}") # flagged: a single size
+ KORNIA_CHECK(x.dim() == 4, f"got {x.size(1)} and {x.numel()}") # flagged: size(i), numel()
+ KORNIA_CHECK(n > 0, f"got {n}") # flagged: an int argument
+ KORNIA_CHECK(k[0] > 0, f"got {k[0]}") # flagged: an element of an int argument
+ KORNIA_CHECK(H > 0, f"got {H} x {W}") # flagged: unpacked from the shape
+ KORNIA_CHECK(rows > 0, f"got {rows}") # flagged: computed from a size
+ KORNIA_CHECK(side > 0, "got {}".format(side)) # flagged: through int/max, by str.format
+ KORNIA_CHECK(n > 0, "got %d" % (n + 1)) # flagged: %, arithmetic
+ KORNIA_CHECK(x.min() >= 0, f"got {x.min().item()}") # flagged: a value read from the data
+ KORNIA_CHECK_SHAPE(x, ["B"], msg="got " + str(B)) # flagged: str(), keyword msg
+ if x.dim() != 4:
+ KORNIA_CHECK(False, f"got {x.shape[0]}") # flagged: still formatted eagerly
+ built = f"got {n}"
+ KORNIA_CHECK(n > 0, built) # flagged: a message built in a local
+ KORNIA_CHECK(n > 0, f"{built}, so no") # flagged: placed in another message
+ KORNIA_CHECK(x.dim() == 4, f"got {x.shape} {tuple(x.shape)} {x.shape[-2:]} {(B, C)}")
+ KORNIA_CHECK(x.dim() == 4, f"got {x.dtype} on {x.device}, {x.ndim} dims, {type(n).__name__}")
+ KORNIA_CHECK(h > 0, f"{name} needs a positive h, got {h}")
+ KORNIA_CHECK(n > 0, lambda: f"got {n} and {x.shape[0]}")
+
+ def deferred() -> str:
+ return f"got {n}"
+
+ KORNIA_CHECK(n > 0, deferred)
+
+def scripted(n: int):
+ KORNIA_CHECK(n > 0, f"got {n}") # TorchScript compiles it: stays eager
+ KORNIA_CHECK(n > 0, lambda: f"got {n}") # flagged: TorchScript rejects a lambda
+
+class M:
+ def __init__(self, n: int):
+ KORNIA_CHECK(n > 0, f"got {n}") # a constructor
+
+ def forward(self, x):
+ KORNIA_CHECK(x.dim() == 4, f"got {x.shape}") # TorchScript compiles it
+"""
+ tree = ast.parse(source)
+ positions = _msg_positions({"m.py": tree})
+ assert positions == {"KORNIA_CHECK": 1, "KORNIA_CHECK_SHAPE": 2}
+ torchscript = {"m.py::scripted", "m.py::M.forward"}
+ n_calls, violations, defined, formatted_in = _violations("m.py", tree, positions, torchscript)
+ flagged = [i + 1 for i, line in enumerate(source.splitlines()) if "# flagged" in line]
+ assert n_calls == 22
+ assert sorted(int(v.split(":")[1].split()[0]) for v in violations) == flagged
+ assert {"m.py::f", "m.py::f.deferred", "m.py::scripted", "m.py::M.__init__", "m.py::M.forward"} <= defined
+ assert formatted_in == torchscript
+
+ @pytest.mark.parametrize(
+ "expression, flagged",
+ [("x.size()[0]", True), ("x.size()[-1]", True), ("x.size()", False), ("x.size()[1:]", False)],
+ )
+ @pytest.mark.parametrize("assigned", [False, True])
+ def test_indexed_size_messages(self, expression, flagged, assigned):
+ assignment = f" size = {expression}\n" if assigned else ""
+ value = "size" if assigned else expression
+ source = f'def f(x):\n{assignment} KORNIA_CHECK(True, f"got {{{value}}}")\n'
+ n_calls, violations, _, _ = _violations("m.py", ast.parse(source), {"KORNIA_CHECK": 1}, set())
+ assert n_calls == 1
+ assert bool(violations) is flagged
+
+ @pytest.mark.parametrize("message", ['f"got {n}"', '"invalid input"'])
+ @pytest.mark.parametrize("assignment", ["msg =", "msg: Callable[[], str] =", "original ="])
+ @pytest.mark.parametrize("scripted", [False, True])
+ def test_assigned_lambda_messages(self, message, assignment, scripted):
+ alias = " msg = original\n" if assignment == "original =" else ""
+ source = f"def f(n: int):\n {assignment} lambda: {message}\n{alias} KORNIA_CHECK(n > 0, msg)\n"
+ torchscript = {"m.py::f"} if scripted else set()
+ n_calls, violations, _, _ = _violations("m.py", ast.parse(source), {"KORNIA_CHECK": 1}, torchscript)
+ assert n_calls == 1
+ if scripted:
+ assert len(violations) == 1
+ assert "has a lambda message, which TorchScript rejects" in violations[0]
+ else:
+ assert not violations
+
+ @pytest.mark.parametrize("conditional", [False, True])
+ @pytest.mark.parametrize("alias", [False, True])
+ @pytest.mark.parametrize("scripted", [False, True])
+ def test_mixed_eager_and_lambda_assignments(self, conditional, alias, scripted):
+ reassignment = ' msg = f"eager {n}"\n'
+ if conditional:
+ reassignment = " if eager:\n " + reassignment
+ passed_name = "other" if alias else "msg"
+ source = (
+ 'def f(n: int, eager: bool):\n msg = lambda: f"deferred {n}"\n'
+ + reassignment
+ + (" other = msg\n" if alias else "")
+ + f" KORNIA_CHECK(n > 0, {passed_name})\n"
+ )
+ torchscript = {"m.py::f"} if scripted else set()
+ _, violations, _, _ = _violations("m.py", ast.parse(source), {"KORNIA_CHECK": 1}, torchscript)
+ assert len(violations) == 1
+ expected = "has a lambda message, which TorchScript rejects" if scripted else f"formats {passed_name}"
+ assert expected in violations[0]
+
+
+def _rand(*shape: int, device: torch.device, dtype: torch.dtype) -> torch.Tensor:
+ return torch.rand(*shape, device=device, dtype=dtype)
+
+
+def _pnp_inputs(n: int, device: torch.device, dtype: torch.dtype) -> tuple[torch.Tensor, ...]:
+ world = _rand(2, n, 3, device=device, dtype=dtype) + torch.tensor([0.0, 0.0, 4.0], device=device, dtype=dtype)
+ intrinsics = torch.eye(3, device=device, dtype=dtype).expand(2, 3, 3)
+ return world, _rand(2, n, 2, device=device, dtype=dtype), intrinsics
+
+
+# Entry points whose messages formatted a size or an int on every call, which recompiled for each new value under a
+# dynamic-shape torch.compile: name -> (op, inputs for one value of the formatted size or int)
+_COMPILE_CASES = {
+ "get_motion_kernel2d (angle batch)": (
+ lambda angle, direction: kornia.filters.get_motion_kernel2d(5, angle, direction),
+ lambda b, device, dtype: (_rand(b, device=device, dtype=dtype) * 90, _rand(b, device=device, dtype=dtype)),
+ ),
+ "motion_blur (angle batch)": (
+ lambda x, angle, direction: kornia.filters.motion_blur(x, 5, angle, direction),
+ lambda b, device, dtype: (
+ _rand(b, 3, 9, 11, device=device, dtype=dtype),
+ _rand(b, device=device, dtype=dtype) * 90,
+ _rand(b, device=device, dtype=dtype),
+ ),
+ ),
+ "fft_conv valid (image size)": (
+ lambda x, kernel: kornia.filters.fft_conv(x, kernel, padding="valid"),
+ lambda h, device, dtype: (
+ _rand(2, 3, h, h + 3, device=device, dtype=dtype),
+ _rand(1, 3, 3, device=device, dtype=dtype),
+ ),
+ ),
+ "gaussian_blur2d (kernel size)": (
+ lambda x, k: kornia.filters.gaussian_blur2d(x, (k, k), (1.5, 1.5)),
+ lambda k, device, dtype: (_rand(2, 3, 16, 19, device=device, dtype=dtype), k),
+ ),
+ "solve_pnp_dlt (number of points)": (
+ kornia.geometry.calibration.solve_pnp_dlt,
+ _pnp_inputs,
+ ),
+ "jpeg_codec_differentiable (batch)": (
+ kornia.enhance.jpeg_codec_differentiable,
+ lambda b, device, dtype: (
+ _rand(b, 3, 16, 16, device=device, dtype=dtype),
+ torch.full((b,), 50.0, device=device, dtype=dtype),
+ ),
+ ),
+ "dedode PatchEmbed (image size)": (
+ None,
+ lambda h, device, dtype: (_rand(2, 3, h, h + 4, device=device, dtype=dtype),),
+ ),
+}
+# the formatted size or int takes these values; none equals another size of the same call, so Dynamo's duck sizing
+# cannot tie it to one
+_COMPILE_VALUES = {
+ "get_motion_kernel2d (angle batch)": (2, 3, 4),
+ "motion_blur (angle batch)": (2, 4, 6),
+ "fft_conv valid (image size)": (6, 8, 10),
+ # 3 is avoided: on macOS arm64, F.conv2d picks another backend for a 3 x 3 kernel, which adds a graph by itself
+ "gaussian_blur2d (kernel size)": (5, 7, 9),
+ "solve_pnp_dlt (number of points)": (7, 9, 11),
+ "jpeg_codec_differentiable (batch)": (2, 3, 4),
+ "dedode PatchEmbed (image size)": (16, 20, 24),
+}
+
+
+class TestDeferredMessagesUnderCompile:
+ @pytest.mark.parametrize("case", sorted(_COMPILE_CASES))
+ def test_dynamo_new_values_compile_no_new_graph(self, case, device, dtype, torch_optimizer, optimizer_backend):
+ """A new value of a size or int that a check message formats compiles no new graph."""
+ from torch._dynamo.testing import CompileCounter
+
+ if optimizer_backend == "jit":
+ pytest.skip("counts the graphs of torch.compile, which torch.jit.script does not build")
+ if dtype not in (torch.float32, torch.float64):
+ pytest.skip("the graph count does not depend on the floating dtype")
+ op, make_inputs = _COMPILE_CASES[case]
+ if op is None:
+ from kornia.feature.dedode.transformer.layers.patch_embed import PatchEmbed
+
+ op = PatchEmbed(img_size=224, patch_size=4, in_chans=3, embed_dim=8).to(device, dtype)
+ counter = CompileCounter()
+ compiled = torch_optimizer(op, backend=counter, dynamic=True)
+ values = _COMPILE_VALUES[case]
+ compiled(*make_inputs(values[0], device, dtype))
+ first = counter.frame_count
+ for value in values[1:]:
+ compiled(*make_inputs(value, device, dtype))
+ assert counter.frame_count == first, f"{counter.frame_count - first} new graphs for new values of {case}"
diff --git a/tests/enhance/test_jpeg.py b/tests/enhance/test_jpeg.py
index f8fc7d000..404e3cd0d 100644
--- a/tests/enhance/test_jpeg.py
+++ b/tests/enhance/test_jpeg.py
@@ -256,7 +256,8 @@ class TestDiffJPEG(BaseTester):
qt_c = torch.randint(low=1, high=255, size=(B * 2, 8, 8), device=device, dtype=dtype)
with pytest.raises(BaseError) as errinfo:
kornia.enhance.jpeg_codec_differentiable(img, jpeg_quality, qt_y, qt_c)
- assert "Batch dimensions do not match" in str(errinfo.value)
+ assert "expected 16 or 1, got 8" in str(errinfo.value)
+ assert "quantization_table_c needs one table per image" in str(errinfo.value)
from kornia.core.exceptions import BaseError
@@ -267,7 +268,8 @@ class TestDiffJPEG(BaseTester):
qt_c = torch.randint(low=1, high=255, size=(B * B, 8, 8), device=device, dtype=dtype)
with pytest.raises(BaseError) as errinfo:
kornia.enhance.jpeg_codec_differentiable(img, jpeg_quality, qt_y, qt_c)
- assert "Batch dimensions do not match" in str(errinfo.value)
+ assert "expected 16 or 1, got 8" in str(errinfo.value)
+ assert "quantization_table_y needs one table per image" in str(errinfo.value)
from kornia.core.exceptions import BaseError
@@ -278,7 +280,8 @@ class TestDiffJPEG(BaseTester):
qt_c = torch.randint(low=1, high=255, size=(B * B, 8, 8), device=device, dtype=dtype)
with pytest.raises(BaseError) as errinfo:
kornia.enhance.jpeg_codec_differentiable(img, jpeg_quality, qt_y, qt_c)
- assert "Batch dimensions do not match" in str(errinfo.value)
+ assert "expected 16 or 1, got 8" in str(errinfo.value)
+ assert "jpeg_quality needs one quality per image" in str(errinfo.value)
def test_cardinality(self, device, dtype) -> None:
B, H, W = 1, 16, 16
diff --git a/tests/feature/test_dedode.py b/tests/feature/test_dedode.py
index d938637cc..0b216bd85 100644
--- a/tests/feature/test_dedode.py
+++ b/tests/feature/test_dedode.py
@@ -25,6 +25,7 @@ from kornia.feature.dedode import DeDoDe
from kornia.feature.dedode.decoder import ConvRefiner
from kornia.feature.dedode.transformer.dinov2 import DinoVisionTransformer
from kornia.feature.dedode.transformer.layers import MemEffAttention, NestedTensorBlock
+from kornia.feature.dedode.transformer.layers.patch_embed import PatchEmbed
from kornia.feature.dedode.utils import dedode_denormalize_pixel_coordinates
from testing.base import BaseTester
@@ -63,6 +64,17 @@ class TestMemEffAttention(BaseTester):
attention(x, attn_bias=torch.zeros(1, 2, 5, 5, device=device, dtype=dtype))
+class TestPatchEmbed(BaseTester):
+ def test_jit_script(self, device, dtype):
+ # TorchScript compiles the patch-size checks, whose messages format the input shape rather than a lambda
+ embed = PatchEmbed(img_size=32, patch_size=4, in_chans=3, embed_dim=8).to(device, dtype)
+ x = torch.rand(2, 3, 16, 20, device=device, dtype=dtype)
+ scripted = torch.jit.script(embed)
+ self.assert_close(scripted(x), embed(x))
+ with pytest.raises(Exception, match="height is not a multiple of patch height 4"):
+ scripted(torch.rand(2, 3, 18, 20, device=device, dtype=dtype))
+
+
class TestNestedTensorBlock(BaseTester):
def test_tensor_input(self, device, dtype):
block = NestedTensorBlock(dim=8, num_heads=2).to(device, dtype).eval()
diff --git a/tests/filters/test_bilateral.py b/tests/filters/test_bilateral.py
index e9d647551..12c0566a3 100644
--- a/tests/filters/test_bilateral.py
+++ b/tests/filters/test_bilateral.py
@@ -141,7 +141,9 @@ class TestBilateralBlur(BaseTester):
lambda: JointBilateralBlur(3, sigma_color, sigma_space)(image, image),
)
for call in calls:
- with pytest.raises(BaseError, match=f"{name} batch of {rows} for an input batch of {batch}"):
+ with pytest.raises(
+ BaseError, match=rf"(?s)expected {batch}(?: or 1)?, got {rows}\..*{name} must have a batch of 1 or the"
+ ):
call()
@pytest.mark.parametrize("name", ["sigma_color", "sigma_space"])
diff --git a/tests/filters/test_filters.py b/tests/filters/test_filters.py
index 84bca4b57..6f0dba3c8 100644
--- a/tests/filters/test_filters.py
+++ b/tests/filters/test_filters.py
@@ -1655,7 +1655,7 @@ class TestConventionsFilter2d(BaseTester):
self.assert_close(own[i : i + 1], run(image[i : i + 1], i, i + 1))
# 2 kernels divide the 4 samples and 3 do not: both raise the kornia error, not a torch view error
for count in (2, 3):
- with pytest.raises(BaseError, match=f"kernel batch of {count} for an input batch of 4"):
+ with pytest.raises(BaseError, match=rf"(?s)expected 4 or 1, got {count}\..*kernel batch must be 1 or the"):
run(image, 0, count)
def test_convention_fft_conv_rejects_a_kernel_batch_for_one_sample_5154(self, device, dtype):
@@ -1664,7 +1664,7 @@ class TestConventionsFilter2d(BaseTester):
image = _rand(1, 1, 5, 7, device=device, dtype=dtype)
kernels = _rand(4, 3, 3, device=device, dtype=dtype, seed=1)
for fn in (fft_conv, filter2d):
- with pytest.raises(BaseError, match="kernel batch of 4 for an input batch of 1"):
+ with pytest.raises(BaseError, match=r"(?s)expected 1, got 4\..*kernel batch must be 1 or the input batch"):
fn(image, kernels, border_type="constant")
@pytest.mark.parametrize("per_sample", [False, True])
diff --git a/tests/filters/test_gaussian.py b/tests/filters/test_gaussian.py
index 0e8b1d7ae..6df01855e 100644
--- a/tests/filters/test_gaussian.py
+++ b/tests/filters/test_gaussian.py
@@ -736,7 +736,7 @@ class TestGaussianBlur2d(BaseTester):
# a torch reshape error
for rows in (2, 3):
sigma = torch.full((rows, 2), 1.5, device=device, dtype=dtype)
- with pytest.raises(BaseError, match=f"sigma batch of {rows} for an input batch of 4"):
+ with pytest.raises(BaseError, match=rf"(?s)expected 4 or 1, got {rows}\..*sigma must have a batch of 1 or"):
gaussian_blur2d(sample, (3, 3), sigma, separable=separable)
# one row for the whole batch and one row per sample run
for rows in (1, 4):
diff --git a/tests/filters/test_motion.py b/tests/filters/test_motion.py
index 4edfc8169..c550da2be 100644
--- a/tests/filters/test_motion.py
+++ b/tests/filters/test_motion.py
@@ -137,7 +137,7 @@ class TestMotionBlur(BaseTester):
def test_get_motion_kernel2d_mismatched_batch_size(self, device, dtype):
angle = torch.zeros(3, device=device, dtype=dtype)
direction = torch.zeros(2, device=device, dtype=dtype)
- with pytest.raises(Exception, match=r"direction and angle must have the same length. Got 2 and 3."):
+ with pytest.raises(Exception, match=r"(?s)expected 3, got 2\..*direction and angle must have the same length"):
get_motion_kernel2d(3, angle, direction)
@pytest.mark.parametrize("kernel_size", [(5, 5), [5, 5], 5.0], ids=["tuple", "list", "float"])
diff --git a/tests/losses/test_focal_loss.py b/tests/losses/test_focal_loss.py
index 26625890d..b972d31ad 100644
--- a/tests/losses/test_focal_loss.py
+++ b/tests/losses/test_focal_loss.py
@@ -108,6 +108,19 @@ class TestBinaryFocalLossWithLogits(BaseTester):
expected = op(logits, labels, *args)
self.assert_close(actual, expected)
+ def test_jit_script(self, device, dtype):
+ # TorchScript compiles the loss with its weight checks, whose messages format shapes rather than a lambda
+ logits = torch.rand(2, 3, 2, device=device, dtype=dtype)
+ labels = torch.rand(2, 3, 2, device=device, dtype=dtype).round()
+ pos_weight = torch.rand(3, device=device, dtype=dtype)
+ weight = torch.rand(3, 1, device=device, dtype=dtype)
+ op = kornia.losses.binary_focal_loss_with_logits
+ op_script = torch.jit.script(op)
+ for args in ((0.25, 2.0, "mean", None, None), (0.25, 2.0, "mean", pos_weight, weight)):
+ self.assert_close(op_script(logits, labels, *args), op(logits, labels, *args))
+ with pytest.raises(Exception, match="pos_weight must hold one value per class of pred"):
+ op_script(logits, labels, 0.25, 2.0, "mean", torch.rand(4, device=device, dtype=dtype), None)
+
@pytest.mark.parametrize("gamma", [0.5, 2.0])
def test_gradcheck(self, device, dtype, gamma):
logits = torch.rand(2, 3, 2, device=device, dtype=torch.float64)
@@ -525,6 +538,19 @@ class TestFocalLoss(BaseTester):
expected = op(logits, labels, *args)
self.assert_close(actual, expected)
+ def test_jit_script(self, device, dtype):
+ # TorchScript compiles the loss with its class and weight checks, whose messages format shapes
+ num_classes = 3
+ logits = torch.rand(2, num_classes, 4, device=device, dtype=dtype)
+ labels = torch.randint(num_classes, (2, 4), device=device)
+ weight = torch.rand(num_classes, device=device, dtype=dtype)
+ op = kornia.losses.focal_loss
+ op_script = torch.jit.script(op)
+ for w in (None, weight):
+ self.assert_close(op_script(logits, labels, 0.25, 2.0, "mean", w), op(logits, labels, 0.25, 2.0, "mean", w))
+ with pytest.raises(Exception, match="weight must hold one value per class of pred"):
+ op_script(logits, labels, 0.25, 2.0, "mean", torch.rand(num_classes + 1, device=device, dtype=dtype))
+
def test_gradcheck(self, device, dtype):
num_classes = 3
logits = torch.rand(2, num_classes, 3, 2, device=device, dtype=torch.float64)
diff --git a/tests/losses/test_lovaz_softmax.py b/tests/losses/test_lovaz_softmax.py
index 9ebe9fee9..41e5abfa4 100644
--- a/tests/losses/test_lovaz_softmax.py
+++ b/tests/losses/test_lovaz_softmax.py
@@ -258,6 +258,19 @@ class TestLovaszSoftmaxLoss(BaseTester):
labels = torch.randint(0, num_classes, (2, 3, 2), device=device)
self.gradcheck(kornia.losses.lovasz_softmax_loss, (logits, labels), dtypes=[torch.float64, torch.int64])
+ def test_jit_script(self, device, dtype):
+ # TorchScript compiles the loss with its weight check, whose message formats shapes rather than a lambda
+ num_classes = 4
+ logits = torch.rand(2, num_classes, 3, 2, device=device, dtype=dtype)
+ labels = torch.randint(0, num_classes, (2, 3, 2), device=device)
+ weight = torch.rand(num_classes, device=device, dtype=dtype)
+ op = kornia.losses.lovasz_softmax_loss
+ op_script = torch.jit.script(op)
+ for w in (None, weight):
+ self.assert_close(op_script(logits, labels, w), op(logits, labels, w))
+ with pytest.raises(Exception, match="weight must hold one value per class of pred"):
+ op_script(logits, labels, torch.rand(num_classes + 1, device=device, dtype=dtype))
+
@pytest.mark.skip(reason="Not matching results")
def test_dynamo(self, device, dtype, torch_optimizer):
# TODO: investigate if we can fix it or report the issue
diff --git a/tests/metrics/test_map.py b/tests/metrics/test_map.py
index 279890f76..0097e70d3 100644
--- a/tests/metrics/test_map.py
+++ b/tests/metrics/test_map.py
@@ -254,11 +254,11 @@ class TestMeanAveragePrecision(BaseTester):
kornia.metrics.mean_average_precision([boxes] * 2, [labels] * 2, [scores] * 2, [boxes], [labels], 3)
with pytest.raises(BaseError, match=r"same length.*pred_scores 1"):
kornia.metrics.mean_average_precision([boxes] * 2, [labels] * 2, [scores], [boxes] * 2, [labels] * 2, 3)
- with pytest.raises(BaseError, match=r"one row per object.*2 boxes and 1 labels"):
+ with pytest.raises(BaseError, match=r"(?s)expected 1, got 2\..*one row per object in every image \(image 0\)"):
kornia.metrics.mean_average_precision([boxes], [labels], [scores], [boxes], [labels[:1]], 3)
- with pytest.raises(BaseError, match=r"one row per detection.*2 boxes, 2 labels and 1 scores"):
+ with pytest.raises(BaseError, match=r"(?s)expected 1, got 2\..*pred_boxes and pred_scores must.*\(image 0\)"):
kornia.metrics.mean_average_precision([boxes], [labels], [scores[:1]], [boxes], [labels], 3)
- with pytest.raises(BaseError, match=r"one row per detection.*1 boxes, 2 labels and 2 scores"):
+ with pytest.raises(BaseError, match=r"(?s)expected 2, got 1\..*pred_boxes and pred_labels must.*\(image 0\)"):
kornia.metrics.mean_average_precision([boxes[:1]], [labels], [scores], [boxes], [labels], 3)
# each of the five lists in turn one image short
lists = [[boxes] * 2, [labels] * 2, [scores] * 2, [boxes] * 2, [labels] * 2]
@@ -284,14 +284,14 @@ class TestMeanAveragePrecision(BaseTester):
mean_ap, _ = kornia.metrics.mean_average_precision(boxes, labels, scores, boxes, labels, 2)
self.assert_close(mean_ap, torch.tensor(1.0, device=device, dtype=dtype))
- with pytest.raises(BaseError, match=r"one row per object in every image. Got image 0: 2 boxes and 1 labels"):
+ with pytest.raises(BaseError, match=r"(?s)expected 1, got 2\..*one row per object in every image \(image 0\)"):
kornia.metrics.mean_average_precision(boxes, labels, scores, boxes, one_each, 2)
with pytest.raises(
- BaseError, match=r"one row per detection in every image. Got image 0: 2 boxes, 1 labels and 1 scores"
+ BaseError, match=r"(?s)expected 1, got 2\..*pred_labels must have one row per detection in every image"
):
kornia.metrics.mean_average_precision(boxes, one_each, one_score_each, boxes, labels, 2)
# the first image is consistent, so the second is named
- with pytest.raises(BaseError, match=r"Got image 1: 2 boxes and 1 labels"):
+ with pytest.raises(BaseError, match=r"(?s)expected 1, got 2\..*\(image 1\)"):
kornia.metrics.mean_average_precision(
[a, a, b],
one_each + one_each[:1],
@@ -301,11 +301,11 @@ class TestMeanAveragePrecision(BaseTester):
2,
)
# the first image holds the extra row, of each kind the checks compare in turn
- with pytest.raises(BaseError, match=r"Got image 0: 1 boxes and 2 labels"):
+ with pytest.raises(BaseError, match=r"(?s)expected 2, got 1\..*one row per object.*\(image 0\)"):
kornia.metrics.mean_average_precision(boxes, labels, scores, [a, b], labels, 2)
- with pytest.raises(BaseError, match=r"Got image 0: 2 boxes, 1 labels and 2 scores"):
+ with pytest.raises(BaseError, match=r"(?s)expected 1, got 2\..*pred_boxes and pred_labels must.*\(image 0\)"):
kornia.metrics.mean_average_precision(boxes, one_each, scores, boxes, labels, 2)
- with pytest.raises(BaseError, match=r"Got image 0: 1 boxes, 1 labels and 2 scores"):
+ with pytest.raises(BaseError, match=r"(?s)expected 2, got 1\..*pred_boxes and pred_scores must.*\(image 0\)"):
kornia.metrics.mean_average_precision([a, b], one_each, scores, boxes, labels, 2)
@pytest.mark.parametrize("box_dtype", [torch.int64, torch.int32, torch.uint8])