π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
perf(morphology): update shift reduction in place (#4759)
NiteeshGowda72d03a751d636e
diff --git a/changelog.d/4759.fixed.md b/changelog.d/4759.fixed.mdnew file mode 100644index 000000000..1a016e07b--- /dev/null+++ b/changelog.d/4759.fixed.md@@ -0,0 +1 @@+dilation, erosion and the operations built on them (opening, closing, gradient, top_hat, bottom_hat) update the shift engine's running maximum/minimum in place when the call records no gradient, instead of allocating a new output-sized tensor at every kernel position. This is about 1.1-1.5x faster on CPU for a batch of eight 256 x 256 images, about neutral for a single small image, and unchanged on MPS; outputs are identical. Calls that record a backward graph, carry a forward-mode AD tangent on the image or the structuring element, run under torch.func transforms, or are traced or scripted keep the out-of-place reduction.diff --git a/kornia/morphology/morphology.py b/kornia/morphology/morphology.pyindex 12a35e0d6..05d0104b3 100644--- a/kornia/morphology/morphology.py+++ b/kornia/morphology/morphology.py@@ -48,7 +48,21 @@ def _neight2channels_like_kernel(kernel: torch.Tensor) -> torch.Tensor:return kernel.view(h * w, 1, h, w)-def _shift_reduce(padded: torch.Tensor, offsets: torch.Tensor, height: int, width: int, dilate: bool) -> torch.Tensor:+def _can_reduce_in_place(padded: torch.Tensor, offsets: torch.Tensor) -> bool:+ if torch.jit.is_tracing() or torch._C._are_functorch_transforms_active():+ return False+ return all(torch.autograd.forward_ad.unpack_dual(t).tangent is None for t in (padded, offsets))+++def _shift_reduce(+ padded: torch.Tensor,+ offsets: torch.Tensor,+ height: int,+ width: int,+ dilate: bool,+ inplace: bool,+) -> torch.Tensor:"""Running max (``dilate``) or min over the ``k_h * k_w`` shifted views of ``padded`` plus their offsets.The ``shift`` engine: output pixel ``(y, x)`` reduces ``padded[y + i, x + j] + offsets[i, j]`` over the@@ -74,7 +88,10 @@ def _shift_reduce(padded: torch.Tensor, offsets: torch.Tensor, height: int, widtif i == 0 and j == 0:continueshifted = padded[..., i : i + height, j : j + width] + offsets[i : i + 1, j : j + 1]- output = torch.maximum(output, shifted) if dilate else torch.minimum(output, shifted)+ if inplace:+ torch.maximum(output, shifted, out=output) if dilate else torch.minimum(output, shifted, out=output)+ else:+ output = torch.maximum(output, shifted) if dilate else torch.minimum(output, shifted)return output@@ -258,7 +275,8 @@ def dilation(# The max-plus terms compute in the promoted dtype, which the dtype rule of ``auto`` has to see: a# float16 image with a float32 kernel computes, and differentiates, in float32.compute_dtype = torch.promote_types(tensor.dtype, neighborhood.dtype)- engine = _resolve_engine(engine, tensor, _records_grad(tensor, structuring_element), compute_dtype)+ recording_grad = _records_grad(tensor, structuring_element)+ engine = _resolve_engine(engine, tensor, recording_grad, compute_dtype)if engine == "unfold":output = output.unfold(2, se_h, 1).unfold(3, se_w, 1)output, _ = torch.max(output + neighborhood.flip((0, 1)), 4)@@ -275,7 +293,18 @@ def dilation().max(dim=1)output = output.view(B, C, H, W)elif engine == "shift":- output = _shift_reduce(output, neighborhood.flip((0, 1)), tensor.shape[-2], tensor.shape[-1], True)+ offsets = neighborhood.flip((0, 1))+ inplace = False+ if not torch.jit.is_scripting():+ inplace = not recording_grad and _can_reduce_in_place(output, offsets)+ output = _shift_reduce(+ output,+ offsets,+ tensor.shape[-2],+ tensor.shape[-1],+ True,+ inplace,+ )else:raise NotImplementedError(f"engine {engine} is unknown, use 'auto', 'convolution', 'shift' or 'unfold'")return output.view_as(tensor)@@ -389,7 +418,8 @@ def erosion(# The max-plus terms compute in the promoted dtype, which the dtype rule of ``auto`` has to see: a# float16 image with a float32 kernel computes, and differentiates, in float32.compute_dtype = torch.promote_types(tensor.dtype, neighborhood.dtype)- engine = _resolve_engine(engine, tensor, _records_grad(tensor, structuring_element), compute_dtype)+ recording_grad = _records_grad(tensor, structuring_element)+ engine = _resolve_engine(engine, tensor, recording_grad, compute_dtype)if engine == "unfold":output = output.unfold(2, se_h, 1).unfold(3, se_w, 1)output, _ = torch.min(output - neighborhood, 4)@@ -406,7 +436,18 @@ def erosion().min(dim=1)output = output.view(B, C, H, W)elif engine == "shift":- output = _shift_reduce(output, -neighborhood, tensor.shape[-2], tensor.shape[-1], False)+ offsets = -neighborhood+ inplace = False+ if not torch.jit.is_scripting():+ inplace = not recording_grad and _can_reduce_in_place(output, offsets)+ output = _shift_reduce(+ output,+ offsets,+ tensor.shape[-2],+ tensor.shape[-1],+ False,+ inplace,+ )else:raise NotImplementedError(f"engine {engine} is unknown, use 'auto', 'convolution', 'shift' or 'unfold'")diff --git a/tests/morphology/test_dilation.py b/tests/morphology/test_dilation.pyindex f1ee45cb7..e6dbd6d05 100644--- a/tests/morphology/test_dilation.py+++ b/tests/morphology/test_dilation.py@@ -437,6 +437,107 @@ class TestDilate(BaseTester):self.assert_close(dilation(tensor, kernel), op_optimized(tensor, kernel))+ def test_shift_engine_forward_only_matches_autograd_safe(self, device, dtype):+ tensor = torch.rand(2, 3, 9, 9, device=device, dtype=dtype)+ kernel = torch.randn(3, 3, device=device, dtype=dtype)++ forward = dilation(tensor, kernel, engine="shift")+ safe = dilation(tensor.clone().requires_grad_(True), kernel, engine="shift").detach()++ assert torch.equal(forward, safe)++ @pytest.mark.parametrize("operand", ["image", "structuring_element"])+ def test_shift_engine_forward_ad(self, device, dtype, operand):+ # ``out=`` ops have no forward-mode AD formula, so a tangent on either operand must keep the+ # out-of-place reduction. ``make_dual`` is used because ``torch.func.jvp`` is a functorch transform,+ # which the in-place gate declines before it looks at the tangents.+ if dtype not in (torch.float32, torch.float64):+ pytest.skip("half-precision sums tie, and tied tangents differ between engines")++ tensor = torch.rand(1, 1, 9, 11, device=device, dtype=dtype)+ kernel = torch.ones(3, 3, device=device, dtype=dtype)+ structuring_element = torch.randn(3, 3, device=device, dtype=dtype)+ primal = tensor if operand == "image" else structuring_element+ tangent = torch.randn_like(primal)++ def run(engine):+ with torch.autograd.forward_ad.dual_level():+ dual = torch.autograd.forward_ad.make_dual(primal, tangent)+ if operand == "image":+ output = dilation(dual, kernel, structuring_element, engine=engine)+ else:+ output = dilation(tensor, kernel, dual, engine=engine)+ return torch.autograd.forward_ad.unpack_dual(output)++ actual, expected = run("shift"), run("unfold")++ self.assert_close(actual.primal, expected.primal)+ self.assert_close(actual.tangent, expected.tangent)++ def test_shift_engine_vmap(self, device, dtype):+ tensor = torch.rand(2, 3, 1, 9, 11, device=device, dtype=dtype)+ kernel = torch.ones(3, 3, device=device, dtype=dtype)++ actual = torch.func.vmap(lambda x: dilation(x, kernel, engine="shift"))(tensor)+ expected = torch.func.vmap(lambda x: dilation(x, kernel, engine="unfold"))(tensor)++ assert torch.equal(actual, expected)++ def test_shift_engine_jit_save(self, device, dtype):+ import io++ scripted = torch.jit.script(dilation)+ buffer = io.BytesIO()+ torch.jit.save(scripted, buffer)+ assert buffer.getbuffer().nbytes > 0++ def test_shift_engine_onnx_trace(self, device, dtype):+ import io++ if device.type != "cpu":+ pytest.skip("the TorchScript-based ONNX export is checked on CPU")+ pytest.importorskip("onnx")++ class Morphology(torch.nn.Module):+ def forward(self, x):+ kernel = torch.ones(3, 3, device=x.device, dtype=x.dtype)+ return dilation(x, kernel, engine="shift")++ tensor = torch.rand(1, 1, 9, 11, device=device, dtype=dtype)+ buffer = io.BytesIO()++ torch.onnx.export(+ Morphology(),+ (tensor,),+ buffer,+ dynamo=False,+ )++ assert buffer.getbuffer().nbytes > 0++ def test_shift_engine_reduces_in_place_only_without_grad(self, device, dtype, monkeypatch):+ calls = []+ original = morphology_module._shift_reduce++ def wrapped(*args, **kwargs):+ calls.append(args[-1])+ return original(*args, **kwargs)++ monkeypatch.setattr(morphology_module, "_shift_reduce", wrapped)++ tensor = torch.rand(1, 1, 9, 11, device=device, dtype=dtype)+ kernel = torch.ones(3, 3, device=device, dtype=dtype)++ dilation(tensor, kernel, engine="shift")++ with torch.enable_grad():+ dilation(tensor.requires_grad_(True), kernel, engine="shift")++ with torch.no_grad():+ dilation(tensor, kernel, engine="shift")++ assert calls == [True, False, True]+def test_shift_engine_jit(self, device, dtype):op_script = torch.jit.script(dilation)tensor = torch.rand(1, 2, 7, 7, device=device, dtype=dtype)diff --git a/tests/morphology/test_erosion.py b/tests/morphology/test_erosion.pyindex eb9102fbe..5348e9d20 100644--- a/tests/morphology/test_erosion.py+++ b/tests/morphology/test_erosion.py@@ -423,6 +423,107 @@ class TestErode(BaseTester):self.assert_close(erosion(tensor, kernel), op_optimized(tensor, kernel))+ def test_shift_engine_forward_only_matches_autograd_safe(self, device, dtype):+ tensor = torch.rand(2, 3, 9, 9, device=device, dtype=dtype)+ kernel = torch.randn(3, 3, device=device, dtype=dtype)++ forward = erosion(tensor, kernel, engine="shift")+ safe = erosion(tensor.clone().requires_grad_(True), kernel, engine="shift").detach()++ assert torch.equal(forward, safe)++ @pytest.mark.parametrize("operand", ["image", "structuring_element"])+ def test_shift_engine_forward_ad(self, device, dtype, operand):+ # ``out=`` ops have no forward-mode AD formula, so a tangent on either operand must keep the+ # out-of-place reduction. ``make_dual`` is used because ``torch.func.jvp`` is a functorch transform,+ # which the in-place gate declines before it looks at the tangents.+ if dtype not in (torch.float32, torch.float64):+ pytest.skip("half-precision sums tie, and tied tangents differ between engines")++ tensor = torch.rand(1, 1, 9, 11, device=device, dtype=dtype)+ kernel = torch.ones(3, 3, device=device, dtype=dtype)+ structuring_element = torch.randn(3, 3, device=device, dtype=dtype)+ primal = tensor if operand == "image" else structuring_element+ tangent = torch.randn_like(primal)++ def run(engine):+ with torch.autograd.forward_ad.dual_level():+ dual = torch.autograd.forward_ad.make_dual(primal, tangent)+ if operand == "image":+ output = erosion(dual, kernel, structuring_element, engine=engine)+ else:+ output = erosion(tensor, kernel, dual, engine=engine)+ return torch.autograd.forward_ad.unpack_dual(output)++ actual, expected = run("shift"), run("unfold")++ self.assert_close(actual.primal, expected.primal)+ self.assert_close(actual.tangent, expected.tangent)++ def test_shift_engine_vmap(self, device, dtype):+ tensor = torch.rand(2, 3, 1, 9, 11, device=device, dtype=dtype)+ kernel = torch.ones(3, 3, device=device, dtype=dtype)++ actual = torch.func.vmap(lambda x: erosion(x, kernel, engine="shift"))(tensor)+ expected = torch.func.vmap(lambda x: erosion(x, kernel, engine="unfold"))(tensor)++ assert torch.equal(actual, expected)++ def test_shift_engine_jit_save(self, device, dtype):+ import io++ scripted = torch.jit.script(erosion)+ buffer = io.BytesIO()+ torch.jit.save(scripted, buffer)+ assert buffer.getbuffer().nbytes > 0++ def test_shift_engine_onnx_trace(self, device, dtype):+ import io++ if device.type != "cpu":+ pytest.skip("the TorchScript-based ONNX export is checked on CPU")+ pytest.importorskip("onnx")++ class Morphology(torch.nn.Module):+ def forward(self, x):+ kernel = torch.ones(3, 3, device=x.device, dtype=x.dtype)+ return erosion(x, kernel, engine="shift")++ tensor = torch.rand(1, 1, 9, 11, device=device, dtype=dtype)+ buffer = io.BytesIO()++ torch.onnx.export(+ Morphology(),+ (tensor,),+ buffer,+ dynamo=False,+ )++ assert buffer.getbuffer().nbytes > 0++ def test_shift_engine_reduces_in_place_only_without_grad(self, device, dtype, monkeypatch):+ calls = []+ original = morphology_module._shift_reduce++ def wrapped(*args, **kwargs):+ calls.append(args[-1])+ return original(*args, **kwargs)++ monkeypatch.setattr(morphology_module, "_shift_reduce", wrapped)++ tensor = torch.rand(1, 1, 9, 11, device=device, dtype=dtype)+ kernel = torch.ones(3, 3, device=device, dtype=dtype)++ erosion(tensor, kernel, engine="shift")++ with torch.enable_grad():+ erosion(tensor.requires_grad_(True), kernel, engine="shift")++ with torch.no_grad():+ erosion(tensor, kernel, engine="shift")++ assert calls == [True, False, True]+def test_shift_engine_jit(self, device, dtype):op_script = torch.jit.script(erosion)tensor = torch.rand(1, 2, 7, 7, device=device, dtype=dtype)