Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

feat(augmentation): add opt-in geometry audit reports (#4465)

trueoneplusone5386634810f8
diff --git a/changelog.d/4465.added.md b/changelog.d/4465.added.md
new file mode 100644
index 000000000..f2f989e6c
--- /dev/null
+++ b/changelog.d/4465.added.md
@@ -0,0 +1,3 @@
+Added opt-in `kornia.contrib.augmentation_audit` reports with executed geometric provenance,
+native parameter snapshots, out-of-frame diagnostics and actual keypoint/box round-trip
+measurements, including explicit unsupported transforms and JSON export.
diff --git a/docs/source/contrib.rst b/docs/source/contrib.rst
index 1a79bcf97..e13414d86 100644
--- a/docs/source/contrib.rst
+++ b/docs/source/contrib.rst
@@ -6,6 +6,113 @@ kornia.contrib
.. currentmodule:: kornia.contrib
+Augmentation Geometry Audit
+---------------------------
+
+``kornia.contrib.augmentation_audit.audit`` executes an
+``AugmentationSequential`` once and returns ``(outputs, report)``. It records the
+executed operation order, native parameter snapshots, image shapes, effective
+flags, and coordinate matrices. It also checks keypoint and box round trips against
+the labels actually returned by the pipeline. The ordinary ``forward`` path has no
+reporting overhead.
+
+For example, a training-data validation step can inspect coordinates and export a
+report without storing image pixels::
+
+ import json
+ from pathlib import Path
+ import torch
+ import kornia.augmentation as K
+ from kornia.contrib import audit
+
+ image = torch.rand(2, 3, 32, 48)
+ points = torch.tensor([[[4., 6.], [20., 15.]]]).expand(2, -1, -1)
+ pipeline = K.AugmentationSequential(
+ K.RandomHorizontalFlip(p=1.0),
+ K.RandomAffine(degrees=15, p=1.0),
+ data_keys=["input", "keypoints"],
+ )
+ (image_out, points_out), report = audit(
+ pipeline, image, points, roundtrip_tolerance=1e-3, out_of_frame_tolerance=0.25,
+ )
+ print(report.summary())
+ point_audit = report.spatial[0]
+ assert report.geometry_status == "available"
+ assert torch.equal(point_audit.roundtrip_valid_count, point_audit.count)
+ assert bool((point_audit.roundtrip_max <= 1e-3).all())
+ Path("augmentation-audit.json").write_text(report.to_json(), encoding="utf-8")
+ assert json.loads(report.to_json())["image_reconstruction_evaluated"] is False
+
+ # Native parameter snapshots replay the run with this pipeline configuration.
+ replay_image, replay_points = pipeline(image, points, params=report.params)
+ torch.testing.assert_close(replay_image, image_out)
+ torch.testing.assert_close(replay_points, points_out)
+
+Interpreting the report
+^^^^^^^^^^^^^^^^^^^^^^^
+
+* ``matrix`` maps original pixel coordinates to final image coordinates, including
+ ``RandomCrop`` prepadding when it belongs to the returned image mapping.
+ ``inverse_matrix`` is its algebraic inverse, with nonfinite entries for batches
+ that cannot be inverted. ``invertible`` identifies those batches explicitly.
+* ``geometry_status="available"`` describes matrix availability rather than spatial
+ alignment. Round trips inverse-map the returned labels and compare them with the
+ source. An invertible matrix can therefore accompany a nonzero label error.
+* Keypoint errors are Euclidean distances. Box errors are symmetric Hausdorff
+ distances between corner sets. Tensor box exports take axis-aligned envelopes,
+ so rotation or shear can introduce measurable loss; ``Boxes`` objects retain the
+ transformed quadrilateral.
+* Per-batch statistics include only finite errors. Inspect
+ ``roundtrip_valid_count`` together with the mean, median, or maximum. Empty labels
+ and unavailable inverses do not produce a successful zero-error measurement.
+* Out-of-frame counts use inclusive pixel centers from zero to ``width - 1`` and
+ ``height - 1``. A box is outside when any corner is outside. Nonfinite labels are
+ counted separately.
+* Crop matrices can invert coordinates even after image content has been discarded.
+ The report records this distinction and never evaluates image reconstruction.
+ Cropping and downsampling emit possible content-loss warnings.
+* Partially applied ``RandomCrop`` mappings follow the returned image branch. A
+ crop skipped for the whole batch leaves images and labels unchanged, including
+ with ``padding`` or ``pad_if_needed`` (#4473). Manually supplied parameters that
+ apply the crop to only some rows can still return a transformed image with
+ untransformed labels on the skipped rows; the resulting round-trip error records
+ that inconsistency. Mixed shape-changing operations are reported as
+ ``unsupported`` when their cached matrices cannot certify every returned image row.
+* Non-rigid and unknown operations are explicitly unsupported for matrix
+ composition. A transformation-matrix identity fallback is not treated as proof
+ of correspondence. Supported neighboring operations remain in the provenance.
+* Captured operations must match the ordered operations selected by the sampled
+ parameters. Missing or out-of-order captures make the geometry unsupported.
+ ``RandAugment``, ``AutoAugment``, ``TrivialAugment``, and custom sequential
+ subclasses are currently opaque and therefore unsupported when selected.
+
+Diagnostics use float32 for half-precision inputs and disable autocast for matrix
+composition and inverse mapping. The pipeline forward itself inherits the caller's
+autocast context, so returned labels remain identical to an ordinary forward call.
+Autocast can quantize spatial-label propagation and produce real round-trip errors;
+the report does not suppress those differences.
+
+The API accepts one nonempty BCHW image first, followed by optional batched masks,
+keypoints, or boxes in the usual positional ``data_keys`` forms. Dictionaries,
+ragged or unbatched inputs, video, patch, and 3D containers, and modules registered
+under multiple names are unsupported. Repeated sampled operations and nested
+built-in 2D sequences are supported. Spatial operations must preserve label shapes
+and cardinality. This is an eager diagnostic utility and the same stateful pipeline
+must not be audited concurrently.
+
+``params`` is an independent, detached native replay snapshot. JSON is a portable
+diagnostic export rather than a replay loader. Tensor exports include dtype, device,
+and shape metadata; nonfinite values become JSON ``null``.
+
+.. autofunction:: audit
+
+.. autoclass:: AugmentationAuditReport
+ :members: summary, to_dict, to_json
+
+.. autoclass:: AugmentationAuditStep
+
+.. autoclass:: SpatialAudit
+
Models
------
diff --git a/kornia/contrib/__init__.py b/kornia/contrib/__init__.py
index 86fb6bc20..1cd4eecab 100644
--- a/kornia/contrib/__init__.py
+++ b/kornia/contrib/__init__.py
@@ -22,6 +22,7 @@ This subpackage provides community-contributed and experimental features.
from kornia.models.tiny_vit import TinyViT
+from .augmentation_audit import AugmentationAuditReport, AugmentationAuditStep, SpatialAudit, audit
from .connected_components import connected_components
from .diamond_square import diamond_square
from .distance_transform import DistanceTransform, distance_transform
@@ -42,6 +43,8 @@ from .object_detection import ObjectDetector, RTDETRDetectorBuilder
from .super_resolution import RRDBNetBuilder, SmallSRBuilder, SuperResolution, SuperResolutionConfig
__all__ = [
+ "AugmentationAuditReport",
+ "AugmentationAuditStep",
"CombineTensorPatches",
"DistanceTransform",
"EdgeDetector",
@@ -54,9 +57,11 @@ __all__ = [
"RRDBNetBuilder",
"RTDETRDetectorBuilder",
"SmallSRBuilder",
+ "SpatialAudit",
"SuperResolution",
"SuperResolutionConfig",
"TinyViT",
+ "audit",
"combine_tensor_patches",
"compute_padding",
"connected_components",
diff --git a/kornia/contrib/augmentation_audit.py b/kornia/contrib/augmentation_audit.py
new file mode 100644
index 000000000..bd729d426
--- /dev/null
+++ b/kornia/contrib/augmentation_audit.py
@@ -0,0 +1,574 @@
+# 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.
+#
+
+"""Opt-in diagnostics for the geometry of an executed augmentation pipeline."""
+
+from __future__ import annotations
+
+import json
+import math
+from dataclasses import dataclass, fields, is_dataclass
+from enum import Enum
+from functools import partial
+from typing import TYPE_CHECKING, Any, Literal, TypeVar, cast
+
+import torch
+from torch import Tensor, nn
+
+from kornia.augmentation._2d.geometric.base import GeometricAugmentationBase2D
+from kornia.augmentation._2d.geometric.crop import RandomCrop
+from kornia.augmentation._2d.intensity.base import IntensityAugmentationBase2D
+from kornia.augmentation._3d.base import AugmentationBase3D
+from kornia.augmentation.container.image import ImageSequential
+from kornia.augmentation.container.ops import DataType
+from kornia.augmentation.container.params import ParamItem
+from kornia.augmentation.container.patch import PatchSequential
+from kornia.augmentation.container.video import VideoSequential
+from kornia.constants import DataKey
+from kornia.geometry.boxes import Boxes
+from kornia.geometry.keypoints import Keypoints
+
+if TYPE_CHECKING:
+ from kornia.augmentation.container.augment import AugmentationSequential
+
+__all__ = ["AugmentationAuditReport", "AugmentationAuditStep", "SpatialAudit", "audit"]
+
+_T = TypeVar("_T")
+_BOX_MODES = {DataKey.BBOX: "vertices_plus", DataKey.BBOX_XYXY: "xyxy_plus", DataKey.BBOX_XYWH: "xywh"}
+
+
+def _snapshot(value: _T) -> _T:
+ if isinstance(value, Tensor):
+ return cast(_T, value.detach().clone())
+ if isinstance(value, ParamItem):
+ return cast(_T, ParamItem(value.name, _snapshot(value.data)))
+ if isinstance(value, dict):
+ return cast(_T, {key: _snapshot(item) for key, item in value.items()})
+ if isinstance(value, (tuple, list)):
+ return cast(_T, type(value)(_snapshot(item) for item in value))
+ return value
+
+
+def _json_value(value: Any) -> Any:
+ if isinstance(value, Tensor):
+ return {
+ "values": _json_value(value.detach().cpu().tolist()),
+ "shape": list(value.shape),
+ "dtype": str(value.dtype),
+ "device": str(value.device),
+ }
+ if isinstance(value, ParamItem):
+ return {"name": value.name, "data": _json_value(value.data)}
+ if is_dataclass(value) and not isinstance(value, type):
+ return {field.name: _json_value(getattr(value, field.name)) for field in fields(value)}
+ if isinstance(value, Enum):
+ return value.name
+ if isinstance(value, dict):
+ return {str(_json_value(key)): _json_value(item) for key, item in value.items()}
+ if isinstance(value, (list, tuple)):
+ return [_json_value(item) for item in value]
+ if isinstance(value, float) and not math.isfinite(value):
+ return None
+ if value is None or isinstance(value, (str, bool, int, float)):
+ return value
+ if isinstance(value, (torch.dtype, torch.device)):
+ return str(value)
+ raise TypeError(f"Audit metadata of type {type(value).__name__} cannot be serialized to JSON.")
+
+
+@dataclass(frozen=True)
+class AugmentationAuditStep:
+ """Snapshot of one captured leaf operation, including repeated occurrences.
+
+ ``matrix`` maps this occurrence's local input pixel coordinates to its output
+ coordinates, including RandomCrop prepadding. The full pipeline mapping is
+ stored separately on the report. ``None`` means that the
+ operation has no supported 2D matrix, not that it is an identity transform.
+ Parameters and flags are detached copies; ``occurrence`` is zero-based for
+ each qualified module name. Shapes describe the image path. Flags include
+ keyword overrides observed on that image call.
+ """
+
+ name: str
+ occurrence: int
+ module: str
+ input_shape: tuple[int, ...]
+ output_shape: tuple[int, ...]
+ params: dict[str, Any]
+ flags: dict[str, Any]
+ matrix: Tensor | None
+ unsupported_reason: str | None
+
+
+@dataclass(frozen=True)
+class SpatialAudit:
+ """Per-batch diagnostics for one returned box or keypoint input.
+
+ Each point or box is one item. A box is outside if any corner is outside
+ the inclusive pixel-center rectangle ``[0, width-1] x [0, height-1]``.
+ Nonfinite items are counted separately, not counted as outside. Fractions
+ use the total item count; empty inputs have a NaN fraction.
+
+ Round trips inverse-map the *actual returned coordinates* with the recorded
+ composed matrix. Errors are Euclidean point distances or symmetric Hausdorff
+ distances between the four box corners (independent of corner ordering).
+ Tensor box exports can lose orientation by taking an axis-aligned envelope;
+ this loss is included in the measurement. ``Boxes`` objects retain corners.
+ Statistics cover only finite errors, in pixels; a batch with no valid errors
+ has NaN statistics and zero ``roundtrip_valid_count``. Diagnostics use float32
+ for half inputs, otherwise the image dtype.
+ """
+
+ input_index: int
+ data_key: str
+ metric: Literal["euclidean", "corner_hausdorff"]
+ count: Tensor
+ out_of_frame: Tensor
+ nonfinite: Tensor
+ out_of_frame_fraction: Tensor
+ roundtrip_valid_count: Tensor
+ roundtrip_mean: Tensor
+ roundtrip_median: Tensor
+ roundtrip_max: Tensor
+
+
+@dataclass(frozen=True)
+class AugmentationAuditReport:
+ """Geometry provenance and spatial diagnostics from one augmentation call.
+
+ ``params`` is a detached snapshot of native ``ParamItem`` values for replay
+ with the same pipeline configuration. JSON is a diagnostic export, not a
+ parameter deserializer. Reports retain neither image pixels nor autograd
+ graphs. Tensor fields are independent snapshots, not read-only tensors.
+
+ ``geometry_status`` is ``unsupported`` when any executed operation lacks a
+ supported matrix, ``singular`` when any composed matrix cannot be inverted,
+ or ``available``. Inspect the per-batch ``invertible`` mask and spatial
+ errors rather than interpreting availability as alignment success.
+ ``inverse_matrix`` has NaNs for singular/nonfinite batches. No image inverse
+ is evaluated: coordinate invertibility does not imply pixel reconstruction,
+ particularly after cropping, interpolation or intensity changes.
+ """
+
+ inputs: list[dict[str, Any]]
+ output_shape: tuple[int, ...]
+ steps: list[AugmentationAuditStep]
+ params: list[ParamItem]
+ configured_extra_args: dict[DataKey, dict[str, Any]]
+ geometry_status: Literal["available", "unsupported", "singular"]
+ matrix: Tensor | None
+ inverse_matrix: Tensor | None
+ invertible: Tensor
+ spatial: list[SpatialAudit]
+ warnings: list[str]
+ roundtrip_tolerance: float
+ out_of_frame_tolerance: float
+ image_reconstruction_evaluated: bool = False
+
+ def to_dict(self) -> dict[str, Any]:
+ """Export JSON-safe metadata; tensor values include dtype/device/shape, and NaNs become None."""
+ return cast(dict[str, Any], _json_value(self))
+
+ def to_json(self, *, indent: int | None = 2) -> str:
+ """Serialize the report as strict JSON (nonfinite diagnostic values become null)."""
+ return json.dumps(self.to_dict(), indent=indent, allow_nan=False)
+
+ def summary(self) -> str:
+ """Describe matrix availability and diagnostic warnings without claiming image invertibility."""
+ return (
+ f"Augmentation audit: {len(self.steps)} captured operations, geometry {self.geometry_status}, "
+ f"{len(self.spatial)} spatial inputs. Image reconstruction not evaluated."
+ + ("\n" + "\n".join(self.warnings) if self.warnings else "")
+ )
+
+
+def _supported_sequence(module: nn.Module) -> bool:
+ from kornia.augmentation.container.augment import AugmentationSequential
+
+ return type(module) in (ImageSequential, AugmentationSequential)
+
+
+def _leaves(sequence: ImageSequential, prefix: str = "", seen: set[int] | None = None) -> list[tuple[str, nn.Module]]:
+ seen = set() if seen is None else seen
+ result: list[tuple[str, nn.Module]] = []
+ for name, module in sequence._modules.items():
+ if module is None:
+ continue
+ path = f"{prefix}.{name}" if prefix else name
+ if id(module) in seen:
+ raise ValueError("audit does not support a module registered under multiple names.")
+ seen.add(id(module))
+ if isinstance(module, (VideoSequential, PatchSequential, AugmentationBase3D)):
+ raise ValueError("audit supports 2D image pipelines, not video, patch or 3D augmentations.")
+ if _supported_sequence(module):
+ result.extend(_leaves(cast(ImageSequential, module), path, seen))
+ else:
+ result.append((path, module))
+ return result
+
+
+def _selected_paths(sequence: ImageSequential, params: list[ParamItem], prefix: str = "") -> list[str]:
+ paths: list[str] = []
+ for param in params:
+ module = sequence.get_submodule(param.name)
+ path = f"{prefix}.{param.name}" if prefix else param.name
+ if _supported_sequence(module) and isinstance(param.data, list):
+ # Use this occurrence's tree, not the nested module's last cached params.
+ paths.extend(_selected_paths(cast(ImageSequential, module), param.data, path))
+ else:
+ paths.append(path)
+ return paths
+
+
+def _capture_warnings(sequence: AugmentationSequential, steps: list[AugmentationAuditStep]) -> list[str]:
+ if not _supported_sequence(sequence) or sequence._params is None:
+ return ["Forward capture cannot be verified for a custom container or a call without recorded parameters."]
+ selected = _selected_paths(sequence, sequence._params)
+ captured = [step.name for step in steps]
+ if selected != captured:
+ return [f"Forward capture is incomplete or out of order: selected {selected}; captured {captured}."]
+ return []
+
+
+def _crop_matrix(
+ module: RandomCrop,
+ matrix: Tensor,
+ params: dict[str, Any],
+ flags: dict[str, Any],
+ image: Tensor,
+ output: Tensor,
+) -> tuple[Tensor | None, str | None]:
+ applied = params["batch_prob"] > 0.5
+ static = module.p == 1.0 and module.p_batch == 1.0
+ changed_shape = output.shape[-2:] != image.shape[-2:]
+ if not static and changed_shape and flags["cropping_mode"] == "slice" and not bool(applied.all()):
+ # The shape-changing blend returns every transformed row, but slice uses
+ # src indices even where the cached per-row matrix is the identity.
+ return None, "mixed-application slice crop has no reliable per-row image matrix after changing shape"
+ if static or changed_shape:
+ # These paths return the entire transformed branch, including prepadding.
+ applied = torch.ones_like(applied)
+ padding = params["padding_size"].to(matrix)
+ translation = torch.eye(3, device=matrix.device, dtype=matrix.dtype).expand_as(matrix).clone()
+ translation[:, 0, 2] = padding[:, 0] * applied.to(matrix)
+ translation[:, 1, 2] = padding[:, 2] * applied.to(matrix)
+ return matrix @ translation, None
+
+
+def _coordinates(value: DataType, key: DataKey) -> Tensor:
+ if (isinstance(value, Boxes) and key not in _BOX_MODES) or (
+ isinstance(value, Keypoints) and key != DataKey.KEYPOINTS
+ ):
+ raise ValueError("audit Boxes/Keypoints objects must match their data key.")
+ if isinstance(value, (Boxes, Keypoints)):
+ if value._N is not None:
+ raise ValueError("audit does not support ragged Boxes or Keypoints constructed from lists.")
+ return value.data
+ if not isinstance(value, Tensor):
+ raise ValueError("audit requires batched tensors, Boxes or Keypoints; ragged inputs are unsupported.")
+ if key in _BOX_MODES:
+ # Match the container's public representation, including axis-aligned tensor exports.
+ return Boxes.from_tensor(value, mode=_BOX_MODES[key], validate_boxes=False).data
+ return value
+
+
+def _capture(
+ module: nn.Module,
+ inputs: tuple[Any, ...],
+ kwargs: dict[str, Any],
+ output: Any,
+ *,
+ name: str,
+ steps: list[AugmentationAuditStep],
+) -> None:
+ image = inputs[0]
+ params = _snapshot(getattr(module, "_params", {}))
+ # Augmentation forward merges its kwargs into flags without necessarily
+ # saving them on module.flags. `params` is a separate bound argument.
+ flags = _snapshot(
+ {**getattr(module, "flags", {}), **{key: value for key, value in kwargs.items() if key != "params"}}
+ )
+ matrix = None
+ reason = None
+ if isinstance(module, (GeometricAugmentationBase2D, IntensityAugmentationBase2D)):
+ # Materialize lazy matrices in the caller's context so the ordinary spatial
+ # outputs remain identical, then adjust diagnostics outside autocast.
+ matrix = _snapshot(module.transform_matrix)
+ with torch.autocast(device_type=image.device.type, enabled=False):
+ if matrix is not None and isinstance(module, RandomCrop):
+ matrix, reason = _crop_matrix(module, matrix, params, flags, image, output)
+ elif (
+ matrix is not None
+ and output.shape[-2:] != image.shape[-2:]
+ and not (module.p == 1.0 and module.p_batch == 1.0)
+ and not bool((params["batch_prob"] > 0.5).all())
+ ):
+ # A shape-changing image blend returns the transformed branch for
+ # every row when any row is selected. Matrices and spatial labels
+ # remain blended per row, so they cannot certify the returned image.
+ matrix = None
+ reason = "mixed-application shape-changing operation has no reliable per-row image matrix"
+ if matrix is not None and matrix.shape != (image.shape[0], 3, 3):
+ matrix = None
+ reason = "operation produced a matrix with an unsupported shape"
+ elif matrix is None and reason is None:
+ reason = "operation did not produce a 2D matrix"
+ elif type(module) is nn.Identity:
+ matrix = torch.eye(3, device=image.device, dtype=image.dtype).expand(image.shape[0], -1, -1).clone()
+ else:
+ reason = "non-rigid or unknown operation; coordinate propagation is not certified by a 2D matrix"
+ steps.append(
+ AugmentationAuditStep(
+ name,
+ sum(step.name == name for step in steps),
+ type(module).__name__,
+ tuple(image.shape),
+ tuple(output.shape),
+ params,
+ flags,
+ matrix,
+ reason,
+ )
+ )
+
+
+def _matrices(
+ steps: list[AugmentationAuditStep],
+ image: Tensor,
+ *,
+ capture_complete: bool,
+) -> tuple[Tensor | None, Tensor | None, Tensor]:
+ if not capture_complete:
+ return None, None, torch.zeros(image.shape[0], device=image.device, dtype=torch.bool)
+ dtype = torch.float64 if image.dtype == torch.float64 else torch.float32
+ identity = torch.eye(3, device=image.device, dtype=dtype).expand(image.shape[0], -1, -1)
+ matrix = identity.clone()
+ for step in steps:
+ if step.matrix is None or step.matrix.shape != matrix.shape:
+ return None, None, torch.zeros(image.shape[0], device=image.device, dtype=torch.bool)
+ matrix = step.matrix.to(matrix) @ matrix
+ finite = matrix.isfinite().all(dim=(-2, -1))
+ inverse, info = torch.linalg.inv_ex(torch.where(finite[:, None, None], matrix, identity))
+ valid = finite & (info == 0) & inverse.isfinite().all(dim=(-2, -1))
+ inverse = torch.where(valid[:, None, None], inverse, torch.full_like(inverse, float("nan")))
+ return matrix, inverse, valid
+
+
+def _spatial_audit(
+ source: Tensor,
+ result: Tensor,
+ key: DataKey,
+ index: int,
+ shape: tuple[int, ...],
+ inverse: Tensor | None,
+ dtype: torch.dtype,
+) -> SpatialAudit:
+ if source.shape != result.shape:
+ raise ValueError("audit requires spatial outputs to preserve the source shape and label cardinality.")
+ source, result = source.to(dtype=dtype), result.detach().to(dtype=dtype)
+ batch, count = result.shape[:2]
+ finite = result.isfinite().flatten(2).all(-1)
+ outside = (
+ (result[..., 0] < 0)
+ | (result[..., 0] > shape[-1] - 1)
+ | (result[..., 1] < 0)
+ | (result[..., 1] > shape[-2] - 1)
+ )
+ if key in _BOX_MODES:
+ outside = outside.any(-1)
+ counts = torch.full((batch,), count, device=result.device, dtype=torch.long)
+ errors = torch.full((batch, count), float("nan"), device=result.device, dtype=dtype)
+ if inverse is not None and count:
+ flat = result.reshape(batch, -1, 2)
+ homogeneous = torch.cat((flat, torch.ones_like(flat[..., :1])), dim=-1) @ inverse.transpose(-1, -2)
+ # Exact division exposes points at projective infinity instead of replacing the divisor by one.
+ restored = (homogeneous[..., :2] / homogeneous[..., 2:]).reshape_as(result)
+ if key in _BOX_MODES:
+ distances = torch.cdist(restored, source)
+ errors = torch.maximum(distances.amin(-1).amax(-1), distances.amin(-2).amax(-1))
+ else:
+ errors = torch.linalg.vector_norm(restored - source, dim=-1)
+ valid = errors.isfinite()
+ errors = torch.where(valid, errors, torch.full_like(errors, float("nan")))
+ valid_count = valid.sum(-1)
+ mean = errors.nansum(-1) / valid_count
+ if count:
+ median = errors.nanquantile(0.5, dim=-1)
+ maximum = errors.nan_to_num(nan=-float("inf")).amax(-1)
+ maximum = torch.where(valid_count > 0, maximum, torch.full_like(maximum, float("nan")))
+ else:
+ median, maximum = mean.clone(), mean.clone()
+ out_of_frame = (outside & finite).sum(-1)
+ return SpatialAudit(
+ index,
+ key.name,
+ "corner_hausdorff" if key in _BOX_MODES else "euclidean",
+ counts,
+ out_of_frame,
+ (~finite).sum(-1),
+ out_of_frame / counts,
+ valid_count,
+ mean,
+ median,
+ maximum,
+ )
+
+
+def audit(
+ sequence: AugmentationSequential,
+ *args: DataType,
+ params: list[ParamItem] | None = None,
+ data_keys: list[str | int | DataKey] | None = None,
+ roundtrip_tolerance: float = 1e-3,
+ out_of_frame_tolerance: float = 0.0,
+) -> tuple[DataType | list[DataType] | dict[str, DataType], AugmentationAuditReport]:
+ """Run an augmentation sequence once and return its outputs plus a geometry audit report.
+
+ The sequence must use one BCHW image first, followed by batched masks, boxes or
+ keypoints described by positional ``data_keys``. ``params`` and ``data_keys``
+ have the same meaning as in :meth:`kornia.augmentation.AugmentationSequential.forward`.
+ Unknown or non-rigid operations run normally and make composed geometry unavailable.
+
+ Reporting is an eager diagnostic operation. It snapshots executed operations and
+ parameters, checks spatial round trips, and never evaluates image reconstruction.
+ The returned outputs retain the ordinary forward structure, values and gradients.
+ Do not audit the same stateful sequence concurrently.
+
+ Args:
+ sequence: The 2D augmentation sequence to execute and inspect.
+ args: Image and optional spatial inputs accepted by the sequence.
+ params: Optional sampled parameters to replay.
+ data_keys: Optional positional data-key override.
+ roundtrip_tolerance: Nonnegative pixel threshold for round-trip warnings.
+ out_of_frame_tolerance: Fraction in ``[0, 1]`` above which an input gets a warning.
+
+ Returns:
+ A pair ``(outputs, report)``. ``outputs`` matches an ordinary forward call.
+ """
+ if not math.isfinite(roundtrip_tolerance) or roundtrip_tolerance < 0:
+ raise ValueError("roundtrip_tolerance must be finite and nonnegative.")
+ if not math.isfinite(out_of_frame_tolerance) or not 0 <= out_of_frame_tolerance <= 1:
+ raise ValueError("out_of_frame_tolerance must be between zero and one.")
+ selected_keys = sequence.data_keys if data_keys is None else data_keys
+ if selected_keys is None:
+ raise ValueError("audit requires explicit positional data_keys when the pipeline data_keys is None.")
+ keys = [DataKey.get(key) for key in selected_keys]
+ if len(keys) != len(args) or not keys or keys[0] != DataKey.INPUT or keys.count(DataKey.INPUT) != 1:
+ raise ValueError("audit requires exactly one image as the first input and matching data_keys.")
+ image = args[0]
+ if not isinstance(image, Tensor) or image.ndim != 4 or image.shape[0] == 0:
+ raise ValueError(
+ "audit requires a nonempty BCHW image tensor; dictionaries and unbatched inputs are unsupported."
+ )
+ leaves = _leaves(sequence)
+ sources: dict[int, Tensor] = {}
+ metadata = []
+ for index, (value, key) in enumerate(zip(args, keys)):
+ if key not in (DataKey.INPUT, DataKey.MASK, DataKey.KEYPOINTS, *_BOX_MODES):
+ raise ValueError(f"audit does not support the data key {key.name}.")
+ tensor = _coordinates(value, key)
+ # All box coordinates have been converted to (B, N, 4, 2).
+ expected_ndim = 3 if key == DataKey.KEYPOINTS else 4
+ if tensor.ndim != expected_ndim or tensor.shape[0] != image.shape[0] or tensor.device != image.device:
+ raise ValueError("audit inputs must be batched with the same batch size and device as the image.")
+ original = value.data if isinstance(value, (Boxes, Keypoints)) else cast(Tensor, value)
+ metadata.append(
+ {
+ "data_key": key.name,
+ "shape": tuple(original.shape),
+ "dtype": original.dtype,
+ "device": original.device,
+ }
+ )
+ if key == DataKey.KEYPOINTS or key in _BOX_MODES:
+ sources[index] = _snapshot(tensor)
+ steps: list[AugmentationAuditStep] = []
+ handles = [
+ module.register_forward_hook(partial(_capture, name=name, steps=steps), with_kwargs=True)
+ for name, module in leaves
+ ]
+ try:
+ outputs = sequence(*args, params=params, data_keys=keys)
+ finally:
+ for handle in handles:
+ handle.remove()
+ values = outputs if isinstance(outputs, list) else [outputs]
+ output_image = values[0]
+ if not isinstance(output_image, Tensor) or output_image.ndim != 4 or output_image.shape[0] != image.shape[0]:
+ raise ValueError("audit requires operations to preserve the image batch dimension and BCHW layout.")
+ output_shape = tuple(output_image.shape)
+ # The forward above intentionally inherits caller autocast. Diagnostics do not:
+ # reduced-precision matrix products can create false round-trip errors.
+ with torch.no_grad(), torch.autocast(device_type=image.device.type, enabled=False):
+ capture_warnings = _capture_warnings(sequence, steps)
+ matrix, inverse, valid = _matrices(steps, image, capture_complete=not capture_warnings)
+ status: Literal["available", "unsupported", "singular"] = (
+ "unsupported" if matrix is None else "available" if bool(valid.all()) else "singular"
+ )
+ diagnostic_dtype = torch.float64 if image.dtype == torch.float64 else torch.float32
+ spatial = [
+ _spatial_audit(
+ source,
+ _coordinates(values[index], keys[index]),
+ keys[index],
+ index,
+ output_shape,
+ inverse,
+ diagnostic_dtype,
+ )
+ for index, source in sources.items()
+ ]
+ warnings = capture_warnings + [
+ f"{step.name}: {step.unsupported_reason}." for step in steps if step.unsupported_reason
+ ]
+ if status == "singular":
+ warnings.append("Some composed matrices are singular or nonfinite; inspect the invertible mask.")
+ for step in steps:
+ if "Crop" in step.module or any(
+ after < before for before, after in zip(step.input_shape[-2:], step.output_shape[-2:])
+ ):
+ warnings.append(
+ f"{step.name}: cropping or downsampling may discard image content "
+ "even when coordinates are invertible."
+ )
+ for item in spatial:
+ if bool((item.nonfinite > 0).any()):
+ warnings.append(f"Input {item.input_index}: nonfinite output coordinates.")
+ if bool((item.out_of_frame_fraction > out_of_frame_tolerance).any()):
+ warnings.append(f"Input {item.input_index}: out-of-frame fraction exceeds {out_of_frame_tolerance:g}.")
+ if inverse is not None and bool((item.roundtrip_valid_count < item.count).any()):
+ warnings.append(
+ f"Input {item.input_index}: some round-trip errors are nonfinite; inspect valid counts."
+ )
+ if bool((item.roundtrip_max > roundtrip_tolerance).any()):
+ warnings.append(f"Input {item.input_index}: round-trip error exceeds {roundtrip_tolerance:g} pixels.")
+ report = AugmentationAuditReport(
+ metadata,
+ output_shape,
+ steps,
+ _snapshot(sequence._params or []),
+ _snapshot(sequence.extra_args),
+ status,
+ matrix,
+ inverse,
+ valid,
+ spatial,
+ warnings,
+ roundtrip_tolerance,
+ out_of_frame_tolerance,
+ )
+ return outputs, report
diff --git a/tests/contrib/test_augmentation_audit.py b/tests/contrib/test_augmentation_audit.py
new file mode 100644
index 000000000..6c6c35b62
--- /dev/null
+++ b/tests/contrib/test_augmentation_audit.py
@@ -0,0 +1,651 @@
+# 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.
+#
+
+import json
+from copy import deepcopy
+
+import pytest
+import torch
+
+import kornia.augmentation as K
+from kornia import contrib
+from kornia.augmentation.container.params import ParamItem
+from kornia.constants import DataKey, Resample
+from kornia.contrib.augmentation_audit import audit
+from kornia.geometry.boxes import Boxes
+from kornia.geometry.keypoints import Keypoints
+
+from testing.base import BaseTester
+
+
+class TestAugmentationAudit(BaseTester):
+ def test_contrib_public_api(self):
+ assert contrib.audit is audit
+ assert contrib.AugmentationAuditReport.__module__ == "kornia.contrib.augmentation_audit"
+ assert not hasattr(K.AugmentationSequential, "audit")
+
+ def test_flip_and_actual_keypoints(self, device, dtype):
+ image = torch.rand(2, 1, 8, 10, device=device, dtype=dtype)
+ points = torch.tensor([[[1.0, 2.0], [11.0, 4.0]]], device=device, dtype=dtype).expand(2, -1, -1)
+ aug = K.AugmentationSequential(K.RandomHorizontalFlip(p=1), data_keys=["input", "keypoints"])
+ outputs, report = audit(aug, image, points)
+ self.assert_close(
+ outputs[1], torch.tensor([[[8.0, 2.0], [-2.0, 4.0]]], device=device, dtype=dtype).expand(2, -1, -1)
+ )
+ assert report.geometry_status == "available"
+ assert report.steps[0].name == "RandomHorizontalFlip_0"
+ assert report.spatial[0].metric == "euclidean"
+ self.assert_close(report.spatial[0].out_of_frame, torch.ones(2, device=device, dtype=torch.long))
+ self.assert_close(report.spatial[0].roundtrip_max, torch.zeros_like(report.spatial[0].roundtrip_max))
+ assert json.loads(report.to_json())["geometry_status"] == "available"
+
+ def test_rng_and_replay(self, device, dtype):
+ image = torch.rand(2, 1, 10, 10, device=device, dtype=dtype)
+ aug = K.AugmentationSequential(K.RandomAffine(30), K.RandomBrightness(0.2))
+ torch.manual_seed(123)
+ ordinary = aug(image)
+ state = torch.random.get_rng_state()
+ torch.manual_seed(123)
+ audited, report = audit(aug, image)
+ self.assert_close(audited, ordinary)
+ assert torch.equal(torch.random.get_rng_state(), state)
+ self.assert_close(aug(image, params=report.params), audited)
+
+ def test_nested_order(self, device, dtype):
+ image = torch.rand(1, 1, 8, 10, device=device, dtype=dtype)
+ points = image.new_tensor([[[2, 3]]])
+ aug = K.AugmentationSequential(
+ K.ImageSequential(K.RandomHorizontalFlip(p=1), K.RandomVerticalFlip(p=1)),
+ K.RandomBrightness(0.2),
+ data_keys=["input", "keypoints"],
+ )
+ _, report = audit(aug, image, points)
+ assert [step.name for step in report.steps] == [
+ "ImageSequential_0.RandomHorizontalFlip_0",
+ "ImageSequential_0.RandomVerticalFlip_1",
+ "RandomBrightness_1",
+ ]
+ diagnostic_dtype = torch.float64 if dtype == torch.float64 else torch.float32
+ expected = torch.tensor([[[-1, 0, 9], [0, -1, 7], [0, 0, 1]]], device=device, dtype=diagnostic_dtype)
+ self.assert_close(report.matrix, expected)
+ assert report.spatial[0].roundtrip_max.item() < 1e-4
+
+ def test_repeated_operations_capture_each_matrix(self, device, dtype):
+ image = torch.rand(1, 1, 10, 10, device=device, dtype=dtype)
+ points = image.new_tensor([[[2, 3]]])
+ module = K.RandomAffine(0, translate=(0.3, 0.3), p=1)
+ aug = K.AugmentationSequential(module, data_keys=["input", "keypoints"])
+ first = module.forward_parameters(image.shape)
+ second = deepcopy(first)
+ first["translations"] = image.new_tensor([[1, 0]])
+ second["translations"] = image.new_tensor([[0, 2]])
+ params = [ParamItem("RandomAffine_0", first), ParamItem("RandomAffine_0", second)]
+ outputs, report = audit(aug, image, points, params=params)
+ assert [step.occurrence for step in report.steps] == [0, 1]
+ self.assert_close(report.steps[0].matrix[..., :2, 2], image.new_tensor([[1, 0]]))
+ self.assert_close(report.steps[1].matrix[..., :2, 2], image.new_tensor([[0, 2]]))
+ self.assert_close(outputs[1], image.new_tensor([[[3, 5]]]))
+ assert report.spatial[0].roundtrip_max.item() < 1e-4
+
+ def test_mixed_application(self, device, dtype):
+ image = torch.rand(2, 1, 8, 10, device=device, dtype=dtype)
+ points = image.new_tensor([[[1, 2]], [[1, 2]]])
+ flip = K.RandomHorizontalFlip(p=0.5)
+ params = flip.forward_parameters(image.shape)
+ params["batch_prob"] = image.new_tensor([1, 0])
+ aug = K.AugmentationSequential(flip, data_keys=["input", "keypoints"])
+ outputs, report = audit(aug, image, points, params=[ParamItem("RandomHorizontalFlip_0", params)])
+ self.assert_close(outputs[1], image.new_tensor([[[8, 2]], [[1, 2]]]))
+ self.assert_close(report.matrix[1], torch.eye(3, device=device, dtype=report.matrix.dtype))
+ assert report.spatial[0].roundtrip_max.max().item() < 1e-4
+
+ @pytest.mark.parametrize("with_identity", [False, True])
+ def test_diagnostics_disable_cpu_autocast(self, with_identity):
+ image = torch.zeros(1, 1, 32, 48)
+ points = torch.tensor([[[20.01, 15.03]]])
+ modules = [torch.nn.Identity()] if with_identity else []
+ aug = K.AugmentationSequential(*modules, data_keys=["input", "keypoints"])
+ with torch.autocast("cpu", dtype=torch.bfloat16):
+ outputs, report = audit(aug, image, points)
+ assert torch.equal(outputs[0], image)
+ assert torch.equal(outputs[1], points)
+ assert report.matrix.dtype == torch.float32
+ self.assert_close(report.spatial[0].roundtrip_max, torch.zeros(1))
+ assert not any("round-trip error" in warning for warning in report.warnings)
+
+ def test_outputs_match_forward_under_cpu_autocast_for_lazy_matrix(self):
+ image = torch.rand(2, 3, 32, 48)
+ points = torch.tensor([[[20.01, 15.03], [40.7, 3.3]], [[7.77, 29.1], [33.3, 11.1]]])
+ aug = K.AugmentationSequential(
+ K.RandomResizedCrop((20, 30), scale=(0.5, 1.0)), data_keys=["input", "keypoints"]
+ )
+ with torch.autocast("cpu", dtype=torch.bfloat16):
+ torch.manual_seed(1)
+ expected = aug(image, points)
+ torch.manual_seed(1)
+ actual, _ = audit(aug, image, points)
+ assert torch.equal(actual[0], expected[0])
+ assert torch.equal(actual[1], expected[1])
+
+ def test_shape_changing_mixed_application_is_unsupported(self, device, dtype):
+ image = torch.zeros(2, 1, 8, 10, device=device, dtype=dtype)
+ image[:, 0, 2, 4] = 1
+ points = image.new_tensor([[[4, 2]], [[4, 2]]])
+ resize = K.Resize((4, 5), resample="nearest", p=0.5)
+ params = resize.forward_parameters(image.shape)
+ params["batch_prob"] = image.new_tensor([0, 1])
+ aug = K.AugmentationSequential(resize, data_keys=["input", "keypoints"])
+ outputs, report = audit(aug, image, points, params=[ParamItem("Resize_0", params)])
+ assert outputs[0][0, 0, 1, 2].item() == 1
+ self.assert_close(outputs[1][0], points[0])
+ assert report.geometry_status == "unsupported"
+ assert report.matrix is None and report.inverse_matrix is None
+ assert "mixed-application shape-changing" in report.summary()
+
+ @pytest.mark.parametrize("cropping_mode", ["slice", "resample"])
+ def test_crop_padding_and_content_loss(self, device, dtype, cropping_mode):
+ image = torch.rand(2, 1, 6, 8, device=device, dtype=dtype)
+ points = image.new_tensor([[[0, 0], [3, 3], [7, 5]]]).expand(2, -1, -1)
+ aug = K.AugmentationSequential(
+ K.RandomCrop((4, 5), padding=2, cropping_mode=cropping_mode),
+ data_keys=["input", "keypoints"],
+ )
+ _, report = audit(aug, image, points)
+ assert report.geometry_status == "available"
+ assert report.spatial[0].roundtrip_max.max().item() < 1e-4
+ assert any("discard image content" in message for message in report.warnings)
+ assert not report.image_reconstruction_evaluated
+
+ @pytest.mark.parametrize("mode", ["bbox", "bbox_xyxy", "bbox_xywh"])
+ def test_box_corner_order(self, device, dtype, mode):
+ image = torch.rand(1, 1, 10, 10, device=device, dtype=dtype)
+ vertices = image.new_tensor([[[[1, 2], [5, 2], [5, 6], [1, 6]]]])
+ box = Boxes(vertices)
+ tensor_mode = {"bbox": "vertices_plus", "bbox_xyxy": "xyxy_plus", "bbox_xywh": "xywh"}[mode]
+ aug = K.AugmentationSequential(K.RandomHorizontalFlip(p=1), data_keys=["input", mode])
+ _, report = audit(aug, image, box.to_tensor(mode=tensor_mode))
+ assert report.spatial[0].metric == "corner_hausdorff"
+ assert report.spatial[0].roundtrip_max.item() < 1e-4
+
+ def test_box_tensor_envelope_loss(self, device, dtype):
+ image = torch.rand(1, 1, 20, 20, device=device, dtype=dtype)
+ boxes = Boxes(image.new_tensor([[[[6, 7], [12, 7], [12, 13], [6, 13]]]]))
+ aug = K.AugmentationSequential(K.RandomRotation((45, 45), p=1), data_keys=["input", "bbox"])
+ _, tensor_report = audit(aug, image, boxes.to_tensor(mode="vertices_plus"))
+ _, object_report = audit(aug, image, boxes)
+ assert tensor_report.spatial[0].roundtrip_max.item() > 1
+ # Half-precision corners are quantized before the float32 diagnostics.
+ # Budget one source-dtype epsilon over the image extent, while retaining
+ # the strict bound for float32/float64 and the >1px envelope-loss check.
+ tolerance = max(1e-4, torch.finfo(dtype).eps * max(image.shape[-2:]))
+ assert object_report.spatial[0].roundtrip_max.item() < tolerance
+ assert any("round-trip error" in warning for warning in tensor_report.warnings)
+
+ def test_detects_actual_spatial_error(self, device, dtype):
+ class BrokenFlip(K.RandomHorizontalFlip):
+ def apply_transform_keypoint(self, input, params, flags, transform=None):
+ return input.clone()
+
+ image = torch.rand(1, 1, 8, 10, device=device, dtype=dtype)
+ aug = K.AugmentationSequential(BrokenFlip(p=1), data_keys=["input", "keypoints"])
+ _, report = audit(aug, image, image.new_tensor([[[1, 2]]]))
+ diagnostic_dtype = torch.float64 if dtype == torch.float64 else torch.float32
+ self.assert_close(report.spatial[0].roundtrip_max, torch.tensor([7], device=device, dtype=diagnostic_dtype))
+ assert "round-trip error" in report.summary()
+
+ def test_nonrigid_silent_identity_is_not_supported(self, device, dtype):
+ image = torch.rand(1, 1, 8, 10, device=device, dtype=dtype)
+ aug = K.AugmentationSequential(K.RandomElasticTransform(p=1), data_keys=["input", "keypoints"])
+ points = image.new_tensor([[[1, 2]]])
+ outputs, report = audit(aug, image, points)
+ self.assert_close(outputs[1], points)
+ assert report.geometry_status == "unsupported"
+ assert report.matrix is None and report.inverse_matrix is None
+ assert report.spatial[0].roundtrip_valid_count.item() == 0
+ assert torch.isnan(report.spatial[0].roundtrip_max).all()
+ assert "non-rigid" in report.summary()
+
+ def test_singular_and_nonfinite_matrices(self, device, dtype):
+ class SingularFlip(K.RandomHorizontalFlip):
+ def compute_transformation(self, input, params, flags):
+ matrix = self.identity_matrix(input)
+ matrix[1, 1, 1] = 0
+ matrix[2, 0, 0] = float("nan")
+ return matrix
+
+ image = torch.rand(3, 1, 8, 10, device=device, dtype=dtype)
+ aug = K.AugmentationSequential(SingularFlip(p=1))
+ _, report = audit(aug, image)
+ assert report.geometry_status == "singular"
+ assert report.invertible.tolist() == [True, False, False]
+ assert report.inverse_matrix[1:].isnan().all()
+ assert json.loads(report.to_json())["matrix"]["values"][2][0][0] is None
+
+ @pytest.mark.parametrize("key, shape", [("keypoints", (2, 0, 2)), ("bbox", (2, 0, 4, 2))])
+ def test_empty_spatial_inputs(self, device, dtype, key, shape):
+ image = torch.rand(2, 1, 8, 10, device=device, dtype=dtype)
+ aug = K.AugmentationSequential(K.RandomHorizontalFlip(p=1), data_keys=["input", key])
+ _, report = audit(aug, image, torch.empty(shape, device=device, dtype=dtype))
+ assert report.spatial[0].count.tolist() == [0, 0]
+ assert report.spatial[0].roundtrip_valid_count.tolist() == [0, 0]
+ assert report.spatial[0].roundtrip_max.isnan().all()
+ assert json.loads(report.to_json())["spatial"][0]["roundtrip_max"]["values"] == [None, None]
+
+ def test_nonfinite_and_boundaries(self, device, dtype):
+ image = torch.rand(1, 1, 8, 10, device=device, dtype=dtype)
+ points = image.new_tensor([[[0, 0], [9, 7], [10, 7], [float("nan"), 0]]])
+ aug = K.AugmentationSequential(torch.nn.Identity(), data_keys=["input", "keypoints"])
+ _, report = audit(aug, image, points)
+ item = report.spatial[0]
+ assert item.count.item() == 4 and item.out_of_frame.item() == 1 and item.nonfinite.item() == 1
+ assert item.out_of_frame_fraction.item() == 0.25 and item.roundtrip_valid_count.item() == 3
+ json.loads(report.to_json())
+
+ def test_snapshots_and_gradients(self, device, dtype):
+ image = torch.rand(2, 1, 8, 10, device=device, dtype=dtype, requires_grad=True)
+ points = image.new_tensor([[[1, 2]], [[1, 2]]]).requires_grad_()
+ aug = K.AugmentationSequential(K.RandomAffine(20, p=1), data_keys=["input", "keypoints"])
+ outputs, report = audit(aug, image, points)
+ audited_grad = torch.autograd.grad(outputs[0].square().sum() + outputs[1].square().sum(), (image, points))
+ serialized = report.to_json()
+ ordinary = aug(image, points, params=report.params)
+ normal_grad = torch.autograd.grad(ordinary[0].square().sum() + ordinary[1].square().sum(), (image, points))
+ for actual, expected in zip(audited_grad, normal_grad):
+ self.assert_close(actual, expected)
+ aug(image, points)
+ assert report.to_json() == serialized
+ assert report.matrix.grad_fn is None
+ assert report.steps[0].matrix.grad_fn is None
+ assert report.params[0].data["translations"].grad_fn is None
+
+ def test_mask_metadata_and_data_key_override(self, device, dtype):
+ image = torch.rand(1, 1, 8, 10, device=device, dtype=dtype)
+ aug = K.AugmentationSequential(K.RandomHorizontalFlip(p=1))
+ outputs, report = audit(aug, image, image.clone(), data_keys=["input", "mask"])
+ self.assert_close(outputs[0], outputs[1])
+ assert report.inputs[1]["data_key"] == "MASK"
+ assert report.configured_extra_args[DataKey.MASK]["resample"] == Resample.NEAREST
+ assert aug.data_keys == [DataKey.INPUT]
+
+ @pytest.mark.parametrize("threshold", [-1.0, float("nan"), float("inf")])
+ def test_invalid_threshold_no_side_effect(self, threshold):
+ aug = K.AugmentationSequential(K.RandomHorizontalFlip())
+ state = torch.random.get_rng_state()
+ with pytest.raises(ValueError, match="roundtrip_tolerance"):
+ audit(aug, torch.ones(1, 1, 8, 8), roundtrip_tolerance=threshold)
+ assert torch.equal(state, torch.random.get_rng_state())
+ assert aug._params is None
+
+ def test_unsupported_inputs_before_execution(self):
+ module = K.RandomHorizontalFlip()
+ aug = K.AugmentationSequential(module)
+ state = torch.random.get_rng_state()
+ for image in [torch.ones(1, 8, 8), torch.ones(0, 1, 8, 8), {"input": torch.ones(1, 1, 8, 8)}]:
+ with pytest.raises(ValueError, match="BCHW"):
+ audit(aug, image)
+ assert torch.equal(state, torch.random.get_rng_state())
+ assert not module._forward_hooks
+
+ def test_hooks_removed_after_failure(self):
+ class FailingModule(torch.nn.Module):
+ def forward(self, input):
+ raise RuntimeError("deliberate failure")
+
+ module = FailingModule()
+ aug = K.AugmentationSequential(module)
+ with pytest.raises(RuntimeError, match="deliberate failure"):
+ audit(aug, torch.ones(1, 1, 8, 8))
+ assert not module._forward_hooks
+
+ def test_reject_shared_aliases_and_video(self):
+ module = K.RandomHorizontalFlip()
+ shared = K.AugmentationSequential(module, module)
+ video = K.AugmentationSequential(K.VideoSequential(K.RandomHorizontalFlip()))
+ for aug in (shared, video):
+ with pytest.raises(ValueError):
+ audit(aug, torch.ones(1, 1, 8, 8))
+ assert not module._forward_hooks
+
+ def test_empty_pipeline(self, device, dtype):
+ image = torch.rand(1, 1, 8, 10, device=device, dtype=dtype)
+ output, report = audit(K.AugmentationSequential(), image)
+ self.assert_close(output, image)
+ assert report.steps == [] and report.params == []
+ assert report.geometry_status == "available"
+ self.assert_close(report.matrix, torch.eye(3, device=device, dtype=report.matrix.dtype).unsqueeze(0))
+
+ def test_random_repeated_sampling(self, device, dtype):
+ image = torch.rand(1, 1, 10, 10, device=device, dtype=dtype)
+ aug = K.AugmentationSequential(K.RandomAffine(20, p=1), random_apply=3)
+ output, report = audit(aug, image)
+ assert [step.occurrence for step in report.steps] == [0, 1, 2]
+ assert len(report.params) == 3
+ self.assert_close(aug(image, params=report.params), output)
+
+ def test_input_box_metadata_and_warning_threshold(self, device, dtype):
+ image = torch.rand(1, 1, 8, 10, device=device, dtype=dtype)
+ boxes = image.new_tensor([[[1, 2, 12, 6]]])
+ aug = K.AugmentationSequential(K.RandomHorizontalFlip(p=1), data_keys=["input", "bbox_xyxy"])
+ _, report = audit(aug, image, boxes, out_of_frame_tolerance=1)
+ assert report.inputs[1]["shape"] == (1, 1, 4)
+ assert report.spatial[0].out_of_frame.item() == 1
+ assert not any("out-of-frame" in warning for warning in report.warnings)
+
+ def test_inverse_projective_horizon_is_invalid(self, device, dtype):
+ class HorizonFlip(K.RandomHorizontalFlip):
+ def compute_transformation(self, input, params, flags):
+ matrix = self.identity_matrix(input)
+ matrix[:, 2, 0] = 1
+ return matrix
+
+ def apply_transform_keypoint(self, input, params, flags, transform=None):
+ return input.clone()
+
+ image = torch.rand(1, 1, 8, 10, device=device, dtype=dtype)
+ aug = K.AugmentationSequential(HorizonFlip(p=1), data_keys=["input", "keypoints"])
+ _, report = audit(aug, image, image.new_tensor([[[1, 2]]]))
+ assert report.geometry_status == "available"
+ assert report.spatial[0].nonfinite.item() == 0
+ assert report.spatial[0].roundtrip_valid_count.item() == 0
+ assert "some round-trip errors are nonfinite" in report.summary()
+
+ def test_unknown_module_is_unavailable(self, device, dtype):
+ aug = K.AugmentationSequential(torch.nn.ReLU())
+ output, report = audit(aug, torch.ones(1, 1, 8, 10, device=device, dtype=dtype))
+ assert output.shape == (1, 1, 8, 10)
+ assert report.geometry_status == "unsupported"
+ assert report.steps[0].unsupported_reason is not None
+
+ def test_reject_ragged_container_objects_before_execution(self, device, dtype):
+ image = torch.ones(2, 1, 8, 10, device=device, dtype=dtype)
+ vertices = image.new_tensor([[[1, 2], [5, 2], [5, 6], [1, 6]], [[2, 3], [6, 3], [6, 7], [2, 7]]])
+ spatial = Boxes([vertices, vertices[:1]])
+ module = K.RandomHorizontalFlip()
+ aug = K.AugmentationSequential(module, data_keys=["input", "bbox"])
+ state = torch.random.get_rng_state()
+ with pytest.raises(ValueError, match="ragged"):
+ audit(aug, image, spatial)
+ assert torch.equal(state, torch.random.get_rng_state())
+ assert aug._params is None
+ assert not module._forward_hooks
+
+ def test_even_median_and_invalid_errors(self, device, dtype):
+ class BrokenFlip(K.RandomHorizontalFlip):
+ def apply_transform_keypoint(self, input, params, flags, transform=None):
+ return input.clone()
+
+ image = torch.rand(1, 1, 8, 10, device=device, dtype=dtype)
+ aug = K.AugmentationSequential(BrokenFlip(p=1), data_keys=["input", "keypoints"])
+ _, report = audit(aug, image, image.new_tensor([[[3, 2], [4, 2], [float("nan"), 2]]]))
+ item = report.spatial[0]
+ assert item.roundtrip_valid_count.item() == 2
+ assert item.roundtrip_mean.item() == 2
+ assert item.roundtrip_median.item() == 2
+ assert item.roundtrip_max.item() == 3
+
+ def test_none_data_keys_requires_explicit_override(self):
+ aug = K.AugmentationSequential(K.RandomHorizontalFlip(), data_keys=None)
+ image = torch.ones(1, 1, 8, 8)
+ with pytest.raises(ValueError, match="data_keys"):
+ audit(aug, image)
+ _, report = audit(aug, image, data_keys=["input"])
+ assert report.geometry_status == "available"
+
+ def test_changed_label_cardinality_cannot_broadcast(self, device, dtype):
+ class DroppingFlip(K.RandomHorizontalFlip):
+ def apply_transform_keypoint(self, input, params, flags, transform=None):
+ return Keypoints(input.data[:, :1])
+
+ image = torch.rand(1, 1, 8, 10, device=device, dtype=dtype)
+ module = DroppingFlip(p=1)
+ aug = K.AugmentationSequential(module, data_keys=["input", "keypoints"])
+ with pytest.raises(ValueError, match=r"spatial.*shape"):
+ audit(aug, image, image.new_tensor([[[3, 2], [4, 2]]]))
+ assert not module._forward_hooks
+
+ @pytest.mark.parametrize("policy_name", ["RandAugment", "AutoAugment", "TrivialAugment"])
+ def test_uncaptured_policy_is_unsupported(self, device, dtype, policy_name):
+ if policy_name == "RandAugment":
+ policy = K.auto.RandAugment(1, 10, policy=[[("rotate", -10.0, 10.0)]])
+ elif policy_name == "AutoAugment":
+ policy = K.auto.AutoAugment(policy=[[("rotate", 1.0, 5)]])
+ else:
+ policy = K.auto.TrivialAugment(policy=[[("rotate", -10.0, 10.0)]])
+ image = torch.rand(1, 1, 8, 10, device=device, dtype=dtype)
+ points = image.new_tensor([[[2, 3]]])
+ aug = K.AugmentationSequential(policy, data_keys=["input", "keypoints"])
+ outputs, report = audit(aug, image, points)
+ assert report.geometry_status == "unsupported"
+ assert report.matrix is None and report.inverse_matrix is None
+ assert not report.invertible.any()
+ assert report.spatial[0].roundtrip_valid_count.item() == 0
+ assert report.steps == []
+ assert policy_name in report.summary() and "capture" in report.summary()
+ replay = aug(image, points, params=report.params)
+ for actual, expected in zip(outputs, replay):
+ self.assert_close(actual, expected)
+
+ def test_missing_hook_with_other_captured_steps(self, device, dtype):
+ class BypassFlip(K.RandomHorizontalFlip):
+ def __call__(self, *args, **kwargs):
+ return self.forward(*args, **kwargs)
+
+ image = torch.rand(1, 1, 8, 10, device=device, dtype=dtype)
+ aug = K.AugmentationSequential(K.RandomVerticalFlip(p=1), BypassFlip(p=1))
+ _, report = audit(aug, image)
+ assert [step.name for step in report.steps] == ["RandomVerticalFlip_0"]
+ assert report.geometry_status == "unsupported"
+ assert "BypassFlip_1" in report.summary()
+
+ def test_repeated_leaf_missing_one_hook(self, device, dtype):
+ class AlternatingFlip(K.RandomHorizontalFlip):
+ calls = 0
+
+ def __call__(self, *args, **kwargs):
+ self.calls += 1
+ return super().__call__(*args, **kwargs) if self.calls % 2 else self.forward(*args, **kwargs)
+
+ image = torch.rand(1, 1, 8, 10, device=device, dtype=dtype)
+ module = AlternatingFlip(p=1)
+ aug = K.AugmentationSequential(module)
+ param = ParamItem("AlternatingFlip_0", module.forward_parameters(image.shape))
+ output, report = audit(aug, image, params=[param, deepcopy(param)])
+ self.assert_close(output, image)
+ assert len(report.steps) == 1
+ assert report.geometry_status == "unsupported"
+ assert "capture" in report.summary()
+
+ def test_captured_order_matches_selected_params(self, device, dtype, monkeypatch):
+ nested = K.ImageSequential(K.RandomHorizontalFlip(p=1), K.RandomVerticalFlip(p=1))
+ original = nested.transform_inputs
+
+ def reverse(input, params, extra_args=None):
+ return original(input, list(reversed(params)), extra_args)
+
+ monkeypatch.setattr(nested, "transform_inputs", reverse)
+ aug = K.AugmentationSequential(nested)
+ _, report = audit(aug, torch.rand(1, 1, 8, 10, device=device, dtype=dtype))
+ assert [step.module for step in report.steps] == ["RandomVerticalFlip", "RandomHorizontalFlip"]
+ assert report.geometry_status == "unsupported"
+ assert "order" in report.summary()
+
+ @pytest.mark.parametrize("with_child", [False, True])
+ def test_custom_sequence_is_opaque(self, device, dtype, with_child):
+ class HiddenGeometry(K.ImageSequential):
+ def transform_inputs(self, input, params, extra_args=None):
+ return super().transform_inputs(input, params, extra_args).flip(-1)
+
+ child = [torch.nn.Identity()] if with_child else []
+ aug = K.AugmentationSequential(HiddenGeometry(*child))
+ image = torch.rand(1, 1, 8, 10, device=device, dtype=dtype)
+ output, report = audit(aug, image)
+ self.assert_close(output, image.flip(-1))
+ assert report.geometry_status == "unsupported"
+ assert "HiddenGeometry_0" in report.summary()
+
+ def test_unselected_opaque_leaf_is_not_missing(self, device, dtype):
+ policy = K.auto.RandAugment(1, 10, policy=[[("rotate", -10.0, 10.0)]])
+ nested = K.ImageSequential(policy, torch.nn.Identity(), random_apply=1, random_apply_weights=[0.0, 1.0])
+ aug = K.AugmentationSequential(nested)
+ image = torch.rand(1, 1, 8, 10, device=device, dtype=dtype)
+ output, report = audit(aug, image)
+ self.assert_close(output, image)
+ assert report.geometry_status == "available"
+ assert [step.name for step in report.steps] == ["ImageSequential_0.Identity_1"]
+ assert not report.warnings
+
+ def test_repeated_nested_uses_each_parameter_tree(self, device, dtype):
+ nested = K.ImageSequential(K.RandomHorizontalFlip(p=1), K.RandomVerticalFlip(p=1))
+ aug = K.AugmentationSequential(nested)
+ image = torch.rand(1, 1, 8, 10, device=device, dtype=dtype)
+ children = nested.forward_parameters(image.shape)
+ params = [ParamItem("ImageSequential_0", [children[0]]), ParamItem("ImageSequential_0", [children[1]])]
+ output, report = audit(aug, image, params=params)
+ self.assert_close(output, image.flip(-1, -2))
+ assert report.geometry_status == "available"
+ assert [step.module for step in report.steps] == ["RandomHorizontalFlip", "RandomVerticalFlip"]
+
+ @pytest.mark.parametrize("nested", [False, True])
+ def test_empty_selected_sequence_stays_available(self, device, dtype, nested):
+ aug = K.AugmentationSequential(K.ImageSequential()) if nested else K.AugmentationSequential(torch.nn.ReLU())
+ image = torch.rand(1, 1, 8, 10, device=device, dtype=dtype)
+ output, report = audit(aug, image, params=None if nested else [])
+ self.assert_close(output, image)
+ assert report.steps == [] and report.geometry_status == "available"
+ assert not report.warnings
+
+ @pytest.mark.parametrize("name", ["Resize", "LongestMaxSize"])
+ def test_downsampling_content_warning(self, device, dtype, name):
+ module = K.Resize((4, 5)) if name == "Resize" else K.LongestMaxSize(5)
+ aug = K.AugmentationSequential(module)
+ _, report = audit(aug, torch.rand(1, 1, 8, 10, device=device, dtype=dtype))
+ assert report.geometry_status == "available"
+ assert any("downsampling" in warning for warning in report.warnings)
+ assert not report.image_reconstruction_evaluated
+
+ @pytest.mark.parametrize("cropping_mode", ["slice", "resample"])
+ @pytest.mark.parametrize(
+ "p, batch_prob",
+ [
+ (0.0, None),
+ (1.0, None),
+ (0.5, [0.0, 0.0]),
+ (0.5, [0.0, 1.0]),
+ (0.5, [1.0, 1.0]),
+ (1.0, [0.0, 1.0]),
+ ],
+ )
+ @pytest.mark.parametrize(
+ "size, padding, pad_if_needed",
+ [
+ ((4, 8), None, False),
+ ((4, 8), (1, 2), False),
+ ((6, 10), (1, 2, 3, 0), False),
+ ((8, 12), None, True),
+ ],
+ )
+ def test_crop_matrix_tracks_actual_pixels(
+ self, device, dtype, cropping_mode, p, batch_prob, size, padding, pad_if_needed
+ ):
+ image = torch.zeros(2, 1, 6, 10, device=device, dtype=dtype)
+ image[:, 0, 1, 3] = 1 # An independent image landmark at keypoint (3, 1).
+ points = image.new_tensor([[[3, 1]], [[3, 1]]])
+ boxes = Boxes(image.new_tensor([[[[2, 1], [3, 1], [3, 2], [2, 2]]]]).expand(2, -1, -1, -1).clone())
+ module = K.RandomCrop(
+ size, padding=padding, pad_if_needed=pad_if_needed, p=p, cropping_mode=cropping_mode, resample="nearest"
+ )
+ params = module.forward_parameters(image.shape)
+ if batch_prob is not None:
+ params["batch_prob"] = image.new_tensor(batch_prob)
+ pad = params["padding_size"][0].tolist()
+ x = min(1, image.shape[-1] + pad[0] + pad[1] - size[1])
+ y = min(1, image.shape[-2] + pad[2] + pad[3] - size[0])
+ params["src"] = (
+ image.new_tensor([[[x, y], [x + size[1] - 1, y], [x + size[1] - 1, y + size[0] - 1], [x, y + size[0] - 1]]])
+ .expand(2, -1, -1)
+ .clone()
+ )
+ aug = K.AugmentationSequential(module, data_keys=["input", "keypoints", "bbox"])
+ outputs, report = audit(aug, image, points, boxes, params=[ParamItem("RandomCrop_0", params)])
+ selected = params["batch_prob"] > 0.5
+ static = p == 1.0
+ all_transformed = static or (size != image.shape[-2:] and bool(selected.any()))
+ transformed = torch.ones_like(selected) if all_transformed else selected
+ padded = torch.nn.functional.pad(image, pad)
+ expected_images = []
+ image_shift = image.new_zeros((2, 2))
+ for row in range(2):
+ if transformed[row]:
+ # Slice ignores the cached matrix; resample uses its per-row identity/crop selection.
+ use_crop = cropping_mode == "slice" or static or bool(selected[row])
+ left, top = (x, y) if use_crop else (0, 0)
+ expected_images.append(padded[row, :, top : top + size[0], left : left + size[1]])
+ image_shift[row] = image.new_tensor([pad[0] - left, pad[2] - top])
+ else:
+ expected_images.append(image[row])
+ self.assert_close(outputs[0], torch.stack(expected_images))
+ for row in range(2):
+ destination = points[row, 0] + image_shift[row]
+ assert outputs[0][row, 0, int(destination[1]), int(destination[0])].item() == 1
+ ambiguous_slice = cropping_mode == "slice" and all_transformed and not static and not bool(selected.all())
+ if ambiguous_slice:
+ assert report.geometry_status == "unsupported"
+ assert report.matrix is None and "slice" in report.summary()
+ else:
+ assert report.geometry_status == "available"
+ diagnostic_dtype = torch.float64 if dtype == torch.float64 else torch.float32
+ self.assert_close(report.matrix[:, :2, 2], image_shift.to(diagnostic_dtype))
+ # Measure against the observed pixel mapping. Manually mixed rows can still
+ # return untransformed labels beside a transformed image.
+ restored_points = outputs[1][:, 0].to(diagnostic_dtype) - image_shift.to(diagnostic_dtype)
+ error = torch.linalg.vector_norm(restored_points - points[:, 0].to(diagnostic_dtype), dim=-1)
+ self.assert_close(report.spatial[0].roundtrip_max, error)
+ restored_boxes = outputs[2].data.to(diagnostic_dtype) - image_shift[:, None, None, :].to(diagnostic_dtype)
+ box_error = (
+ torch.linalg.vector_norm(restored_boxes - boxes.data.to(diagnostic_dtype), dim=-1).amax(-1).amax(-1)
+ )
+ self.assert_close(report.spatial[1].roundtrip_max, box_error)
+ if bool((error > report.roundtrip_tolerance).any()):
+ assert "round-trip error exceeds" in report.summary()
+ if batch_prob is None or bool(selected.all()) or not bool(selected.any()):
+ # Whole-batch application or skip keeps labels aligned with the image (#4473).
+ self.assert_close(error, torch.zeros_like(error))
+
+ @pytest.mark.parametrize("configured, effective", [("resample", "slice"), ("slice", "resample")])
+ def test_crop_effective_mode_override(self, device, dtype, configured, effective):
+ image = torch.zeros(2, 1, 6, 10, device=device, dtype=dtype)
+ image[:, 0, 1, 3] = 1
+ module = K.RandomCrop((4, 8), padding=(1, 2), p=0.5, cropping_mode=configured, resample="nearest")
+ params = module.forward_parameters(image.shape)
+ params["batch_prob"] = image.new_tensor([0, 1])
+ params["src"] = image.new_tensor([[[1, 1], [8, 1], [8, 4], [1, 4]]]).expand(2, -1, -1).clone()
+ aug = K.AugmentationSequential(
+ module, data_keys=["input", "keypoints"], extra_args={DataKey.INPUT: {"cropping_mode": effective}}
+ )
+ outputs, report = audit(
+ aug, image, image.new_tensor([[[3, 1]], [[3, 1]]]), params=[ParamItem("RandomCrop_0", params)]
+ )
+ assert report.steps[0].flags["cropping_mode"] == effective
+ assert module.flags["cropping_mode"] == configured
+ assert outputs[0][1, 0, 2, 3].item() == 1
+ if effective == "slice":
+ assert outputs[0][0, 0, 2, 3].item() == 1
+ assert report.geometry_status == "unsupported" and report.matrix is None
+ else:
+ assert outputs[0][0, 0, 3, 4].item() == 1
+ assert report.geometry_status == "available"
+ self.assert_close(report.matrix[:, :2, 2], report.matrix.new_tensor([[1, 2], [0, 1]]))