Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

[FIX] Soft-argmax test fixes, renaming and enables jit (#553)

Aiden Nibalie2e6818c021b
diff --git a/docs/source/geometry.rst b/docs/source/geometry.rst
index 737423f63..35abe745d 100644
--- a/docs/source/geometry.rst
+++ b/docs/source/geometry.rst
@@ -16,13 +16,13 @@ kornia.geometry
Coordinates Subpixel
--------------------
-.. autofunction:: spatial_softmax_2d
-.. autofunction:: spatial_softargmax_2d
-.. autofunction:: render_gaussian_2d
+.. autofunction:: spatial_soft_argmax2d
.. autofunction:: conv_soft_argmax2d
.. autofunction:: conv_soft_argmax3d
.. autofunction:: conv_quad_interp3d
-.. autofunction:: spatial_softmax_2d
+.. autofunction:: spatial_softmax2d
+.. autofunction:: spatial_expectation2d
+.. autofunction:: render_gaussian2d
Module
------
diff --git a/kornia/geometry/dsnt.py b/kornia/geometry/dsnt.py
index 5a0d39a8e..b8a207899 100644
--- a/kornia/geometry/dsnt.py
+++ b/kornia/geometry/dsnt.py
@@ -3,25 +3,23 @@ operations, as described in the paper "Numerical Coordinate Regression with
Convolutional Neural Networks" by Nibali et al.
"""
-from typing import Any, Tuple
+from typing import Tuple
import torch
import torch.nn.functional as F
-from torch import finfo # type: ignore
+from kornia.testing import check_is_tensor
from kornia.utils.grid import create_meshgrid
def _validate_batched_image_tensor_input(tensor):
- if not torch.is_tensor(tensor):
- raise TypeError("Input type is not a torch.Tensor. Got {}"
- .format(type(tensor)))
+ check_is_tensor(tensor)
if not len(tensor.shape) == 4:
raise ValueError("Invalid input shape, we expect BxCxHxW. Got: {}"
.format(tensor.shape))
-def spatial_softmax_2d(
+def spatial_softmax2d(
input: torch.Tensor,
temperature: torch.Tensor = torch.tensor(1.0),
) -> torch.Tensor:
@@ -51,21 +49,21 @@ def spatial_softmax_2d(
return x_soft.view(batch_size, channels, height, width)
-def spatial_softargmax_2d(
+def spatial_expectation2d(
input: torch.Tensor,
normalized_coordinates: bool = True,
) -> torch.Tensor:
- r"""Computes the 2D soft-argmax of a given input heatmap.
+ r"""Computes the expectation of coordinate values using spatial probabilities.
The input heatmap is assumed to represent a valid spatial probability
distribution, which can be achieved using
- :class:`~kornia.contrib.dsnt.spatial_softmax_2d`.
+ :class:`~kornia.geometry.dsnt.spatial_softmax2d`.
- Returns the index of the maximum 2D coordinates of the given heatmap.
+ Returns the expected value of the 2D coordinates.
The output order of the coordinates is (x, y).
Arguments:
- input (torch.Tensor): the input tensor.
+ input (torch.Tensor): the input tensor representing dense spatial probabilities.
normalized_coordinates (bool): whether to return the
coordinates normalized in the range of [-1, 1]. Otherwise,
it will return the coordinates in the range of the input shape.
@@ -80,7 +78,7 @@ def spatial_softargmax_2d(
[0., 0., 0.],
[0., 0., 0.],
[0., 1., 0.]]]])
- >>> coords = spatial_softargmax_2d(heatmaps, False)
+ >>> coords = spatial_expectation_2d(heatmaps, False)
tensor([[[1.0000, 2.0000]]])
"""
_validate_batched_image_tensor_input(input)
@@ -88,9 +86,8 @@ def spatial_softargmax_2d(
batch_size, channels, height, width = input.shape
# Create coordinates grid.
- grid: torch.Tensor = create_meshgrid(
- height, width, normalized_coordinates)
- grid = grid.to(device=input.device, dtype=input.dtype)
+ grid: torch.Tensor = create_meshgrid(height, width, normalized_coordinates, input.device)
+ grid = grid.to(input.dtype)
pos_x: torch.Tensor = grid[..., 0].reshape(-1)
pos_y: torch.Tensor = grid[..., 1].reshape(-1)
@@ -109,12 +106,12 @@ def spatial_softargmax_2d(
def _safe_zero_division(
numerator: torch.Tensor,
denominator: torch.Tensor,
+ eps: float = 1e-32,
) -> torch.Tensor:
- eps: float = finfo(numerator.dtype).tiny
return numerator / torch.clamp(denominator, min=eps)
-def render_gaussian_2d(
+def render_gaussian2d(
mean: torch.Tensor,
std: torch.Tensor,
size: Tuple[int, int],
@@ -138,17 +135,13 @@ def render_gaussian_2d(
- `std`: :math:`(*, 2)`. Should be able to be broadcast with `mean`.
- Output: :math:`(*, H, W)`
"""
- mean_dtype: Any = mean.dtype
- if not mean_dtype.is_floating_point:
- raise TypeError("Expected `mean` to have floating point values. Got {}"
- .format(mean.dtype))
if not (std.dtype == mean.dtype and std.device == mean.device):
raise TypeError("Expected inputs to have the same dtype and device")
height, width = size
# Create coordinates grid.
- grid: torch.Tensor = create_meshgrid(height, width, normalized_coordinates)
- grid = grid.to(device=mean.device, dtype=mean.dtype)
+ grid: torch.Tensor = create_meshgrid(height, width, normalized_coordinates, mean.device)
+ grid = grid.to(mean.dtype)
pos_x: torch.Tensor = grid[..., 0].view(height, width)
pos_y: torch.Tensor = grid[..., 1].view(height, width)
diff --git a/kornia/geometry/spatial_soft_argmax.py b/kornia/geometry/spatial_soft_argmax.py
index 26ba5d573..21cc3a1fd 100644
--- a/kornia/geometry/spatial_soft_argmax.py
+++ b/kornia/geometry/spatial_soft_argmax.py
@@ -511,9 +511,8 @@ def spatial_soft_argmax2d(
>>> coords = kornia.spatial_soft_argmax2d(input, False)
tensor([[[1.0000, 1.0000]]])
"""
- input_soft: torch.Tensor = dsnt.spatial_softmax_2d(input, temperature)
- output: torch.Tensor = dsnt.spatial_softargmax_2d(input_soft,
- normalized_coordinates)
+ input_soft: torch.Tensor = dsnt.spatial_softmax2d(input, temperature)
+ output: torch.Tensor = dsnt.spatial_expectation2d(input_soft, normalized_coordinates)
return output
diff --git a/kornia/jit/__init__.py b/kornia/jit/__init__.py
index e7b914da0..6e31e8232 100644
--- a/kornia/jit/__init__.py
+++ b/kornia/jit/__init__.py
@@ -4,3 +4,8 @@ import kornia as K
# expose functions to torch.jit
# TODO: find an automatic way to do this
rgb_to_grayscale = torch.jit.script(K.color.rgb_to_grayscale)
+
+spatial_soft_argmax2d = torch.jit.script(K.geometry.spatial_soft_argmax2d)
+spatial_softmax2d = torch.jit.script(K.geometry.dsnt.spatial_softmax2d)
+spatial_expectation2d = torch.jit.script(K.geometry.dsnt.spatial_expectation2d)
+render_gaussian2d = torch.jit.script(K.geometry.dsnt.render_gaussian2d)
diff --git a/kornia/testing/__init__.py b/kornia/testing/__init__.py
index f43e1b0b7..0f7226882 100644
--- a/kornia/testing/__init__.py
+++ b/kornia/testing/__init__.py
@@ -45,3 +45,10 @@ def compute_patch_error(x, y, h, w):
"""Compute the absolute error between patches.
"""
return torch.abs(x - y)[..., h // 4:-h // 4, w // 4:-w // 4].mean()
+
+
+def check_is_tensor(obj):
+ """Checks whether the supplied object is a tensor.
+ """
+ if not isinstance(obj, torch.Tensor):
+ raise TypeError("Input type is not a torch.Tensor. Got {}".format(type(obj)))
diff --git a/kornia/utils/grid.py b/kornia/utils/grid.py
index 392a8d80b..9b3a1598e 100644
--- a/kornia/utils/grid.py
+++ b/kornia/utils/grid.py
@@ -6,7 +6,7 @@ import torch
def create_meshgrid(
height: int,
width: int,
- normalized_coordinates: Optional[bool] = True,
+ normalized_coordinates: bool = True,
device: Optional[torch.device] = torch.device('cpu')) -> torch.Tensor:
"""Generates a coordinate grid for an image.
@@ -18,7 +18,7 @@ def create_meshgrid(
Args:
height (int): the image height (rows).
width (int): the image width (cols).
- normalized_coordinates (Optional[bool]): whether to normalize
+ normalized_coordinates (bool): whether to normalize
coordinates in the range [-1, 1] in order to be consistent with the
PyTorch function grid_sample.
@@ -44,7 +44,7 @@ def create_meshgrid3d(
depth: int,
height: int,
width: int,
- normalized_coordinates: Optional[bool] = True,
+ normalized_coordinates: bool = True,
device: Optional[torch.device] = torch.device('cpu')) -> torch.Tensor:
"""Generates a coordinate grid for an image.
@@ -57,7 +57,7 @@ def create_meshgrid3d(
depth (int): the image depth (channels).
height (int): the image height (rows).
width (int): the image width (cols).
- normalized_coordinates (Optional[bool]): wether to normalize
+ normalized_coordinates (bool): whether to normalize
coordinates in the range [-1, 1] in order to be consistent with the
PyTorch function grid_sample.
diff --git a/test/common.py b/test/common.py
index 32e758313..832f2a150 100644
--- a/test/common.py
+++ b/test/common.py
@@ -18,7 +18,7 @@ def get_test_devices() -> Dict[str, torch.device]:
return devices
-def get_test_dtypes() -> Dict[str, torch.device]:
+def get_test_dtypes() -> Dict[str, torch.dtype]:
"""Creates a dictionary with the dtypes the source code.
Return:
@@ -44,6 +44,6 @@ def device(request) -> torch.device:
@pytest.fixture()
-def dtype(request) -> torch.device:
+def dtype(request) -> torch.dtype:
_dtype_name: str = request.config.getoption('--dtypetest')
return TEST_DTYPES[_dtype_name]
diff --git a/test/geometry/test_dsnt.py b/test/geometry/test_dsnt.py
new file mode 100644
index 000000000..2c73f5f14
--- /dev/null
+++ b/test/geometry/test_dsnt.py
@@ -0,0 +1,108 @@
+import pytest
+
+import kornia as kornia
+from test.common import dtype, device
+
+import torch
+from torch.testing import assert_allclose
+
+
+class TestRenderGaussian2d:
+ @pytest.fixture
+ def gaussian(self, device, dtype):
+ return torch.tensor([
+ [0.002969, 0.013306, 0.021938, 0.013306, 0.002969],
+ [0.013306, 0.059634, 0.098320, 0.059634, 0.013306],
+ [0.021938, 0.098320, 0.162103, 0.098320, 0.021938],
+ [0.013306, 0.059634, 0.098320, 0.059634, 0.013306],
+ [0.002969, 0.013306, 0.021938, 0.013306, 0.002969],
+ ], dtype=dtype, device=device)
+
+ def test_pixel_coordinates(self, gaussian, device, dtype):
+ mean = torch.tensor([2.0, 2.0], dtype=dtype, device=device)
+ std = torch.tensor([1.0, 1.0], dtype=dtype, device=device)
+ actual = kornia.geometry.dsnt.render_gaussian2d(mean, std, (5, 5), False)
+ assert_allclose(actual, gaussian, rtol=0, atol=1e-4)
+
+ def test_normalized_coordinates(self, gaussian, device, dtype):
+ mean = torch.tensor([0.0, 0.0], dtype=dtype, device=device)
+ std = torch.tensor([0.25, 0.25], dtype=dtype, device=device)
+ actual = kornia.geometry.dsnt.render_gaussian2d(mean, std, (5, 5), True)
+ assert_allclose(actual, gaussian, rtol=0, atol=1e-4)
+
+ def test_jit(self, device, dtype):
+ mean = torch.tensor([0.0, 0.0], dtype=dtype, device=device)
+ std = torch.tensor([0.25, 0.25], dtype=dtype, device=device)
+ args = (mean, std, (5, 5), True)
+ op = kornia.geometry.dsnt.render_gaussian2d
+ op_jit = kornia.jit.render_gaussian2d
+ assert_allclose(op(*args), op_jit(*args), rtol=0, atol=1e-5)
+
+ def test_jit_trace(self, device, dtype):
+ def op(mean, std):
+ return kornia.geometry.dsnt.render_gaussian2d(mean, std, (5, 5), True)
+ mean = torch.tensor([0.0, 0.0], dtype=dtype, device=device)
+ std = torch.tensor([0.25, 0.25], dtype=dtype, device=device)
+ args = (mean, std)
+ op_jit = torch.jit.trace(op, args)
+ assert_allclose(op(*args), op_jit(*args), rtol=0, atol=1e-5)
+
+
+class TestSpatialSoftmax2d:
+ @pytest.fixture(params=[
+ torch.ones(1, 1, 5, 7),
+ torch.randn(2, 3, 16, 16),
+ ])
+ def input(self, request, device, dtype):
+ return request.param.to(device, dtype)
+
+ def test_forward(self, input):
+ actual = kornia.geometry.dsnt.spatial_softmax2d(input)
+ assert actual.lt(0).sum().item() == 0, 'expected no negative values'
+ sums = actual.sum(-1).sum(-1)
+ assert_allclose(sums, torch.ones_like(sums))
+
+ def test_jit(self, input):
+ op = kornia.geometry.dsnt.spatial_softmax2d
+ op_jit = kornia.jit.spatial_softmax2d
+ assert_allclose(op(input), op_jit(input), rtol=0, atol=1e-5)
+
+ def test_jit_trace(self, input):
+ op = kornia.geometry.dsnt.spatial_softmax2d
+ op_jit = torch.jit.trace(op, (input,))
+ assert_allclose(op(input), op_jit(input), rtol=0, atol=1e-5)
+
+
+class TestSpatialExpectation2d:
+ @pytest.fixture(params=[
+ (
+ torch.tensor([[[
+ [0.0, 0.0, 1.0],
+ [0.0, 0.0, 0.0],
+ ]]]),
+ torch.tensor([[[1.0, -1.0]]]),
+ torch.tensor([[[2.0, 0.0]]]),
+ ),
+ ])
+ def example(self, request, device, dtype):
+ input, expected_norm, expected_px = request.param
+ return input.to(device, dtype), expected_norm.to(device, dtype), expected_px.to(device, dtype)
+
+ def test_forward(self, example):
+ input, expected_norm, expected_px = example
+ actual_norm = kornia.geometry.dsnt.spatial_expectation2d(input, True)
+ assert_allclose(actual_norm, expected_norm)
+ actual_px = kornia.geometry.dsnt.spatial_expectation2d(input, False)
+ assert_allclose(actual_px, expected_px)
+
+ def test_jit(self, example):
+ input = example[0]
+ op = kornia.geometry.dsnt.spatial_expectation2d
+ op_jit = kornia.jit.spatial_expectation2d
+ assert_allclose(op(input), op_jit(input), rtol=0, atol=1e-5)
+
+ def test_jit_trace(self, example):
+ input = example[0]
+ op = kornia.geometry.dsnt.spatial_expectation2d
+ op_jit = torch.jit.trace(op, (input,))
+ assert_allclose(op(input), op_jit(input), rtol=0, atol=1e-5)
diff --git a/test/geometry/test_spatial_softargmax.py b/test/geometry/test_spatial_softargmax.py
index da6562e3c..d0d99623d 100644
--- a/test/geometry/test_spatial_softargmax.py
+++ b/test/geometry/test_spatial_softargmax.py
@@ -2,7 +2,7 @@ import pytest
import kornia as kornia
import kornia.testing as utils # test utils
-from test.common import device
+from test.common import device, dtype
import torch
from torch.nn.functional import mse_loss
@@ -123,92 +123,21 @@ class TestSpatialSoftArgmax2d:
assert_allclose(coord[1, 1, 0].item(), 1.0) # bottom-right
assert_allclose(coord[1, 1, 1].item(), 1.0)
- @pytest.mark.skip(reason="turn off all jit for a while")
- def test_jit(self, device):
- @torch.jit.script
- def op_script(input: torch.Tensor,
- temperature: torch.Tensor,
- normalize_coords: bool,
- eps: float) -> torch.Tensor:
- return kornia.spatial_soft_argmax2d(
- input, temperature, normalize_coords, eps)
-
- input = torch.rand(1, 2, 3, 4).to(device)
- actual = op_script(input, torch.tensor(1.0), True, 1e-8)
- expected = kornia.spatial_soft_argmax2d(input)
-
- assert_allclose(actual, expected)
-
def test_gradcheck(self, device):
input = torch.rand(2, 3, 3, 2).to(device)
input = utils.tensor_to_gradcheck_var(input) # to var
assert gradcheck(kornia.spatial_soft_argmax2d,
(input), raise_exception=True)
-
-class TestDSNT:
- GAUSSIAN = torch.tensor([
- [0.002969, 0.013306, 0.021938, 0.013306, 0.002969],
- [0.013306, 0.059634, 0.098320, 0.059634, 0.013306],
- [0.021938, 0.098320, 0.162103, 0.098320, 0.021938],
- [0.013306, 0.059634, 0.098320, 0.059634, 0.013306],
- [0.002969, 0.013306, 0.021938, 0.013306, 0.002969],
- ])
-
- def test_render_gaussian_2d(self, device):
- expected = self.GAUSSIAN.to(device)
- actual = kornia.geometry.dsnt.render_gaussian_2d(torch.tensor([2.0, 2.0]),
- torch.tensor([1.0, 1.0]),
- (5, 5),
- normalized_coordinates=False).to(device)
- assert_allclose(actual, expected, rtol=0, atol=1e-5)
-
- def test_render_gaussian_2d_normalized_coordinates(self, device):
- expected = self.GAUSSIAN.to(device)
- actual = kornia.geometry.dsnt.render_gaussian_2d(torch.tensor([0.0, 0.0]),
- torch.tensor([0.25, 0.25]),
- (5, 5),
- normalized_coordinates=True).to(device)
- assert_allclose(actual, expected, rtol=0, atol=1e-5)
-
- @pytest.mark.parametrize('input', [
- torch.ones(1, 1, 5, 7),
- torch.randn(2, 3, 16, 16),
- ])
- def test_spatial_softmax_2d(self, device, input):
- actual = kornia.geometry.dsnt.spatial_softmax_2d(input.to(device))
- assert actual.lt(0).sum().item() == 0, 'expected no negative values'
- sums = actual.sum(-1).sum(-1)
- assert_allclose(sums, torch.ones_like(sums))
-
- @pytest.mark.parametrize('input,expected_norm,expected_px', [
- (
- torch.tensor([[[
- [0.0, 0.0, 1.0],
- [0.0, 0.0, 0.0],
- ]]]),
- torch.tensor([[[1.0, -1.0]]]),
- torch.tensor([[[2.0, 0.0]]]),
- ),
- ])
- def test_spatial_softargmax_2d(self, device, input, expected_norm, expected_px):
- input = input.to(device)
- expected_norm = expected_norm.to(device)
- expected_px = expected_px.to(device)
- actual_norm = kornia.geometry.dsnt.spatial_softargmax_2d(input, True)
- assert_allclose(actual_norm, expected_norm)
- actual_px = kornia.geometry.dsnt.spatial_softargmax_2d(input, False)
- assert_allclose(actual_px, expected_px)
-
def test_end_to_end(self, device):
input = torch.full((1, 2, 7, 7), 1.0, requires_grad=True).to(device)
target = torch.as_tensor([[[0.0, 0.0], [1.0, 1.0]]]).to(device)
std = torch.tensor([1.0, 1.0]).to(device)
- hm = kornia.geometry.dsnt.spatial_softmax_2d(input)
+ hm = kornia.geometry.dsnt.spatial_softmax2d(input)
assert_allclose(hm.sum(-1).sum(-1), torch.tensor(1.0).to(device))
- pred = kornia.geometry.dsnt.spatial_softargmax_2d(hm)
+ pred = kornia.geometry.dsnt.spatial_expectation2d(hm)
assert_allclose(pred, torch.as_tensor([[[0.0, 0.0], [0.0, 0.0]]]).to(device))
loss1 = mse_loss(pred, target, size_average=None, reduce=None,
@@ -216,7 +145,7 @@ class TestDSNT:
expected_loss1 = torch.as_tensor([[0.0, 1.0]]).to(device)
assert_allclose(loss1, expected_loss1)
- target_hm = kornia.geometry.dsnt.render_gaussian_2d(
+ target_hm = kornia.geometry.dsnt.render_gaussian2d(
target, std, input.shape[-2:]).contiguous()
loss2 = kornia.losses.js_div_loss_2d(hm, target_hm, reduction='none')
@@ -226,28 +155,17 @@ class TestDSNT:
loss = (loss1 + loss2).mean()
loss.backward()
- @pytest.mark.skip(reason="turn off all jit for a while")
- def test_jit(self, device):
- def op(input: torch.Tensor, target: torch.Tensor,
- temperature: torch.Tensor, normalized_coordinates: bool,
- std: torch.Tensor) -> torch.Tensor:
- hm = kornia.geometry.dsnt.spatial_softmax_2d(input, temperature)
- pred = kornia.geometry.dsnt.spatial_softargmax_2d(hm, normalized_coordinates)
- size = (input.shape[-2], input.shape[-1])
- target_hm = kornia.geometry.dsnt.render_gaussian_2d(target, std, size,
- normalized_coordinates)
- loss1 = mse_loss(pred, target, size_average=None, reduce=None,
- reduction='mean')
- loss2 = kornia.losses.js_div_loss_2d(hm, target_hm, 'mean')
- return loss1 + loss2
-
- op_script = torch.jit.script(op)
-
- args = [torch.rand(2, 3, 7, 7).to(device), torch.rand(2, 3, 2).to(device) * 7,
- torch.tensor(1.0).to(device), False, torch.tensor([1.0, 1.0]).to(device)]
- actual = op_script(*args)
- expected = op(*args)
- assert_allclose(actual, expected)
+ def test_jit(self, device, dtype):
+ input = torch.rand((2, 3, 7, 7), dtype=dtype, device=device)
+ op = kornia.spatial_soft_argmax2d
+ op_jit = kornia.jit.spatial_soft_argmax2d
+ assert_allclose(op(input), op_jit(input), rtol=0, atol=1e-5)
+
+ def test_jit_trace(self, device, dtype):
+ input = torch.rand((2, 3, 7, 7), dtype=dtype, device=device)
+ op = kornia.spatial_soft_argmax2d
+ op_jit = torch.jit.trace(op, (input,))
+ assert_allclose(op(input), op_jit(input), rtol=0, atol=1e-5)
class TestConvSoftArgmax2d:
diff --git a/test/test_losses.py b/test/test_losses.py
index f173b011f..128f1704c 100644
--- a/test/test_losses.py
+++ b/test/test_losses.py
@@ -2,7 +2,7 @@ import pytest
import kornia
import kornia.testing as utils # test utils
-from test.common import device
+from test.common import device, dtype
import math
import torch
@@ -277,6 +277,22 @@ class TestDivergenceLoss:
assert gradcheck(kornia.losses.js_div_loss_2d, (input, target),
raise_exception=True)
+ def test_jit_trace_kl(self, device, dtype):
+ input = torch.randn((2, 4, 10, 16), dtype=dtype, device=device)
+ target = torch.randn((2, 4, 10, 16), dtype=dtype, device=device)
+ args = (input, target)
+ op = kornia.losses.kl_div_loss_2d
+ op_jit = torch.jit.trace(op, args)
+ assert_allclose(op(*args), op_jit(*args), rtol=0, atol=1e-5)
+
+ def test_jit_trace_js(self, device, dtype):
+ input = torch.randn((2, 4, 10, 16), dtype=dtype, device=device)
+ target = torch.randn((2, 4, 10, 16), dtype=dtype, device=device)
+ args = (input, target)
+ op = kornia.losses.js_div_loss_2d
+ op_jit = torch.jit.trace(op, args)
+ assert_allclose(op(*args), op_jit(*args), rtol=0, atol=1e-5)
+
class TestTotalVariation:
# Total variation of constant vectors is 0