π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
Optimize render_gaussian2d (~18x speedup) and fix PDF variance bug (#3366)
Sidd2b6d466bcb5b
diff --git a/kornia/geometry/subpix/dsnt.py b/kornia/geometry/subpix/dsnt.pyindex 3762bafd5..498e90cc4 100644--- a/kornia/geometry/subpix/dsnt.py+++ b/kornia/geometry/subpix/dsnt.py@@ -118,10 +118,6 @@ def spatial_expectation2d(input: Tensor, normalized_coordinates: bool = True) ->return output.view(batch_size, channels, 2) # BxNx2-def _safe_zero_division(numerator: Tensor, denominator: Tensor, eps: float = 1e-32) -> Tensor:- return numerator / torch.clamp(denominator, min=eps)--def render_gaussian2d(mean: Tensor, std: Tensor, size: tuple[int, int], normalized_coordinates: bool = True) -> Tensor:r"""Render the PDF of a 2D Gaussian distribution.@@ -141,32 +137,40 @@ def render_gaussian2d(mean: Tensor, std: Tensor, size: tuple[int, int], normalizraise TypeError("Expected inputs to have the same dtype and device")height, width = size-- # Create coordinates grid.- grid = create_meshgrid(height, width, normalized_coordinates, mean.device)- grid = grid.to(mean.dtype)- pos_x = grid[..., 0].view(height, width)- pos_y = grid[..., 1].view(height, width)+ dtype = mean.dtype+ device = mean.device++ # Create coordinates vectors.+ if normalized_coordinates:+ xs = torch.linspace(-1, 1, width, device=device, dtype=dtype)+ ys = torch.linspace(-1, 1, height, device=device, dtype=dtype)+ else:+ xs = torch.linspace(0, width - 1, width, device=device, dtype=dtype)+ ys = torch.linspace(0, height - 1, height, device=device, dtype=dtype)++ mu_x = mean[..., 0].unsqueeze(-1)+ mu_y = mean[..., 1].unsqueeze(-1)+ sigma_x = std[..., 0].unsqueeze(-1)+ sigma_y = std[..., 1].unsqueeze(-1)# 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+ dist_x_sq = (xs - mu_x) ** 2+ dist_y_sq = (ys - mu_y) ** 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])+ k_x = -0.5 * torch.reciprocal(sigma_x**2)+ k_y = -0.5 * torch.reciprocal(sigma_y**2)# 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+ gauss_x = torch.exp(dist_x_sq * k_x)+ gauss_y = torch.exp(dist_y_sq * k_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)+ gauss_x = gauss_x / (gauss_x.sum(dim=-1, keepdim=True) + 1e-8)+ gauss_y = gauss_y / (gauss_y.sum(dim=-1, keepdim=True) + 1e-8)- return gauss+ return gauss_y.unsqueeze(-1) * gauss_x.unsqueeze(-2)diff --git a/tests/geometry/subpix/test_dsnt.py b/tests/geometry/subpix/test_dsnt.pyindex 6d318cce8..8b8364bc5 100644--- a/tests/geometry/subpix/test_dsnt.py+++ b/tests/geometry/subpix/test_dsnt.py@@ -26,29 +26,35 @@ from testing.base import assert_closeclass 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,- )+ # For a standard gaussian on 5 points [-1, -0.5, 0, 0.5, 1] with std=0.25+ # The equation is exp( -x^2 / (2 * std^2) ) -> exp( -x^2 * 8 )+ # x=0 -> exp(0) = 1.0+ # x=0.5 -> exp(-2) β 0.135335+ # x=1.0 -> exp(-8) β 0.000335- 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.subpix.render_gaussian2d(mean, std, (5, 5), False)- assert_close(actual, gaussian, rtol=0, atol=1e-4)+ vec = torch.tensor([0.00033546, 0.13533528, 1.00000000, 0.13533528, 0.00033546], device=device, dtype=dtype)++ # Create 2D from 1D (Outer Product)+ grid = vec.unsqueeze(1) * vec.unsqueeze(0)++ # Normalize sum to 1+ return grid / grid.sum()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.subpix.render_gaussian2d(mean, std, (5, 5), True)- assert_close(actual, gaussian, rtol=0, atol=1e-4)++ actual = kornia.geometry.subpix.render_gaussian2d(mean.view(1, 2), std.view(1, 2), (5, 5), True)++ assert_close(actual[0], gaussian, rtol=1e-5, atol=1e-5)++ def test_pixel_coordinates(self, gaussian, device, dtype):+ mean = torch.tensor([2.0, 2.0], dtype=dtype, device=device)+ std = torch.tensor([0.5, 0.5], dtype=dtype, device=device)++ actual = kornia.geometry.subpix.render_gaussian2d(mean.view(1, 2), std.view(1, 2), (5, 5), False)++ assert_close(actual[0], gaussian, rtol=1e-5, atol=1e-5)def test_dynamo(self, device, dtype, torch_optimizer):mean = torch.tensor([0.0, 0.0], dtype=dtype, device=device)@@ -57,7 +63,10 @@ class TestRenderGaussian2d:op = kornia.geometry.subpix.render_gaussian2dop_optimized = torch_optimizer(op)- assert_close(op(mean, std, (5, 5), True), op_optimized(mean, std, (5, 5), True))+ res_orig = op(mean.view(1, 2), std.view(1, 2), (5, 5), True)+ res_opt = op_optimized(mean.view(1, 2), std.view(1, 2), (5, 5), True)++ assert_close(res_orig, res_opt)class TestSpatialSoftmax2d: