Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

fix(conversions): reject integer dtype in normal_transform_pixel (#3974)

Roshan Ramani04650cc2a5b3
diff --git a/changelog.d/3974.fixed.md b/changelog.d/3974.fixed.md
new file mode 100644
index 000000000..2c89d6016
--- /dev/null
+++ b/changelog.d/3974.fixed.md
@@ -0,0 +1,5 @@
+`normal_transform_pixel` and `normal_transform_pixel3d` now raise `ValueError` for an integer
+`dtype` instead of returning a rank-deficient matrix. The scale `2 / (size - 1)` truncated to `0`,
+so `normal_transform_pixel(4, 5, dtype=torch.int64)` returned `[[0, 0, -1], [0, 0, -1], [0, 0, 1]]`
+and mapped every pixel to `(-1, -1)`, with no error or warning. Floating point dtypes, including the
+`float8` formats, and complex dtypes are unaffected.
diff --git a/kornia/geometry/conversions.py b/kornia/geometry/conversions.py
index e8c8ef075..399101098 100644
--- a/kornia/geometry/conversions.py
+++ b/kornia/geometry/conversions.py
@@ -2121,11 +2121,21 @@ def normal_transform_pixel(
explicit ``dtype=`` overrides that
.. warning::
- An integer ``dtype`` truncates the scale instead of raising:
- ``normal_transform_pixel(4, 5, dtype=torch.int64)`` returns
- ``[[0, 0, -1], [0, 0, -1], [0, 0, 1]]``, which maps every pixel to the
- constant ``(-1, -1)``. Tracked in
- `#3959 <https://github.com/kornia/kornia/issues/3959>`_.
+ An integer ``dtype`` is rejected:
+ ``normal_transform_pixel(4, 5, dtype=torch.int64)`` raises
+ ``ValueError``. The scale ``2 / (size - 1)`` is fractional for every
+ dimension larger than 3 pixels, so an integer dtype would truncate it
+ to ``0`` and return ``[[0, 0, -1], [0, 0, -1], [0, 0, 1]]``, mapping
+ every pixel to the constant ``(-1, -1)``. The accepted dtypes are a
+ property of the function rather than of ``height`` and ``width``: a
+ dimension of 3 pixels or fewer makes the scale integral, and the
+ rejection is uniform rather than depending on the image size. Any
+ floating point dtype, including the ``float8`` formats, and any complex
+ dtype are accepted. The rejection is unconditional β€” it is not a ``KORNIA_CHECK``, so
+ ``disable_checks()``, ``python -O`` and ``KORNIA_CHECKS=0`` do not
+ switch it off. One clause of
+ `#3959 <https://github.com/kornia/kornia/issues/3959>`_, which stays
+ open for the other functions it covers.
.. note::
Legacy ``torch.jit.trace`` graphs assume positive runtime sizes because
@@ -2161,6 +2171,34 @@ def normal_transform_pixel(
"""
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}.")
+ # A normalization matrix scales by 2/(size - 1), which is fractional for every
+ # dimension larger than 3 pixels. An integer dtype truncates those scales to 0 and
+ # yields a rank-deficient matrix that maps the whole image to a single point. The
+ # accepted dtypes are a property of the function rather than of height and width, so
+ # the rejection is uniform: a dimension of 3 pixels or fewer makes the scale integral
+ # and would survive, and accepting integers only there would make the domain depend
+ # on the image.
+ # Raised directly rather than through KORNIA_CHECK, which disable_checks(),
+ # python -O and KORNIA_CHECKS=0 all switch off: a domain restriction whose
+ # alternative is silently wrong output cannot be optional.
+ # A zero-element probe rather than dtype.is_floating_point, because TorchScript cannot
+ # access dtype attributes and this runs inside the scripted warp_affine path. The probe
+ # answers for any dtype, including the float8 formats and whatever torch adds next. The
+ # membership test in front of it is a fast path, not the domain, and it carries the
+ # complex dtypes so that a `complex32` call does not emit torch's experimental-ComplexHalf
+ # warning from an allocation the caller never asked for.
+ if dtype is not None and dtype not in (
+ torch.float16,
+ torch.float32,
+ torch.float64,
+ torch.bfloat16,
+ torch.complex32,
+ torch.complex64,
+ torch.complex128,
+ ):
+ probe = torch.empty(0, dtype=dtype)
+ if not (probe.is_floating_point() or probe.is_complex()):
+ raise ValueError(f"dtype must be a floating point or complex type. Got {dtype}.")
if not torch.jit.is_scripting() and not torch.jit.is_tracing() and not is_compiling() and eps != 1e-14:
warnings.warn("`eps` is deprecated and ignored by `normal_transform_pixel`.", FutureWarning, stacklevel=2)
@@ -2255,11 +2293,12 @@ def normal_transform_pixel3d(
grid built for one silently permutes axes when fed to the other
.. warning::
- 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>`_.
+ As in :func:`~kornia.geometry.conversions.normal_transform_pixel`, an
+ integer ``dtype`` is rejected: ``normal_transform_pixel3d(2, 4, 5,
+ dtype=torch.int64)`` raises ``ValueError`` rather than returning a
+ matrix with diagonal ``[0, 0, 2]``. Unconditional and uniform over
+ sizes, for the reason given there. One clause of
+ `#3959 <https://github.com/kornia/kornia/issues/3959>`_.
.. note::
Legacy ``torch.jit.trace`` graphs assume positive runtime sizes for the
@@ -2290,6 +2329,23 @@ def normal_transform_pixel3d(
"""
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}.")
+ # As in 2-D: an integer dtype truncates the 2/(size - 1) scales to 0 and returns a
+ # rank-deficient matrix, so the dtype is rejected rather than silently truncated, and
+ # uniformly rather than only for the sizes where the scale happens to be integral.
+ # Raised directly, not through KORNIA_CHECK, which python -O and disable_checks()
+ # switch off; the probe and its fast path are as in 2-D.
+ if dtype is not None and dtype not in (
+ torch.float16,
+ torch.float32,
+ torch.float64,
+ torch.bfloat16,
+ torch.complex32,
+ torch.complex64,
+ torch.complex128,
+ ):
+ probe = torch.empty(0, dtype=dtype)
+ if not (probe.is_floating_point() or probe.is_complex()):
+ raise ValueError(f"dtype must be a floating point or complex type. Got {dtype}.")
if not torch.jit.is_scripting() and not torch.jit.is_tracing() and not is_compiling() and eps != 1e-14:
warnings.warn("`eps` is deprecated and ignored by `normal_transform_pixel3d`.", FutureWarning, stacklevel=2)
diff --git a/tests/geometry/test_conversions.py b/tests/geometry/test_conversions.py
index 6750b303e..e1ca9b746 100644
--- a/tests/geometry/test_conversions.py
+++ b/tests/geometry/test_conversions.py
@@ -31,7 +31,7 @@ import torch
import kornia
from kornia.core._compat import torch_version, torch_version_lt
-from kornia.core.check import KORNIA_CHECK, KORNIA_CHECK_SHAPE
+from kornia.core.check import KORNIA_CHECK, KORNIA_CHECK_SHAPE, are_checks_enabled, disable_checks, enable_checks
from kornia.core.exceptions import BaseError, ShapeError
from kornia.core.ops import eye_like
from kornia.geometry.conversions import (
@@ -668,10 +668,11 @@ class TestAngleAxisToQuaternion(BaseTester):
# one, with no error and no warning. The buffer now takes its dtype from the computed
# values (sqrt already promotes them), so the result is the float quaternion below.
# The wart this replaces said the intended behavior was undecided -- promote, or raise a
- # TypeError the way a dtype guard would. Promotion is the choice; the sibling wart
- # TestNormalTransformPixel.test_wart_integer_dtype_truncates_the_scale_to_zero_3959 pins
- # the same family of defect and is still open, so this pin is also the precedent it should
- # follow.
+ # TypeError the way a dtype guard would. Promotion is the choice here. The same family of
+ # defect in normal_transform_pixel went the OTHER way and now REJECTS the dtype -- see
+ # TestNormalTransformPixel.test_convention_integer_dtype_is_rejected_3959, which records
+ # why the precedent was not followed there -- so kornia#3959 is deliberately no longer
+ # uniform, and neither cell is the precedent for the rest of it.
# Four cells because the promotion happens through torch's own type rules rather than an
# explicit .float(): a signed/unsigned or narrow/wide difference would show up here.
# The dtype fixture is dropped because the claim is about the input dtype itself.
@@ -4032,39 +4033,84 @@ class TestNormalTransformPixel(BaseTester):
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
- # Python floats, so an integer dtype truncates every scale below 1 to 0 and the function
- # returns a rank-deficient matrix -- no error, no warning. The 2-D result maps EVERY pixel
- # to the constant (-1, -1) -- recorded in the snippet as pure arithmetic on the
- # bitwise-pinned integer matrix, so it is not asserted separately (and no integer matmul
- # runs, which CUDA would not implement). The 3-D cell keeps depth = 2 so that its z scale, 2/1 = 2,
- # survives the truncation: a partial fix that only promotes float scales would still have
- # to flip the two zeroed axes.
- # There is deliberately NO companion strict xfail: the intended behavior is undecided
- # (promote to float, or raise), and an assertion-shaped xfail can express only the first.
- # kornia#3948, the same defect in axis_angle_to_quaternion, was settled by PROMOTING --
- # see TestAngleAxisToQuaternion.test_convention_integer_input_is_promoted_to_float_3948 --
- # so that is the precedent a fix here should follow, but it is precedent and not a decision
- # taken for this function, which is why the pin stays a wart rather than becoming an xfail.
- # If either cell fails, #3959 was (partly) fixed -- remove this pin. NOT a contract that an
- # integer dtype must keep returning a degenerate matrix.
+ @pytest.mark.parametrize("rejected_dtype", [torch.int64, torch.int32, torch.uint8, torch.bool])
+ def test_convention_integer_dtype_is_rejected_3959(self, device, rejected_dtype):
+ # Replaces the wart pin test_wart_integer_dtype_truncates_the_scale_to_zero_3959, which
+ # recorded the truncation as undecided behavior. It is decided: the dtype is rejected.
+ # The matrix scales by 2/(size - 1), fractional for every dimension larger than 3 pixels,
+ # so an integer dtype truncated every scale below 1 to 0 and the function returned a
+ # rank-deficient matrix -- [[0, 0, -1], [0, 0, -1], [0, 0, 1]] in 2-D, mapping EVERY pixel
+ # to the constant (-1, -1), and diagonal [0, 0, 2] in 3-D, where depth = 2 keeps 2/1 = 2
+ # alive through the truncation. No error, no warning.
+ # kornia#3948 (axis_angle_to_quaternion) settled the sibling defect by PROMOTING, and the
+ # wart named that as the precedent a fix here should follow. It is not followed, for a
+ # reason specific to this function: promotion would silently change the dtype a caller
+ # explicitly asked for, on a function whose whole contract is "give me this dtype", and the
+ # matrix feeds torch.jit-scripted warp_affine where a surprise dtype propagates. Rejecting
+ # is the narrower change; #3948's own float output is not a dtype the caller named.
+ # Four cells because the guard asks a zero-element probe whether the dtype is floating or
+ # complex (TorchScript cannot reach dtype attributes): a signed/unsigned, narrow/wide, or
+ # bool difference would show up here. uint8 is the one cell that already raised on base,
+ # with RuntimeError: value cannot be converted to type uint8 without overflow from the
+ # -1.0 offset rather than a silent truncation; it is kept because it pins that the error
+ # is now kornia's own and uniform with the other three.
# The dtype fixture is dropped because the claim is about the dtype argument itself.
- # Snippet used to generate expected (torch only, executed on cpu):
- # normal_transform_pixel(4, 5, dtype=torch.int64)
- # -> [[0, 0, -1], [0, 0, -1], [0, 0, 1]]
- # normal_transform_pixel3d(2, 4, 5, dtype=torch.int64)
- # -> diag [0, 0, 2] (2/(5-1) and 2/(4-1) truncate, 2/(2-1) does not)
- # matrix @ (x, y, 1) -> (-1, -1, 1) for every pixel -- e.g. (0, 0), (4, 3), (2, 1)
- matrix = kornia.geometry.conversions.normal_transform_pixel(4, 5, device=device, dtype=torch.int64)
- matrix3d = kornia.geometry.conversions.normal_transform_pixel3d(2, 4, 5, device=device, dtype=torch.int64)
+ with pytest.raises(ValueError, match="floating point or complex"):
+ kornia.geometry.conversions.normal_transform_pixel(4, 5, device=device, dtype=rejected_dtype)
+ with pytest.raises(ValueError, match="floating point or complex"):
+ kornia.geometry.conversions.normal_transform_pixel3d(2, 4, 5, device=device, dtype=rejected_dtype)
+ # A 3-pixel image is the case where the scale 2/(size - 1) is integral, so an integer
+ # dtype would have returned the exactly correct matrix on base. The rejection is uniform
+ # over sizes by decision, not by accident, and this cell is what makes that a decision.
+ with pytest.raises(ValueError, match="floating point or complex"):
+ kornia.geometry.conversions.normal_transform_pixel(3, 3, device=device, dtype=rejected_dtype)
- assert matrix[0].tolist() == [[0, 0, -1], [0, 0, -1], [0, 0, 1]], (
- "kornia#3959: an integer dtype no longer truncates the 2-D normalization scales to 0"
- )
- assert [matrix3d[0, i, i].item() for i in range(3)] == [0, 0, 2], (
- "kornia#3959: an integer dtype no longer truncates the 3-D normalization scales to 0"
- )
+ @pytest.mark.parametrize(
+ "accepted_dtype",
+ [torch.float16, torch.bfloat16, torch.complex64, getattr(torch, "float8_e4m3fn", None)],
+ )
+ def test_convention_non_default_float_and_complex_dtypes_are_accepted_3959(self, device, accepted_dtype):
+ # The guard must reject integers WITHOUT narrowing the accepted set to the common floats.
+ # Complex is accepted because a complex scale is a well-defined answer, and float8 because
+ # it is an ordinary floating point dtype whose scales round rather than truncate: on base
+ # float8_e4m3fn returned [[0.5, 0, -1], [0, 0.6875, -1], [0, 0, 1]], where 0.6875 is 2/3 in
+ # that format. An allowlist rejected both float8 formats by omission, which is the reason
+ # the guard asks a probe instead. Fetched through getattr because kornia declares
+ # torch>=2.0.0 and the float8 dtypes are newer, in the style of the linalg.cross probe.
+ if accepted_dtype is None:
+ pytest.skip("this torch build has no float8_e4m3fn")
+ matrix = kornia.geometry.conversions.normal_transform_pixel(4, 5, device=device, dtype=accepted_dtype)
+ assert matrix.dtype == accepted_dtype
+ assert matrix.shape == (1, 3, 3)
+ # Asserting the value, not only the dtype and shape: an all-zero matrix is the failure this
+ # whole change is about, and it would satisfy both of those.
+ # Widening the result rather than narrowing the expectation keeps the complex cell exact
+ # (a cast the other way discards the imaginary part and warns), and the tolerance is set
+ # for float8_e4m3fn, where 2/3 is 0.6875. The comparison runs on cpu because mps supports
+ # neither float64 nor complex128, and the device is asserted separately.
+ assert matrix.device.type == torch.device(device).type
+ expected = torch.tensor([[[0.5, 0.0, -1.0], [0.0, 2.0 / 3.0, -1.0], [0.0, 0.0, 1.0]]])
+ self.assert_close(matrix.cpu().to(torch.complex128), expected.to(torch.complex128), atol=0.05, rtol=0.05)
+
+ def test_convention_integer_dtype_rejection_is_unconditional_3959(self, device):
+ # The guard is deliberately NOT a KORNIA_CHECK. KORNIA_CHECK is gated on
+ # _KORNIA_CHECKS_ENABLED, which disable_checks(), python -O and KORNIA_CHECKS=0 all clear,
+ # and the module documents that as the production path -- so a KORNIA_CHECK here would
+ # leave the rank-deficient matrix reachable in exactly the configuration a deployment
+ # runs. This pin is the difference between the two tiers; if it fails, the guard has been
+ # demoted to an optional assertion and kornia#3959 is unfixed under -O.
+ # python -O cannot be entered from inside a test (the flag is read at import), so this
+ # covers the runtime switch; the -O and KORNIA_CHECKS=0 legs are covered by construction,
+ # the guard being a plain if/raise that reads no flag at all.
+ checks_were_enabled = are_checks_enabled()
+ disable_checks()
+ try:
+ assert not are_checks_enabled()
+ with pytest.raises(ValueError, match="floating point or complex"):
+ kornia.geometry.conversions.normal_transform_pixel(4, 5, device=device, dtype=torch.int64)
+ finally:
+ if checks_were_enabled:
+ enable_checks()
class TestNormalizeHomography(BaseTester):
@@ -4552,8 +4598,10 @@ class TestNormalizeHomography(BaseTester):
def test_wart_integer_input_raises_or_nans_by_backend_3959(self, device):
# Wart pin for kornia#3959's homography reach, companion to normalize_homography's
# integer-input warning: the normalization matrices are cast to the input's int64 by
- # .to(input), truncating their scales to zero (the truncation itself is pinned in
- # test_wart_integer_dtype_truncates_the_scale_to_zero_3959 above), and the downstream
+ # .to(input), truncating their scales to zero (the CALLER does the truncating here: both
+ # functions call normal_transform_pixel WITHOUT a dtype and cast the float result with
+ # .to(input), so normal_transform_pixel's own dtype guard never sees the int64 and this
+ # leg of kornia#3959 is untouched by it), and the downstream
# failure differs by backend. normalize_homography dies in the FINAL CHAIN MATMUL with a
# RuntimeError -- the closed-form inverse does not raise, it silently promotes the
# truncated int64 matrix to an all-nan float32 one, and the int64-vs-float32 matmul then