Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

fix(geometry): handle singleton normalization axes (#4006)

Dmytro Mishkin4dd9c6aa7362
diff --git a/.github/workflows/pr_test_cpu.yml b/.github/workflows/pr_test_cpu.yml
index 41ef867e1..4ea7bd658 100644
--- a/.github/workflows/pr_test_cpu.yml
+++ b/.github/workflows/pr_test_cpu.yml
@@ -147,7 +147,7 @@ jobs:
pytorch-version: '["2.9.1"]'
pytorch-dtype: float32
optimizer: inductor
- pytest-extra: 'tests/augmentation tests/enhance tests/filters tests/color tests/losses tests/morphology -k "dynamo or compile"'
+ pytest-extra: 'tests/augmentation tests/enhance tests/filters tests/color tests/geometry tests/losses tests/morphology -k "dynamo or compile"'
cache-path: weights/
cache-key: model-weights-${{ needs.pre-tests.outputs.hash }}
cache-restore-keys: |
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 5706f524f..61f8c1cd4 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -6,6 +6,28 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
****
+## Unreleased
+
+### Bug fixes
+
+* Define singleton pixel axes at normalized center, reject non-positive normalization sizes, preserve empty warp
+ destinations, and deprecate the now-unused `eps` normalization parameters (#4006). The four
+ `{de,}normalize_pixel_coordinates{,3d}` helpers and `normal_transform_pixel{,3d}` now derive their scale from the
+ size directly instead of rounding the size into the coordinate dtype first, so results at non-degenerate sizes can
+ move toward the exact value: by up to one ulp in `float32`/`float64`, but materially more in `float16`/`bfloat16`,
+ where the old code could not represent the size at all (`denormalize_pixel_coordinates` at `bfloat16` and size 3000
+ returns 1496 where it returned 1504).
+
+ A singleton axis previously divided by zero (or by the `eps` substituted for it), so the change is not confined to
+ those helpers: it reaches every operation that normalizes a coordinate frame with a size-1 dimension.
+ `create_meshgrid(1, 4, normalized_coordinates=True)` returned `nan` in the singleton component and now returns `0`;
+ `warp_perspective`, `crop_by_transform_mat`, `homography_warp` and `warp_image_tps` onto a 1-pixel-high destination
+ returned all-`nan` and now return the finite row the 2-pixel control produces; `spatial_soft_argmax2d` and
+ `spatial_expectation2d` on a 1-pixel-high input returned `nan` and now return `0`; and `conv_soft_argmax2d`,
+ `conv_soft_argmax3d` and their `ConvSoftArgmax*` module forms shift by one normalized unit when a kernel or input
+ axis is `1` (`conv_soft_argmax2d` with a `(3, 1)` kernel returned `[-1.6667, -1.0, ...]` and now returns
+ `[-1.0, -0.3333, ...]`).
+
## :rocket: [0.6.11] - 2022-03-28
### :new: New Features
diff --git a/kornia/geometry/conversions.py b/kornia/geometry/conversions.py
index fa8c2c1f4..fba730675 100644
--- a/kornia/geometry/conversions.py
+++ b/kornia/geometry/conversions.py
@@ -17,6 +17,7 @@
from __future__ import annotations
+import warnings
from typing import Optional
import torch
@@ -1456,22 +1457,28 @@ def normalize_pixel_coordinates(
explicitly when feeding this output to it. Note that kornia's own
:func:`~kornia.geometry.transform.remap` resolves
``align_corners=None`` to ``False``
+ - a singleton axis uses scale ``1`` and offset ``0``: its only valid
+ pixel coordinate maps to the normalized centre, and the unit-scale
+ extension keeps this function exactly invertible outside that lone
+ valid coordinate. Zero and negative sizes raise ``ValueError``
- the output is **not** clamped: coordinates outside the image
extrapolate linearly past ``[-1, 1]``, as the example below shows
- .. warning::
- ``height`` and ``width`` are not validated. For a degenerate size (``1``,
- ``0`` or negative) the denominator ``size - 1`` is clamped up to ``eps``,
- so
- ``normalize_pixel_coordinates(torch.tensor([[1., 1.]], dtype=torch.float64), 1, 1)``
- silently returns ``[[199999999.0, 199999999.0]]`` instead of raising.
- Tracked in `#3940 <https://github.com/kornia/kornia/issues/3940>`_.
+ .. note::
+ Legacy ``torch.jit.trace`` graphs assume positive runtime sizes because
+ tracing cannot retain the Python ``ValueError`` validation. Eager,
+ TorchScript, and ``torch.compile`` calls validate sizes.
+
+ .. deprecated:: 0.9.0
+ ``eps`` no longer participates in the explicitly defined singleton-axis
+ mapping. Passing a non-default value warns in eager mode; the parameter
+ will be removed in a future breaking release.
Args:
pixel_coordinates: the grid with pixel coordinates. Shape can be :math:`(*, 2)`.
height: the maximum height in the y-axis.
width: the maximum width in the x-axis.
- eps: safe division by zero.
+ eps: deprecated compatibility parameter. It is ignored.
Return:
the normalized pixel coordinates with shape :math:`(*, 2)`.
@@ -1484,20 +1491,50 @@ def normalize_pixel_coordinates(
"""
if pixel_coordinates.shape[-1] != 2:
raise ValueError(f"Input pixel_coordinates must be of shape (*, 2). Got {pixel_coordinates.shape}")
+ if not torch.jit.is_tracing() and (height <= 0 or width <= 0):
+ raise ValueError(f"Input image size must be positive. Got height={height}, width={width}.")
+ if (
+ not torch.jit.is_scripting()
+ and not torch.jit.is_tracing()
+ and not torch.compiler.is_compiling()
+ and eps != 1e-8
+ ):
+ warnings.warn("`eps` is deprecated and ignored by `normalize_pixel_coordinates`.", FutureWarning, stacklevel=2)
+
+ if torch.jit.is_scripting() or (not torch.jit.is_tracing() and not torch.compiler.is_compiling()):
+ sx = 1.0 if width == 1 else 2.0 / (width - 1.0)
+ sy = 1.0 if height == 1 else 2.0 / (height - 1.0)
+ tx = 0.0 if width == 1 else -1.0
+ ty = 0.0 if height == 1 else -1.0
+ if torch.jit.is_scripting():
+ anchor = torch.ones((), device=pixel_coordinates.device, dtype=pixel_coordinates.dtype)
+ factor = torch.stack([anchor * sx, anchor * sy])
+ offset = torch.stack([anchor * tx, anchor * ty])
+ else:
+ work_dtype = pixel_coordinates.dtype if pixel_coordinates.is_floating_point() else torch.get_default_dtype()
+ factor = torch.tensor([sx, sy], device=pixel_coordinates.device, dtype=work_dtype)
+ offset = torch.tensor([tx, ty], device=pixel_coordinates.device, dtype=work_dtype)
+ else:
+ out_dtype = pixel_coordinates.dtype if pixel_coordinates.is_floating_point() else torch.get_default_dtype()
+ # Low-precision floating types cannot represent every practical image size exactly
+ # (e.g. bfloat16 rounds 257 to 256). Keep the symbolic size arithmetic in at least
+ # float32, then cast the finished factors back to the coordinate dtype.
+ work_dtype = torch.float32 if out_dtype in (torch.float16, torch.bfloat16) else out_dtype
+ width_t = torch.scalar_tensor(width, device=pixel_coordinates.device, dtype=work_dtype)
+ height_t = torch.scalar_tensor(height, device=pixel_coordinates.device, dtype=work_dtype)
+ one = torch.ones((), device=pixel_coordinates.device, dtype=work_dtype)
+ zero = torch.zeros((), device=pixel_coordinates.device, dtype=work_dtype)
+ factor = torch.stack(
+ [
+ torch.where(width_t == 1, one, 2.0 / (width_t - 1.0)),
+ torch.where(height_t == 1, one, 2.0 / (height_t - 1.0)),
+ ]
+ )
+ offset = torch.stack([torch.where(width_t == 1, zero, -one), torch.where(height_t == 1, zero, -one)])
+ factor = factor.to(out_dtype)
+ offset = offset.to(out_dtype)
- # compute normalization factor
- hw: torch.Tensor = torch.stack(
- [
- torch.tensor(width, device=pixel_coordinates.device, dtype=pixel_coordinates.dtype),
- torch.tensor(height, device=pixel_coordinates.device, dtype=pixel_coordinates.dtype),
- ]
- )
-
- factor: torch.Tensor = torch.tensor(2.0, device=pixel_coordinates.device, dtype=pixel_coordinates.dtype) / (
- hw - 1
- ).clamp(eps)
-
- return factor * pixel_coordinates - 1
+ return factor * pixel_coordinates + offset
def denormalize_pixel_coordinates(
@@ -1514,23 +1551,14 @@ def denormalize_pixel_coordinates(
component order and the same ``(pixel_coordinates, height, width)``
positional order
- .. warning::
- For a degenerate ``height``/``width`` (``1``, ``0`` or negative) the
- clamped denominator collapses that component instead of exploding it:
- ``denormalize_pixel_coordinates(torch.tensor([[0., 0.]], dtype=torch.float64), 4, 1)``
- returns ``[[5e-09, 1.5]]``. This clamp is the exact reciprocal of the one
- in :func:`~kornia.geometry.conversions.normalize_pixel_coordinates`, so a
- normalize-then-denormalize round trip returns the input as long as the
- normalized value is finite β€” in ``float16`` ``eps`` underflows, the
- normalized component is ``inf`` and the round trip returns ``nan``; it
- is a single call on its own that is wrong. Tracked in
- `#3940 <https://github.com/kornia/kornia/issues/3940>`_.
+ - singleton axes, non-positive-size validation, tracing assumptions, and
+ the deprecated ``eps`` parameter follow the normalization function
Args:
pixel_coordinates: the normalized grid coordinates. Shape can be :math:`(*, 2)`.
height: the maximum height in the y-axis.
width: the maximum width in the x-axis.
- eps: safe division by zero.
+ eps: deprecated compatibility parameter. It is ignored.
Return:
the denormalized pixel coordinates with shape :math:`(*, 2)`.
@@ -1543,16 +1571,51 @@ def denormalize_pixel_coordinates(
"""
if pixel_coordinates.shape[-1] != 2:
raise ValueError(f"Input pixel_coordinates must be of shape (*, 2). Got {pixel_coordinates.shape}")
- # compute normalization factor
- hw: torch.Tensor = (
- torch.stack([torch.tensor(width), torch.tensor(height)])
- .to(pixel_coordinates.device)
- .to(pixel_coordinates.dtype)
- )
-
- factor: torch.Tensor = torch.tensor(2.0) / (hw - 1).clamp(eps)
+ if not torch.jit.is_tracing() and (height <= 0 or width <= 0):
+ raise ValueError(f"Input image size must be positive. Got height={height}, width={width}.")
+ if (
+ not torch.jit.is_scripting()
+ and not torch.jit.is_tracing()
+ and not torch.compiler.is_compiling()
+ and eps != 1e-8
+ ):
+ warnings.warn(
+ "`eps` is deprecated and ignored by `denormalize_pixel_coordinates`.",
+ FutureWarning,
+ stacklevel=2,
+ )
- return torch.tensor(1.0) / factor * (pixel_coordinates + 1)
+ if torch.jit.is_scripting() or (not torch.jit.is_tracing() and not torch.compiler.is_compiling()):
+ sx = 1.0 if width == 1 else (width - 1.0) / 2.0
+ sy = 1.0 if height == 1 else (height - 1.0) / 2.0
+ tx = 0.0 if width == 1 else sx
+ ty = 0.0 if height == 1 else sy
+ if torch.jit.is_scripting():
+ anchor = torch.ones((), device=pixel_coordinates.device, dtype=pixel_coordinates.dtype)
+ factor = torch.stack([anchor * sx, anchor * sy])
+ offset = torch.stack([anchor * tx, anchor * ty])
+ else:
+ work_dtype = pixel_coordinates.dtype if pixel_coordinates.is_floating_point() else torch.get_default_dtype()
+ factor = torch.tensor([sx, sy], device=pixel_coordinates.device, dtype=work_dtype)
+ offset = torch.tensor([tx, ty], device=pixel_coordinates.device, dtype=work_dtype)
+ else:
+ out_dtype = pixel_coordinates.dtype if pixel_coordinates.is_floating_point() else torch.get_default_dtype()
+ # Low-precision floating types cannot represent every practical image size exactly
+ # (e.g. bfloat16 rounds 257 to 256). Keep the symbolic size arithmetic in at least
+ # float32, then cast the finished factors back to the coordinate dtype.
+ work_dtype = torch.float32 if out_dtype in (torch.float16, torch.bfloat16) else out_dtype
+ width_t = torch.scalar_tensor(width, device=pixel_coordinates.device, dtype=work_dtype)
+ height_t = torch.scalar_tensor(height, device=pixel_coordinates.device, dtype=work_dtype)
+ one = torch.ones((), device=pixel_coordinates.device, dtype=work_dtype)
+ zero = torch.zeros((), device=pixel_coordinates.device, dtype=work_dtype)
+ sx_t = torch.where(width_t == 1, one, (width_t - 1.0) / 2.0)
+ sy_t = torch.where(height_t == 1, one, (height_t - 1.0) / 2.0)
+ factor = torch.stack([sx_t, sy_t])
+ offset = torch.stack([torch.where(width_t == 1, zero, sx_t), torch.where(height_t == 1, zero, sy_t)])
+ factor = factor.to(out_dtype)
+ offset = offset.to(out_dtype)
+
+ return factor * pixel_coordinates + offset
def normalize_pixel_coordinates3d(
@@ -1571,20 +1634,15 @@ def normalize_pixel_coordinates3d(
``(pixel_coordinates, depth, height, width)``
- corner-aligned and unclamped in each axis exactly as in
:func:`~kornia.geometry.conversions.normalize_pixel_coordinates`
-
- .. warning::
- ``depth``, ``height`` and ``width`` are not validated; a degenerate size
- (``1``, ``0`` or negative) clamps that axis' denominator up to ``eps``
- and blows the corresponding component up by a factor of ``2e8``
- (``inf`` in ``float16``, where ``eps`` underflows). Tracked
- in `#3940 <https://github.com/kornia/kornia/issues/3940>`_.
+ - singleton axes, non-positive-size validation, tracing assumptions, and
+ the deprecated ``eps`` parameter likewise follow that function
Args:
pixel_coordinates: the grid with pixel coordinates. Shape can be :math:`(*, 3)`.
depth: the maximum depth in the z-axis.
height: the maximum height in the y-axis.
width: the maximum width in the x-axis.
- eps: safe division by zero.
+ eps: deprecated compatibility parameter. It is ignored.
Return:
the normalized pixel coordinates.
@@ -1592,16 +1650,64 @@ def normalize_pixel_coordinates3d(
"""
if pixel_coordinates.shape[-1] != 3:
raise ValueError(f"Input pixel_coordinates must be of shape (*, 3). Got {pixel_coordinates.shape}")
- # compute normalization factor
- dhw: torch.Tensor = (
- torch.stack([torch.tensor(depth), torch.tensor(width), torch.tensor(height)])
- .to(pixel_coordinates.device)
- .to(pixel_coordinates.dtype)
- )
+ if not torch.jit.is_tracing() and (depth <= 0 or height <= 0 or width <= 0):
+ raise ValueError(f"Input image size must be positive. Got depth={depth}, height={height}, width={width}.")
+ if (
+ not torch.jit.is_scripting()
+ and not torch.jit.is_tracing()
+ and not torch.compiler.is_compiling()
+ and eps != 1e-8
+ ):
+ warnings.warn(
+ "`eps` is deprecated and ignored by `normalize_pixel_coordinates3d`.",
+ FutureWarning,
+ stacklevel=2,
+ )
- factor: torch.Tensor = torch.tensor(2.0) / (dhw - 1).clamp(eps)
+ if torch.jit.is_scripting() or (not torch.jit.is_tracing() and not torch.compiler.is_compiling()):
+ sd = 1.0 if depth == 1 else 2.0 / (depth - 1.0)
+ sx = 1.0 if width == 1 else 2.0 / (width - 1.0)
+ sy = 1.0 if height == 1 else 2.0 / (height - 1.0)
+ td = 0.0 if depth == 1 else -1.0
+ tx = 0.0 if width == 1 else -1.0
+ ty = 0.0 if height == 1 else -1.0
+ if torch.jit.is_scripting():
+ anchor = torch.ones((), device=pixel_coordinates.device, dtype=pixel_coordinates.dtype)
+ factor = torch.stack([anchor * sd, anchor * sx, anchor * sy])
+ offset = torch.stack([anchor * td, anchor * tx, anchor * ty])
+ else:
+ work_dtype = pixel_coordinates.dtype if pixel_coordinates.is_floating_point() else torch.get_default_dtype()
+ factor = torch.tensor([sd, sx, sy], device=pixel_coordinates.device, dtype=work_dtype)
+ offset = torch.tensor([td, tx, ty], device=pixel_coordinates.device, dtype=work_dtype)
+ else:
+ out_dtype = pixel_coordinates.dtype if pixel_coordinates.is_floating_point() else torch.get_default_dtype()
+ # Low-precision floating types cannot represent every practical image size exactly
+ # (e.g. bfloat16 rounds 257 to 256). Keep the symbolic size arithmetic in at least
+ # float32, then cast the finished factors back to the coordinate dtype.
+ work_dtype = torch.float32 if out_dtype in (torch.float16, torch.bfloat16) else out_dtype
+ depth_t = torch.scalar_tensor(depth, device=pixel_coordinates.device, dtype=work_dtype)
+ width_t = torch.scalar_tensor(width, device=pixel_coordinates.device, dtype=work_dtype)
+ height_t = torch.scalar_tensor(height, device=pixel_coordinates.device, dtype=work_dtype)
+ one = torch.ones((), device=pixel_coordinates.device, dtype=work_dtype)
+ zero = torch.zeros((), device=pixel_coordinates.device, dtype=work_dtype)
+ factor = torch.stack(
+ [
+ torch.where(depth_t == 1, one, 2.0 / (depth_t - 1.0)),
+ torch.where(width_t == 1, one, 2.0 / (width_t - 1.0)),
+ torch.where(height_t == 1, one, 2.0 / (height_t - 1.0)),
+ ]
+ )
+ offset = torch.stack(
+ [
+ torch.where(depth_t == 1, zero, -one),
+ torch.where(width_t == 1, zero, -one),
+ torch.where(height_t == 1, zero, -one),
+ ]
+ )
+ factor = factor.to(out_dtype)
+ offset = offset.to(out_dtype)
- return factor * pixel_coordinates - 1
+ return factor * pixel_coordinates + offset
def denormalize_pixel_coordinates3d(
@@ -1617,21 +1723,15 @@ def denormalize_pixel_coordinates3d(
``depth=3, height=5, width=9`` the input ``[0., 0., 0.]`` maps back to
``[1., 4., 2.]``
- .. warning::
- For a degenerate ``depth``/``height``/``width`` (``1``, ``0`` or
- negative) the clamped denominator scales that component by ``5e-09``
- (``0`` in ``float16``, where ``eps`` underflows) instead of by
- ``(size - 1) / 2`` β€” the same reciprocal-clamp behavior as
- :func:`~kornia.geometry.conversions.denormalize_pixel_coordinates`,
- whose warning walks through the round trip. Tracked in
- `#3940 <https://github.com/kornia/kornia/issues/3940>`_.
+ - singleton axes, non-positive-size validation, tracing assumptions, and
+ the deprecated ``eps`` parameter follow the 2-D counterpart
Args:
pixel_coordinates: the normalized grid coordinates. Shape can be :math:`(*, 3)`.
depth: the maximum depth in the z-axis.
height: the maximum height in the y-axis.
width: the maximum width in the x-axis.
- eps: safe division by zero.
+ eps: deprecated compatibility parameter. It is ignored.
Return:
the denormalized pixel coordinates.
@@ -1639,16 +1739,61 @@ def denormalize_pixel_coordinates3d(
"""
if pixel_coordinates.shape[-1] != 3:
raise ValueError(f"Input pixel_coordinates must be of shape (*, 3). Got {pixel_coordinates.shape}")
- # compute normalization factor
- dhw: torch.Tensor = (
- torch.stack([torch.tensor(depth), torch.tensor(width), torch.tensor(height)])
- .to(pixel_coordinates.device)
- .to(pixel_coordinates.dtype)
- )
+ if not torch.jit.is_tracing() and (depth <= 0 or height <= 0 or width <= 0):
+ raise ValueError(f"Input image size must be positive. Got depth={depth}, height={height}, width={width}.")
+ if (
+ not torch.jit.is_scripting()
+ and not torch.jit.is_tracing()
+ and not torch.compiler.is_compiling()
+ and eps != 1e-8
+ ):
+ warnings.warn(
+ "`eps` is deprecated and ignored by `denormalize_pixel_coordinates3d`.",
+ FutureWarning,
+ stacklevel=2,
+ )
- factor: torch.Tensor = torch.tensor(2.0) / (dhw - 1).clamp(eps)
+ if torch.jit.is_scripting() or (not torch.jit.is_tracing() and not torch.compiler.is_compiling()):
+ sd = 1.0 if depth == 1 else (depth - 1.0) / 2.0
+ sx = 1.0 if width == 1 else (width - 1.0) / 2.0
+ sy = 1.0 if height == 1 else (height - 1.0) / 2.0
+ td = 0.0 if depth == 1 else sd
+ tx = 0.0 if width == 1 else sx
+ ty = 0.0 if height == 1 else sy
+ if torch.jit.is_scripting():
+ anchor = torch.ones((), device=pixel_coordinates.device, dtype=pixel_coordinates.dtype)
+ factor = torch.stack([anchor * sd, anchor * sx, anchor * sy])
+ offset = torch.stack([anchor * td, anchor * tx, anchor * ty])
+ else:
+ work_dtype = pixel_coordinates.dtype if pixel_coordinates.is_floating_point() else torch.get_default_dtype()
+ factor = torch.tensor([sd, sx, sy], device=pixel_coordinates.device, dtype=work_dtype)
+ offset = torch.tensor([td, tx, ty], device=pixel_coordinates.device, dtype=work_dtype)
+ else:
+ out_dtype = pixel_coordinates.dtype if pixel_coordinates.is_floating_point() else torch.get_default_dtype()
+ # Low-precision floating types cannot represent every practical image size exactly
+ # (e.g. bfloat16 rounds 257 to 256). Keep the symbolic size arithmetic in at least
+ # float32, then cast the finished factors back to the coordinate dtype.
+ work_dtype = torch.float32 if out_dtype in (torch.float16, torch.bfloat16) else out_dtype
+ depth_t = torch.scalar_tensor(depth, device=pixel_coordinates.device, dtype=work_dtype)
+ width_t = torch.scalar_tensor(width, device=pixel_coordinates.device, dtype=work_dtype)
+ height_t = torch.scalar_tensor(height, device=pixel_coordinates.device, dtype=work_dtype)
+ one = torch.ones((), device=pixel_coordinates.device, dtype=work_dtype)
+ zero = torch.zeros((), device=pixel_coordinates.device, dtype=work_dtype)
+ sd_t = torch.where(depth_t == 1, one, (depth_t - 1.0) / 2.0)
+ sx_t = torch.where(width_t == 1, one, (width_t - 1.0) / 2.0)
+ sy_t = torch.where(height_t == 1, one, (height_t - 1.0) / 2.0)
+ factor = torch.stack([sd_t, sx_t, sy_t])
+ offset = torch.stack(
+ [
+ torch.where(depth_t == 1, zero, sd_t),
+ torch.where(width_t == 1, zero, sx_t),
+ torch.where(height_t == 1, zero, sy_t),
+ ]
+ )
+ factor = factor.to(out_dtype)
+ offset = offset.to(out_dtype)
- return torch.tensor(1.0) / factor * (pixel_coordinates + 1)
+ return factor * pixel_coordinates + offset
def angle_to_rotation_matrix(angle: torch.Tensor) -> torch.Tensor:
@@ -1783,26 +1928,6 @@ def normalize_homography(
is the point, not the digits. Tracked in
`#3958 <https://github.com/kornia/kornia/issues/3958>`_.
- .. warning::
- Scope: the degenerate-denominator branch only, as delimited in
- :func:`~kornia.geometry.conversions.normal_transform_pixel`'s
- degenerate-size warning. Neither ``dsize`` is validated, so
- :func:`~kornia.geometry.conversions.normal_transform_pixel`'s
- degenerate sizes propagate straight into the homography. On the
- identity, holding the other size at ``(4, 5)``: a **source** ``dsize``
- of ``(4, 1)`` collapses the ``x`` scale to ``2.500000167887412e-15``,
- the same ``(4, 1)`` as the **destination** blows it up to the reciprocal
- ``400000001507328.0``, and a size of ``0`` silently mirrors that axis
- (source ``(4, 0)``, destination ``(4, 5)``, first row
- ``[-0.25, 0.0, -1.25]``). Those three figures pass through ``matmul``
- and an inverse, so their trailing digits are backend-dependent; the
- orders of magnitude are the point. This is the
- executed root of 1-pixel warp outputs coming back all-``nan`` on cpu
- and mps β€” the devices executed; no CUDA behavior is claimed. Tracked
- in
- `#3957 <https://github.com/kornia/kornia/issues/3957>`_ and, for the
- symptom, `#3929 <https://github.com/kornia/kornia/issues/3929>`_.
-
.. warning::
Integer inputs are handled inconsistently and the inconsistency is
device-dependent: on cpu (torch 2.9.1) an ``int64`` call raises
@@ -1920,11 +2045,7 @@ def normal_transform_pixel(
**not**
:func:`torch.nn.functional.grid_sample`'s default half-pixel
``(2 * x + 1) / width - 1``, which would put column ``0`` of a 5-wide
- image at ``-0.8`` rather than ``-1.0``. At the degenerate sizes the
- two diverge outright β€” they clamp through different ``eps``
- mechanisms, ``2e14``-scale here against ``2e8``-scale there at
- ``size == 1``, and with opposite signs at ``size == 0`` (executed; see
- the warning below)
+ image at ``-0.8`` rather than ``-1.0``
- *how far apart the two routes get, and why* β€” a measurement of the
build's matmul kernel rather than a statement about the convention;
skip it unless a reduced-precision difference is what brought you
@@ -1953,32 +2074,16 @@ def normal_transform_pixel(
``align_corners`` parameter β€” and
:func:`~kornia.geometry.conversions.normalize_homography` and its
siblings inherit it; see the convention warning there
+ - a singleton axis maps its only pixel to the centre of the normalized
+ range: that axis uses scale ``1`` and offset ``0``. The unit scale is
+ an invertible extension outside the lone valid coordinate, allowing
+ homography composition to handle one-pixel source and destination
+ sizes. Zero and negative sizes raise ``ValueError``
- with ``dtype=None`` the matrix is built from Python floats, so it
takes ``torch.get_default_dtype()``: ``float32`` by default, and
``float64`` under ``torch.set_default_dtype(torch.float64)``. An
explicit ``dtype=`` overrides that
- .. warning::
- This paragraph is about the degenerate-denominator branch only, not
- about the ``2 / (size - 1)`` scaling or the corner-aligned convention,
- which are `#3904 <https://github.com/kornia/kornia/issues/3904>`_'s
- territory. ``height`` and ``width`` are not validated. A size of ``1``
- takes the ``eps`` branch,
- so with the default ``eps = 1e-14`` the scale becomes ``2 / eps``:
- ``normal_transform_pixel(4, 1)`` has ``sx = 200000000753664.0``, finite
- and silent. A size of ``0`` divides by ``-1`` instead and gives
- ``sx = -2.0``, a mirroring transform, and negative sizes are accepted
- too (``width = -3`` gives ``-0.5``). ``eps`` is consulted **only** in
- the ``size == 1`` branch, so it does not guard the ``size == 0`` case;
- raising it to ``eps=1.0`` changes the ``size == 1`` scale to ``2.0`` and
- leaves the ``size == 0`` scale at ``-2.0``. The blow-up reaches users:
- an identity :func:`~kornia.geometry.transform.warp_perspective` onto a
- 1-pixel-high output is all-``nan`` at ``align_corners=True``, where the
- 2-pixel-high control is finite (executed on cpu and mps; no CUDA
- behavior is claimed). Tracked in
- `#3957 <https://github.com/kornia/kornia/issues/3957>`_ and, for the
- symptom, `#3929 <https://github.com/kornia/kornia/issues/3929>`_.
-
.. warning::
An integer ``dtype`` truncates the scale instead of raising:
``normal_transform_pixel(4, 5, dtype=torch.int64)`` returns
@@ -1986,11 +2091,20 @@ def normal_transform_pixel(
constant ``(-1, -1)``. Tracked in
`#3959 <https://github.com/kornia/kornia/issues/3959>`_.
+ .. note::
+ Legacy ``torch.jit.trace`` graphs assume positive runtime sizes because
+ tracing cannot retain the Python ``ValueError`` validation. Eager,
+ TorchScript, and ``torch.compile`` calls validate sizes.
+
+ .. deprecated:: 0.9.0
+ ``eps`` no longer participates in the explicitly defined singleton-axis
+ mapping. Passing a non-default value warns in eager mode; the parameter
+ will be removed in a future breaking release.
+
Args:
height: image height.
width: image width.
- eps: denominator substituted for ``size - 1`` when a size equals ``1``;
- it is not consulted on any other path.
+ eps: deprecated compatibility parameter. It is ignored.
device: device to place the result on.
dtype: dtype of the result. ``None`` means ``torch.get_default_dtype()``.
@@ -2004,19 +2118,50 @@ def normal_transform_pixel(
[ 0.0000, 0.0000, 1.0000]]])
"""
- # prevent divide by zero bugs
- width_denom: float = eps if width == 1 else width - 1.0
- height_denom: float = eps if height == 1 else height - 1.0
-
- sx: float = 2.0 / width_denom
- sy: float = 2.0 / height_denom
-
- # Construct the matrix in one shot (no in-place mutation).
- tr_mat = torch.tensor(
- [[sx, 0.0, -1.0], [0.0, sy, -1.0], [0.0, 0.0, 1.0]],
- device=device,
- dtype=dtype,
- ) # 3x3
+ if not torch.jit.is_tracing() and (height <= 0 or width <= 0):
+ raise ValueError(f"Input image size must be positive. Got height={height}, width={width}.")
+ if (
+ not torch.jit.is_scripting()
+ and not torch.jit.is_tracing()
+ and not torch.compiler.is_compiling()
+ and eps != 1e-14
+ ):
+ warnings.warn("`eps` is deprecated and ignored by `normal_transform_pixel`.", FutureWarning, stacklevel=2)
+
+ if torch.jit.is_scripting() or (not torch.jit.is_tracing() and not torch.compiler.is_compiling()):
+ # Eager and TorchScript take the scalar branch, which is an order of magnitude
+ # cheaper on this hot path. Graph capture takes the tensor form below so symbolic
+ # sizes retain the singleton decision.
+ sx = 1.0 if width == 1 else 2.0 / (width - 1.0)
+ sy = 1.0 if height == 1 else 2.0 / (height - 1.0)
+ tx = 0.0 if width == 1 else -1.0
+ ty = 0.0 if height == 1 else -1.0
+ tr_mat = torch.tensor([[sx, 0.0, tx], [0.0, sy, ty], [0.0, 0.0, 1.0]], device=device, dtype=dtype)
+ else:
+ # Low-precision floating types cannot represent every practical image size exactly
+ # (e.g. bfloat16 rounds 257 to 256). Keep symbolic size arithmetic in at least
+ # float32, then cast the finished matrix to the requested output dtype. Resolve that
+ # output dtype FIRST: a ``dtype=None`` call inherits the default floating dtype, which
+ # may itself be a half type, so promoting only an *explicit* half ``dtype`` would leave
+ # ``torch.set_default_dtype(torch.float16)`` rounding the size below.
+ out_dtype = dtype if dtype is not None else torch.get_default_dtype()
+ work_dtype = out_dtype if out_dtype in (torch.float32, torch.float64) else torch.float32
+ width_t = torch.scalar_tensor(width, device=device, dtype=work_dtype)
+ height_t = torch.scalar_tensor(height, device=device, dtype=work_dtype)
+ one = torch.ones((), device=device, dtype=work_dtype)
+ zero = torch.zeros((), device=device, dtype=work_dtype)
+
+ # A singleton axis has no extent. Map its only pixel to the normalized centre
+ # while keeping the homogeneous transform invertible for homography composition.
+ sx_t = torch.where(width_t == 1, one, 2.0 / (width_t - 1.0))
+ sy_t = torch.where(height_t == 1, one, 2.0 / (height_t - 1.0))
+ tx_t = torch.where(width_t == 1, zero, -one)
+ ty_t = torch.where(height_t == 1, zero, -one)
+
+ # Construct the matrix in one shot (no in-place mutation).
+ tr_mat = torch.stack(
+ [torch.stack([sx_t, zero, tx_t]), torch.stack([zero, sy_t, ty_t]), torch.stack([zero, zero, one])]
+ ).to(dtype=out_dtype) # 3x3
return tr_mat.unsqueeze(0) # 1x3x3
@@ -2037,7 +2182,8 @@ def normal_transform_pixel3d(
corner-aligned ``2 / (size - 1)`` scaling with offset ``-1``, same
unconditional application, same ``dtype=None`` /
``torch.get_default_dtype()`` rule, and likewise **never batched**.
- Only the lines below differ
+ Singleton axes use the same invertible centre mapping, and zero or
+ negative sizes raise ``ValueError``. Only the lines below differ
- the result has shape :math:`(1, 4, 4)` and acts on homogeneous
``(x, y, z, 1)`` column vectors with ``x`` scaled by ``width``, ``y``
by ``height`` and ``z`` by ``depth``, while the positional argument
@@ -2053,25 +2199,25 @@ def normal_transform_pixel3d(
grid built for one silently permutes axes when fed to the other
.. warning::
- Scope: the degenerate-denominator branch only, as delimited in
- :func:`~kornia.geometry.conversions.normal_transform_pixel`'s
- degenerate-size warning. The degenerate-size
- and integer-``dtype`` behaviours of
- :func:`~kornia.geometry.conversions.normal_transform_pixel` apply here
- per axis: ``depth=1`` gives a ``z``
- scale of ``2e14`` under the default ``eps``, ``depth=0`` gives ``-2.0``,
- negative sizes are accepted, and
- ``normal_transform_pixel3d(2, 4, 5, dtype=torch.int64)`` returns a
- matrix with diagonal ``[0, 0, 2]``. Tracked in
- `#3957 <https://github.com/kornia/kornia/issues/3957>`_ and
- `#3959 <https://github.com/kornia/kornia/issues/3959>`_.
+ The integer-``dtype`` behaviour of
+ :func:`~kornia.geometry.conversions.normal_transform_pixel` applies
+ here per axis: ``normal_transform_pixel3d(2, 4, 5,
+ dtype=torch.int64)`` returns a matrix with diagonal ``[0, 0, 2]``.
+ Tracked in `#3959 <https://github.com/kornia/kornia/issues/3959>`_.
+
+ .. note::
+ Legacy ``torch.jit.trace`` graphs assume positive runtime sizes for the
+ same reason as the 2-D counterpart.
+
+ .. deprecated:: 0.9.0
+ ``eps`` is ignored and follows the deprecation policy of the 2-D
+ counterpart.
Args:
depth: image depth.
height: image height.
width: image width.
- eps: denominator substituted for ``size - 1`` when a size equals ``1``;
- it is not consulted on any other path.
+ eps: deprecated compatibility parameter. It is ignored.
device: device to place the result on.
dtype: dtype of the result. ``None`` means ``torch.get_default_dtype()``.
@@ -2086,20 +2232,57 @@ def normal_transform_pixel3d(
[ 0.0000, 0.0000, 0.0000, 1.0000]]])
"""
- tr_mat = torch.tensor(
- [[1.0, 0.0, 0.0, -1.0], [0.0, 1.0, 0.0, -1.0], [0.0, 0.0, 1.0, -1.0], [0.0, 0.0, 0.0, 1.0]],
- device=device,
- dtype=dtype,
- ) # 4x4
-
- # prevent divide by zero bugs
- width_denom: float = eps if width == 1 else width - 1.0
- height_denom: float = eps if height == 1 else height - 1.0
- depth_denom: float = eps if depth == 1 else depth - 1.0
-
- tr_mat[0, 0] = tr_mat[0, 0] * 2.0 / width_denom
- tr_mat[1, 1] = tr_mat[1, 1] * 2.0 / height_denom
- tr_mat[2, 2] = tr_mat[2, 2] * 2.0 / depth_denom
+ if not torch.jit.is_tracing() and (depth <= 0 or height <= 0 or width <= 0):
+ raise ValueError(f"Input image size must be positive. Got depth={depth}, height={height}, width={width}.")
+ if (
+ not torch.jit.is_scripting()
+ and not torch.jit.is_tracing()
+ and not torch.compiler.is_compiling()
+ and eps != 1e-14
+ ):
+ warnings.warn("`eps` is deprecated and ignored by `normal_transform_pixel3d`.", FutureWarning, stacklevel=2)
+
+ if torch.jit.is_scripting() or (not torch.jit.is_tracing() and not torch.compiler.is_compiling()):
+ # As in 2-D, graph capture uses the tensor form below for symbolic sizes.
+ sx = 1.0 if width == 1 else 2.0 / (width - 1.0)
+ sy = 1.0 if height == 1 else 2.0 / (height - 1.0)
+ sz = 1.0 if depth == 1 else 2.0 / (depth - 1.0)
+ tx = 0.0 if width == 1 else -1.0
+ ty = 0.0 if height == 1 else -1.0
+ tz = 0.0 if depth == 1 else -1.0
+ tr_mat = torch.tensor(
+ [[sx, 0.0, 0.0, tx], [0.0, sy, 0.0, ty], [0.0, 0.0, sz, tz], [0.0, 0.0, 0.0, 1.0]],
+ device=device,
+ dtype=dtype,
+ )
+ else:
+ # As in 2-D: keep the symbolic size arithmetic in at least float32, and resolve the
+ # output dtype first so a ``dtype=None`` call under a half default dtype is promoted too.
+ out_dtype = dtype if dtype is not None else torch.get_default_dtype()
+ work_dtype = out_dtype if out_dtype in (torch.float32, torch.float64) else torch.float32
+ width_t = torch.scalar_tensor(width, device=device, dtype=work_dtype)
+ height_t = torch.scalar_tensor(height, device=device, dtype=work_dtype)
+ depth_t = torch.scalar_tensor(depth, device=device, dtype=work_dtype)
+ one = torch.ones((), device=device, dtype=work_dtype)
+ zero = torch.zeros((), device=device, dtype=work_dtype)
+
+ # As in 2-D, a singleton axis maps its only pixel to the normalized centre,
+ # with unit scale so that homography composition can still invert the matrix.
+ sx_t = torch.where(width_t == 1, one, 2.0 / (width_t - 1.0))
+ sy_t = torch.where(height_t == 1, one, 2.0 / (height_t - 1.0))
+ sz_t = torch.where(depth_t == 1, one, 2.0 / (depth_t - 1.0))
+ tx_t = torch.where(width_t == 1, zero, -one)
+ ty_t = torch.where(height_t == 1, zero, -one)
+ tz_t = torch.where(depth_t == 1, zero, -one)
+
+ tr_mat = torch.stack(
+ [
+ torch.stack([sx_t, zero, zero, tx_t]),
+ torch.stack([zero, sy_t, zero, ty_t]),
+ torch.stack([zero, zero, sz_t, tz_t]),
+ torch.stack([zero, zero, zero, one]),
+ ]
+ ).to(dtype=out_dtype) # 4x4
return tr_mat.unsqueeze(0) # 1x4x4
@@ -2120,9 +2303,7 @@ def denormalize_homography(
batching, the corner-aligned frames β€” is as documented there, and so
are that function's shape-guard (`#3960
<https://github.com/kornia/kornia/issues/3960>`_), dtype-pass-through
- (`#3958 <https://github.com/kornia/kornia/issues/3958>`_),
- degenerate-size (`#3957
- <https://github.com/kornia/kornia/issues/3957>`_), int64-handling
+ (`#3958 <https://github.com/kornia/kornia/issues/3958>`_), int64-handling
(`#3959 <https://github.com/kornia/kornia/issues/3959>`_ β€” this
function's own clause there) and corner-alignment (`#3904
<https://github.com/kornia/kornia/issues/3904>`_) warnings. The
@@ -2245,28 +2426,6 @@ def normalize_homography3d(
that takes 4x4 matrices. Tracked in
`#3960 <https://github.com/kornia/kornia/issues/3960>`_.
- .. warning::
- Scope: the degenerate-denominator branch only, as delimited in
- :func:`~kornia.geometry.conversions.normal_transform_pixel`'s
- degenerate-size warning. A source
- ``depth`` of ``1`` collapses the ``z`` scale through
- :func:`~kornia.geometry.conversions.normal_transform_pixel3d`'s ``2e14``
- blow-up, leaving a value that is **not** an exact zero and merely prints
- as ``0.`` at the default precision. Both it and the determinant scale
- with the destination depth, so neither means anything without both
- sizes: from ``dsize_src = (1, 4, 5)`` to ``dsize_dst = (3, 8, 9)`` the
- ``z`` scale is ``4.99999991225835e-15`` and ``det`` is
- ``1.0714285980035544e-15``, while the same source against
- ``(2, 8, 9)`` gives ``9.9999998245167e-15`` and
- ``2.1428571960071087e-15`` (torch 2.9.1, cpu β€” these run through an
- inverse, a ``matmul`` and ``linalg.det``, so read the exponents, not
- the trailing digits). ``torch.linalg.inv`` still succeeds on such
- a matrix, so it is unusable in practice rather than formally singular,
- and it annihilates every ``z`` coordinate. Returned without any
- warning. The ``float32`` constants of
- `#3958 <https://github.com/kornia/kornia/issues/3958>`_ apply here too.
- Tracked in `#3957 <https://github.com/kornia/kornia/issues/3957>`_.
-
Args:
dst_pix_trans_src_pix: homography/ies from source to destination to be
normalized. :math:`(B, 4, 4)`
diff --git a/kornia/geometry/grid.py b/kornia/geometry/grid.py
index c3a46304b..8b38cc5a8 100644
--- a/kornia/geometry/grid.py
+++ b/kornia/geometry/grid.py
@@ -32,7 +32,10 @@ def create_meshgrid(
When the flag ``normalized_coordinates`` is set to True, the grid is
normalized to be in the range :math:`[-1,1]` to be consistent with the pytorch
- function :py:func:`torch.nn.functional.grid_sample`.
+ function :py:func:`torch.nn.functional.grid_sample`. A singleton axis is
+ represented by ``0``, the centre of the normalized range. A zero spatial size
+ produces a correspondingly empty grid; this differs from pixel-coordinate
+ normalization, where a zero-sized coordinate system is undefined.
Args:
height: the image height (rows).
@@ -62,19 +65,49 @@ def create_meshgrid(
[1., 1.]]]])
"""
- xs: torch.Tensor = torch.linspace(0, width - 1, width, device=device, dtype=dtype)
- ys: torch.Tensor = torch.linspace(0, height - 1, height, device=device, dtype=dtype)
+ if not torch.jit.is_scripting() and torch.compiler.is_compiling():
+ # ``linspace`` specializes symbolic ``steps`` under export; ``arange`` retains the
+ # dynamic output length. Match ``linspace``'s default floating dtype when none is given.
+ arange_dtype = dtype if dtype is not None else torch.get_default_dtype()
+ xs = torch.arange(width, device=device, dtype=arange_dtype)
+ ys = torch.arange(height, device=device, dtype=arange_dtype)
+ else:
+ xs = torch.linspace(0, width - 1, width, device=device, dtype=dtype)
+ ys = torch.linspace(0, height - 1, height, device=device, dtype=dtype)
# Fix TracerWarning
- # Note: normalize_pixel_coordinates still gots TracerWarning since new width and height
- # tensors will be generated.
+ # Note: keeping this formula inline avoids the extra tensors and shape checks incurred by
+ # normalize_pixel_coordinates. The two paths use the same singleton-centre policy.
# Below is the code using normalize_pixel_coordinates:
# base_grid: torch.Tensor = torch.stack(torch.meshgrid([xs, ys]), dim=2)
# if normalized_coordinates:
# base_grid = K.geometry.normalize_pixel_coordinates(base_grid, height, width)
# return torch.unsqueeze(base_grid.transpose(0, 1), dim=0)
if normalized_coordinates:
- xs = (xs / (width - 1) - 0.5) * 2
- ys = (ys / (height - 1) - 0.5) * 2
+ if torch.jit.is_tracing() or torch.compiler.is_compiling():
+ # Graph capture needs the tensor form to keep a symbolic size dynamic. Low-precision
+ # floating types cannot represent every practical image size exactly (e.g. bfloat16
+ # rounds 257 to 256 and 299 to 300), so the size arithmetic runs in float32. Divide
+ # against the *unrounded* divisor and round the quotient, which is what eager does
+ # against its Python-int divisor: casting the divisor down first would round it into
+ # the coordinate dtype, which eager never does.
+ work_dtype = torch.float32 if xs.dtype in (torch.float16, torch.bfloat16) else xs.dtype
+ width_t = torch.scalar_tensor(width, device=xs.device, dtype=work_dtype)
+ height_t = torch.scalar_tensor(height, device=ys.device, dtype=work_dtype)
+ xs_norm = xs.to(work_dtype) / (width_t - 1)
+ ys_norm = ys.to(work_dtype) / (height_t - 1)
+ if xs.is_floating_point():
+ # A widened half type rounds back down here, which is exactly where eager rounds.
+ # An integral grid dtype must instead stay promoted into the default float, as the
+ # eager true-division leaves it.
+ xs_norm = xs_norm.to(xs.dtype)
+ ys_norm = ys_norm.to(ys.dtype)
+ xs = torch.where(width_t > 1, (xs_norm - 0.5) * 2, torch.zeros_like(xs_norm))
+ ys = torch.where(height_t > 1, (ys_norm - 0.5) * 2, torch.zeros_like(ys_norm))
+ else:
+ # ``* 0.0`` rather than ``zeros_like`` so that a singleton axis follows the
+ # same integer-to-float promotion the non-singleton branch performs.
+ xs = (xs / (width - 1) - 0.5) * 2 if width > 1 else xs * 0.0
+ ys = (ys / (height - 1) - 0.5) * 2 if height > 1 else ys * 0.0
# generate grid by stacking coordinates
base_grid: torch.Tensor = torch.stack(torch.meshgrid([xs, ys], indexing="ij"), dim=-1) # WxHx2
return base_grid.permute(1, 0, 2).unsqueeze(0) # 1xHxWx2
@@ -92,7 +125,10 @@ def create_meshgrid3d(
When the flag ``normalized_coordinates`` is set to True, the grid is
normalized to be in the range :math:`[-1,1]` to be consistent with the pytorch
- function :py:func:`torch.nn.functional.grid_sample`.
+ function :py:func:`torch.nn.functional.grid_sample`. A singleton axis is
+ represented by ``0``, the centre of the normalized range. A zero spatial size
+ produces a correspondingly empty grid; this differs from pixel-coordinate
+ normalization, where a zero-sized coordinate system is undefined.
Args:
depth: the image depth (channels).
@@ -108,14 +144,40 @@ def create_meshgrid3d(
grid tensor with shape :math:`(1, D, H, W, 3)`.
"""
- xs: torch.Tensor = torch.linspace(0, width - 1, width, device=device, dtype=dtype)
- ys: torch.Tensor = torch.linspace(0, height - 1, height, device=device, dtype=dtype)
- zs: torch.Tensor = torch.linspace(0, depth - 1, depth, device=device, dtype=dtype)
+ if not torch.jit.is_scripting() and torch.compiler.is_compiling():
+ arange_dtype = dtype if dtype is not None else torch.get_default_dtype()
+ xs = torch.arange(width, device=device, dtype=arange_dtype)
+ ys = torch.arange(height, device=device, dtype=arange_dtype)
+ zs = torch.arange(depth, device=device, dtype=arange_dtype)
+ else:
+ xs = torch.linspace(0, width - 1, width, device=device, dtype=dtype)
+ ys = torch.linspace(0, height - 1, height, device=device, dtype=dtype)
+ zs = torch.linspace(0, depth - 1, depth, device=device, dtype=dtype)
# Fix TracerWarning
if normalized_coordinates:
- xs = (xs / (width - 1) - 0.5) * 2
- ys = (ys / (height - 1) - 0.5) * 2
- zs = (zs / (depth - 1) - 0.5) * 2
+ if torch.jit.is_tracing() or torch.compiler.is_compiling():
+ # See ``create_meshgrid``: low-precision dtypes round large sizes, so the size
+ # arithmetic runs in float32 and the quotient, not the divisor, is what gets cast down.
+ work_dtype = torch.float32 if xs.dtype in (torch.float16, torch.bfloat16) else xs.dtype
+ width_t = torch.scalar_tensor(width, device=xs.device, dtype=work_dtype)
+ height_t = torch.scalar_tensor(height, device=ys.device, dtype=work_dtype)
+ depth_t = torch.scalar_tensor(depth, device=zs.device, dtype=work_dtype)
+ xs_norm = xs.to(work_dtype) / (width_t - 1)
+ ys_norm = ys.to(work_dtype) / (height_t - 1)
+ zs_norm = zs.to(work_dtype) / (depth_t - 1)
+ if xs.is_floating_point():
+ # As in ``create_meshgrid``: round a widened half type back down, but leave an
+ # integral grid dtype promoted into the default float.
+ xs_norm = xs_norm.to(xs.dtype)
+ ys_norm = ys_norm.to(ys.dtype)
+ zs_norm = zs_norm.to(zs.dtype)
+ xs = torch.where(width_t > 1, (xs_norm - 0.5) * 2, torch.zeros_like(xs_norm))
+ ys = torch.where(height_t > 1, (ys_norm - 0.5) * 2, torch.zeros_like(ys_norm))
+ zs = torch.where(depth_t > 1, (zs_norm - 0.5) * 2, torch.zeros_like(zs_norm))
+ else:
+ xs = (xs / (width - 1) - 0.5) * 2 if width > 1 else xs * 0.0
+ ys = (ys / (height - 1) - 0.5) * 2 if height > 1 else ys * 0.0
+ zs = (zs / (depth - 1) - 0.5) * 2 if depth > 1 else zs * 0.0
# generate grid by stacking coordinates
base_grid = torch.stack(torch.meshgrid([zs, xs, ys], indexing="ij"), dim=-1) # DxWxHx3
return base_grid.permute(0, 2, 1, 3).unsqueeze(0) # 1xDxHxWx3
diff --git a/kornia/geometry/transform/crop2d.py b/kornia/geometry/transform/crop2d.py
index 26d7671fb..8aacc78fc 100644
--- a/kornia/geometry/transform/crop2d.py
+++ b/kornia/geometry/transform/crop2d.py
@@ -319,10 +319,7 @@ def crop_by_transform_mat(
- padding_mode: ``'zeros'`` by default
.. warning::
- The :math:`(B, 3, 3)` full-matrix behavior above has degenerate-``out_size``
- exceptions: with ``align_corners=True`` and an ``out_size`` dimension equal to
- ``1``, the destination-side grid is singular and the output is all-``NaN``; with
- ``align_corners=False`` and an ``out_size`` dimension equal to ``1``, this
+ With ``align_corners=False`` and an ``out_size`` dimension equal to ``1``, this
function silently falls back to the :math:`(B, 2, 3)` :func:`warp_affine` path
(dropping the projective row entirely), so two :math:`(B, 3, 3)` matrices that
differ only in their third row produce byte-identical output. Tracked in
diff --git a/kornia/geometry/transform/imgwarp.py b/kornia/geometry/transform/imgwarp.py
index 966b5e6bf..1f5d6e550 100644
--- a/kornia/geometry/transform/imgwarp.py
+++ b/kornia/geometry/transform/imgwarp.py
@@ -66,6 +66,115 @@ __all__ = [
]
+def _matrix_warp_grid_dtype(src: torch.Tensor, transform: torch.Tensor) -> torch.dtype:
+ """Return the sampling-grid dtype the non-empty matrix-warp pipeline would build.
+
+ ``normalize_homography`` scales ``transform`` by floating factors, so an integral or boolean
+ matrix already fails there and must fail here too. Otherwise the base grid is created in
+ ``src.dtype`` and combined with the normalized matrix, so the grid promotes the two: a float32
+ matrix against a float64 image still samples in float64, while the reverse narrows and is
+ rejected by ``grid_sample``.
+ """
+ if not transform.is_floating_point():
+ raise RuntimeError(f"Expected a floating point transform, got {transform.dtype}.")
+ return torch.promote_types(src.dtype, transform.dtype)
+
+
+def _remap_grid_dtype(map_xy: torch.Tensor, normalized_coordinates: bool) -> torch.dtype:
+ """Return the sampling-grid dtype the non-empty :func:`remap` pipeline would build.
+
+ Already-normalized maps reach ``grid_sample`` untouched. Pixel maps first go through
+ :func:`~kornia.geometry.conversions.normalize_pixel_coordinates`, which keeps a floating map in
+ its own dtype and lifts an integral or boolean one into the default floating dtype.
+ """
+ if normalized_coordinates or map_xy.is_floating_point():
+ return map_xy.dtype
+ # Read the default floating dtype off a zero-element promotion rather than
+ # ``torch.get_default_dtype()``, which TorchScript does not expose.
+ return (map_xy.reshape(-1)[:0] * 1.0).dtype
+
+
+def _empty_warp_output_2d(
+ src: torch.Tensor,
+ transform: torch.Tensor,
+ dsize: tuple[int, int],
+ mode: str,
+ padding_mode: str,
+ align_corners: bool,
+ grid_dtype: torch.dtype,
+ fill_value: Optional[torch.Tensor] = None,
+ expand_transform_batch: bool = False,
+ allow_fill: bool = True,
+ operand: str = "transform",
+) -> torch.Tensor:
+ """Return an empty warp while retaining normal grid-sample validation and autograd links.
+
+ ``operand`` names the second tensor in the error messages. ``remap`` has no ``transform``
+ parameter β€” it delegates here with its stacked maps β€” so it must not be told about one.
+ """
+ if src.device != transform.device:
+ raise RuntimeError(f"Expected src and {operand} on the same device, got {src.device} and {transform.device}.")
+ # An integral ``src`` fails inside ``grid_sample`` itself on the non-empty path, so it must
+ # fail here too β€” but name ``src`` rather than blaming the other operand for it below. (MPS is the
+ # exception: its ``grid_sample`` samples an integral image back into ``int64`` instead of
+ # rejecting it. Matching that would mean bilinear-sampling into an integer output, so the
+ # cpu/cuda contract is the one enforced here.)
+ if not src.is_floating_point():
+ raise RuntimeError(f"Expected a floating point src, got {src.dtype}.")
+ # ``grid_sample`` requires the sampling grid in ``src.dtype``. ``grid_dtype`` is the dtype the
+ # caller's non-empty pipeline would actually produce from ``transform``, so checking it here
+ # makes a zero-sized ``dsize`` neither stricter nor laxer than a non-empty one.
+ if grid_dtype != src.dtype:
+ raise RuntimeError(f"Expected src and {operand} with the same dtype, got {src.dtype} and {transform.dtype}.")
+ if src.dtype != transform.dtype:
+ transform = transform.to(src.dtype)
+ grid_zero = transform.reshape(-1)[:1].sum() * 0.0
+ grid = grid_zero.reshape(1, 1, 1, 1).expand(transform.shape[0], dsize[0], dsize[1], 2)
+ if expand_transform_batch and transform.shape[0] == 1 and src.shape[0] > 1:
+ grid = grid.expand(src.shape[0], -1, -1, -1)
+
+ # ``grid_sample`` rejects an empty source even when the destination is also empty. Validate
+ # all its other contracts against a connected 1x1 stand-in so the public empty-source policy
+ # remains useful without silently accepting invalid batches, dtypes, devices, or modes.
+ sample_src = src
+ if src.shape[-2] == 0 or src.shape[-1] == 0:
+ src_zero = src.reshape(-1)[:1].sum() * 0.0
+ sample_src = src_zero.reshape(1, 1, 1, 1).expand(src.shape[0], src.shape[1], 1, 1)
+
+ if padding_mode == "fill" and allow_fill:
+ if fill_value is None:
+ fill_value = torch.zeros(src.shape[1], device=src.device, dtype=src.dtype)
+ return _fill_and_warp(sample_src, grid, align_corners=align_corners, mode=mode, fill_value=fill_value)
+ return F.grid_sample(sample_src, grid, align_corners=align_corners, mode=mode, padding_mode=padding_mode)
+
+
+def _empty_warp_output_3d(
+ src: torch.Tensor,
+ transform: torch.Tensor,
+ dsize: tuple[int, int, int],
+ mode: str,
+ padding_mode: str,
+ align_corners: bool,
+) -> torch.Tensor:
+ """Return an empty volume warp with normal grid-sample validation and autograd links."""
+ if src.device != transform.device:
+ raise RuntimeError(f"Expected src and transform on the same device, got {src.device} and {transform.device}.")
+ # As in the 2-D helper: an integral ``src`` cannot reach cpu/cuda ``grid_sample`` on either
+ # path, so reject it by name instead of via the transform-dtype message below.
+ if not src.is_floating_point():
+ raise RuntimeError(f"Expected a floating point src, got {src.dtype}.")
+ if src.dtype != transform.dtype:
+ raise RuntimeError(f"Expected src and transform with the same dtype, got {src.dtype} and {transform.dtype}.")
+ grid_zero = transform.reshape(-1)[:1].sum() * 0.0
+ grid = grid_zero.reshape(1, 1, 1, 1, 1).expand(transform.shape[0], dsize[0], dsize[1], dsize[2], 3)
+
+ sample_src = src
+ if src.shape[-3] == 0 or src.shape[-2] == 0 or src.shape[-1] == 0:
+ src_zero = src.reshape(-1)[:1].sum() * 0.0
+ sample_src = src_zero.reshape(1, 1, 1, 1, 1).expand(src.shape[0], src.shape[1], 1, 1, 1)
+ return F.grid_sample(sample_src, grid, align_corners=align_corners, mode=mode, padding_mode=padding_mode)
+
+
def warp_perspective(
src: torch.Tensor,
M: torch.Tensor,
@@ -93,6 +202,8 @@ def warp_perspective(
- coordinates: ``(x, y)``, pixel centers, origin at top-left
- align_corners: ``True`` by default
- padding_mode: ``'zeros'`` by default
+ - a zero output dimension returns an autograd-connected empty tensor;
+ negative output dimensions raise ``ValueError``
Args:
src: input image with shape :math:`(B, C, H, W)`.
@@ -142,6 +253,12 @@ def warp_perspective(
B, _, H, W = src.size()
h_out, w_out = dsize
+ if h_out < 0 or w_out < 0:
+ raise ValueError(f"Output size must be non-negative. Got {dsize}.")
+ if h_out == 0 or w_out == 0:
+ return _empty_warp_output_2d(
+ src, M, dsize, mode, padding_mode, align_corners, _matrix_warp_grid_dtype(src, M), fill_value
+ )
# we F.normalize the 3x3 transformation matrix and convert to 3x4
dst_norm_trans_src_norm: torch.Tensor = normalize_homography(M, (H, W), (h_out, w_out)) # Bx3x3
@@ -202,6 +319,8 @@ def warp_affine(
- coordinates: ``(x, y)``, pixel centers, origin at top-left
- align_corners: ``True`` by default
- padding_mode: ``'zeros'`` by default
+ - a zero output dimension returns an autograd-connected empty tensor;
+ negative output dimensions raise ``ValueError``
Args:
src: input torch.Tensor of shape :math:`(B, C, H, W)`.
@@ -240,11 +359,25 @@ def warp_affine(
if not len(src.shape) == 4:
raise ValueError(f"Input src must be a BxCxHxW torch.Tensor. Got {src.shape}")
- if not (len(M.shape) == 3 or M.shape[-2:] == (2, 3)):
+ if not (len(M.shape) == 3 and M.shape[-2:] == (2, 3)):
raise ValueError(f"Input M must be a Bx2x3 torch.Tensor. Got {M.shape}")
B, C, H, W = src.size()
B_M = M.shape[0]
+ if dsize[0] < 0 or dsize[1] < 0:
+ raise ValueError(f"Output size must be non-negative. Got {dsize}.")
+ if dsize[0] == 0 or dsize[1] == 0:
+ return _empty_warp_output_2d(
+ src,
+ M,
+ dsize,
+ mode,
+ padding_mode,
+ align_corners,
+ _matrix_warp_grid_dtype(src, M),
+ fill_value,
+ expand_transform_batch=True,
+ )
M_3x3: torch.Tensor = convert_affinematrix_to_homography(M)
dst_norm_trans_src_norm: torch.Tensor = normalize_homography(M_3x3, (H, W), dsize)
@@ -269,8 +402,16 @@ def warp_affine(
# corners at +/-1 vs pixel centers). A shared (1x2x3) matrix broadcasts across the batch.
h_out, w_out = dsize
if align_corners:
- xs = torch.linspace(-1.0, 1.0, w_out, device=src.device, dtype=src.dtype)
- ys = torch.linspace(-1.0, 1.0, h_out, device=src.device, dtype=src.dtype)
+ xs = (
+ torch.zeros(1, device=src.device, dtype=src.dtype)
+ if w_out == 1
+ else torch.linspace(-1.0, 1.0, w_out, device=src.device, dtype=src.dtype)
+ )
+ ys = (
+ torch.zeros(1, device=src.device, dtype=src.dtype)
+ if h_out == 1
+ else torch.linspace(-1.0, 1.0, h_out, device=src.device, dtype=src.dtype)
+ )
else:
xs = torch.linspace(-1.0 + 1.0 / w_out, 1.0 - 1.0 / w_out, w_out, device=src.device, dtype=src.dtype)
ys = torch.linspace(-1.0 + 1.0 / h_out, 1.0 - 1.0 / h_out, h_out, device=src.device, dtype=src.dtype)
@@ -645,6 +786,8 @@ def remap(
unless ``normalized_coordinates=True``
- align_corners: ``None`` by default, resolved to ``False`` internally
- padding_mode: ``'zeros'`` by default
+ - the output spatial size comes from the maps; a zero map axis returns an
+ autograd-connected empty output, including when the matching source axis is empty
Args:
image: the torch.Tensor to remap with shape (B, C, H, W).
@@ -687,6 +830,24 @@ def remap(
# grid_sample need the grid between -1/1
map_xy: torch.Tensor = torch.stack([map_x, map_y], -1)
+ # Default to False if align_corners is None to avoid PyTorch warning
+ if align_corners is None:
+ align_corners = False
+
+ if map_xy.shape[-3] == 0 or map_xy.shape[-2] == 0:
+ return _empty_warp_output_2d(
+ image,
+ map_xy,
+ (map_xy.shape[-3], map_xy.shape[-2]),
+ mode,
+ padding_mode,
+ align_corners,
+ _remap_grid_dtype(map_xy, normalized_coordinates),
+ expand_transform_batch=True,
+ allow_fill=False,
+ operand="map",
+ )
+
# F.normalize coordinates if not already normalized
if not normalized_coordinates:
map_xy = normalize_pixel_coordinates(map_xy, height, width)
@@ -694,10 +855,6 @@ def remap(
# simulate broadcasting since grid_sample does not support it
map_xy = map_xy.expand(batch_size, -1, -1, -1)
- # Default to False if align_corners is None to avoid PyTorch warning
- if align_corners is None:
- align_corners = False
-
# warp the image tensor and return
return F.grid_sample(image, map_xy, mode=mode, padding_mode=padding_mode, align_corners=align_corners)
@@ -1061,6 +1218,8 @@ def warp_affine3d(
- ``M`` is the source→destination **pixel** affine matrix :math:`(B, 3, 4)`
- align_corners: ``True`` by default
- padding_mode: ``'zeros'`` by default
+ - a zero output dimension returns an autograd-connected empty tensor;
+ negative output dimensions raise ``ValueError``
Args:
src : input torch.Tensor of shape :math:`(B, C, D, H, W)`.
@@ -1087,6 +1246,10 @@ def warp_affine3d(
if len(dsize) != 3:
raise AssertionError(dsize)
B, C, D, H, W = src.size()
+ if dsize[0] < 0 or dsize[1] < 0 or dsize[2] < 0:
+ raise ValueError(f"Output size must be non-negative. Got {dsize}.")
+ if dsize[0] == 0 or dsize[1] == 0 or dsize[2] == 0:
+ return _empty_warp_output_3d(src, M, dsize, flags, padding_mode, align_corners)
size_src: tuple[int, int, int] = (D, H, W)
size_out: tuple[int, int, int] = dsize
@@ -1438,6 +1601,8 @@ def warp_perspective3d(
- align_corners: ``False`` by default (differs from the 2D :func:`warp_perspective`,
whose default is ``True``)
- border_mode: ``'zeros'`` by default
+ - a zero output dimension returns an autograd-connected empty tensor;
+ negative output dimensions raise ``ValueError``
Args:
src: input image with shape :math:`(B, C, D, H, W)`.
@@ -1465,9 +1630,20 @@ def warp_perspective3d(
if not len(src.shape) == 5:
raise ValueError(f"Input src must be a BxCxDxHxW torch.Tensor. Got {src.shape}")
- if not (len(M.shape) == 3 or M.shape[-2:] == (4, 4)):
+ # An unbatched 4x4 matrix has always been accepted here (the historical shape guard used
+ # ``or``, so it never fired for one), and it warps correctly. Keep that working by promoting
+ # it, rather than letting the tightened guard below turn it into a ``ValueError``.
+ if len(M.shape) == 2 and M.shape[-2:] == (4, 4):
+ M = M[None]
+
+ if not (len(M.shape) == 3 and M.shape[-2:] == (4, 4)):
raise ValueError(f"Input M must be a Bx4x4 torch.Tensor. Got {M.shape}")
+ if dsize[0] < 0 or dsize[1] < 0 or dsize[2] < 0:
+ raise ValueError(f"Output size must be non-negative. Got {dsize}.")
+ if dsize[0] == 0 or dsize[1] == 0 or dsize[2] == 0:
+ return _empty_warp_output_3d(src, M, dsize, flags, border_mode, align_corners)
+
# launches the warper
d, h, w = src.shape[-3:]
return _transform_warp_impl3d(src, M, (d, h, w), dsize, flags, border_mode, align_corners)
@@ -1499,6 +1675,7 @@ def homography_warp(
honored when ``normalized_homography=True`` β€” the pixel-homography path currently
forces ``align_corners=True`` and ``mode='bilinear'``)
- padding_mode: ``'zeros'`` by default
+ - negative output dimensions raise ``ValueError``
Args:
patch_src: The image or torch.Tensor to warp. Should be from source of shape :math:`(N, C, H, W)`.
@@ -1531,6 +1708,8 @@ def homography_warp(
torch.Size([1, 4, 4, 2])
"""
+ if dsize[0] < 0 or dsize[1] < 0:
+ raise ValueError(f"Output size must be non-negative. Got {dsize}.")
if not src_homo_dst.device == patch_src.device:
raise TypeError(
f"Patch and homography must be on the same device. Got patch.device: {patch_src.device} "
@@ -1582,6 +1761,7 @@ def homography_warp3d(
:math:`[-1, 1]` coordinates by default (``normalized_coordinates=True``)
- align_corners: ``False`` by default
- padding_mode: ``'zeros'`` by default
+ - negative output dimensions raise ``ValueError``
Args:
patch_src: The image or torch.Tensor to warp. Should be from source of shape :math:`(N, C, D, H, W)`.
@@ -1602,6 +1782,8 @@ def homography_warp3d(
>>> output = homography_warp3d(input, homography, (8, 32, 32))
"""
+ if dsize[0] < 0 or dsize[1] < 0 or dsize[2] < 0:
+ raise ValueError(f"Output size must be non-negative. Got {dsize}.")
if not src_homo_dst.device == patch_src.device:
raise TypeError(
f"Patch and homography must be on the same device. Got patch.device: {patch_src.device} "
diff --git a/tests/geometry/subpix/test_spatial_softargmax.py b/tests/geometry/subpix/test_spatial_softargmax.py
index b56275f64..ce39a62ce 100644
--- a/tests/geometry/subpix/test_spatial_softargmax.py
+++ b/tests/geometry/subpix/test_spatial_softargmax.py
@@ -422,7 +422,7 @@ class TestConvSoftArgmax3d(BaseTester):
)
expected_val = torch.tensor([[[[[1.0, 0.0], [0.0, 1.0]]]]], device=device, dtype=dtype)
expected_coord = torch.tensor(
- [[[[[[-1.0, -1.0], [-1.0, -1.0]]], [[[-0.5, 0.5], [-0.5, 0.5]]], [[[-0.5, -0.5], [0.5, 0.5]]]]]],
+ [[[[[[0.0, 0.0], [0.0, 0.0]]], [[[-0.5, 0.5], [-0.5, 0.5]]], [[[-0.5, -0.5], [0.5, 0.5]]]]]],
device=device,
dtype=dtype,
)
@@ -453,7 +453,7 @@ class TestConvSoftArgmax3d(BaseTester):
)
expected_val = torch.tensor([[[[[0.1214, 0.0], [0.0, 0.1214]]]]], device=device, dtype=dtype)
expected_coord = torch.tensor(
- [[[[[[-1.0, -1.0], [-1.0, -1.0]]], [[[-0.5, 0.5], [-0.5, 0.5]]], [[[-0.5, -0.5], [0.5, 0.5]]]]]],
+ [[[[[[0.0, 0.0], [0.0, 0.0]]], [[[-0.5, 0.5], [-0.5, 0.5]]], [[[-0.5, -0.5], [0.5, 0.5]]]]]],
device=device,
dtype=dtype,
)
diff --git a/tests/geometry/test_conversions.py b/tests/geometry/test_conversions.py
index 75f05c2ba..3e15dc341 100644
--- a/tests/geometry/test_conversions.py
+++ b/tests/geometry/test_conversions.py
@@ -3068,38 +3068,8 @@ def _skip_if_mps_clamp_caching(device):
)
-def _assert_degenerate_size_cell(
- func_2d, func_3d, fill, ndim, arg_name, degenerate_size, expected, tols, device, dtype
-):
- # Shared driver for the two kornia#3940 wart matrices below -- the normalize and
- # denormalize halves differ only in function pair, fill value, tolerances and expected
- # table -- so the eventual #3940 cleanup edits one body and one MPS-skip helper. eps=1e-8 is
- # passed explicitly so the pinned literals do not silently track a later change to the default eps
- # while the clamp bug itself is still present.
- _skip_if_mps_clamp_caching(device)
-
- if ndim == "2d":
- sizes = {"height": 5, "width": 7}
- func = func_2d
- else:
- sizes = {"depth": 5, "height": 7, "width": 9}
- func = func_3d
- sizes[arg_name] = degenerate_size
- pts = torch.full((1, len(sizes)), fill, device=device, dtype=dtype)
-
- out = func(pts, *sizes.values(), eps=1e-8)
-
- expected_t = torch.tensor([expected], device=device, dtype=dtype)
- if tols is None:
- assert_close(out, expected_t)
- else:
- atol, rtol = tols
- assert_close(out, expected_t, atol=atol, rtol=rtol)
-
-
class TestNormalizePixelCoordinates(BaseTester):
def test_tensor_bhw2(self, device, dtype, atol, rtol):
- eps = torch.finfo(dtype).eps
height, width = 3, 4
grid = kornia.geometry.create_meshgrid(height, width, normalized_coordinates=False, device=device).to(
dtype=dtype
@@ -3109,12 +3079,11 @@ class TestNormalizePixelCoordinates(BaseTester):
dtype=dtype
)
- grid_norm = kornia.geometry.conversions.normalize_pixel_coordinates(grid, height, width, eps=eps)
+ grid_norm = kornia.geometry.conversions.normalize_pixel_coordinates(grid, height, width)
self.assert_close(grid_norm, expected, atol=atol, rtol=rtol)
def test_list(self, device, dtype, atol, rtol):
- eps = torch.finfo(dtype).eps
height, width = 3, 4
grid = kornia.geometry.create_meshgrid(height, width, normalized_coordinates=False, device=device).to(
dtype=dtype
@@ -3126,7 +3095,7 @@ class TestNormalizePixelCoordinates(BaseTester):
)
expected = expected.contiguous().view(-1, 2)
- grid_norm = kornia.geometry.conversions.normalize_pixel_coordinates(grid, height, width, eps=eps)
+ grid_norm = kornia.geometry.conversions.normalize_pixel_coordinates(grid, height, width)
self.assert_close(grid_norm, expected, atol=atol, rtol=rtol)
@@ -3219,99 +3188,61 @@ class TestNormalizePixelCoordinates(BaseTester):
out_swapped = kornia.geometry.conversions.normalize_pixel_coordinates3d(swapped, 3, 5, 9)
self.assert_close(out_swapped, torch.tensor([[1.0, 0.0, 3.0]], device=device, dtype=dtype))
- # Wart-pin matrix for kornia#3940, normalizing half: one cell per (size argument x
- # degenerate class) of normalize_pixel_coordinates and normalize_pixel_coordinates3d,
- # asserting the CURRENT broken output that the docstring warnings document. If any cell
- # fails, #3940 was (partly) fixed -- update or remove the degenerate-size warnings in
- # normalize_pixel_coordinates, denormalize_pixel_coordinates, normalize_pixel_coordinates3d
- # and denormalize_pixel_coordinates3d. The cells are NOT a contract that degenerate sizes
- # must keep returning these values.
- # They are regular tests rather than strict xfails on purpose: the intended behavior
- # (raise ValueError, or clamp the *output*, or keep the current pass-through) is a
- # maintainer decision, and a strict xfail asserting one of those answers would stay
- # silently XFAIL forever if a different one were chosen. A wart pin flips loudly under
- # every polarity, and covering the full matrix means any partial fix -- one function, one
- # argument, or one degenerate class -- flips at least one cell.
- # Exactly one size argument is degenerate per cell (the others stay at 5/7 in 2-D and
- # 5/7/9 in 3-D), so the finite components pin which argument was degenerated. All three
- # classes give the same output because the mechanism is `(size - 1).clamp(eps)`: size 1
- # gives 0, size 0 gives -1 and size -3 gives -4, all clamped up to eps = 1e-8, so the
- # factor becomes 2e8.
- # Snippet used to generate expected (torch only; same output for bad in (1, 0, -3)):
- # npc = kornia.geometry.conversions.normalize_pixel_coordinates
- # npc3 = kornia.geometry.conversions.normalize_pixel_coordinates3d
- # npc(torch.tensor([[1., 1.]], dtype=torch.float64), bad, 7, eps=1e-8)
- # -> [[-0.6666666666666667, 199999999.0]]
- # npc(torch.tensor([[1., 1.]], dtype=torch.float64), 5, bad, eps=1e-8) -> [[199999999.0, -0.5]]
- # npc3(torch.tensor([[1., 1., 1.]], dtype=torch.float64), bad, 7, 9, eps=1e-8)
- # -> [[199999999.0, -0.75, -0.6666666666666667]]
- # npc3(torch.tensor([[1., 1., 1.]], dtype=torch.float64), 5, bad, 9, eps=1e-8)
- # -> [[-0.5, -0.75, 199999999.0]]
- # npc3(torch.tensor([[1., 1., 1.]], dtype=torch.float64), 5, 7, bad, eps=1e-8)
- # -> [[-0.5, 199999999.0, -0.6666666666666667]]
- # At float16 2e8 overflows to inf and the literal overflows identically; at bfloat16 both
- # sides round to 200278016.0, so the comparison stays meaningful at every dtype.
- @pytest.mark.parametrize("degenerate_size", [1, 0, -3], ids=["one", "zero", "negative"])
+ def test_singleton_axes_map_to_center_and_keep_unit_extension(self, device, dtype):
+ pts = torch.tensor([[0.0, 0.0], [0.25, -0.5]], device=device, dtype=dtype)
+ out = kornia.geometry.conversions.normalize_pixel_coordinates(pts, 1, 1)
+ self.assert_close(out, pts, atol=0.0, rtol=0.0)
+
+ pts3d = torch.tensor([[0.0, 0.0, 0.0], [0.25, -0.5, 0.75]], device=device, dtype=dtype)
+ out3d = kornia.geometry.conversions.normalize_pixel_coordinates3d(pts3d, 1, 1, 1)
+ self.assert_close(out3d, pts3d, atol=0.0, rtol=0.0)
+
+ @pytest.mark.parametrize("bad_size", [0, -3], ids=["zero", "negative"])
@pytest.mark.parametrize(
- ("ndim", "arg_name", "expected"),
+ ("op_name", "sizes"),
[
- ("2d", "height", [-0.6666667, 199999999.0]),
- ("2d", "width", [199999999.0, -0.5]),
- ("3d", "depth", [199999999.0, -0.75, -0.6666667]),
- ("3d", "height", [-0.5, -0.75, 199999999.0]),
- ("3d", "width", [-0.5, 199999999.0, -0.6666667]),
+ ("normalize_pixel_coordinates", (5, 7)),
+ ("normalize_pixel_coordinates3d", (5, 7, 9)),
],
- ids=["2d-height", "2d-width", "3d-depth", "3d-height", "3d-width"],
)
- def test_wart_degenerate_size_matrix(self, ndim, arg_name, degenerate_size, expected, device, dtype):
- _assert_degenerate_size_cell(
- kornia.geometry.conversions.normalize_pixel_coordinates,
- kornia.geometry.conversions.normalize_pixel_coordinates3d,
- 1.0,
- ndim,
- arg_name,
- degenerate_size,
- expected,
- None,
- device,
- dtype,
- )
-
- def test_wart_all_size_arguments_degenerate_together(self, device, dtype):
- # Wart pin for kornia#3940, companion to the matrix above: both sizes degenerate at
- # once also passes silently, exploding every component. Flips together with the matrix
- # when #3940 is fixed -- see the cleanup note above the matrix.
- # Snippet used to generate expected (torch only):
- # npc = kornia.geometry.conversions.normalize_pixel_coordinates
- # npc(torch.tensor([[1., 1.]], dtype=torch.float64), 1, 1, eps=1e-8)
- # -> [[199999999.0, 199999999.0]]
- _skip_if_mps_clamp_caching(device)
-
- pts = torch.tensor([[1.0, 1.0]], device=device, dtype=dtype)
-
- out = kornia.geometry.conversions.normalize_pixel_coordinates(pts, 1, 1, eps=1e-8)
-
- expected = torch.tensor([[199999999.0, 199999999.0]], device=device, dtype=dtype)
- self.assert_close(out, expected)
-
-
-def test_wart_default_eps_1e_8_backs_the_quoted_warning_numbers():
- # The wart pins in this file pass eps=1e-8 explicitly so their literals do not track the
- # default, which leaves the default itself pinned by nothing while six docstring warnings
- # quote numbers that hold only for eps=1e-8: cart2pol (rho = 1e-04 at the origin),
- # convert_points_from_homogeneous (the -1/3 and +1 relative errors at w = +/-2e-8),
- # normalize_pixel_coordinates and normalize_pixel_coordinates3d (the 199999999.0 / 2e8
- # blow-up factor) and denormalize_pixel_coordinates / denormalize_pixel_coordinates3d (the
- # 5e-09 collapse factor). If this fails, the default moved -- rework those warnings'
- # numbers together with this list.
- for op_name in (
- "cart2pol",
- "convert_points_from_homogeneous",
- "normalize_pixel_coordinates",
- "denormalize_pixel_coordinates",
- "normalize_pixel_coordinates3d",
- "denormalize_pixel_coordinates3d",
- ):
+ def test_non_positive_sizes_raise(self, op_name, sizes, bad_size, device, dtype):
+ op = getattr(kornia.geometry.conversions, op_name)
+ for index in range(len(sizes)):
+ bad_sizes = list(sizes)
+ bad_sizes[index] = bad_size
+ coords = torch.zeros(1, len(sizes), device=device, dtype=dtype)
+ with pytest.raises(ValueError, match="must be positive"):
+ op(coords, *bad_sizes)
+
+ def test_trace_crosses_singleton_boundary(self, device, dtype):
+ class Normalize(torch.nn.Module):
+ def forward(self, image, coords):
+ return kornia.geometry.conversions.normalize_pixel_coordinates(coords, image.shape[-2], image.shape[-1])
+
+ coords = torch.tensor([[0.0, 0.0], [0.5, 0.5]], device=device, dtype=dtype)
+ for trace_height, runtime_height in ((2, 1), (1, 2)):
+ example = torch.zeros(1, 1, trace_height, 4, device=device, dtype=dtype)
+ runtime = torch.zeros(1, 1, runtime_height, 4, device=device, dtype=dtype)
+ traced = torch.jit.trace(Normalize(), (example, coords))
+ self.assert_close(traced(runtime, coords), Normalize()(runtime, coords), atol=0.0, rtol=0.0)
+
+ class Normalize3d(torch.nn.Module):
+ def forward(self, volume, coords):
+ return kornia.geometry.conversions.normalize_pixel_coordinates3d(
+ coords, volume.shape[-3], volume.shape[-2], volume.shape[-1]
+ )
+
+ coords3d = torch.tensor([[0.0, 0.0, 0.0], [0.5, 0.5, 0.5]], device=device, dtype=dtype)
+ for trace_depth, runtime_depth in ((2, 1), (1, 2)):
+ example = torch.zeros(1, 1, trace_depth, 3, 4, device=device, dtype=dtype)
+ runtime = torch.zeros(1, 1, runtime_depth, 3, 4, device=device, dtype=dtype)
+ traced = torch.jit.trace(Normalize3d(), (example, coords3d))
+ self.assert_close(traced(runtime, coords3d), Normalize3d()(runtime, coords3d), atol=0.0, rtol=0.0)
+
+
+def test_wart_default_eps_1e_8_backs_the_remaining_quoted_warning_numbers():
+ # These two APIs still use eps numerically and quote outputs based on its default.
+ for op_name in ("cart2pol", "convert_points_from_homogeneous"):
op = getattr(kornia.geometry.conversions, op_name)
assert inspect.signature(op).parameters["eps"].default == 1e-8, op_name
@@ -3339,24 +3270,6 @@ def test_wart_float16_underflowed_default_eps_flips_branches(device):
assert_close(out, torch.tensor([[2.0, 4.0]], device=device, dtype=torch.float16), atol=0.0, rtol=0.0)
-def test_wart_float16_degenerate_roundtrip_is_inf_then_nan(device):
- # Wart pin for the float16 sentence of the #3940 warnings, float16-hardcoded like the test
- # above: with the default eps underflowed to 0, the clamp keeps the degenerate denominator
- # at 0, the normalized component is inf (not the 2e8 the other dtypes pin) and the
- # denormalize round trip of that is nan, not the input.
- # Snippet used to generate expected (torch only, executed on cpu float16):
- # normalize_pixel_coordinates(torch.ones(1, 2, dtype=torch.float16), 1, 1) -> [[inf, inf]]
- # denormalize_pixel_coordinates(<that>, 1, 1) -> [[nan, nan]]
- _skip_if_mps_clamp_caching(device)
-
- ones = torch.ones(1, 2, device=device, dtype=torch.float16)
- norm = kornia.geometry.conversions.normalize_pixel_coordinates(ones, 1, 1)
- assert (norm == torch.inf).all()
-
- denorm = kornia.geometry.conversions.denormalize_pixel_coordinates(norm, 1, 1)
- assert torch.isnan(denorm).all()
-
-
class TestDenormalizePixelCoordinates(BaseTester):
def test_tensor_bhw2(self, device, dtype):
height, width = 3, 4
@@ -3446,58 +3359,196 @@ class TestDenormalizePixelCoordinates(BaseTester):
out = kornia.geometry.conversions.denormalize_pixel_coordinates3d(norm, 3, 5, 9)
self.assert_close(out, pts)
- # Wart-pin matrix for kornia#3940, denormalizing half: one cell per (size argument x
- # degenerate class) of denormalize_pixel_coordinates and denormalize_pixel_coordinates3d,
- # asserting the CURRENT broken output that the docstring warnings document. If any cell
- # fails, #3940 was (partly) fixed -- update or remove the degenerate-size warnings in
- # normalize_pixel_coordinates, denormalize_pixel_coordinates, normalize_pixel_coordinates3d
- # and denormalize_pixel_coordinates3d. The cells are NOT a contract that degenerate sizes
- # must keep returning these values; see the polarity note on the normalize wart matrix,
- # which also explains why exactly one argument is degenerate per cell and why all three
- # classes (1, 0, -3) give the same output.
- # Here the clamped denominator multiplies instead of divides, so the degenerate axis
- # collapses to eps / 2 = 5e-09 rather than exploding to 2e8. The tolerance is tight
- # (rtol 1e-6, atol 0) on purpose: at atol 1e-2 the collapsed component would compare
- # equal to any small number, including the 0.0 a "clamp the output" fix might return.
- # It still holds at every dtype -- at float16 5e-09 underflows to 0.0 on both the
- # measured and the literal side, at bfloat16 both round to 5.005858838558197e-09, and the
- # finite components 2.0/3.0/4.0 are exact in every dtype.
- # Snippet used to generate expected (torch only; same output for bad in (1, 0, -3)):
- # dpc = kornia.geometry.conversions.denormalize_pixel_coordinates
- # dpc3 = kornia.geometry.conversions.denormalize_pixel_coordinates3d
- # dpc(torch.tensor([[0., 0.]], dtype=torch.float64), bad, 7, eps=1e-8) -> [[3.0, 5e-09]]
- # dpc(torch.tensor([[0., 0.]], dtype=torch.float64), 5, bad, eps=1e-8) -> [[5e-09, 2.0]]
- # dpc3(torch.tensor([[0., 0., 0.]], dtype=torch.float64), bad, 7, 9, eps=1e-8)
- # -> [[5e-09, 4.0, 3.0]]
- # dpc3(torch.tensor([[0., 0., 0.]], dtype=torch.float64), 5, bad, 9, eps=1e-8)
- # -> [[2.0, 4.0, 5e-09]]
- # dpc3(torch.tensor([[0., 0., 0.]], dtype=torch.float64), 5, 7, bad, eps=1e-8)
- # -> [[2.0, 5e-09, 3.0]]
- @pytest.mark.parametrize("degenerate_size", [1, 0, -3], ids=["one", "zero", "negative"])
+ def test_singleton_axes_are_exact_inverses(self, device, dtype):
+ pts = torch.tensor([[0.0, 0.0], [0.25, -0.5]], device=device, dtype=dtype)
+ norm = kornia.geometry.conversions.normalize_pixel_coordinates(pts, 1, 1)
+ out = kornia.geometry.conversions.denormalize_pixel_coordinates(norm, 1, 1)
+ self.assert_close(out, pts, atol=0.0, rtol=0.0)
+
+ pts3d = torch.tensor([[0.0, 0.0, 0.0], [0.25, -0.5, 0.75]], device=device, dtype=dtype)
+ norm3d = kornia.geometry.conversions.normalize_pixel_coordinates3d(pts3d, 1, 1, 1)
+ out3d = kornia.geometry.conversions.denormalize_pixel_coordinates3d(norm3d, 1, 1, 1)
+ self.assert_close(out3d, pts3d, atol=0.0, rtol=0.0)
+
+ @pytest.mark.parametrize("bad_size", [0, -3], ids=["zero", "negative"])
@pytest.mark.parametrize(
- ("ndim", "arg_name", "expected"),
+ ("op_name", "sizes"),
[
- ("2d", "height", [3.0, 5e-09]),
- ("2d", "width", [5e-09, 2.0]),
- ("3d", "depth", [5e-09, 4.0, 3.0]),
- ("3d", "height", [2.0, 4.0, 5e-09]),
- ("3d", "width", [2.0, 5e-09, 3.0]),
+ ("denormalize_pixel_coordinates", (5, 7)),
+ ("denormalize_pixel_coordinates3d", (5, 7, 9)),
],
- ids=["2d-height", "2d-width", "3d-depth", "3d-height", "3d-width"],
)
- def test_wart_degenerate_size_matrix(self, ndim, arg_name, degenerate_size, expected, device, dtype):
- _assert_degenerate_size_cell(
- kornia.geometry.conversions.denormalize_pixel_coordinates,
- kornia.geometry.conversions.denormalize_pixel_coordinates3d,
- 0.0,
- ndim,
- arg_name,
- degenerate_size,
- expected,
- (0.0, 1e-6),
- device,
- dtype,
- )
+ def test_non_positive_sizes_raise(self, op_name, sizes, bad_size, device, dtype):
+ op = getattr(kornia.geometry.conversions, op_name)
+ for index in range(len(sizes)):
+ bad_sizes = list(sizes)
+ bad_sizes[index] = bad_size
+ coords = torch.zeros(1, len(sizes), device=device, dtype=dtype)
+ with pytest.raises(ValueError, match="must be positive"):
+ op(coords, *bad_sizes)
+
+ @pytest.mark.parametrize(
+ "op_name",
+ [
+ "normalize_pixel_coordinates",
+ "denormalize_pixel_coordinates",
+ "normalize_pixel_coordinates3d",
+ "denormalize_pixel_coordinates3d",
+ ],
+ )
+ def test_non_default_eps_warns_and_is_ignored(self, op_name, device, dtype):
+ op = getattr(kornia.geometry.conversions, op_name)
+ ndim = 3 if op_name.endswith("3d") else 2
+ coords = torch.zeros(1, ndim, device=device, dtype=dtype)
+ sizes = (1, 1, 1) if ndim == 3 else (1, 1)
+ expected = op(coords, *sizes)
+ with pytest.warns(FutureWarning, match="deprecated and ignored"):
+ actual = op(coords, *sizes, eps=1.0)
+ self.assert_close(actual, expected, atol=0.0, rtol=0.0)
+
+ def test_trace_crosses_singleton_boundary(self, device, dtype):
+ class Denormalize(torch.nn.Module):
+ def forward(self, image, coords):
+ return kornia.geometry.conversions.denormalize_pixel_coordinates(
+ coords, image.shape[-2], image.shape[-1]
+ )
+
+ coords = torch.tensor([[0.0, 0.0], [0.5, 0.5]], device=device, dtype=dtype)
+ for trace_height, runtime_height in ((2, 1), (1, 2)):
+ example = torch.zeros(1, 1, trace_height, 4, device=device, dtype=dtype)
+ runtime = torch.zeros(1, 1, runtime_height, 4, device=device, dtype=dtype)
+ traced = torch.jit.trace(Denormalize(), (example, coords))
+ self.assert_close(traced(runtime, coords), Denormalize()(runtime, coords), atol=0.0, rtol=0.0)
+
+ class Denormalize3d(torch.nn.Module):
+ def forward(self, volume, coords):
+ return kornia.geometry.conversions.denormalize_pixel_coordinates3d(
+ coords, volume.shape[-3], volume.shape[-2], volume.shape[-1]
+ )
+
+ coords3d = torch.tensor([[0.0, 0.0, 0.0], [0.5, 0.5, 0.5]], device=device, dtype=dtype)
+ for trace_depth, runtime_depth in ((2, 1), (1, 2)):
+ example = torch.zeros(1, 1, trace_depth, 3, 4, device=device, dtype=dtype)
+ runtime = torch.zeros(1, 1, runtime_depth, 3, 4, device=device, dtype=dtype)
+ traced = torch.jit.trace(Denormalize3d(), (example, coords3d))
+ self.assert_close(traced(runtime, coords3d), Denormalize3d()(runtime, coords3d), atol=0.0, rtol=0.0)
+
+
+ ("op_name", "args"),
+ [
+ ("normalize_pixel_coordinates", (1, 1)),
+ ("denormalize_pixel_coordinates", (1, 1)),
+ ("normalize_pixel_coordinates3d", (1, 1, 1)),
+ ("denormalize_pixel_coordinates3d", (1, 1, 1)),
+ ],
+)
+def test_pixel_coordinate_singleton_policy_scripts(op_name, args, device, dtype):
+ op = getattr(kornia.geometry.conversions, op_name)
+ coords = torch.zeros(1, len(args), device=device, dtype=dtype)
+ scripted = torch.jit.script(op)
+ assert_close(scripted(coords, *args), op(coords, *args), atol=0.0, rtol=0.0)
+
+
+ ("op_name", "ndim"),
+ [
+ ("normalize_pixel_coordinates", 2),
+ ("denormalize_pixel_coordinates", 2),
+ ("normalize_pixel_coordinates3d", 3),
+ ("denormalize_pixel_coordinates3d", 3),
+ ],
+)
+def test_pixel_coordinate_export_crosses_singleton_boundary(op_name, ndim):
+ op = getattr(kornia.geometry.conversions, op_name)
+
+ class ExportCoordinates(torch.nn.Module):
+ def forward(self, image, coords):
+ if ndim == 2:
+ return op(coords, image.shape[-2], image.shape[-1])
+ return op(coords, image.shape[-3], image.shape[-2], image.shape[-1])
+
+ image_shape = (1, 1, 2, 4) if ndim == 2 else (1, 1, 2, 3, 4)
+ example = torch.zeros(image_shape)
+ coords = torch.tensor([[0.0] * ndim, [0.5] * ndim])
+ exported = torch.export.export(
+ ExportCoordinates(),
+ (example, coords),
+ dynamic_shapes=({2: torch.export.Dim("singleton_axis", min=1, max=8)}, None),
+ ).module()
+
+ for runtime_size in (1, 5):
+ runtime = torch.zeros(*image_shape[:2], runtime_size, *image_shape[3:])
+ assert_close(exported(runtime, coords), ExportCoordinates()(runtime, coords), atol=0.0, rtol=0.0)
+
+
+ ("op_name", "sizes"),
+ [
+ ("normalize_pixel_coordinates", (4, 5)),
+ ("denormalize_pixel_coordinates", (4, 5)),
+ ("normalize_pixel_coordinates3d", (4, 5, 6)),
+ ("denormalize_pixel_coordinates3d", (4, 5, 6)),
+ ("normal_transform_pixel", (4, 5)),
+ ("normal_transform_pixel3d", (4, 5, 6)),
+ ],
+)
+def test_non_default_eps_does_not_break_fullgraph_compile(op_name, sizes):
+ op = getattr(kornia.geometry, op_name)
+ value = torch.zeros(1, len(sizes))
+ if op_name.startswith("normal_transform"):
+
+ def captured(tensor):
+ return op(*sizes, eps=1e-6, device=tensor.device, dtype=tensor.dtype)
+
+ expected = op(*sizes, device=value.device, dtype=value.dtype)
+ else:
+
+ def captured(tensor):
+ return op(tensor, *sizes, eps=1e-6)
+
+ expected = op(value, *sizes)
+
+ actual = torch.compile(captured, fullgraph=True)(value)
+ assert_close(actual, expected, atol=0.0, rtol=0.0)
+
+
[email protected]("is_3d", [False, True], ids=["2d", "3d"])
+ ("dtype", "runtime_sizes"),
+ [
+ (torch.float32, (1, 5)),
+ (torch.bfloat16, (1, 257)),
+ (torch.float16, (1, 2049)),
+ ],
+ ids=["float32", "bfloat16-rounding-boundary", "float16-rounding-boundary"],
+)
+def test_normal_transform_export_crosses_singleton_boundary(is_3d, dtype, runtime_sizes):
+ class ExportTransform(torch.nn.Module):
+ def forward(self, image):
+ if is_3d:
+ return kornia.geometry.normal_transform_pixel3d(
+ image.shape[-3],
+ image.shape[-2],
+ image.shape[-1],
+ device=image.device,
+ dtype=image.dtype,
+ )
+ return kornia.geometry.normal_transform_pixel(
+ image.shape[-2], image.shape[-1], device=image.device, dtype=image.dtype
+ )
+
+ image_shape = (1, 1, 2, 3, 4) if is_3d else (1, 1, 2, 4)
+ example = torch.zeros(image_shape, dtype=dtype)
+ exported = torch.export.export(
+ ExportTransform(),
+ (example,),
+ dynamic_shapes=({2: torch.export.Dim("singleton_axis", min=1, max=max(runtime_sizes) + 1)},),
+ ).module()
+
+ for runtime_size in runtime_sizes:
+ runtime = torch.zeros(*image_shape[:2], runtime_size, *image_shape[3:], dtype=dtype)
+ assert_close(exported(runtime), ExportTransform()(runtime), atol=0.0, rtol=0.0)
class TestNormalTransformPixel(BaseTester):
@@ -3781,43 +3832,6 @@ class TestNormalTransformPixel(BaseTester):
self.assert_close(via_matrix, torch.tensor([1.0, -0.5, 0.75], device=device, dtype=dtype), atol=0.0, rtol=0.0)
self.assert_close(via_helper[[1, 2, 0]], via_matrix, atol=0.0, rtol=0.0)
- # Wart-pin matrix for kornia#3957: one cell per (size argument x degenerate class) of
- # normal_transform_pixel and normal_transform_pixel3d, asserting the CURRENT scale factor that
- # a degenerate size produces. If any cell fails, #3957 was (partly) fixed -- update or remove
- # the degenerate-size warnings on normal_transform_pixel, normal_transform_pixel3d,
- # normalize_homography and normalize_homography3d (denormalize_homography inherits these
- # warnings by reference), and also the
- # expected_2d_1 / expected_3d_1 rows of TestHomographyNormalTransform in
- # tests/geometry/transform/test_homography_warper.py, which hardcode the same
- # size == 1 -> 2e14 literal and would otherwise fail two directories away with nothing
- # connecting them to the fix. The cells are NOT a
- # contract that a degenerate size must keep returning these numbers.
- # They are regular tests rather than strict xfails for the same reason as the #3940 matrix in
- # TestNormalizePixelCoordinates: the intended behavior (raise, clamp, or keep the current
- # silent pass-through) is a maintainer decision, and a strict xfail asserting one of those
- # answers would stay silently XFAIL forever if a different one were chosen. A wart pin flips
- # loudly under every polarity, and covering the full matrix means any partial fix -- one
- # function, one argument, or one degenerate class -- flips at least one cell.
- # Exactly one size argument is degenerate per cell (the others stay at 3/5 in 2-D and 3/5/9 in
- # 3-D, whose scales are exact in every dtype), so the finite components pin which argument was
- # degenerated. The three classes give three different answers because only size == 1 is routed
- # to eps: size == 1 divides by eps = 1e-14 and gives 2e14, size == 0 divides by -1 and gives a
- # sign-flipped -2.0 (a mirroring transform), size == -3 divides by -4 and gives -0.5.
- # float32 is hardcoded and the dtype fixture dropped: any kornia-side change to a scale flips
- # the float32 cell. The 2-D scales are pure Python floats (2.0 / width_denom and friends)
- # computed before any tensor exists, so other legs would only test torch's cast; the 3-D
- # helper computes its scales as tensor arithmetic in the requested dtype
- # (tr_mat[i, i] * 2.0 / denominator), so its other legs would re-run that division under a
- # different rounding -- a claim about torch's arithmetic, not about which scale kornia
- # chooses, which the float32 cell already pins.
- # Snippet used to generate expected (torch only, executed on cpu float32/float64):
- # normal_transform_pixel(3, 1)[0, 0, 0] -> 200000000753664.0 (2 / 1e-14)
- # normal_transform_pixel(3, 0)[0, 0, 0] -> -2.0
- # normal_transform_pixel(3, -3)[0, 0, 0] -> -0.5
- # normal_transform_pixel3d(1, 5, 9)[0, 2, 2] -> 200000000753664.0
- @pytest.mark.parametrize(
- ("degenerate_size", "degenerate_scale"), [(1, 2e14), (0, -2.0), (-3, -0.5)], ids=["one", "zero", "negative"]
- )
@pytest.mark.parametrize(
("ndim", "arg_name", "diagonal"),
[
@@ -3829,21 +3843,20 @@ class TestNormalTransformPixel(BaseTester):
],
ids=["2d-height", "2d-width", "3d-depth", "3d-height", "3d-width"],
)
- def test_wart_degenerate_size_scale_matrix_3957(
- self, ndim, arg_name, diagonal, degenerate_size, degenerate_scale, device
- ):
+ def test_singleton_axis_maps_to_center(self, ndim, arg_name, diagonal, device):
expected = list(diagonal)
- expected[diagonal.index(None)] = degenerate_scale
+ axis = diagonal.index(None)
+ expected[axis] = 1.0
if ndim == "2d":
sizes = {"height": 3, "width": 5}
- sizes[arg_name] = degenerate_size
+ sizes[arg_name] = 1
matrix = kornia.geometry.conversions.normal_transform_pixel(
sizes["height"], sizes["width"], device=device, dtype=torch.float32
)
else:
sizes = {"depth": 3, "height": 5, "width": 9}
- sizes[arg_name] = degenerate_size
+ sizes[arg_name] = 1
matrix = kornia.geometry.conversions.normal_transform_pixel3d(
sizes["depth"], sizes["height"], sizes["width"], device=device, dtype=torch.float32
)
@@ -3851,38 +3864,74 @@ class TestNormalTransformPixel(BaseTester):
scales = torch.stack([matrix[0, i, i] for i in range(len(expected))])
self.assert_close(scales, torch.tensor(expected, device=device, dtype=torch.float32), atol=0.0, rtol=0.0)
+ self.assert_close(matrix[0, axis, -1], torch.tensor(0.0, device=device), atol=0.0, rtol=0.0)
- def test_wart_eps_guards_only_the_size_one_branch_3957(self, device):
- # Wart pin for kornia#3957, companion to the matrix above: eps is consulted ONLY in the
- # size == 1 branch -- the docstring now says exactly that ("denominator substituted for
- # size - 1 when a size equals 1; it is not consulted on any other path"), and this pin is
- # what keeps that sentence honest -- so the eps argument does not reach the case that is
- # literally a zero-sized image. float32 is
- # hardcoded and the dtype fixture dropped: which branch consults eps is a Python-level
- # size comparison decided before any tensor arithmetic, and the pinned answers 2.0 and
- # -2.0 are exact in every dtype, so no other-dtype leg can fail where float32 passes and
- # the fixture only multiplied cells. Three cells:
- # (0) the eps default is still 1e-14 -- a re-tuned default already flips the size == 1
- # cells of the matrix above loudly (they call with the default and pin 2/1e-14), so
- # this cell adds attribution, not detection: it fails naming the default itself
- # instead of leaving a reader to reverse-engineer a 2e14 mismatch;
- # (1) eps=1.0 changes the size == 1 answer to 2.0, proving that branch reads eps;
- # (2) the same eps=1.0 leaves the size == 0 answer at -2.0, proving that branch does not.
- # If any cell fails, #3957 was (partly) fixed -- flip/remove the matrix above. NOT a
- # contract that eps must keep being ignored on the size == 0 path.
- # Snippet used to generate expected (torch only, executed on cpu):
- # normal_transform_pixel(3, 1, eps=1.0)[0, 0, 0] -> 2.0
- # normal_transform_pixel(3, 0, eps=1.0)[0, 0, 0] -> -2.0
- normal_transform_pixel = kornia.geometry.conversions.normal_transform_pixel
- assert inspect.signature(normal_transform_pixel).parameters["eps"].default == 1e-14, (
- "kornia#3957: the eps default moved, so the 2e14 literals pinned above no longer describe a default call"
- )
+ @pytest.mark.parametrize(
+ ("op_name", "sizes"), [("normal_transform_pixel", (3, 1)), ("normal_transform_pixel3d", (3, 1, 5))]
+ )
+ def test_non_default_eps_warns_and_is_ignored(self, op_name, sizes, device):
+ op = getattr(kornia.geometry.conversions, op_name)
+ default = op(*sizes, device=device, dtype=torch.float32)
+ with pytest.warns(FutureWarning, match="deprecated and ignored"):
+ overridden = op(*sizes, eps=1.0, device=device, dtype=torch.float32)
+ self.assert_close(default, overridden, atol=0.0, rtol=0.0)
- size_one = normal_transform_pixel(3, 1, eps=1.0, device=device, dtype=torch.float32)[0, 0, 0]
- size_zero = normal_transform_pixel(3, 0, eps=1.0, device=device, dtype=torch.float32)[0, 0, 0]
+ @pytest.mark.parametrize("invalid_size", [0, -3], ids=["zero", "negative"])
+ @pytest.mark.parametrize(
+ ("ndim", "arg_name"),
+ [("2d", "height"), ("2d", "width"), ("3d", "depth"), ("3d", "height"), ("3d", "width")],
+ )
+ def test_non_positive_size_raises(self, ndim, arg_name, invalid_size, device):
+ if ndim == "2d":
+ sizes = {"height": 3, "width": 5}
+ sizes[arg_name] = invalid_size
+ with pytest.raises(ValueError, match="Input image size must be positive"):
+ kornia.geometry.conversions.normal_transform_pixel(sizes["height"], sizes["width"], device=device)
+ else:
+ sizes = {"depth": 3, "height": 5, "width": 9}
+ sizes[arg_name] = invalid_size
+ with pytest.raises(ValueError, match="Input image size must be positive"):
+ kornia.geometry.conversions.normal_transform_pixel3d(
+ sizes["depth"], sizes["height"], sizes["width"], device=device
+ )
- self.assert_close(size_one, torch.tensor(2.0, device=device, dtype=torch.float32), atol=0.0, rtol=0.0)
- self.assert_close(size_zero, torch.tensor(-2.0, device=device, dtype=torch.float32), atol=0.0, rtol=0.0)
+ @pytest.mark.parametrize("ndim", ["2d", "3d"])
+ @pytest.mark.parametrize(
+ ("default_dtype", "size"), [(torch.float16, 2049), (torch.bfloat16, 257)], ids=["float16", "bfloat16"]
+ )
+ def test_half_default_dtype_does_not_round_the_size_under_tracing(self, ndim, default_dtype, size, device):
+ # The graph-capture branch keeps the size arithmetic in at least float32 because a half
+ # type cannot hold every practical image size. That promotion has to key off the dtype the
+ # matrix is actually built in, not off the ``dtype`` ARGUMENT: with ``dtype=None`` the
+ # matrix inherits torch.get_default_dtype(), which may itself be a half type, and reading
+ # the argument alone leaves the size rounded in exactly the case the promotion exists for.
+ # The coordinate helpers resolve the output dtype first and were always right here; these
+ # two did not, so nothing else in this file covers the ``dtype=None`` + half-default cell.
+ # Sizes are picked so the size ITSELF is unrepresentable in the default dtype AND the
+ # rounding survives into the scale: float16 holds 2049 only as 2048, bfloat16 holds 257
+ # only as 256. Merely-unrepresentable is not enough -- at float16 and size 3001 the two
+ # paths compute 2/3000 and 2/2999, which round to the SAME float16, so that cell would
+ # pass whether or not the promotion happens. 2049 and 257 are the smallest sizes at which
+ # each dtype actually disagrees under torch.jit.trace.
+ class NormalTransformPixel(torch.nn.Module):
+ def forward(self, image):
+ if ndim == "3d":
+ return kornia.geometry.conversions.normal_transform_pixel3d(
+ image.shape[-3], image.shape[-2], image.shape[-1], device=image.device
+ )
+ return kornia.geometry.conversions.normal_transform_pixel(
+ image.shape[-2], image.shape[-1], device=image.device
+ )
+
+ previous = torch.get_default_dtype()
+ torch.set_default_dtype(default_dtype)
+ try:
+ shape = (1, 1, 3, size, 5) if ndim == "3d" else (1, 1, size, 5)
+ image = torch.zeros(*shape, device=device)
+ traced = torch.jit.trace(NormalTransformPixel(), image)
+ self.assert_close(traced(image), NormalTransformPixel()(image), atol=0.0, rtol=0.0)
+ finally:
+ torch.set_default_dtype(previous)
def test_wart_integer_dtype_truncates_the_scale_to_zero_3959(self, device):
# Wart pin for kornia#3959: the matrix is built by torch.tensor([...], dtype=dtype) from
@@ -3927,8 +3976,7 @@ class TestNormalizeHomography(BaseTester):
# constants leak, pinned separately below with non-dyadic sizes): a fix for #3958 must not flip
# an ordering or direction pin. The exactness invariant is theirs alone -- the bug pins below
# deliberately step outside it (the round-trip pin's non-dyadic (4, 5)/(8, 9) legs at
- # atol=32*eps, the #3960 shape-guard cells, the #3957 propagation warts), so a new atol=0 pin
- # belongs here
+ # atol=32*eps, the #3960 shape-guard cells), so a new atol=0 pin belongs here
# only at these sizes AND with a literal whose intermediates are exact. The invariant also
# leans on the SHAPE of the normalization matrices -- upper-triangular with power-of-two
# pivots -- surviving BOTH inverse routes actually in play (the functions do NOT share one):
@@ -3943,8 +3991,8 @@ class TestNormalizeHomography(BaseTester):
# No pin asserts anything about kornia#3962 (no denormalize_homography3d, no
# ColmapQTVecs_to_ARKitQTVecs) -- a missing symbol is a scope question, not a defect.
# NOTE: kornia#3904 (reserved) may extend this surface. EVERY literal in this class -- the
- # composition, direction, round-trip, batching and 3-D pins as much as the #3957 and #3958 bug
- # pins, and whether or not the pin repeats this line -- is built from the corner-aligned
+ # composition, direction, round-trip, batching and 3-D pins as much as the #3957 singleton and
+ # #3958 bug pins, and whether or not the pin repeats this line -- is built from the corner-aligned
# 2/(size - 1) constants these three functions inherit from normal_transform_pixel, so a #3904
# fix that made the normalization respect align_corners would flip all of them. They record
# current default behavior; none of them ratifies that choice as contract. (The #3958 pins would
@@ -4407,9 +4455,8 @@ class TestNormalizeHomography(BaseTester):
# rejects the mix. denormalize_homography inverts the other matrix and by the other route
# -- _torch_inverse_cast, i.e. torch.linalg.inv -- which dies on the zero diagonal of the
# truncated matrix before any matmul runs.
- # Both legs are gated by capability PROBES rather than a device-name list, matching
- # test_wart_one_pixel_output_makes_warp_perspective_all_nan_3957 below: each probe IS the
- # mechanism its leg claims, so a future backend that behaves like cpu is covered instead
+ # Both legs are gated by capability PROBES rather than a device-name list: each probe IS
+ # the mechanism its leg claims, so a future backend that behaves like cpu is covered instead
# of skipped. Executed: cpu rejects the mixed batched matmul and reports a singular
# inverse as torch.linalg.LinAlgError; mps accepts the matmul (hence the all-nan float32
# result) and reports the singular inverse as a plain RuntimeError. The matmul probe must
@@ -4558,100 +4605,21 @@ class TestNormalizeHomography(BaseTester):
with pytest.raises(ValueError, match="dst_pix_trans_src_pix"):
op(eye.expand(2, 1, size, size), *sizes)
- def test_wart_degenerate_dsize_propagates_into_the_homography_3957(self, device):
- # Wart pin for kornia#3957 in the homography functions: the degenerate scales pinned in
- # TestNormalTransformPixel are not contained by the composition -- they arrive in the
- # returned matrix, silently and finite. Four cells, each a different way the same root
- # shows up:
- # (1) normalize_homography with a 1-pixel-wide source collapses the x scale to 2.5e-15;
- # (2) denormalize_homography with the same sizes explodes it to 4.0e+14 instead -- the
- # reciprocal, because the two functions invert opposite factors;
- # (3) normalize_homography with a ZERO-wide source silently mirrors (a negative x scale
- # and a shifted offset), a different degenerate class that no fix for (1) need touch;
- # (4) normalize_homography3d with depth == 1 returns a matrix whose z scale is 5.0e-15 --
- # near-singular in practice, not formally singular, so nothing downstream raises.
- # If any cell fails, #3957 was (partly) fixed -- flip/remove the matrix in
- # TestNormalTransformPixel too. NOT a contract that a degenerate dsize must keep producing
- # these numbers.
- # float32 is hardcoded and the dtype fixture dropped: at float16 the 2e14 scale overflows to
- # inf and the chain degenerates by a different mechanism (this pin does not decide that
- # case), while at float64 the constants are still built in float32 (kornia#3958) so the
- # literals would be the same numbers pinned twice.
- # rtol 1e-6 rather than an exact comparison: the entries are float32 values printed at
- # float64 precision, and one ulp of 2.5e-15 is 5e-22 -- far tighter than any claim made here.
- # Snippet used to generate expected (torch only, executed on cpu float32):
- # normalize_homography(eye(3)[None], (4, 1), (4, 5))[0, 0] -> 2.500000167887412e-15
- # denormalize_homography(eye(3)[None], (4, 1), (4, 5))[0, 0] -> 400000001507328.0
- # normalize_homography(eye(3)[None], (4, 0), (4, 5))[0] -> [-0.25, 0.0, -1.25]
- # normalize_homography3d(eye(4)[None], (1, 4, 5), (3, 8, 9))[2, 2] -> 4.99999991225835e-15
+ def test_singleton_dsize_produces_finite_homographies(self, device):
identity = torch.eye(3, device=device, dtype=torch.float32)[None]
identity3d = torch.eye(4, device=device, dtype=torch.float32)[None]
- collapsed = kornia.geometry.conversions.normalize_homography(identity, (4, 1), (4, 5))[0, 0, 0]
- exploded = kornia.geometry.conversions.denormalize_homography(identity, (4, 1), (4, 5))[0, 0, 0]
- mirrored = kornia.geometry.conversions.normalize_homography(identity, (4, 0), (4, 5))[0, 0]
- near_singular = kornia.geometry.conversions.normalize_homography3d(identity3d, (1, 4, 5), (3, 8, 9))[0, 2, 2]
-
- assert_close(
- collapsed,
- torch.tensor(2.500000167887412e-15, device=device, dtype=torch.float32),
- rtol=1e-6,
- atol=0.0,
- msg=_issue_msg("kornia#3957: a 1-pixel-wide source no longer collapses the normalized x scale"),
- )
- assert_close(
- exploded,
- torch.tensor(400000001507328.0, device=device, dtype=torch.float32),
- rtol=1e-6,
- atol=0.0,
- msg=_issue_msg("kornia#3957: a 1-pixel-wide source no longer explodes the denormalized x scale"),
- )
- assert_close(
- mirrored,
- torch.tensor([-0.25, 0.0, -1.25], device=device, dtype=torch.float32),
- rtol=1e-6,
- atol=0.0,
- msg=_issue_msg("kornia#3957: a zero-wide source no longer produces a mirrored normalization"),
- )
- assert_close(
- near_singular,
- torch.tensor(4.99999991225835e-15, device=device, dtype=torch.float32),
- rtol=1e-6,
- atol=0.0,
- msg=_issue_msg("kornia#3957: depth == 1 no longer collapses the normalized z scale"),
- )
-
- def test_wart_one_pixel_output_makes_warp_perspective_all_nan_3957(self, device):
- # Wart pin for the user-visible end of kornia#3957, executed rather than argued: a
- # 1-pixel-high output size sends normalize_homography's 2e14 scale into
- # warp_perspective's grid and every sampled value comes back NaN -- with align_corners=True,
- # i.e. in the branch kornia#3904's reserved fix does not touch. crop_by_transform_mat is
- # pinned in the same test because it is the caller kornia#3929 reports the symptom from.
- # The finite control at a 2-pixel-high output is what makes the two NaN cells evidence of
- # the degenerate denominator rather than of warp_perspective being broken in general.
- # NaN is checked with torch.isnan, never with an equality against a NaN literal.
- # If any cell fails, #3957 was (partly) fixed -- flip/remove the wart pins above. NOT a
- # contract that a 1-pixel output must keep returning NaN.
- # float32 is hardcoded and the dtype fixture dropped: this pin is about a size, not a dtype.
- # TWO LAYERS, on purpose. The load-bearing claim -- the 1-pixel output is BROKEN while the
- # 2-pixel control is not -- is asserted device-portably: the 1-row output does not reproduce
- # the row the same identity warp produces at 2 rows. The stronger "and the breakage is
- # specifically all-NaN" form is asserted only on the devices it was generated and verified
- # on backends whose grid_sample propagates an all-NaN grid (probed below; cpu and mps,
- # executed), because the NaN depends on backend NaN handling inside grid_sample: the
- # sampling grid entering it is entirely NaN, and with padding_mode='zeros' a kernel that
- # turns floor(NaN) into a failed within-bounds check would emit 0.0 instead of NaN. That
- # would still be a broken output -- and the portable assertion would still catch it -- but
- # it is not a fact this branch has executed, and no CUDA fact is claimed anywhere in this
- # work. Asserting all-NaN unconditionally would let an untested backend fail here and be
- # misread as "#3957 was partly fixed", which is the one misreading this pin must not invite.
- # Snippet used to generate expected (torch only, executed on cpu float32, torch 2.9.1; the
- # same three lines re-executed on mps give the same verdicts):
- # img = torch.arange(25.).view(1, 1, 5, 5)
- # warp_perspective(img, torch.eye(3)[None], (1, 4), align_corners=True) -> all nan
- # crop_by_transform_mat(img, torch.eye(3)[None], (1, 4), align_corners=True) -> all nan
- # warp_perspective(img, torch.eye(3)[None], (2, 4), align_corners=True)
- # -> [[0., 1., 2., 3.], [5., 6., 7., 8.]] (finite control)
+ outputs = [
+ kornia.geometry.conversions.normalize_homography(identity, (4, 1), (4, 5)),
+ kornia.geometry.conversions.normalize_homography(identity, (4, 5), (4, 1)),
+ kornia.geometry.conversions.denormalize_homography(identity, (4, 1), (4, 5)),
+ kornia.geometry.conversions.denormalize_homography(identity, (4, 5), (4, 1)),
+ kornia.geometry.conversions.normalize_homography3d(identity3d, (1, 4, 5), (3, 8, 9)),
+ kornia.geometry.conversions.normalize_homography3d(identity3d, (3, 8, 9), (1, 4, 5)),
+ ]
+ assert all(torch.isfinite(output).all() for output in outputs)
+
+ def test_one_pixel_output_is_finite_3957(self, device):
image = torch.arange(25.0, device=device, dtype=torch.float32).view(1, 1, 5, 5)
identity = torch.eye(3, device=device, dtype=torch.float32)[None]
@@ -4659,37 +4627,22 @@ class TestNormalizeHomography(BaseTester):
cropped = kornia.geometry.transform.crop_by_transform_mat(image, identity, (1, 4), align_corners=True)
control = kornia.geometry.transform.warp_perspective(image, identity, (2, 4), align_corners=True)
- assert torch.isfinite(control).all(), (
- "kornia#3957: the 2-pixel-high control is no longer finite, so the cells above stopped being evidence"
- )
- assert not torch.equal(warped[0, 0, 0], control[0, 0, 0]), (
- "kornia#3957: a 1-pixel-high warp_perspective output now reproduces the 2-row control's first row, "
- "i.e. the degenerate size no longer corrupts the sampling grid"
- )
- assert not torch.equal(cropped[0, 0, 0], control[0, 0, 0]), (
- "kornia#3957: a 1-pixel-high crop_by_transform_mat output now reproduces the 2-row control's first row"
- )
+ assert torch.isfinite(warped).all()
+ assert torch.isfinite(cropped).all()
+ self.assert_close(warped[0, 0, 0], control[0, 0, 0], atol=0.0, rtol=0.0)
+ self.assert_close(cropped[0, 0, 0], control[0, 0, 0], atol=0.0, rtol=0.0)
- # Capability probe instead of a device-name list, so the all-NaN leg self-extends to any
- # backend whose grid_sample propagates an all-NaN grid and shows up as a SKIP (not a
- # silent pass) anywhere else. The portable corruption assertions above have already run
- # by this point on every device.
- nan_grid = torch.full((1, 1, 1, 2), float("nan"), device=device, dtype=torch.float32)
- probe = torch.nn.functional.grid_sample(
- torch.zeros(1, 1, 2, 2, device=device, dtype=torch.float32), nan_grid, align_corners=True
- )
- if not torch.isnan(probe).all():
- pytest.skip(
- "this backend's grid_sample does not propagate an all-NaN sampling grid; the "
- "all-NaN symptom leg is scoped to backends where it does (executed: cpu, mps)"
- )
+ @pytest.mark.parametrize(("trace_height", "runtime_height"), [(5, 1), (1, 5)])
+ def test_one_pixel_output_trace_crosses_singleton_source_boundary(self, trace_height, runtime_height, device):
+ class WarpPerspective(torch.nn.Module):
+ def forward(self, image, transform):
+ return kornia.geometry.transform.warp_perspective(image, transform, (1, 4), align_corners=True)
- assert torch.isnan(warped).all(), (
- "kornia#3957: a 1-pixel-high warp_perspective output is no longer all-NaN on this device"
- )
- assert torch.isnan(cropped).all(), (
- "kornia#3957: a 1-pixel-high crop_by_transform_mat output is no longer all-NaN on this device"
- )
+ identity = torch.eye(3, device=device, dtype=torch.float32)[None]
+ example = torch.arange(float(trace_height * 5), device=device).view(1, 1, trace_height, 5)
+ runtime = torch.arange(float(runtime_height * 5), device=device).view(1, 1, runtime_height, 5)
+ traced = torch.jit.trace(WarpPerspective(), (example, identity))
+ self.assert_close(traced(runtime, identity), WarpPerspective()(runtime, identity), atol=0.0, rtol=0.0)
class TestProjectPoints(BaseTester):
@@ -5532,7 +5485,7 @@ class TestCamtoworldRtToPoseRt(BaseTester):
# There is deliberately NO companion strict xfail: the intended behavior is undecided -- a
# fix could raise on a non-orthogonal R, or fall back to a true inverse -- and an
# assertion-shaped xfail could express only one of those and would stay silently XFAIL if
- # the other were chosen. Same shape as the #3948 and #3957 wart pins in this file.
+ # the other were chosen. Same shape as the #3948 wart pins in this file.
# If any cell fails, #3961 was (partly) fixed -- remove this pin. NOT a contract that a
# non-orthogonal R must keep producing these numbers.
# R = [[1, 0.5, 0], [0, 1, 0], [0, 0, 2]] has det = 2 and dyadic entries, so every literal
diff --git a/tests/geometry/test_grid.py b/tests/geometry/test_grid.py
index fb1ad8661..8f03bce48 100644
--- a/tests/geometry/test_grid.py
+++ b/tests/geometry/test_grid.py
@@ -71,6 +71,159 @@ def test_normalize_pixel_grid(device, dtype):
assert_close(grid_norm, grid_pix_to_norm)
[email protected](("height", "width"), [(1, 4), (4, 1), (1, 1)])
+def test_normalized_meshgrid_singleton_axis_is_centered(height, width, device, dtype):
+ grid = kornia.geometry.create_meshgrid(height, width, normalized_coordinates=True, device=device, dtype=dtype)
+
+ if height == 1:
+ assert_close(grid[..., 1], torch.zeros_like(grid[..., 1]), atol=0.0, rtol=0.0)
+ if width == 1:
+ assert_close(grid[..., 0], torch.zeros_like(grid[..., 0]), atol=0.0, rtol=0.0)
+
+
[email protected](("height", "width"), [(1, 4), (4, 1), (1, 1), (4, 6)])
[email protected]("grid_dtype", [torch.int32, torch.int64])
+def test_normalized_meshgrid_integer_dtype_promotes_uniformly(height, width, grid_dtype, device):
+ # An integer ``dtype`` makes the non-singleton branch promote to the default float dtype
+ # (integer division), so the singleton branch must promote identically or torch.meshgrid
+ # rejects the mixed pair. Eager and tracing take different code paths here; this pins that
+ # they agree, and that a singleton axis is still centred once promoted.
+ grid = kornia.geometry.create_meshgrid(height, width, normalized_coordinates=True, device=device, dtype=grid_dtype)
+
+ assert grid.dtype == torch.get_default_dtype()
+ if height == 1:
+ assert_close(grid[..., 1], torch.zeros_like(grid[..., 1]), atol=0.0, rtol=0.0)
+ if width == 1:
+ assert_close(grid[..., 0], torch.zeros_like(grid[..., 0]), atol=0.0, rtol=0.0)
+
+
[email protected]("grid_dtype", [torch.int32, torch.int64])
[email protected](("trace_height", "runtime_height"), [(2, 1), (1, 2)])
+def test_normalized_meshgrid_integer_trace_crosses_singleton_boundary(grid_dtype, trace_height, runtime_height, device):
+ class IntegerMeshGrid(torch.nn.Module):
+ def forward(self, image):
+ return kornia.geometry.create_meshgrid(
+ image.shape[-2],
+ image.shape[-1],
+ normalized_coordinates=True,
+ device=image.device,
+ dtype=grid_dtype,
+ )
+
+ example = torch.zeros(1, 1, trace_height, 4, device=device)
+ runtime = torch.zeros(1, 1, runtime_height, 4, device=device)
+ traced = torch.jit.trace(IntegerMeshGrid(), example)
+ assert_close(traced(runtime), IntegerMeshGrid()(runtime), atol=0.0, rtol=0.0)
+
+
[email protected](("trace_height", "runtime_height"), [(2, 1), (1, 2)])
+def test_normalized_meshgrid_trace_crosses_singleton_boundary(trace_height, runtime_height, device, dtype):
+ class MeshGrid(torch.nn.Module):
+ def forward(self, image):
+ return kornia.geometry.create_meshgrid(
+ image.shape[-2], image.shape[-1], normalized_coordinates=True, device=image.device, dtype=image.dtype
+ )
+
+ example = torch.zeros(1, 1, trace_height, 4, device=device, dtype=dtype)
+ runtime = torch.zeros(1, 1, runtime_height, 4, device=device, dtype=dtype)
+ traced = torch.jit.trace(MeshGrid(), example)
+ assert_close(traced(runtime), MeshGrid()(runtime), atol=0.0, rtol=0.0)
+
+
[email protected]("is_3d", [False, True], ids=["2d", "3d"])
[email protected]("size", [258, 300, 1000, 2050, 3000])
+def test_normalized_meshgrid_trace_matches_eager_at_unrepresentable_sizes(is_3d, size, device, dtype):
+ """A size whose predecessor does not fit the coordinate dtype must not round the divisor.
+
+ ``bfloat16`` holds 299 only as 300, so casting ``size - 1`` into the coordinate dtype before
+ dividing shifts every normalized coordinate -- up to 0.0078 in bfloat16, 0.00098 in float16.
+ Eager divides by a Python ``int``, so the traced graph has to divide against the unrounded
+ size too and round only the quotient. Every size the singleton-boundary tests above use is
+ representable in all four dtypes, so none of them can catch this.
+
+ The sizes here are the ones whose predecessor is *not* exactly representable in bfloat16
+ (all five) or float16 (2050 and 3000); at float32 and float64 they all are, which pins the
+ two paths as agreeing there rather than merely not being compared.
+ """
+
+ class MeshGrid(torch.nn.Module):
+ def forward(self, image):
+ if is_3d:
+ return kornia.geometry.create_meshgrid3d(
+ image.shape[-3],
+ image.shape[-2],
+ image.shape[-1],
+ normalized_coordinates=True,
+ device=image.device,
+ dtype=image.dtype,
+ )
+ return kornia.geometry.create_meshgrid(
+ image.shape[-2], image.shape[-1], normalized_coordinates=True, device=image.device, dtype=image.dtype
+ )
+
+ shape = (1, 1, 2, size, 4) if is_3d else (1, 1, size, 4)
+ image = torch.zeros(*shape, device=device, dtype=dtype)
+ traced = torch.jit.trace(MeshGrid(), image)
+ assert_close(traced(image), MeshGrid()(image), atol=0.0, rtol=0.0)
+
+
[email protected]("normalized_coordinates", [False, True], ids=["pixel", "normalized"])
[email protected]("is_3d", [False, True], ids=["2d", "3d"])
+def test_meshgrid_export_crosses_singleton_boundary(is_3d, normalized_coordinates):
+ class MeshGrid(torch.nn.Module):
+ def forward(self, image):
+ if is_3d:
+ return kornia.geometry.create_meshgrid3d(
+ image.shape[-3],
+ image.shape[-2],
+ image.shape[-1],
+ normalized_coordinates=normalized_coordinates,
+ device=image.device,
+ )
+ return kornia.geometry.create_meshgrid(
+ image.shape[-2],
+ image.shape[-1],
+ normalized_coordinates=normalized_coordinates,
+ device=image.device,
+ )
+
+ image_shape = (1, 1, 2, 3, 4) if is_3d else (1, 1, 2, 4)
+ example = torch.zeros(image_shape)
+ exported = torch.export.export(
+ MeshGrid(),
+ (example,),
+ dynamic_shapes=({2: torch.export.Dim("singleton_axis", min=1, max=8)},),
+ ).module()
+
+ for runtime_size in (1, 5):
+ runtime = torch.zeros(*image_shape[:2], runtime_size, *image_shape[3:])
+ assert_close(exported(runtime), MeshGrid()(runtime), atol=0.0, rtol=0.0)
+
+
[email protected]("default_dtype", [torch.float32, torch.float64])
[email protected]("is_3d", [False, True], ids=["2d", "3d"])
+def test_pixel_meshgrid_default_dtype_matches_compile(is_3d, default_dtype):
+ class MeshGrid(torch.nn.Module):
+ def forward(self, image):
+ if is_3d:
+ return kornia.geometry.create_meshgrid3d(
+ image.shape[-3], image.shape[-2], image.shape[-1], False, device=image.device
+ )
+ return kornia.geometry.create_meshgrid(image.shape[-2], image.shape[-1], False, device=image.device)
+
+ image = torch.zeros((1, 1, 2, 3, 4) if is_3d else (1, 1, 3, 4), dtype=torch.float32)
+ previous_dtype = torch.get_default_dtype()
+ try:
+ torch.set_default_dtype(default_dtype)
+ expected = MeshGrid()(image)
+ actual = torch.compile(MeshGrid(), fullgraph=True)(image)
+ finally:
+ torch.set_default_dtype(previous_dtype)
+
+ assert actual.dtype == expected.dtype == default_dtype
+ assert_close(actual, expected, atol=0.0, rtol=0.0)
+
+
def test_create_meshgrid3d(device, dtype):
depth, height, width = 5, 4, 6
normalized_coordinates = False
@@ -85,3 +238,30 @@ def test_create_meshgrid3d(device, dtype):
# check grid corner values
assert tuple(grid[0, 0, 0, 0].cpu().numpy()) == (0.0, 0.0, 0.0)
assert tuple(grid[0, depth - 1, height - 1, width - 1].cpu().numpy()) == (depth - 1, width - 1, height - 1)
+
+
[email protected](("depth", "height", "width", "axis"), [(1, 4, 6, 0), (5, 1, 6, 2), (5, 4, 1, 1)])
+def test_normalized_meshgrid3d_singleton_axis_is_centered(depth, height, width, axis, device, dtype):
+ grid = kornia.geometry.create_meshgrid3d(
+ depth, height, width, normalized_coordinates=True, device=device, dtype=dtype
+ )
+ assert_close(grid[..., axis], torch.zeros_like(grid[..., axis]), atol=0.0, rtol=0.0)
+
+
[email protected](("trace_depth", "runtime_depth"), [(2, 1), (1, 2)])
+def test_normalized_meshgrid3d_trace_crosses_singleton_boundary(trace_depth, runtime_depth, device, dtype):
+ class MeshGrid3d(torch.nn.Module):
+ def forward(self, volume):
+ return kornia.geometry.create_meshgrid3d(
+ volume.shape[-3],
+ volume.shape[-2],
+ volume.shape[-1],
+ normalized_coordinates=True,
+ device=volume.device,
+ dtype=volume.dtype,
+ )
+
+ example = torch.zeros(1, 1, trace_depth, 3, 4, device=device, dtype=dtype)
+ runtime = torch.zeros(1, 1, runtime_depth, 3, 4, device=device, dtype=dtype)
+ traced = torch.jit.trace(MeshGrid3d(), example)
+ assert_close(traced(runtime), MeshGrid3d()(runtime), atol=0.0, rtol=0.0)
diff --git a/tests/geometry/transform/test_homography_warper.py b/tests/geometry/transform/test_homography_warper.py
index 042edca68..6c7037a2d 100644
--- a/tests/geometry/transform/test_homography_warper.py
+++ b/tests/geometry/transform/test_homography_warper.py
@@ -367,18 +367,14 @@ class TestHomographyWarper(BaseTester):
class TestHomographyNormalTransform(BaseTester):
expected_2d_0 = torch.tensor([[[0.5, 0.0, -1.0], [0.0, 2.0, -1.0], [0.0, 0.0, 1.0]]])
- # kornia#3957: the 2e14 rows below hardcode the size == 1 -> 2 / eps degenerate scale, the same
- # literal pinned by TestNormalTransformPixel's wart matrix in tests/geometry/test_conversions.py
- # -- a #3957 fix flips both files together.
- expected_2d_1 = torch.tensor([[[0.5, 0.0, -1.0], [0.0, 2e14, -1.0], [0.0, 0.0, 1.0]]])
+ expected_2d_1 = torch.tensor([[[0.5, 0.0, -1.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]]])
expected_3d_0 = expected = torch.tensor(
[[[0.4, 0.0, 0.0, -1.0], [0.0, 2.0, 0.0, -1.0], [0.0, 0.0, 0.6667, -1.0], [0.0, 0.0, 0.0, 1.0]]]
)
- # kornia#3957: same degenerate-scale literal as expected_2d_1 above, 3-D variant.
expected_3d_1 = torch.tensor(
- [[[0.4, 0.0, 0.0, -1.0], [0.0, 2e14, 0.0, -1.0], [0.0, 0.0, 0.6667, -1.0], [0.0, 0.0, 0.0, 1.0]]]
+ [[[0.4, 0.0, 0.0, -1.0], [0.0, 1.0, 0.0, 0.0], [0.0, 0.0, 0.6667, -1.0], [0.0, 0.0, 0.0, 1.0]]]
)
@pytest.mark.parametrize("height,width,expected", [(2, 5, expected_2d_0), (1, 5, expected_2d_1)])
diff --git a/tests/geometry/transform/test_imgwarp.py b/tests/geometry/transform/test_imgwarp.py
index 9ed55a3a2..37dcfd36c 100644
--- a/tests/geometry/transform/test_imgwarp.py
+++ b/tests/geometry/transform/test_imgwarp.py
@@ -27,6 +27,17 @@ from kornia.core.utils import _torch_inverse_cast
from testing.base import BaseTester
+def _skip_if_mps_empty_grid_sample(device):
+ """Skip when a zero-element sampling grid cannot reach ``grid_sample``.
+
+ PyTorch's MPS backend raises ``[srcBuf length] > 0 INTERNAL ASSERT FAILED ... Placeholder
+ tensor is empty!`` for a zero-element ``grid_sample`` argument, so an empty warp destination
+ is unreachable there regardless of how kornia builds it.
+ """
+ if device.type == "mps":
+ pytest.skip("MPS grid_sample asserts on zero-element tensors")
+
+
class DummyNNModule(torch.nn.Module):
def __init__(self, h: int, w: int, align_corners: bool, padding_mode: str):
super().__init__()
@@ -37,6 +48,157 @@ class DummyNNModule(torch.nn.Module):
return kornia.geometry.transform.warp_affine(x, y, dsize=(self.h, self.w), align_corners=False)
[email protected]("op_name", ["warp_affine", "warp_perspective"])
[email protected]("dsize", [(0, 4), (3, 0)])
[email protected]("align_corners", [True, False])
[email protected]("padding_mode", ["zeros", "fill"])
+def test_empty_destination_is_autograd_connected(op_name, dsize, align_corners, padding_mode, device, dtype):
+ _skip_if_mps_empty_grid_sample(device)
+ src = torch.rand(1, 3, 3, 4, device=device, dtype=dtype, requires_grad=True)
+ if op_name == "warp_affine":
+ transform = torch.eye(2, 3, device=device, dtype=dtype).unsqueeze(0).requires_grad_()
+ else:
+ transform = torch.eye(3, device=device, dtype=dtype).unsqueeze(0).requires_grad_()
+ op = getattr(kornia.geometry.transform, op_name)
+
+ out = op(
+ src,
+ transform,
+ dsize,
+ padding_mode=padding_mode,
+ align_corners=align_corners,
+ fill_value=torch.tensor([0.1, 0.2, 0.3], device=device, dtype=dtype),
+ )
+
+ assert out.shape == (1, 3, *dsize)
+ assert out.numel() == 0
+ out.sum().backward()
+ assert src.grad is not None and torch.count_nonzero(src.grad) == 0
+ assert transform.grad is not None and torch.count_nonzero(transform.grad) == 0
+
+
[email protected]("op_name", ["warp_affine", "warp_perspective"])
+def test_empty_source_policy(op_name, device, dtype):
+ _skip_if_mps_empty_grid_sample(device)
+ src = torch.empty(1, 3, 0, 4, device=device, dtype=dtype, requires_grad=True)
+ if op_name == "warp_affine":
+ transform = torch.eye(2, 3, device=device, dtype=dtype).unsqueeze(0).requires_grad_()
+ else:
+ transform = torch.eye(3, device=device, dtype=dtype).unsqueeze(0).requires_grad_()
+ op = getattr(kornia.geometry.transform, op_name)
+
+ empty = op(src, transform, (0, 4))
+ assert empty.shape == (1, 3, 0, 4)
+ empty.sum().backward()
+ assert src.grad is not None and transform.grad is not None
+
+ with pytest.raises(ValueError, match="must be positive"):
+ op(src, transform, (3, 4))
+
+
+def _output_dtype_or_none(call):
+ """Return the output dtype of ``call``, or ``None`` when it rejects its inputs."""
+ try:
+ return call().dtype
+ except Exception:
+ return None
+
+
[email protected]("op_name", ["warp_affine", "warp_perspective"])
[email protected]("src_dtype", [torch.float32, torch.float64])
[email protected]("matrix_dtype", [torch.float32, torch.float64, torch.int64])
+def test_empty_destination_follows_nonempty_dtype_policy(op_name, src_dtype, matrix_dtype, device):
+ if device.type == "mps":
+ pytest.skip("MPS does not support float64")
+ op = getattr(kornia.geometry.transform, op_name)
+ rows = 2 if op_name == "warp_affine" else 3
+ src = torch.zeros(1, 3, 3, 4, device=device, dtype=src_dtype)
+ matrix = torch.eye(3, device=device)[:rows].to(matrix_dtype).unsqueeze(0)
+
+ # An empty ``dsize`` must accept exactly the matrix dtypes the non-empty pipeline accepts:
+ # a matrix that promotes into ``src.dtype`` samples fine, one that narrows it or is integral
+ # (``normalize_homography`` scales it by floating factors) fails on both paths.
+ empty_dtype = _output_dtype_or_none(lambda: op(src, matrix, (0, 4)))
+ assert empty_dtype == _output_dtype_or_none(lambda: op(src, matrix, (1, 4)))
+ if src_dtype == matrix_dtype:
+ # Guards the paired assertion above against passing vacuously on two failures.
+ assert empty_dtype == src_dtype
+ assert op(src, matrix, (0, 4)).shape == (1, 3, 0, 4)
+
+
[email protected]("op_name", ["warp_affine", "warp_perspective"])
+def test_empty_destination_blames_an_integral_src_by_name(op_name, device):
+ """``grid_sample`` rejects an integral image on both paths; the message must name ``src``.
+
+ Scoped away from MPS, whose ``grid_sample`` accepts an integral image and samples it back into
+ ``int64`` instead of rejecting it, so the non-empty half of the pairing does not hold there.
+ """
+ if device.type == "mps":
+ pytest.skip("MPS grid_sample accepts an integral image instead of rejecting it")
+ op = getattr(kornia.geometry.transform, op_name)
+ rows = 2 if op_name == "warp_affine" else 3
+ src = torch.zeros(1, 3, 3, 4, device=device, dtype=torch.int64)
+ matrix = torch.eye(3, device=device)[:rows].unsqueeze(0)
+
+ with pytest.raises(RuntimeError, match="floating point src"):
+ op(src, matrix, (0, 4))
+ # The non-empty path rejects it too, so the empty guard is not stricter.
+ with pytest.raises((RuntimeError, NotImplementedError)):
+ op(src, matrix, (1, 4))
+
+
[email protected]("op_name", ["warp_affine", "warp_perspective"])
+def test_negative_destination_raises(op_name, device, dtype):
+ src = torch.rand(1, 3, 3, 4, device=device, dtype=dtype)
+ transform = (
+ torch.eye(2, 3, device=device, dtype=dtype).unsqueeze(0)
+ if op_name == "warp_affine"
+ else torch.eye(3, device=device, dtype=dtype).unsqueeze(0)
+ )
+ with pytest.raises(ValueError, match="must be non-negative"):
+ getattr(kornia.geometry.transform, op_name)(src, transform, (-1, 4))
+
+
[email protected]("op_name", ["warp_affine", "warp_perspective"])
+def test_empty_destination_keeps_grid_sample_validation(op_name, device, dtype):
+ src = torch.rand(2, 3, 3, 4, device=device, dtype=dtype)
+ matrix_size = (2, 3) if op_name == "warp_affine" else (3, 3)
+ transform = torch.eye(*matrix_size, device=device, dtype=dtype).repeat(3, 1, 1)
+ op = getattr(kornia.geometry.transform, op_name)
+
+ with pytest.raises(RuntimeError, match="same batch size"):
+ op(src, transform, (0, 4))
+ with pytest.raises(ValueError, match="expected mode"):
+ op(src[:1], transform[:1], (0, 4), mode="invalid")
+ with pytest.raises(ValueError, match="expected padding_mode"):
+ op(src[:1], transform[:1], (0, 4), padding_mode="invalid")
+ if device.type == "cpu":
+ # The dtype policy mirrors the non-empty path: a transform that promotes into
+ # ``src.dtype`` is accepted, one that would narrow it is not.
+ narrow_src, wide_transform = src[:1].to(torch.float32), transform[:1].to(torch.float64)
+ with pytest.raises(RuntimeError):
+ op(narrow_src, wide_transform, (0, 4))
+ with pytest.raises(RuntimeError):
+ op(narrow_src, wide_transform, (1, 4))
+
+ wide_src, narrow_transform = src[:1].to(torch.float64), transform[:1].to(torch.float32)
+ empty_out = op(wide_src, narrow_transform, (0, 4))
+ assert empty_out.shape == (1, 3, 0, 4)
+ assert empty_out.dtype == op(wide_src, narrow_transform, (1, 4)).dtype == torch.float64
+
+ if op_name == "warp_affine":
+ with pytest.raises(ValueError, match="Bx2x3"):
+ op(src[:1], torch.eye(4, device=device, dtype=dtype).unsqueeze(0), (0, 4))
+
+
[email protected]("normalized_homography", [True, False])
+def test_homography_warp_negative_destination_raises(normalized_homography, device, dtype):
+ src = torch.rand(1, 3, 3, 4, device=device, dtype=dtype)
+ transform = torch.eye(3, device=device, dtype=dtype).unsqueeze(0)
+ with pytest.raises(ValueError, match="must be non-negative"):
+ kornia.geometry.transform.homography_warp(src, transform, (-1, 4), normalized_homography=normalized_homography)
+
+
class TestGetPerspectiveTransform(BaseTester):
@pytest.mark.parametrize("batch_size", [1, 2, 5])
def test_smoke(self, device, dtype, batch_size):
@@ -219,6 +381,43 @@ class TestWarpAffine(BaseTester):
img_a = kornia.geometry.warp_affine(img_b, aff_ab, (height, width))
self.assert_close(img_b, img_a)
+ @pytest.mark.parametrize("dsize", [(1, 4), (3, 1)])
+ def test_singleton_identity_agrees_with_perspective(self, dsize, device, dtype):
+ src = torch.arange(12.0, device=device, dtype=dtype).reshape(1, 1, 3, 4)
+ affine = torch.eye(2, 3, device=device, dtype=dtype).unsqueeze(0)
+ perspective = torch.eye(3, device=device, dtype=dtype).unsqueeze(0)
+
+ actual = kornia.geometry.warp_affine(src, affine, dsize, align_corners=True)
+ expected = kornia.geometry.warp_perspective(src, perspective, dsize, align_corners=True)
+ literal = (
+ torch.tensor([[[[0.0, 1.0, 2.0, 3.0]]]], device=device, dtype=dtype)
+ if dsize[0] == 1
+ else torch.tensor([[[[0.0], [4.0], [8.0]]]], device=device, dtype=dtype)
+ )
+
+ self.assert_close(actual, expected)
+ self.assert_close(actual, literal)
+
+ @pytest.mark.parametrize("dsize", [(1, 4), (3, 1)])
+ def test_singleton_identity_survives_tracing(self, dsize, device, dtype):
+ if dtype in (torch.float16, torch.bfloat16):
+ # ``torch.jit.trace`` hands ``F.affine_grid`` tensor sizes, and ``affine_grid_generator``
+ # has no cpu Half/BFloat16 kernel, so tracing a singleton warp raises
+ # ``NotImplementedError: "tensor_cpu" not implemented for 'Half'`` before reaching any
+ # kornia code. A non-singleton ``dsize`` traces fine at the same dtype.
+ pytest.skip("traced affine_grid has no cpu half-precision kernel")
+ src = torch.arange(12.0, device=device, dtype=dtype).reshape(1, 1, 3, 4)
+ affine = torch.eye(2, 3, device=device, dtype=dtype).unsqueeze(0)
+ expected = kornia.geometry.warp_affine(src, affine, dsize, align_corners=True)
+
+ class SingletonWarp(torch.nn.Module):
+ def forward(self, image, transform):
+ return kornia.geometry.warp_affine(image, transform, dsize, align_corners=True)
+
+ with pytest.warns(UserWarning, match="unit-size grids"):
+ traced = torch.jit.trace(SingletonWarp(), (src, affine), check_trace=False)
+ self.assert_close(traced(src, affine), expected)
+
@pytest.mark.parametrize("batch_shape", ([1, 3, 2, 5], [2, 4, 3, 4], [3, 5, 6, 2]))
@pytest.mark.parametrize("out_shape", ([2, 5], [3, 4], [6, 2]))
def test_cardinality(self, device, dtype, batch_shape, out_shape):
@@ -582,6 +781,73 @@ class TestRemap(BaseTester):
)
self.assert_close(input_org, input_warped, rtol=1e-4, atol=1e-4)
+ def test_singleton_identity_with_default_align_corners(self, device, dtype):
+ image = torch.tensor([[[[4.0]]]], device=device, dtype=dtype)
+ pixel_grid = kornia.geometry.create_meshgrid(1, 1, normalized_coordinates=False, device=device, dtype=dtype)
+
+ actual = kornia.geometry.remap(image, pixel_grid[..., 0], pixel_grid[..., 1])
+
+ self.assert_close(actual, image, atol=0.0, rtol=0.0)
+
+ @pytest.mark.parametrize("source_empty", [False, True])
+ def test_empty_maps_return_autograd_connected_output(self, source_empty, device, dtype):
+ _skip_if_mps_empty_grid_sample(device)
+ source_height = 0 if source_empty else 3
+ image = torch.empty(1, 2, source_height, 5, device=device, dtype=dtype, requires_grad=True)
+ map_x = torch.empty(1, 0, 5, device=device, dtype=dtype, requires_grad=True)
+ map_y = torch.empty(1, 0, 5, device=device, dtype=dtype, requires_grad=True)
+
+ output = kornia.geometry.remap(image, map_x, map_y)
+
+ assert output.shape == (1, 2, 0, 5)
+ output.sum().backward()
+ assert image.grad is not None
+ assert map_x.grad is not None
+ assert map_y.grad is not None
+
+ def test_empty_maps_keep_grid_sample_validation(self, device, dtype):
+ image = torch.empty(1, 2, 0, 5, device=device, dtype=dtype)
+ map_x = torch.empty(1, 0, 5, device=device, dtype=dtype)
+ map_y = torch.empty(1, 0, 5, device=device, dtype=dtype)
+
+ with pytest.raises(ValueError, match="expected mode"):
+ kornia.geometry.remap(image, map_x, map_y, mode="invalid")
+ with pytest.raises(ValueError, match="expected padding_mode"):
+ kornia.geometry.remap(image, map_x, map_y, padding_mode="fill")
+
+ @pytest.mark.parametrize("image_dtype", [torch.float32, torch.float64])
+ @pytest.mark.parametrize("map_dtype", [torch.float32, torch.float64, torch.int64])
+ @pytest.mark.parametrize("normalized_coordinates", [False, True])
+ def test_empty_maps_follow_nonempty_dtype_policy(self, image_dtype, map_dtype, normalized_coordinates, device):
+ if device.type == "mps":
+ pytest.skip("MPS does not support float64")
+ image = torch.zeros(1, 2, 4, 5, device=device, dtype=image_dtype)
+
+ def call(map_):
+ return kornia.geometry.remap(image, map_, map_, normalized_coordinates=normalized_coordinates)
+
+ empty_map = torch.zeros(1, 0, 5, device=device, dtype=map_dtype)
+ nonempty_map = torch.zeros(1, 1, 5, device=device, dtype=map_dtype)
+
+ # Empty maps must accept exactly what the non-empty pipeline accepts. Pixel maps are
+ # normalized first, so an integer map lifts into the default floating dtype (matching a
+ # float32 image, not a float64 one); already-normalized maps reach ``grid_sample``
+ # unchanged and must match the image dtype exactly.
+ empty_dtype = _output_dtype_or_none(lambda: call(empty_map))
+ assert empty_dtype == _output_dtype_or_none(lambda: call(nonempty_map))
+ if image_dtype == map_dtype:
+ # Guards the paired assertion above against passing vacuously on two failures.
+ assert empty_dtype == image_dtype
+ assert call(empty_map).shape == (1, 2, 0, 5)
+
+ def test_empty_source_with_nonempty_maps_raises(self, device, dtype):
+ image = torch.empty(1, 2, 0, 5, device=device, dtype=dtype)
+ map_x = torch.empty(1, 2, 5, device=device, dtype=dtype)
+ map_y = torch.empty(1, 2, 5, device=device, dtype=dtype)
+
+ with pytest.raises(ValueError, match="must be positive"):
+ kornia.geometry.remap(image, map_x, map_y)
+
def test_different_size(self, device, dtype):
height, width = 3, 4
grid = kornia.geometry.create_meshgrid(height, width, device=device, dtype=dtype)
diff --git a/tests/geometry/transform/test_imgwarp3d.py b/tests/geometry/transform/test_imgwarp3d.py
index c8521fb96..f2f4cf145 100644
--- a/tests/geometry/transform/test_imgwarp3d.py
+++ b/tests/geometry/transform/test_imgwarp3d.py
@@ -25,6 +25,99 @@ from kornia.core.utils import _torch_inverse_cast
from testing.base import BaseTester
[email protected]("op_name", ["warp_affine3d", "warp_perspective3d"])
[email protected]("dsize", [(0, 4, 5), (3, 0, 5), (3, 4, 0)])
[email protected]("align_corners", [True, False])
+def test_empty_destination_is_autograd_connected(op_name, dsize, align_corners, device, dtype):
+ src = torch.rand(1, 2, 3, 4, 5, device=device, dtype=dtype, requires_grad=True)
+ if op_name == "warp_affine3d":
+ transform = torch.eye(3, 4, device=device, dtype=dtype).unsqueeze(0).requires_grad_()
+ out = proj.warp_affine3d(src, transform, dsize, align_corners=align_corners)
+ else:
+ transform = torch.eye(4, device=device, dtype=dtype).unsqueeze(0).requires_grad_()
+ out = proj.warp_perspective3d(src, transform, dsize, align_corners=align_corners)
+
+ assert out.shape == (1, 2, *dsize)
+ assert out.numel() == 0
+ out.sum().backward()
+ assert src.grad is not None and torch.count_nonzero(src.grad) == 0
+ assert transform.grad is not None and torch.count_nonzero(transform.grad) == 0
+
+
[email protected]("op_name", ["warp_affine3d", "warp_perspective3d"])
+def test_empty_source_policy(op_name, device, dtype):
+ src = torch.empty(1, 2, 0, 4, 5, device=device, dtype=dtype, requires_grad=True)
+ if op_name == "warp_affine3d":
+ transform = torch.eye(3, 4, device=device, dtype=dtype).unsqueeze(0).requires_grad_()
+ op = proj.warp_affine3d
+ else:
+ transform = torch.eye(4, device=device, dtype=dtype).unsqueeze(0).requires_grad_()
+ op = proj.warp_perspective3d
+
+ empty = op(src, transform, (0, 4, 5))
+ assert empty.shape == (1, 2, 0, 4, 5)
+ empty.sum().backward()
+ assert src.grad is not None and transform.grad is not None
+
+ with pytest.raises(ValueError, match="must be positive"):
+ op(src, transform, (3, 4, 5))
+
+
[email protected]("op_name", ["warp_affine3d", "warp_perspective3d"])
+def test_negative_destination_raises(op_name, device, dtype):
+ src = torch.rand(1, 2, 3, 4, 5, device=device, dtype=dtype)
+ if op_name == "warp_affine3d":
+ transform = torch.eye(3, 4, device=device, dtype=dtype).unsqueeze(0)
+ op = proj.warp_affine3d
+ else:
+ transform = torch.eye(4, device=device, dtype=dtype).unsqueeze(0)
+ op = proj.warp_perspective3d
+ with pytest.raises(ValueError, match="must be non-negative"):
+ op(src, transform, (-1, 4, 5))
+
+
[email protected]("op_name", ["warp_affine3d", "warp_perspective3d"])
+def test_empty_destination_keeps_grid_sample_validation(op_name, device, dtype):
+ src = torch.rand(2, 2, 3, 4, 5, device=device, dtype=dtype)
+ matrix_size = (3, 4) if op_name == "warp_affine3d" else (4, 4)
+ transform = torch.eye(*matrix_size, device=device, dtype=dtype).repeat(3, 1, 1)
+ op = getattr(proj, op_name)
+
+ with pytest.raises(RuntimeError, match="same batch size"):
+ op(src, transform, (0, 4, 5))
+ with pytest.raises(ValueError, match="expected mode"):
+ op(src[:1], transform[:1], (0, 4, 5), flags="invalid")
+ padding_arg = "padding_mode" if op_name == "warp_affine3d" else "border_mode"
+ with pytest.raises(ValueError, match="expected padding_mode"):
+ op(src[:1], transform[:1], (0, 4, 5), **{padding_arg: "invalid"})
+ if device.type == "cpu":
+ other_dtype = torch.float64 if dtype != torch.float64 else torch.float32
+ with pytest.raises(RuntimeError):
+ op(src[:1], transform[:1].to(other_dtype), (0, 4, 5))
+
+ if op_name == "warp_perspective3d":
+ with pytest.raises(ValueError, match="Bx4x4"):
+ op(src[:1], torch.eye(3, device=device, dtype=dtype).unsqueeze(0), (0, 4, 5))
+
+
[email protected]("dsize", [(3, 4, 5), (0, 4, 5)])
+def test_warp_perspective3d_accepts_an_unbatched_matrix(dsize, device, dtype):
+ """An unbatched 4x4 matrix has always warped correctly here; the shape guard must not reject it."""
+ src = torch.rand(1, 2, 3, 4, 5, device=device, dtype=dtype)
+ transform = torch.eye(4, device=device, dtype=dtype)
+ unbatched = proj.warp_perspective3d(src, transform, dsize)
+ batched = proj.warp_perspective3d(src, transform.unsqueeze(0), dsize)
+ assert unbatched.shape == batched.shape
+ assert torch.equal(unbatched, batched)
+
+
+def test_homography_warp3d_negative_destination_raises(device, dtype):
+ src = torch.rand(1, 2, 3, 4, 5, device=device, dtype=dtype)
+ transform = torch.eye(4, device=device, dtype=dtype).unsqueeze(0)
+ with pytest.raises(ValueError, match="must be non-negative"):
+ proj.homography_warp3d(src, transform, (-1, 4, 5))
+
+
class TestWarpAffine3d(BaseTester):
def test_smoke(self, device, dtype):
sample = torch.rand(1, 3, 3, 4, 5, device=device, dtype=dtype)