Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

implement SpatialSoftArgmax2d and test

edgarriba2fb7ae0e4def
diff --git a/test/test_contrib.py b/test/test_contrib.py
new file mode 100644
index 000000000..f1716fc92
--- /dev/null
+++ b/test/test_contrib.py
@@ -0,0 +1,64 @@
+import pytest
+
+import torch
+import torchgeometry as tgm
+from torch.autograd import gradcheck
+
+import utils
+
+
+class TestSoftArgmax2d:
+ def _test_smoke(self):
+ input = torch.zeros(1, 1, 2, 3)
+ m = tgm.contrib.SpatialSoftArgmax2d()
+ assert m(input).shape == (1, 1, 2)
+
+ def _test_top_left(self):
+ input = torch.zeros(1, 1, 2, 3)
+ input[..., 0, 0] = 10.
+
+ coord = tgm.contrib.spatial_soft_argmax2d(input)
+ assert pytest.approx(coord[..., 0].item(), -1.0)
+ assert pytest.approx(coord[..., 1].item(), -1.0)
+
+ def _test_bottom_right(self):
+ input = torch.zeros(1, 1, 2, 3)
+ input[..., -1, 1] = 10.
+
+ coord = tgm.contrib.spatial_soft_argmax2d(input)
+ assert pytest.approx(coord[..., 0].item(), 1.0)
+ assert pytest.approx(coord[..., 1].item(), 1.0)
+
+ def _test_batch2_n2(self):
+ input = torch.zeros(2, 2, 2, 3)
+ input[0, 0, 0, 0] = 10. # top-left
+ input[0, 1, 0, -1] = 10. # top-right
+ input[1, 0, -1, 0] = 10. # bottom-left
+ input[1, 1, -1, -1] = 10. # bottom-right
+
+ coord = tgm.contrib.spatial_soft_argmax2d(input)
+ assert pytest.approx(coord[0, 0, 0].item(), -1.0) # top-left
+ assert pytest.approx(coord[0, 0, 1].item(), -1.0)
+ assert pytest.approx(coord[0, 1, 0].item(), 1.0) # top-right
+ assert pytest.approx(coord[0, 1, 1].item(), -1.0)
+ assert pytest.approx(coord[1, 0, 0].item(), -1.0) # bottom-left
+ assert pytest.approx(coord[1, 0, 1].item(), 1.0)
+ assert pytest.approx(coord[1, 1, 0].item(), 1.0) # bottom-right
+ assert pytest.approx(coord[1, 1, 1].item(), 1.0)
+
+ # TODO: implement me
+ def _test_jit(self):
+ pass
+
+ def _test_gradcheck(self):
+ input = torch.rand(2, 3, 3, 2)
+ input = utils.tensor_to_gradcheck_var(input) # to var
+ assert gradcheck(tgm.contrib.spatial_soft_argmax2d,
+ (input), raise_exception=True)
+
+ def test_run_all(self):
+ self._test_smoke()
+ self._test_top_left()
+ self._test_bottom_right()
+ self._test_batch2_n2()
+ self._test_gradcheck()
diff --git a/torchgeometry/__init__.py b/torchgeometry/__init__.py
index 645a9da73..b9bd7a92c 100644
--- a/torchgeometry/__init__.py
+++ b/torchgeometry/__init__.py
@@ -5,6 +5,7 @@ from .conversions import *
from .utils import *
from .imgwarp import *
from .transformations import *
+from .contrib import *
from torchgeometry import image
from torchgeometry import losses
diff --git a/torchgeometry/contrib/__init__.py b/torchgeometry/contrib/__init__.py
new file mode 100644
index 000000000..3aa162bb2
--- /dev/null
+++ b/torchgeometry/contrib/__init__.py
@@ -0,0 +1 @@
+from .spatial_soft_argmax2d import SpatialSoftArgmax2d, spatial_soft_argmax2d
diff --git a/torchgeometry/contrib/spatial_soft_argmax2d.py b/torchgeometry/contrib/spatial_soft_argmax2d.py
new file mode 100644
index 000000000..e3a63b7ed
--- /dev/null
+++ b/torchgeometry/contrib/spatial_soft_argmax2d.py
@@ -0,0 +1,77 @@
+from typing import Optional
+
+import torch
+import torch.nn as nn
+import torch.nn.functional as F
+
+
+def create_meshgrid(x):
+ pos_y, pos_x = torch.meshgrid(
+ torch.linspace(-1.0, 1.0, x.size(2), device=x.device, dtype=x.dtype),
+ torch.linspace(-1.0, 1.0, x.size(3), device=x.device, dtype=x.dtype))
+ return pos_y, pos_x
+
+
+class SpatialSoftArgmax2d(nn.Module):
+ r"""Creates a module that computes the Spatial Soft-Argmax 2D
+ of a given input heatmap.
+
+ Returns the index of the maximum 2d coordinates of the give map.
+ The output order is x-coord and y-coord.
+
+ Shape:
+ - Input: :math:`(B, N, H, W)`
+ - Output: :math:`(B, N, 2)`
+
+ Examples::
+ >>> input = torch.rand(1, 4, 2, 3)
+ >>> m = tgm.losses.SpatialSoftArgmax2d()
+ >>> coords = m(input) # 1x4x2
+ >>> x_coord, y_coord = torch.chunk(coords, dim=-1, chunks=2)
+ """
+
+ def __init__(self) -> None:
+ super(SpatialSoftArgmax2d, self).__init__()
+ self.eps: float = 1e-6
+
+ def forward(self, input: torch.Tensor) -> torch.Tensor:
+ if not torch.is_tensor(input):
+ raise TypeError("Input input type is not a torch.Tensor. Got {}"
+ .format(type(input)))
+ if not len(input.shape) == 4:
+ raise ValueError("Invalid input shape, we expect BxCxHxW. Got: {}"
+ .format(input.shape))
+ # unpack shapes and create view from input tensor
+ batch_size, channels, height, width = input.shape
+ x: torch.Tensor = input.view(batch_size, channels, -1)
+
+ # compute softmax with max substraction trick
+ exp_x = torch.exp(x - torch.max(x, dim=-1, keepdim=True)[0])
+ exp_x_sum = 1.0 / (exp_x.sum(dim=-1, keepdim=True) + self.eps)
+
+ # create coordinates grid
+ pos_y, pos_x = create_meshgrid(input)
+ pos_x = pos_x.reshape(-1)
+ pos_y = pos_y.reshape(-1)
+
+ # compute the expected coordinates
+ expected_y: torch.Tensor = torch.sum(
+ (pos_y * exp_x) * exp_x_sum, dim=-1, keepdim=True)
+ expected_x: torch.Tensor = torch.sum(
+ (pos_x * exp_x) * exp_x_sum, dim=-1, keepdim=True)
+ output: torch.Tensor = torch.cat([expected_x, expected_y], dim=-1)
+ return output.view(batch_size, channels, 2) # BxNx2
+
+
+######################
+# functional interface
+######################
+
+
+def spatial_soft_argmax2d(input: torch.Tensor) -> torch.Tensor:
+ r"""Function that computes the Spatial Soft-Argmax 2D of a given heatmap.
+
+ See :class:`torchgeometry.contrib.SpatialSoftArgmax2d` for details.
+ """
+ return SpatialSoftArgmax2d()(input)