Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

bugfix(geometry): support non-contiguous DSNT inputs (#3972)

Ishittac46b7c1cd8f9
diff --git a/kornia/geometry/subpix/dsnt.py b/kornia/geometry/subpix/dsnt.py
index 6909def36..cb90946f8 100644
--- a/kornia/geometry/subpix/dsnt.py
+++ b/kornia/geometry/subpix/dsnt.py
@@ -66,7 +66,7 @@ def spatial_softmax2d(input: torch.Tensor, temperature: Optional[torch.Tensor] =
if temperature is None:
temperature = torch.tensor(1.0)
temperature = temperature.to(device=input.device, dtype=input.dtype)
- x = input.view(batch_size, channels, -1)
+ x = input.reshape(batch_size, channels, -1)
x_soft = F.softmax(x * temperature, dim=-1)
@@ -107,7 +107,7 @@ def spatial_expectation2d(input: torch.Tensor, normalized_coordinates: bool = Tr
pos_x = grid[..., 0].reshape(-1)
pos_y = grid[..., 1].reshape(-1)
- input_flat = input.view(batch_size, channels, -1)
+ input_flat = input.reshape(batch_size, channels, -1)
# Compute the expectation of the coordinates.
expected_y = torch.sum(pos_y * input_flat, -1, keepdim=True)
diff --git a/tests/geometry/subpix/test_dsnt.py b/tests/geometry/subpix/test_dsnt.py
index feb817769..64eda9d56 100644
--- a/tests/geometry/subpix/test_dsnt.py
+++ b/tests/geometry/subpix/test_dsnt.py
@@ -80,6 +80,15 @@ class TestSpatialSoftmax2d(BaseTester):
sums = actual.sum(-1).sum(-1)
self.assert_close(sums, torch.ones_like(sums))
+ def test_non_contiguous(self, device, dtype):
+ input = torch.randn(2, 3, 4, 6, device=device, dtype=dtype).transpose(-2, -1)
+ assert not input.is_contiguous()
+
+ expected = kornia.geometry.subpix.spatial_softmax2d(input.contiguous())
+ actual = kornia.geometry.subpix.spatial_softmax2d(input)
+
+ self.assert_close(actual, expected)
+
def test_dynamo(self, input, torch_optimizer):
op = kornia.geometry.subpix.spatial_softmax2d
op_optimized = torch_optimizer(op)
@@ -108,6 +117,17 @@ class TestSpatialExpectation2d(BaseTester):
actual_px = kornia.geometry.subpix.spatial_expectation2d(input, False)
self.assert_close(actual_px, expected_px)
+ def test_non_contiguous(self, device, dtype):
+ input = torch.rand(2, 3, 4, 6, device=device, dtype=dtype)
+ input = input / input.sum(dim=(-2, -1), keepdim=True)
+ input = input.transpose(-2, -1)
+ assert not input.is_contiguous()
+
+ expected = kornia.geometry.subpix.spatial_expectation2d(input.contiguous())
+ actual = kornia.geometry.subpix.spatial_expectation2d(input)
+
+ self.assert_close(actual, expected)
+
@pytest.mark.skip("After the op be optimized the results are not the same")
def test_dynamo(self, dtype, device, torch_optimizer):
data = torch.tensor([[[[0.0, 0.0, 1.0], [0.0, 0.0, 0.0]]]], device=device, dtype=dtype)