π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
fix(feature): make ellipse_to_laf describe the given ellipse when b != 0 (#4768)
εΊζ’η320f461117ed
diff --git a/changelog.d/4768.breaking.md b/changelog.d/4768.breaking.mdnew file mode 100644index 000000000..2e4f5629b--- /dev/null+++ b/changelog.d/4768.breaking.md@@ -0,0 +1,18 @@+`ellipse_to_laf` now returns the LAF of the ellipse it is given. For an Oxford ellipse `(x, y, a, b, c)` the+returned upright, lower-triangular `A` satisfies `A @ A.T == inverse([[a, b], [b, c]])`, so the LAF maps the unit+circle onto `a x**2 + 2 b x y + c y**2 = 1` and `ellipse_to_laf` of the ellipse implied by a LAF `A0` returns+`make_upright(A0)`. Previously the function took the triangular square root of the lower-triangular matrix+`[[a, 0], [b, c]]` instead of the symmetric `[[a, b], [b, c]]`, so whenever `b != 0` the returned region was+under-tilted: for `(a, b, c) = (1, 0.5, 1)` the region it described was `[[1.0625, 0.25], [0.25, 1]]`, for+`(2, -0.9, 0.5)` it was `[[2.18, -0.3], [-0.3, 0.5]]`. Valid ellipses with `b == 0` give bit-identical results.++`LAFAffineShapeEstimator` feeds its second moment matrix through this function, so its output changes for every+patch whose dominant gradient direction is not axis-aligned. On an anisotropic Gaussian blob rotated by 45 degrees+the estimated region's major axis is now at 45.0 degrees with axis ratio 4.16; before it was at 51.3 degrees+with axis ratio 1.56. Patches whose mixed moment is exactly zero are unchanged.++Inputs that are not positive definite (`a`, `c` or `a * c - b * b` not positive) describe no ellipse. Previously a+negative `a` or `c` was replaced by its absolute value and `b` did not enter the diagonal, so a negative diagonal+entry or `b * b >= a * c` still produced a finite LAF; now such an input gives `inf` or `nan` entries, or huge finite+ones where rounding leaves `a - b * b / c` barely positive. A `c == 0` input now also has `nan` in `A[0, 0]`, which+used to be `1 / sqrt(a)`. Screen results with `laf_is_valid`. Refs #4684.diff --git a/kornia/feature/affine_shape.py b/kornia/feature/affine_shape.pyindex cd090f8c5..ae7a696c0 100644--- a/kornia/feature/affine_shape.py+++ b/kornia/feature/affine_shape.py@@ -219,12 +219,17 @@ class LAFAffineShapeEstimator(nn.Module):)ellipse_shape: torch.Tensor = self.affine_shape_detector(patches)ellipse_det = ellipse_shape[..., 0] * ellipse_shape[..., 2] - ellipse_shape[..., 1].square()+ # ellipse_to_laf takes the square root of a - (b / sqrt(c))^2, formed as below. For a nearly singular+ # shape that can round to zero or below although the determinant above stays positive; its nan would be+ # masked in the forward pass but not in the backward pass through the torch.where below.+ ellipse_schur = ellipse_shape[..., 0] - (ellipse_shape[..., 1] / ellipse_shape[..., 2].sqrt()).square()bad_shape = (~ellipse_shape.isfinite().all(dim=-1)| ~ellipse_det.isfinite()| (ellipse_shape[..., 0] <= 0)| (ellipse_shape[..., 2] <= 0)| (ellipse_det <= 0)+ | ~(ellipse_schur > 0))circular_shape = ellipse_shape.new_tensor([1.0, 0.0, 1.0])safe_ellipse_shape = torch.where(bad_shape[..., None], circular_shape, ellipse_shape)diff --git a/kornia/feature/laf.py b/kornia/feature/laf.pyindex 3a3f3a006..9be9e0bd2 100644--- a/kornia/feature/laf.py+++ b/kornia/feature/laf.py@@ -263,8 +263,10 @@ def make_upright(laf: torch.Tensor, eps: float = 1e-9) -> torch.Tensor:def ellipse_to_laf(ells: torch.Tensor) -> torch.Tensor:"""Convert ellipse regions to LAF format.- Ellipse (a, b, c) and upright covariance matrix [a11 a12; 0 a22] are connected- by inverse matrix square root: A = invsqrt([a b; b c]).+ The returned LAF holds the upright, lower-triangular ``A`` with ``A @ A.T == inverse([[a, b], [b, c]])``: the+ Cholesky factor of the inverse ellipse matrix, not the symmetric inverse square root (the two differ by a+ rotation). Either one maps the unit circle onto the ellipse :math:`a x^2 + 2 b x y + c y^2 = 1` centred at+ ``(x, y)``; the upright one is what :func:`make_upright` returns for a LAF of that region with positive determinant.See also https://github.com/vlfeat/vlfeat/blob/master/toolbox/sift/vl_frame2oell.m@@ -275,14 +277,12 @@ def ellipse_to_laf(ells: torch.Tensor) -> torch.Tensor:LAF :math:`(B, N, 2, 3)`Note:- A degenerate ellipse -- one whose ``a`` or ``c`` is ``0`` after rounding to ``ells.dtype`` --- describes an unbounded strip rather than a bounded region, and makes the matrix being inverted- singular. Its LAF is non-finite: ``inf`` always appears on the diagonal, while ``nan`` appears- only in the sub-case where the off-diagonal ``b`` is exactly ``0`` (``0 * inf``) -- the generic- degenerate ellipse is ``inf``-only, so screen results with :func:`laf_is_valid` rather than an- ``isnan`` test, which misses it. :func:`get_laf_scale` of such a LAF is non-finite as- well. The conversion does not raise. Rounding is part of the condition: in ``float16`` an ``a``- below roughly ``3e-8`` (half the smallest subnormal) rounds to ``0``, and a backend that+ The conversion does not raise and does not check its input. An ellipse that is degenerate or indefinite+ (``a``, ``c`` or ``a * c - b * b`` not positive) is not a bounded region; its LAF has ``inf`` or ``nan``+ entries, or huge finite ones where rounding leaves ``a - b * b / c`` barely positive. Rounding also works the+ other way: a nearly singular valid ellipse can give ``inf`` or ``nan``. Screen results with+ :func:`laf_is_valid` rather than an ``isnan`` test. In ``float16`` an+ ``a`` or ``c`` below roughly ``3e-8`` (half the smallest subnormal) rounds to ``0``, and a backend thatflushes subnormals to zero raises that cutoff to the smallest normal, about ``6e-5``.Example:@@ -297,29 +297,24 @@ def ellipse_to_laf(ells: torch.Tensor) -> torch.Tensor:# torch.cat([ells[..., 3:4], ells[..., 4:5]], dim=2).unsqueeze(2)], dim=2).view(-1, 2, 2)# out = torch.matrix_power(torch.cholesky(ell_shape, False), -1).view(B, N, 2, 2)- # We will calculate 2x2 matrix square root via special case formula- # https://en.wikipedia.org/wiki/Square_root_of_a_matrix- # "The Cholesky factorization provides another particular example of square root- # which should not be confused with the unique non-negative square root."- # https://en.wikipedia.org/wiki/Square_root_of_a_2_by_2_matrix- # M = (A 0; C D)- # R = (sqrt(A) 0; C / (sqrt(A)+sqrt(D)) sqrt(D))- a11 = ells[..., 2:3].abs().sqrt()- a22 = ells[..., 4:5].abs().sqrt()- a21 = ells[..., 3:4] / (a11 + a22)- # The matrix [[a11, 0], [a21, a22]] is lower-triangular, so its inverse is the closed form- # [[1/a11, 0], [-a21/(a11*a22), 1/a22]] β no batched torch.inverse, which is orders of- # magnitude slower, unsupported in float16/bfloat16 on CPU, and pathological on MPS.- inv11 = 1.0 / a11- inv22 = 1.0 / a22- # Divide by the product of the roots instead of multiplying the reciprocals: every ordering of- # `-a21 * inv11 * inv22` has an input region where an intermediate overflows to inf (or a- # mathematically-zero off-diagonal becomes 0 * inf = nan) or flushes a representable result to- # zero. a11 * a22 = sqrt(a) * sqrt(c) can neither overflow nor round to zero, so the single- # division is correctly rounded (not exact) wherever the product is a normal number; when the- # product is subnormal the result loses precision but is never a corrupted zero, inf, or nan.- # What remains non-finite is exactly the singular ellipse, which we deliberately do not guard.- inv21 = -a21 / (a11 * a22)+ # The LAF is the upright (lower-triangular) A with A @ A.T == inverse([[a, b], [b, c]]), i.e. the+ # Cholesky factor of the inverse ellipse matrix, written with the Schur complement a - b^2 / c+ # (= det / c) so that b == 0 reduces to the plain 1 / sqrt(a), 1 / sqrt(c) diagonal.+ # Scaling b by 1 / sqrt(c) first keeps b^2 out of the arithmetic (it overflows for large but valid+ # ellipses) and, for a positive definite ellipse, b / sqrt(c) <= sqrt(a) can neither overflow nor+ # flush a representable off-diagonal to zero. The off-diagonal -b / (c * sqrt(a - b^2 / c)) is then+ # a single division by sqrt(c) * sqrt(a - b^2 / c) = sqrt(det), which stays within range whenever the+ # factors do; forming it as -(b / c) / sqrt(...) or -b / (c * sqrt(...)) instead has valid inputs+ # where b / c underflows or c * sqrt(...) overflows although the result itself is representable.+ a = ells[..., 2:3]+ b = ells[..., 3:4]+ c = ells[..., 4:5]+ sqrt_c = c.sqrt()+ b_scaled = b / sqrt_c+ sqrt_schur = (a - b_scaled * b_scaled).sqrt()+ inv11 = 1.0 / sqrt_schur+ inv22 = 1.0 / sqrt_c+ inv21 = -b_scaled / (sqrt_c * sqrt_schur)A = torch.stack([inv11, torch.zeros_like(inv11), inv21, inv22], dim=-1).view(B, N, 2, 2)return torch.cat([A, ells[..., :2].view(B, N, 2, 1)], dim=3)diff --git a/tests/feature/test_affine_shape_estimator.py b/tests/feature/test_affine_shape_estimator.pyindex fdaecd83a..df95f0d92 100644--- a/tests/feature/test_affine_shape_estimator.py+++ b/tests/feature/test_affine_shape_estimator.py@@ -40,6 +40,15 @@ class OverflowShape(torch.nn.Module):return torch.cat([tiny, one, tiny], dim=-1)+class NearlySingularShape(torch.nn.Module):+ # In float32, a * c - b * b is positive (3e-8) but a - (b / sqrt(c)) ** 2, the square of the first diagonal+ # entry of the inverse LAF that ellipse_to_laf forms, rounds to 0. c is a perfect square, so sqrt(c) is exact on+ # every backend and only the correctly rounded multiplications and division decide where the two paths land.+ def forward(self, patches: torch.Tensor) -> torch.Tensor:+ zero = patches.mean(dim=(-2, -1), keepdim=False).unsqueeze(-1) * 0+ return torch.cat([zero + 0.75, zero + 0.6495190262794495, zero + 0.5625], dim=-1)++class SingularAffNetOutput(torch.nn.Module):def forward(self, patches: torch.Tensor) -> torch.Tensor:zero = patches.mean(dim=(-3, -2, -1), keepdim=True) * 0@@ -262,6 +271,22 @@ class TestLAFAffineShapeEstimator(BaseTester):assert laf.grad is not Noneassert torch.isfinite(laf.grad).all()+ def test_nearly_singular_shape_falls_back_with_finite_backward(self, device):+ dtype = torch.float32+ img = torch.rand(1, 1, 32, 32, device=device, dtype=dtype, requires_grad=True)+ laf = torch.tensor([[[[8.0, 0.0, 16.0], [0.0, 8.0, 16.0]]]], device=device, dtype=dtype, requires_grad=True)+ a, b, c = NearlySingularShape()(img).unbind(-1)+ assert a * c - b * b > 0+ assert a - (b / c.sqrt()).square() <= 0+ out = LAFAffineShapeEstimator(32, NearlySingularShape(), preserve_orientation=True).to(device, dtype)(laf, img)+ assert torch.isfinite(out).all()+ self.assert_close(out, laf)+ out.sum().backward()+ assert img.grad is not None+ assert torch.isfinite(img.grad).all()+ assert laf.grad is not None+ assert torch.isfinite(laf.grad).all()+def test_degenerate_ellipse_fallback_respects_upright_contract(self, device):dtype = torch.float32img = torch.rand(1, 1, 32, 32, device=device, dtype=dtype)diff --git a/tests/feature/test_laf.py b/tests/feature/test_laf.pyindex c92aff904..0118e2a0b 100644--- a/tests/feature/test_laf.py+++ b/tests/feature/test_laf.py@@ -264,31 +264,87 @@ class TestELL2LAF(BaseTester):# assure it is positive definiteself.gradcheck(kornia.feature.ellipse_to_laf, (img,))- def test_small_root_sum_is_not_clamped(self, device):- # The root sum is finite and nonzero, so clamping it changes a valid inverse by orders of magnitude.- tiny = torch.finfo(torch.float32).tiny- inp = torch.tensor([[[0.0, 0.0, tiny, tiny, tiny]]], device=device, dtype=torch.float32)- expected = torch.tensor(-0.5 / math.sqrt(tiny), device=device, dtype=torch.float32)+ def test_boundary_lies_on_the_ellipse(self, device, dtype):+ # The LAF maps the unit circle onto the region it describes, so every boundary point has to+ # satisfy the Oxford quadratic form a x^2 + 2 b x y + c y^2 = 1 of the input ellipse.+ if dtype in (torch.float16, torch.bfloat16):+ pytest.skip("the quadratic form check is meaningful only in full precision")+ ells = torch.tensor(+ [+ [+ [0.0, 0.0, 1.0, 0.0, 1.0],+ [3.0, -2.0, 1.0, 0.5, 1.0],+ [10.0, 20.0, 0.04, 0.01, 0.09],+ [0.0, 0.0, 2.0, -0.9, 0.5],+ ]+ ],+ device=device,+ dtype=dtype,+ )+ laf = kornia.feature.ellipse_to_laf(ells)+ angles = torch.linspace(0.0, 2.0 * math.pi, 9, device=device, dtype=dtype)[:-1]+ circle = torch.stack([angles.cos(), angles.sin()]) # (2, 8)+ boundary = laf[..., :2] @ circle # (1, 4, 2, 8), relative to the centre+ a, b, c = ells[..., 2:3], ells[..., 3:4], ells[..., 4:5]+ x, y = boundary[..., 0, :], boundary[..., 1, :]+ self.assert_close(a * x * x + 2.0 * b * x * y + c * y * y, torch.ones_like(x))++ def test_roundtrip_is_make_upright(self, device, dtype):+ # The ellipse implied by a LAF A is [[a, b], [b, c]] = inverse(A A^T); converting it back must+ # give the upright LAF of the same region.+ if dtype in (torch.float16, torch.bfloat16):+ pytest.skip("torch.inverse does not support half precision and the check needs full precision")+ torch.manual_seed(0)+ A = torch.randn(2, 5, 2, 2, device=device, dtype=dtype) + 3.0 * torch.eye(2, device=device, dtype=dtype)+ det = A[..., 0, 0] * A[..., 1, 1] - A[..., 0, 1] * A[..., 1, 0]+ A = torch.where(det[..., None, None] < 0, A.flip(-1), A) # keep every LAF right-handed+ laf = torch.cat([A, torch.rand(2, 5, 2, 1, device=device, dtype=dtype) * 100.0], dim=-1)+ S = torch.inverse(A @ A.transpose(-1, -2))+ ells = torch.cat([laf[..., 2], S[..., 0, 0:1], S[..., 0, 1:2], S[..., 1, 1:2]], dim=-1)+ self.assert_close(kornia.feature.ellipse_to_laf(ells), kornia.feature.make_upright(laf))++ def test_tiny_valid_ellipse_is_finite(self, device, dtype):+ # a == c == 16 tiny with b == 8 tiny is a valid, strongly tilted ellipse (b / a == 0.5) at the bottom+ # of the normal range: its determinant 192 tiny^2 is subnormal or zero in every dtype and any eps a+ # clamp would use is orders of magnitude above the inputs, yet every intermediate of the correct+ # formula (b / sqrt(c), the Schur complement 12 tiny, sqrt(det) formed as sqrt(c) * sqrt(schur)) is a+ # normal number, so this also runs on backends that flush subnormals. The LAF must be finite and+ # match the closed form, evaluated in double so that the check does not depend on the implementation.+ tiny = torch.finfo(dtype).tiny+ inp = torch.tensor([[[0.0, 0.0, 16.0 * tiny, 8.0 * tiny, 16.0 * tiny]]], device=device, dtype=dtype)laf = kornia.feature.ellipse_to_laf(inp)assert torch.isfinite(laf).all()- self.assert_close(laf[0, 0, 1, 0], expected)+ expected = torch.tensor(+ [[1.0 / math.sqrt(12.0 * tiny), 0.0], [-0.5 / math.sqrt(12.0 * tiny), 1.0 / math.sqrt(16.0 * tiny)]],+ device=device,+ dtype=dtype,+ )+ self.assert_close(laf[0, 0, :, :2], expected)- def test_no_overflow_asymmetric_diag(self, device, dtype):- # Regression test: the closed-form inverse's off-diagonal must divide by the root product,- # not multiply reciprocals. `a` is the dtype's smallest normal and `c` is picked so that- # (sqrt(a) + sqrt(c)) * sqrt(a) == 0.5, which makes the intermediate of the fixed order- # `-a21 * (1 / a11) * (1 / a22)` twice b -- inf for a b above half the dtype's maximum,- # although the result itself is well inside range. https://github.com/kornia/kornia/pull/4122+ def test_no_overflow_large_ellipse(self, device, dtype):+ # b is above sqrt(max), so b^2 (and a * c) overflow in this dtype although the ellipse is valid+ # and its LAF is well inside range: the Schur complement has to be formed from b / sqrt(c), never b^2.finfo = torch.finfo(dtype)- a11 = math.sqrt(finfo.tiny)- a22 = 0.5 / a11- inp = torch.tensor([[[0.0, 0.0, finfo.tiny, finfo.max * 0.75, a22 * a22]]], device=device, dtype=dtype)+ b = 2.0 * math.sqrt(finfo.max)+ inp = torch.tensor([[[0.0, 0.0, b, b, 4.0 * b]]], device=device, dtype=dtype)+ laf = kornia.feature.ellipse_to_laf(inp)+ assert torch.isfinite(laf).all()# Reference in float64, from the inputs as the dtype actually rounded them. Via CPU:# MPS tensors cannot be converted to float64 (TESTING.md, "Writing new tests that work on MPS").- expected = kornia.feature.ellipse_to_laf(inp.cpu().double())[0, 0, 1, 0]+ expected = kornia.feature.ellipse_to_laf(inp.cpu().double())+ self.assert_close(laf, expected.to(device=device, dtype=dtype))++ def test_no_overflow_asymmetric_diag(self, device, dtype):+ # c * sqrt(a) is above max, so an off-diagonal formed as -b / (c * sqrt(a - b^2 / c)) would+ # overflow the denominator and return a false zero, although the true value is representable.+ finfo = torch.finfo(dtype)+ a, b, c = finfo.max / 8.0, math.sqrt(finfo.max) / 2.0, 4.0 * math.sqrt(finfo.max)+ inp = torch.tensor([[[0.0, 0.0, a, b, c]]], device=device, dtype=dtype)laf = kornia.feature.ellipse_to_laf(inp)assert torch.isfinite(laf).all()- self.assert_close(laf[0, 0, 1, 0], expected.to(device=device, dtype=dtype))+ assert laf[0, 0, 1, 0] != 0+ expected = kornia.feature.ellipse_to_laf(inp.cpu().double())+ self.assert_close(laf, expected.to(device=device, dtype=dtype))def test_no_overflow_subnormal_diag(self, device, dtype):# The mirror case: a subnormal but nondegenerate diagonal makes 1 / (a11 * a22) overflow, so@@ -307,24 +363,20 @@ class TestELL2LAF(BaseTester):self.assert_close(laf[0, 0, 1, 0], torch.zeros_like(laf[0, 0, 1, 0]))def test_no_underflow_asymmetric_diag(self, device, dtype):- # Regression test for the ordering the two tests above do not cover: multiplying by the- # smaller reciprocal first (f7b573a3, since replaced by the division form) passes both of- # them but silently flushes a representable off-diagonal to a false zero. `a` is the- # dtype's smallest normal and `c` its reciprocal squared, so a11 * a22 == 1 and- # inv22 == a11 is itself tiny; `b` is picked so a21 * inv22 -- the min/max order's first- # product -- underflows to zero while the true off-diagonal, a21 / (a11 * a22), stays- # representable. https://github.com/kornia/kornia/pull/4122+ # A valid ellipse with an extreme aspect ratio: `a` is the dtype's smallest normal, `c` its+ # reciprocal, and `b` is picked so that the off-diagonal -b / (c * sqrt(a - b^2 / c)) is+ # representable while b / c is not. Forming the off-diagonal from b / c (as in the issue's first+ # draft) or multiplying b / sqrt(c) by 1 / sqrt(c) before dividing by sqrt(a - b^2 / c) flushes it to+ # a false zero. https://github.com/kornia/kornia/pull/4122finfo = torch.finfo(dtype)a11 = math.sqrt(finfo.tiny)a22 = 1.0 / a11b = finfo.eps * math.sqrt(a11)inp = torch.tensor([[[0.0, 0.0, finfo.tiny, b, a22 * a22]]], device=device, dtype=dtype)- # Guard on the arithmetic, not just the storage: a21 is shared by every ordering, so if a- # backend's division already flushes it to zero, no ordering has anything left to get wrong.- a11_t, a22_t = inp[..., 2:3].abs().sqrt(), inp[..., 4:5].abs().sqrt()- a21_t = inp[..., 3:4] / (a11_t + a22_t)- if (a21_t == 0).any():- pytest.skip("backend flushes this off-diagonal's shared numerator to zero regardless of ordering")+ # Guard on the arithmetic, not just the storage: b / sqrt(c) is the numerator of the off-diagonal,+ # so if a backend's division already flushes it to zero, there is nothing left to get wrong.+ if (inp[..., 3:4] / inp[..., 4:5].sqrt() == 0).any():+ pytest.skip("backend flushes this off-diagonal's numerator to zero regardless of ordering")expected = kornia.feature.ellipse_to_laf(inp.cpu().double())[0, 0, 1, 0]laf = kornia.feature.ellipse_to_laf(inp)assert torch.isfinite(laf).all()@@ -342,6 +394,17 @@ class TestELL2LAF(BaseTester):assert not torch.isfinite(laf[0, 0, :, :2]).all()self.assert_close(laf[0, 0, :, 2], inp[0, 0, :2]) # the centre is untouched+ @pytest.mark.parametrize(+ "abc", [(-1.0, 0.0, 4.0), (3.0, 0.0, -4.0), (-3.0, 0.5, -4.0), (3.0, 4.0, 4.0), (3.0, -4.0, 4.0)]+ )+ def test_not_positive_definite_ellipse_is_non_finite(self, device, dtype, abc):+ # A negative a or c, or b * b > a * c, is not an ellipse; the old formula took abs(a) and abs(c) and+ # ignored b on the diagonal, so it returned a finite LAF for all of these.+ inp = torch.tensor([[[1.0, 2.0, *abc]]], device=device, dtype=dtype)+ laf = kornia.feature.ellipse_to_laf(inp)+ assert not torch.isfinite(laf[0, 0, :, :2]).all()+ self.assert_close(laf[0, 0, :, 2], inp[0, 0, :2])+def test_dynamo(self, device, dtype, torch_optimizer):inp = self._well_conditioned_ellipses(device, dtype)op = kornia.feature.ellipse_to_laf