π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
fix(geometry): restore Boxes3D.to_tensor gradients, a false-positive kink (#4184)
Mohansree Vijayakumar7c5db705ab74
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex aa0b8d9ae..e1b7446f0 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -238,6 +238,20 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0### Bug fixes+* `Boxes3D.to_tensor` and `Boxes3D.get_boxes_shape` are differentiable again (#1396). Both reduce a box's 8+ vertices to its min/max corner with `amin`/`amax`, which is a genuine kink -- not differentiable in the+ classical sense -- wherever multiple vertices exactly tie for an axis extremum. Every face of an+ axis-aligned box has such a 4-way tie by construction, where PyTorch's `amin`/`amax` backward splits the+ gradient evenly across the tied vertices (`1/4` each): a valid subgradient, usable for optimization, but+ one that `torch.autograd.gradcheck`'s central-difference estimate does not match at that exact point --+ the same non-uniqueness any reduction has at a kink (`torch.max`, `ReLU`). That mismatch was previously+ taken for a genuine gradient bug and `to_tensor` raised `RuntimeError` whenever its input required grad,+ unconditionally, including for the common case of a caller who never differentiates through a tie at all+ (an oriented, non-axis-aligned box, or a loss that never reaches the tied component). The guard is+ removed; the docstring documents the tie behavior instead of calling it a bug. `Boxes` (2D) uses the same+ reduction and was never guarded, because an axis-aligned rectangle's ties are always 2-way, where the+ `1/2` split happens to numerically coincide with the central-difference estimate -- the same kink, just+ invisible to `gradcheck` there.* The pinned-torch CI legs no longer run against the lockfile's `triton`. `uv sync` installs the locked torch'sdependency set, and each matrix leg then swaps torch alone for a `+cpu` build -- whose wheels declare no `triton` atall -- so the lockfile's triton survived as an orphan of a torch that was no longer installed. torch guards itsdiff --git a/kornia/geometry/boxes.py b/kornia/geometry/boxes.pyindex f65fb17ef..065a272e2 100644--- a/kornia/geometry/boxes.py+++ b/kornia/geometry/boxes.py@@ -1188,8 +1188,20 @@ class Boxes3D:* Any other value: :math:`(N, 6)` or :math:`(B, N, 6)`.Note:- It is currently non-differentiable due to a bug. See github issue- `#1396 <https://github.com/kornia/kornia/issues/1396>`_.+ The vertex-to-corner reduction below is ``amin``/``amax`` over the 8 vertices, which is+ differentiable everywhere except where multiple vertices exactly tie for an axis extremum --+ e.g. every face of an axis-aligned box, where 4 vertices share each min/max coordinate. At an+ exact tie PyTorch's ``amin``/``amax`` backward splits the gradient evenly among the tied+ vertices (``1/k`` for ``k`` ties), a valid subgradient usable for optimization, but one that+ :func:`torch.autograd.gradcheck`'s central-difference estimate will not exactly match at that+ point -- the same non-uniqueness any reduction has at a kink (compare ``torch.max`` or+ :class:`~torch.nn.ReLU` at their own kinks). This was previously (see `#1396+ <https://github.com/kornia/kornia/issues/1396>`_) mistaken for an actual gradient bug and+ gated behind a ``RuntimeError``; :class:`Boxes` (2D) uses the same reduction and was never+ gated, because an axis-aligned rectangle always ties 2-way per extremum, where the ``1/2``+ split happens to coincide with the central-difference estimate -- gradcheck cannot see the+ same kink there. A degenerate 2D box -- zero extent on an axis, so four vertices tie -- reaches+ the same 4-way split and is not guaranteed that coincidence.Examples:>>> boxes_xyzxyz = torch.as_tensor([[0, 3, 6, 1, 4, 8], [5, 1, 3, 8, 4, 9]])@@ -1197,14 +1209,6 @@ class Boxes3D:>>> assert (boxes.to_tensor(mode='xyzxyz') == boxes_xyzxyz).all()"""- if self._data.requires_grad:- raise RuntimeError(- "Boxes3D.to_tensor doesn't support computing gradients since they aren't accurate. "- "Please, create boxes from tensors with `requires_grad=False`. "- "This is a known bug. Help is needed to fix it. For more information, "- "see https://github.com/kornia/kornia/issues/1396."- )-batched_boxes = self._data if self._is_batched else self._data.unsqueeze(0)# Create boxes in xyzxyz_plus format.diff --git a/tests/geometry/test_boxes.py b/tests/geometry/test_boxes.pyindex f50d4be2f..cf5f3d5b5 100644--- a/tests/geometry/test_boxes.py+++ b/tests/geometry/test_boxes.py@@ -966,49 +966,89 @@ class TestBbox3D(BaseTester):assert boxes_moved.data.device == device, boxes_moved.data.dtype == dtypedef test_gradcheck(self, device):- # Uncomment when enabling gradient checks- # def apply_boxes_method(tensor: torch.Tensor, method: str, **kwargs):- # boxes = Boxes3D(tensor)- # result = getattr(boxes, method)(**kwargs)- # return result.data if isinstance(result, Boxes3D) else result-- # t_boxes1 = torch.tensor(- # [- # [- # [0.0, 1.0, 2.0],- # [10, 1, 2],- # [10, 21, 2],- # [0, 21, 2],- # [0, 1, 32],- # [10, 1, 32],- # [10, 21, 32],- # [0, 21, 32],- # ]- # ],- # device=device,- # dtype=torch.float64,- # )-- # Uncomment when enabling gradient checks- # t_boxes2 = tensor_to_gradcheck_var(t_boxes1.detach().clone())- # t_boxes3 = tensor_to_gradcheck_var(t_boxes1.detach().clone())- # t_boxes4 = tensor_to_gradcheck_var(t_boxes1.detach().clone())+ def apply_boxes_method(tensor: torch.Tensor, method: str, **kwargs):+ boxes = Boxes3D(tensor)+ result = getattr(boxes, method)(**kwargs)+ return result.data if isinstance(result, Boxes3D) else result++ # to_tensor (and get_boxes_shape, which calls it) reduce the 8 vertices with amin/amax, whose+ # backward is exact everywhere except where multiple vertices exactly tie for an axis extremum+ # -- see the Note on Boxes3D.to_tensor. An axis-aligned box has a 4-way tie on every face by+ # construction, so it is the wrong input for gradcheck's central-difference comparison: it+ # probes the reduction exactly at its one genuine kink, not a representative point. Jittering+ # every vertex breaks the ties without changing which corner is the true min/max, so gradcheck+ # verifies the reduction everywhere else, which is everywhere a real (non-degenerate) box lives.+ # The jitter is a fixed pattern, not RNG-derived: it only needs to be small and distinct per+ # component to break the exact ties, and a fixed pattern avoids mutating global RNG state that+ # could leak into other tests.+ t_boxes1 = torch.tensor(+ [+ [+ [0.0, 1.0, 2.0],+ [10, 1, 2],+ [10, 21, 2],+ [0, 21, 2],+ [0, 1, 32],+ [10, 1, 32],+ [10, 21, 32],+ [0, 21, 32],+ ]+ ],+ device=device,+ dtype=torch.float64,+ )+ jitter = torch.arange(1, t_boxes1.numel() + 1, dtype=torch.float64, device=device).view_as(t_boxes1) * 1e-4+ t_boxes1 = t_boxes1 + jitter++ t_boxes2 = t_boxes1.detach().clone()+ t_boxes3 = t_boxes1.detach().clone()+ t_boxes4 = t_boxes1.detach().clone()++ self.gradcheck(partial(apply_boxes_method, method="to_tensor"), (t_boxes2,))+ self.gradcheck(partial(apply_boxes_method, method="to_tensor", mode="xyzxyz_plus"), (t_boxes3,))+ self.gradcheck(partial(apply_boxes_method, method="to_tensor", mode="vertices_plus"), (t_boxes4,))+ self.gradcheck(partial(apply_boxes_method, method="get_boxes_shape"), (t_boxes1.detach().clone(),))+t_boxes_xyzxyz = torch.tensor([[1.0, 3.0, 8.0, 5.0, 6.0, 12.0]], device=device, dtype=torch.float64)t_boxes_xyzxyz1 = t_boxes_xyzxyz.detach().clone()-- # Gradient checks for Boxes3D.to_tensor (and Boxes3D.get_boxes_shape) are disable since the is a bug- # in their gradient. See https://github.com/kornia/kornia/issues/1396.- # assert gradcheck(partial(apply_boxes_method, method='to_tensor'), (t_boxes2,), raise_exception=True)- # assert gradcheck(- # partial(apply_boxes_method, method='to_tensor', mode='xyzxyz_plus'), (t_boxes3,), raise_exception=True- # )- # assert gradcheck(- # partial(apply_boxes_method, method='to_tensor', mode='vertices_plus'), (t_boxes4,), raise_exception=True- # )- # assert gradcheck(partial(apply_boxes_method, method='get_boxes_shape'), (t_boxes1,), raise_exception=True)self.gradcheck(lambda x: Boxes3D.from_tensor(x, mode="xyzxyz_plus").data, (t_boxes_xyzxyz,))self.gradcheck(lambda x: Boxes3D.from_tensor(x, mode="xyzwhd").data, (t_boxes_xyzxyz1,))+ def test_convention_to_tensor_tie_gradient_is_an_even_subgradient_1396(self, device):+ # #1396: to_tensor used to raise RuntimeError whenever its input required grad, because+ # gradcheck disagreed with the analytical gradient on an axis-aligned box -- every face of+ # such a box has a 4-way vertex tie, and PyTorch's amin/amax backward splits the gradient+ # evenly across tied vertices (1/4 each here) rather than picking one, which is a valid+ # subgradient but not what central-difference gradcheck expects at a kink (it does not probe+ # a genuine derivative there, since none exists in the classical sense). This pins that even+ # split as the actual, correct, and now-unguarded behavior, so a future change that alters it+ # (e.g. reverting to computing to_tensor without amin/amax) has to touch this test.+ vertices = torch.tensor(+ [+ [+ [0.0, 1.0, 2.0],+ [10.0, 1.0, 2.0],+ [10.0, 21.0, 2.0],+ [0.0, 21.0, 2.0],+ [0.0, 1.0, 32.0],+ [10.0, 1.0, 32.0],+ [10.0, 21.0, 32.0],+ [0.0, 21.0, 32.0],+ ]+ ],+ device=device,+ dtype=torch.float32,+ requires_grad=True,+ )+ boxes = Boxes3D(vertices)+ out = boxes.to_tensor(mode="xyzxyz") # (N=1, 6): not batched, so to_tensor squeezes the batch dim+ out[0, 0].backward() # d(xmin)/d(vertices): xmin ties across vertices 0, 3, 4, 7++ expected_grad = torch.zeros_like(vertices)+ for tied_vertex in (0, 3, 4, 7):+ expected_grad[0, tied_vertex, 0] = 0.25+ self.assert_close(vertices.grad, expected_grad)+class TestTransformBoxes3D(BaseTester):def test_transform_boxes(self, device, dtype):