Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

Add DSNT operations

Aiden Nibali31173c1220ff
diff --git a/kornia/contrib/dsnt.py b/kornia/contrib/dsnt.py
new file mode 100644
index 000000000..5a0d39a8e
--- /dev/null
+++ b/kornia/contrib/dsnt.py
@@ -0,0 +1,176 @@
+r"""Implementation of "differentiable spatial to numerical" (soft-argmax)
+operations, as described in the paper "Numerical Coordinate Regression with
+Convolutional Neural Networks" by Nibali et al.
+"""
+
+from typing import Any, Tuple
+
+import torch
+import torch.nn.functional as F
+from torch import finfo # type: ignore
+
+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)))
+ if not len(tensor.shape) == 4:
+ raise ValueError("Invalid input shape, we expect BxCxHxW. Got: {}"
+ .format(tensor.shape))
+
+
+def spatial_softmax_2d(
+ input: torch.Tensor,
+ temperature: torch.Tensor = torch.tensor(1.0),
+) -> torch.Tensor:
+ r"""Applies the Softmax function over features in each image channel.
+
+ Note that this function behaves differently to `torch.nn.Softmax2d`, which
+ instead applies Softmax over features at each spatial location.
+
+ Returns a 2D probability distribution per image channel.
+
+ Arguments:
+ input (torch.Tensor): the input tensor.
+ temperature (torch.Tensor): factor to apply to input, adjusting the
+ "smoothness" of the output distribution. Default is 1.
+
+ Shape:
+ - Input: :math:`(B, N, H, W)`
+ - Output: :math:`(B, N, H, W)`
+ """
+ _validate_batched_image_tensor_input(input)
+
+ batch_size, channels, height, width = input.shape
+ x: torch.Tensor = input.view(batch_size, channels, -1)
+
+ x_soft: torch.Tensor = F.softmax(x * temperature, dim=-1)
+
+ return x_soft.view(batch_size, channels, height, width)
+
+
+def spatial_softargmax_2d(
+ input: torch.Tensor,
+ normalized_coordinates: bool = True,
+) -> torch.Tensor:
+ r"""Computes the 2D soft-argmax of a given input heatmap.
+
+ The input heatmap is assumed to represent a valid spatial probability
+ distribution, which can be achieved using
+ :class:`~kornia.contrib.dsnt.spatial_softmax_2d`.
+
+ Returns the index of the maximum 2D coordinates of the given heatmap.
+ The output order of the coordinates is (x, y).
+
+ Arguments:
+ input (torch.Tensor): the input tensor.
+ 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.
+ Default is True.
+
+ Shape:
+ - Input: :math:`(B, N, H, W)`
+ - Output: :math:`(B, N, 2)`
+
+ Examples:
+ >>> heatmaps = torch.tensor([[[
+ [0., 0., 0.],
+ [0., 0., 0.],
+ [0., 1., 0.]]]])
+ >>> coords = spatial_softargmax_2d(heatmaps, False)
+ tensor([[[1.0000, 2.0000]]])
+ """
+ _validate_batched_image_tensor_input(input)
+
+ 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)
+
+ pos_x: torch.Tensor = grid[..., 0].reshape(-1)
+ pos_y: torch.Tensor = grid[..., 1].reshape(-1)
+
+ input_flat: torch.Tensor = input.view(batch_size, channels, -1)
+
+ # Compute the expectation of the coordinates.
+ expected_y: torch.Tensor = torch.sum(pos_y * input_flat, -1, keepdim=True)
+ expected_x: torch.Tensor = torch.sum(pos_x * input_flat, -1, keepdim=True)
+
+ output: torch.Tensor = torch.cat([expected_x, expected_y], -1)
+
+ return output.view(batch_size, channels, 2) # BxNx2
+
+
+def _safe_zero_division(
+ numerator: torch.Tensor,
+ denominator: torch.Tensor,
+) -> torch.Tensor:
+ eps: float = finfo(numerator.dtype).tiny
+ return numerator / torch.clamp(denominator, min=eps)
+
+
+def render_gaussian_2d(
+ mean: torch.Tensor,
+ std: torch.Tensor,
+ size: Tuple[int, int],
+ normalized_coordinates: bool = True,
+):
+ r"""Renders the PDF of a 2D Gaussian distribution.
+
+ Arguments:
+ mean (torch.Tensor): the mean location of the Gaussian to render,
+ :math:`(\mu_x, \mu_y)`.
+ std (torch.Tensor): the standard deviation of the Gaussian to render,
+ :math:`(\sigma_x, \sigma_y)`.
+ size (list): the (height, width) of the output image.
+ normalized_coordinates: whether `mean` and `std` are assumed to use
+ coordinates normalized in the range of [-1, 1]. Otherwise,
+ coordinates are assumed to be in the range of the output shape.
+ Default is True.
+
+ Shape:
+ - `mean`: :math:`(*, 2)`
+ - `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)
+ pos_x: torch.Tensor = grid[..., 0].view(height, width)
+ pos_y: torch.Tensor = grid[..., 1].view(height, width)
+
+ # Gaussian PDF = exp(-(x - \mu)^2 / (2 \sigma^2))
+ # = exp(dists * ks),
+ # where dists = (x - \mu)^2 and ks = -1 / (2 \sigma^2)
+
+ # dists <- (x - \mu)^2
+ dist_x = (pos_x - mean[..., 0, None, None]) ** 2
+ dist_y = (pos_y - mean[..., 1, None, None]) ** 2
+
+ # ks <- -1 / (2 \sigma^2)
+ k_x = -0.5 * torch.reciprocal(std[..., 0, None, None])
+ k_y = -0.5 * torch.reciprocal(std[..., 1, None, None])
+
+ # Assemble the 2D Gaussian.
+ exps_x = torch.exp(dist_x * k_x)
+ exps_y = torch.exp(dist_y * k_y)
+ gauss = exps_x * exps_y
+
+ # Rescale so that values sum to one.
+ val_sum = gauss.sum(-2, keepdim=True).sum(-1, keepdim=True)
+ gauss = _safe_zero_division(gauss, val_sum)
+
+ return gauss
diff --git a/kornia/contrib/spatial_soft_argmax2d.py b/kornia/contrib/spatial_soft_argmax2d.py
index e6daea474..e1ee16094 100644
--- a/kornia/contrib/spatial_soft_argmax2d.py
+++ b/kornia/contrib/spatial_soft_argmax2d.py
@@ -1,8 +1,7 @@
import torch
import torch.nn as nn
-import torch.nn.functional as F
-from kornia.utils import create_meshgrid
+import kornia.contrib.dsnt as dsnt
def spatial_soft_argmax2d(
@@ -18,7 +17,7 @@ def spatial_soft_argmax2d(
Arguments:
temperature (torch.Tensor): factor to apply to input. Default is 1.
- normalized_coordinates (bool): wether to return the
+ 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.
Default is True.
@@ -36,33 +35,10 @@ def spatial_soft_argmax2d(
>>> coords = kornia.spatial_soft_argmax2d(input, False)
tensor([[[1.0000, 1.0000]]])
"""
- 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 along the feature map
- x_soft: torch.Tensor = F.softmax(x * temperature, dim=-1)
-
- # create coordinates grid
- grid: torch.Tensor = create_meshgrid(
- height, width, normalized_coordinates)
- grid = grid.to(input.device).to(input.dtype)
-
- pos_x: torch.Tensor = grid[..., 0].reshape(-1)
- pos_y: torch.Tensor = grid[..., 1].reshape(-1)
-
- # compute the expected coordinates
- expected_y: torch.Tensor = torch.sum(pos_y * x_soft, dim=-1, keepdim=True)
- expected_x: torch.Tensor = torch.sum(pos_x * x_soft, dim=-1, keepdim=True)
-
- output: torch.Tensor = torch.cat([expected_x, expected_y], dim=-1)
- return output.view(batch_size, channels, 2) # BxNx2
+ input_soft: torch.Tensor = dsnt.spatial_softmax_2d(input, temperature)
+ output: torch.Tensor = dsnt.spatial_softargmax_2d(input_soft,
+ normalized_coordinates)
+ return output
class SpatialSoftArgmax2d(nn.Module):
diff --git a/kornia/losses/__init__.py b/kornia/losses/__init__.py
index 2443c3188..07421a3f4 100644
--- a/kornia/losses/__init__.py
+++ b/kornia/losses/__init__.py
@@ -5,3 +5,4 @@ from .focal import FocalLoss, focal_loss
from .depth_smooth import (
InverseDepthSmoothnessLoss, inverse_depth_smoothness_loss
)
+from .divergence import kl_div_loss_2d, js_div_loss_2d
diff --git a/kornia/losses/divergence.py b/kornia/losses/divergence.py
new file mode 100644
index 000000000..776a0c86a
--- /dev/null
+++ b/kornia/losses/divergence.py
@@ -0,0 +1,76 @@
+r"""Losses based on the divergence between probability distributions."""
+
+
+import torch
+import torch.nn.functional as F
+
+
+def _kl_div_2d(p, q):
+ # D_KL(P || Q)
+ batch, chans, height, width = p.shape
+ unsummed_kl = F.kl_div(
+ q.view(batch * chans, height * width).log(),
+ p.view(batch * chans, height * width),
+ reduction='none',
+ )
+ kl_values = unsummed_kl.sum(-1).view(batch, chans)
+ return kl_values
+
+
+def _js_div_2d(p, q):
+ # JSD(P || Q)
+ m = 0.5 * (p + q)
+ return 0.5 * _kl_div_2d(p, m) + 0.5 * _kl_div_2d(q, m)
+
+
+def _reduce_loss(losses, reduction):
+ if reduction == 'none':
+ return losses
+ else:
+ return torch.mean(losses) if reduction == 'mean' else torch.sum(losses)
+
+
+def js_div_loss_2d(
+ input: torch.Tensor,
+ target: torch.Tensor,
+ reduction: str = 'mean'
+):
+ r"""Calculates the Jensen-Shannon divergence loss between heatmaps.
+
+ Arguments:
+ input (torch.Tensor): the input tensor.
+ target (torch.Tensor): the target tensor.
+ reduction (string, optional): Specifies the reduction to apply to the
+ output: ``'none'`` | ``'mean'`` | ``'sum'``. ``'none'``: no reduction
+ will be applied, ``'mean'``: the sum of the output will be divided by
+ the number of elements in the output, ``'sum'``: the output will be
+ summed. Default: ``'mean'``.
+
+ Shape:
+ - Input: :math:`(B, N, H, W)`
+ - Target: :math:`(B, N, H, W)`, same shape as the input
+ """
+ return _reduce_loss(_js_div_2d(target, input), reduction)
+
+
+def kl_div_loss_2d(
+ input: torch.Tensor,
+ target: torch.Tensor,
+ reduction: str = 'mean'
+):
+ r"""Calculates the Kullback-Leibler divergence loss between heatmaps.
+
+ Arguments:
+ input (torch.Tensor): the input tensor.
+ target (torch.Tensor): the target tensor.
+ reduction (string, optional): Specifies the reduction to apply to the
+ output: ``'none'`` | ``'mean'`` | ``'sum'``. ``'none'``: no reduction
+ will be applied, ``'mean'``: the sum of the output will be divided by
+ the number of elements in the output, ``'sum'``: the output will be
+ summed. Default: ``'mean'``.
+
+ Shape:
+ - Input: :math:`(B, N, H, W)`
+ - Target: :math:`(B, N, H, W)`, same shape as the input
+ """
+ return _reduce_loss(_kl_div_2d(target, input), reduction)
diff --git a/test/test_contrib.py b/test/test_contrib.py
index 1fc753e8c..167753804 100644
--- a/test/test_contrib.py
+++ b/test/test_contrib.py
@@ -1,12 +1,13 @@
import pytest
-
-import kornia
-import kornia.testing as utils # test utils
-
import torch
from torch.autograd import gradcheck
+from torch.nn.functional import mse_loss
from torch.testing import assert_allclose
+import kornia
+import kornia.contrib.dsnt as dsnt
+import kornia.testing as utils # test utils
+
class TestMaxBlurPool2d:
def test_shape(self):
@@ -242,3 +243,77 @@ class TestSpatialSoftArgmax2d:
input = utils.tensor_to_gradcheck_var(input) # to var
assert gradcheck(kornia.contrib.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):
+ expected = self.GAUSSIAN
+ actual = dsnt.render_gaussian_2d(torch.tensor([2.0, 2.0]),
+ torch.tensor([1.0, 1.0]),
+ (5, 5),
+ normalized_coordinates=False)
+ assert_allclose(actual, expected, rtol=0, atol=1e-5)
+
+ def test_render_gaussian_2d_normalized_coordinates(self):
+ expected = self.GAUSSIAN
+ actual = dsnt.render_gaussian_2d(torch.tensor([0.0, 0.0]),
+ torch.tensor([0.25, 0.25]),
+ (5, 5),
+ normalized_coordinates=True)
+ 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, input):
+ actual = dsnt.spatial_softmax_2d(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))
+
+ @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, input, expected_norm, expected_px):
+ actual_norm = dsnt.spatial_softargmax_2d(input, True)
+ assert_allclose(actual_norm, expected_norm)
+ actual_px = dsnt.spatial_softargmax_2d(input, False)
+ assert_allclose(actual_px, expected_px)
+
+ def test_jit(self):
+ def op(input: torch.Tensor, target: torch.Tensor,
+ temperature: torch.Tensor, normalized_coordinates: bool,
+ std: torch.Tensor) -> torch.Tensor:
+ hm = dsnt.spatial_softmax_2d(input, temperature)
+ pred = dsnt.spatial_softargmax_2d(hm, normalized_coordinates)
+ size = (input.shape[-2], input.shape[-1])
+ target_hm = 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), torch.rand(2, 3, 2) * 7,
+ torch.tensor(1.0), False, torch.tensor([1.0, 1.0])]
+ actual = op_script(*args)
+ expected = op(*args)
+ assert_allclose(actual, expected)
diff --git a/test/test_losses.py b/test/test_losses.py
index d70df551c..959c17b34 100644
--- a/test/test_losses.py
+++ b/test/test_losses.py
@@ -4,6 +4,7 @@ import kornia
import kornia.testing as utils # test utils
from test.common import device_type
+import math
import torch
from torch.autograd import gradcheck
from torch.testing import assert_allclose
@@ -224,3 +225,25 @@ def test_ssim(batch_shape, device_type, window_size, reduction_type):
img1 = utils.tensor_to_gradcheck_var(img1) # to var
img2 = utils.tensor_to_gradcheck_var(img2, requires_grad=False) # to var
assert gradcheck(ssim, (img1, img2), raise_exception=True)
+
+
+class TestDivergenceLoss:
+ @pytest.mark.parametrize('input,target,expected', [
+ (torch.full((1, 1, 2, 4), 0.125), torch.full((1, 1, 2, 4), 0.125), 0.0),
+ (torch.full((1, 7, 2, 4), 0.125), torch.full((1, 7, 2, 4), 0.125), 0.0),
+ (torch.full((1, 7, 2, 4), 0.125), torch.zeros((1, 7, 2, 4)), 0.346574),
+ (torch.zeros((1, 7, 2, 4)), torch.full((1, 7, 2, 4), 0.125), 0.346574),
+ ])
+ def test_js_div_loss_2d(self, input, target, expected):
+ actual = kornia.losses.js_div_loss_2d(input, target).item()
+ assert actual == pytest.approx(expected, abs=1e-6)
+
+ @pytest.mark.parametrize('input,target,expected', [
+ (torch.full((1, 1, 2, 4), 0.125), torch.full((1, 1, 2, 4), 0.125), 0.0),
+ (torch.full((1, 7, 2, 4), 0.125), torch.full((1, 7, 2, 4), 0.125), 0.0),
+ (torch.full((1, 7, 2, 4), 0.125), torch.zeros((1, 7, 2, 4)), 0.0),
+ (torch.zeros((1, 7, 2, 4)), torch.full((1, 7, 2, 4), 0.125), math.inf),
+ ])
+ def test_kl_div_loss_2d(self, input, target, expected):
+ actual = kornia.losses.kl_div_loss_2d(input, target).item()
+ assert actual == pytest.approx(expected, abs=1e-6)