Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

fix(feature): set the patch convolution layout in scripted SOSNet, TFeat and HyNet as in eager (#6567)

Dmytro Mishkin5d23ba2d6d7d
diff --git a/changelog.d/6502.added.md b/changelog.d/6502.added.md
index b1195daf1..95d30783c 100644
--- a/changelog.d/6502.added.md
+++ b/changelog.d/6502.added.md
@@ -1,8 +1,9 @@
`HardNet`, `HardNet8`, `SOSNet`, `TFeat`, `HyNet`, `LAFAffNetShapeEstimator` and `OriNet` now run their convolutions in
-channels-last memory layout where that is faster: on MPS in float32 and float16, where their convolution bodies are
-1.04-1.38x faster on an Apple M1; on CUDA in float16 and bfloat16, where their forwards on 2048 patches are 1.08-1.44x
-faster on an RTX 4090; and on CPU in float32 when torch is built with oneDNN, where they are 1.2-1.5x faster on an x86
-i7-14700K (`HardNet8` gains only at the default thread count). CUDA float32 keeps the default layout, which is faster
-there. `HardNet` used to convert on every CPU float32 build, including the macOS arm64 wheels, whose NNPACK convolutions
-take only the default layout, so the conversion was a copy that changed nothing. Outputs agree up to rounding: bitwise
-on MPS, and within the dtype's rounding on x86 CPUs and on CUDA.
+channels-last memory layout where that is faster, also when scripted with TorchScript (`LAFAffNetShapeEstimator` does
+not script): on MPS in float32 and float16, where their convolution bodies are 1.04-1.38x faster on an Apple M1; on CUDA
+in float16 and bfloat16, where their forwards on 2048 patches are 1.08-1.44x faster on an RTX 4090; and on CPU in
+float32 when torch is built with oneDNN, where they are 1.2-1.5x faster on an x86 i7-14700K (`HardNet8` gains only at
+the default thread count). CUDA float32 keeps the default layout, which is faster there. `HardNet` used to convert on
+every CPU float32 build, including the macOS arm64 wheels, whose NNPACK convolutions take only the default layout, so
+the conversion was a copy that changed nothing. Outputs agree up to rounding: bitwise on MPS, and within the dtype's
+rounding on x86 CPUs and on CUDA.
diff --git a/changelog.d/6567.added.md b/changelog.d/6567.added.md
new file mode 100644
index 000000000..95d30783c
--- /dev/null
+++ b/changelog.d/6567.added.md
@@ -0,0 +1,9 @@
+`HardNet`, `HardNet8`, `SOSNet`, `TFeat`, `HyNet`, `LAFAffNetShapeEstimator` and `OriNet` now run their convolutions in
+channels-last memory layout where that is faster, also when scripted with TorchScript (`LAFAffNetShapeEstimator` does
+not script): on MPS in float32 and float16, where their convolution bodies are 1.04-1.38x faster on an Apple M1; on CUDA
+in float16 and bfloat16, where their forwards on 2048 patches are 1.08-1.44x faster on an RTX 4090; and on CPU in
+float32 when torch is built with oneDNN, where they are 1.2-1.5x faster on an x86 i7-14700K (`HardNet8` gains only at
+the default thread count). CUDA float32 keeps the default layout, which is faster there. `HardNet` used to convert on
+every CPU float32 build, including the macOS arm64 wheels, whose NNPACK convolutions take only the default layout, so
+the conversion was a copy that changed nothing. Outputs agree up to rounding: bitwise on MPS, and within the dtype's
+rounding on x86 CPUs and on CUDA.
diff --git a/kornia/feature/_layout.py b/kornia/feature/_layout.py
index 9a8a5cfb5..ffd56721e 100644
--- a/kornia/feature/_layout.py
+++ b/kornia/feature/_layout.py
@@ -15,12 +15,33 @@
# limitations under the License.
#
+from collections.abc import Iterable
+
import torch
+from torch import nn
# A defaulted argument rather than a closed-over global: TorchScript cannot read module-level Python values.
_CPU_HAS_ONEDNN: bool = torch.backends.mkldnn.is_available()
+def _mark_patch_convolutions(layers: Iterable[nn.Module]) -> None:
+ """Mark the ``nn.Conv2d`` layers among ``layers`` for a scripted layer loop that calls :func:`_patch_conv_layout`.
+
+ ``_mark_patch_convolutions(layers)`` sets ``_patch_conv_input = True`` on each ``nn.Conv2d`` in ``layers`` (not on
+ nested ones). A ``forward`` that loops over its layers sets the layout before each layer that passes
+ ``isinstance(layer, nn.Conv2d)``, else before one with ``getattr(layer, "_patch_conv_input", False)``. Eager needs
+ only the ``isinstance``. TorchScript resolves it against the one ``Conv2d`` class type it compiled first in the
+ process, and gives every ``Conv2d`` with other constants a mangled type that fails it, so a scripted loop would
+ skip the layout before some or all of its convolutions, depending on what had been scripted before it, and convolve
+ in a different layout from eager. TorchScript reads the attribute of each submodule instead. The networks call this
+ from ``__prepare_scriptable__``, which ``torch.jit.script`` runs on every submodule before compiling, so the mark
+ also reaches a convolution swapped in after construction and a model unpickled from an earlier kornia.
+ """
+ for layer in layers:
+ if isinstance(layer, nn.Conv2d):
+ layer._patch_conv_input = True
+
+
def _patch_conv_layout(x: torch.Tensor, cpu_has_onednn: bool = _CPU_HAS_ONEDNN) -> torch.Tensor:
r"""Return a patch network's convolution input in the memory format its device convolves fastest in.
diff --git a/kornia/feature/_normalization.py b/kornia/feature/_normalization.py
index 78502f5f9..ded0ab4a7 100644
--- a/kornia/feature/_normalization.py
+++ b/kornia/feature/_normalization.py
@@ -21,7 +21,7 @@ from collections.abc import Callable
import torch
from torch import nn
-from kornia.feature._layout import _patch_conv_layout
+from kornia.feature._layout import _mark_patch_convolutions, _patch_conv_layout
class _DescriptorSequential(nn.Sequential):
@@ -64,11 +64,19 @@ class _DescriptorSequential(nn.Sequential):
return super()._apply(convert, recurse=recurse)
+ def __prepare_scriptable__(self) -> "_DescriptorSequential":
+ _mark_patch_convolutions(self)
+ return self
+
def forward(self, input: torch.Tensor) -> torch.Tensor:
for module in self:
# SOSNet's leading InstanceNorm2d returns the default layout, so the layout is set per convolution; a
- # convolution's output already has it, which makes the later calls free.
- if isinstance(module, nn.Conv2d):
+ # convolution's output already has it, which makes the later calls free. A scripted loop also needs the
+ # mark (see _mark_patch_convolutions). Ruff's SIM114 would merge the two tests with ``or``, which
+ # TorchScript rejects.
+ if isinstance(module, nn.Conv2d): # noqa: SIM114
+ input = _patch_conv_layout(input)
+ elif getattr(module, "_patch_conv_input", False):
input = _patch_conv_layout(input)
if getattr(module, "_descriptor_float32_statistics", False) and input.dtype == torch.float16:
# MPS also requires the input and running statistics to have the same dtype.
diff --git a/kornia/feature/tfeat.py b/kornia/feature/tfeat.py
index f9e3703b7..f74058eb8 100644
--- a/kornia/feature/tfeat.py
+++ b/kornia/feature/tfeat.py
@@ -22,7 +22,7 @@ from torch import nn
from kornia.core.check import KORNIA_CHECK_SHAPE
from kornia.core.download import hf_url, load_state_dict_from_url
-from kornia.feature._layout import _patch_conv_layout
+from kornia.feature._layout import _mark_patch_convolutions, _patch_conv_layout
urls: Dict[str, str | list[str]] = {}
urls["liberty"] = [
@@ -96,6 +96,10 @@ class TFeat(nn.Module):
self.load_state_dict(pretrained_dict, strict=True)
self.eval()
+ def __prepare_scriptable__(self) -> "TFeat":
+ _mark_patch_convolutions(self.features)
+ return self
+
def forward(self, input: torch.Tensor) -> torch.Tensor:
"""Compute TFeat descriptors for grayscale 32x32 patches.
@@ -109,8 +113,12 @@ class TFeat(nn.Module):
x = input
for layer in self.features:
# The leading InstanceNorm2d returns the default layout, so the layout is set per convolution; a
- # convolution's output already has it, which makes the second call free.
- if isinstance(layer, nn.Conv2d):
+ # convolution's output already has it, which makes the second call free. A scripted loop also needs the
+ # mark (see _mark_patch_convolutions). Ruff's SIM114 would merge the two tests with ``or``, which
+ # TorchScript rejects.
+ if isinstance(layer, nn.Conv2d): # noqa: SIM114
+ x = _patch_conv_layout(x)
+ elif getattr(layer, "_patch_conv_input", False):
x = _patch_conv_layout(x)
x = layer(x)
x = x.flatten(1)
diff --git a/tests/feature/test_patch_network_layout.py b/tests/feature/test_patch_network_layout.py
index bced01264..146b80a33 100644
--- a/tests/feature/test_patch_network_layout.py
+++ b/tests/feature/test_patch_network_layout.py
@@ -18,6 +18,7 @@
import pytest
import torch
from torch import nn
+from torch.utils._python_dispatch import TorchDispatchMode
import kornia.feature._normalization
import kornia.feature.affine_shape
@@ -52,6 +53,54 @@ CALLERS = [
]
+# The layer loops that set the layout per convolution: eager finds the convolutions by type, a scripted loop by type or
+# by the mark ``__prepare_scriptable__`` sets.
+LOOPS = {"SOSNet": "layers", "TFeat": "features", "HyNet": "layer7"}
+
+# A model unpickled from a kornia without the convolution marks, and one with a convolution swapped in after building.
+CHANGES = ("unmarked", "swapped")
+
+
+def _change(name, net, change):
+ """Return the layer loop of ``net``, after removing its convolution marks or swapping in a new first convolution."""
+ loop = getattr(net, LOOPS[name])
+ if change == "unmarked":
+ # As in a model pickled by a kornia whose layers carried no marks.
+ for layer in loop:
+ layer.__dict__.pop("_patch_conv_input", None)
+ elif change == "swapped":
+ index = next(i for i, layer in enumerate(loop) if isinstance(layer, nn.Conv2d))
+ conv = loop[index]
+ loop[index] = nn.Conv2d(
+ conv.in_channels, conv.out_channels, conv.kernel_size, conv.stride, conv.padding, bias=conv.bias is not None
+ )
+ return loop
+
+
+def _call_sites(scripted):
+ return [
+ node
+ for module in scripted.modules()
+ for node in module.graph.findAllNodes("prim::CallFunction")
+ if node.inputsAt(0).node().s("name") == "_patch_conv_layout"
+ ]
+
+
+class _ConvolutionLayouts(TorchDispatchMode):
+ """Record the layout of each convolution output: ``c`` channels-last, ``n`` the default, ``b`` either."""
+
+ def __init__(self):
+ super().__init__()
+ self.layouts = []
+
+ def __torch_dispatch__(self, func, types, args=(), kwargs=None):
+ out = func(*args, **(kwargs or {}))
+ if func is torch.ops.aten.convolution.default:
+ channels_last = out.is_contiguous(memory_format=torch.channels_last)
+ self.layouts.append(("b" if out.is_contiguous() else "c") if channels_last else "n")
+ return out
+
+
def _run(name, net, device, dtype):
if name == "AffNet":
img = torch.rand(1, 1, 64, 64, device=device, dtype=dtype)
@@ -120,6 +169,67 @@ class TestPatchConvLayout(BaseTester):
assert (is_channels_last and not is_contiguous) == channels_last, conv
assert is_contiguous != channels_last, conv
+ @pytest.mark.device_agnostic
+ @pytest.mark.parametrize(
+ ("name", "change"),
+ [("HardNet", None), ("HardNet8", None)] + [(name, change) for name in LOOPS for change in (None, *CHANGES)],
+ )
+ def test_scripted_network_sets_the_layout_where_eager_does(self, name, change, monkeypatch):
+ # TorchScript resolves ``isinstance(layer, nn.Conv2d)`` against the one Conv2d class type it compiled first in
+ # the process, and every Conv2d with other constants gets a mangled type that fails the test. A scripted SOSNet
+ # or TFeat, which loop over their layers, therefore set the layout before none of their convolutions once
+ # another Conv2d had been scripted, and convolved in a different layout from eager. Scripting a Conv2d first
+ # sets up that state. Eager must find a loop's convolutions by type, so that one without the mark still gets the
+ # layout. Counting the calls discriminates on every CPU, also where ``_patch_conv_layout`` keeps the layout.
+ torch.jit.script(nn.Conv2d(3, 5, 7))
+ net = NETWORKS[name](pretrained=False).eval()
+ convs = [layer for layer in _change(name, net, change) if isinstance(layer, nn.Conv2d)] if name in LOOPS else []
+ calls = []
+ inputs = []
+
+ def count(x):
+ calls.append(_patch_conv_layout(x))
+ return calls[-1]
+
+ hooks = [conv.register_forward_pre_hook(lambda module, args: inputs.append(args[0])) for conv in convs]
+ try:
+ with monkeypatch.context() as patch:
+ for module in CALLERS:
+ patch.setattr(module, "_patch_conv_layout", count)
+ with torch.no_grad():
+ _run(name, net, "cpu", torch.float32)
+ finally:
+ for hook in hooks:
+ hook.remove()
+ assert len(inputs) == len(convs)
+ assert all(any(x is call for call in calls) for x in inputs)
+ assert len(_call_sites(torch.jit.script(net))) == len(calls)
+
+ @pytest.mark.parametrize("change", [None, *CHANGES])
+ @pytest.mark.parametrize("name", LOOPS)
+ def test_scripted_convolutions_run_in_the_eager_layout(self, name, change, device, dtype):
+ # The layouts the convolutions run in, eager and scripted, after another Conv2d was scripted first. Where
+ # ``_patch_conv_layout`` keeps the layout (CPU without oneDNN, float64, CUDA float32) every layout is the
+ # default, so they cannot tell a skipped call; test_scripted_network_sets_the_layout_where_eager_does can.
+ torch.jit.script(nn.Conv2d(3, 5, 7))
+ torch.manual_seed(0)
+ net = NETWORKS[name](pretrained=False).eval()
+ _change(name, net, change)
+ net = net.to(device, dtype)
+ probe = torch.empty(1, 2, 3, 3, device=device, dtype=dtype)
+ expected = "c" if _patch_conv_layout(probe) is not probe else "n"
+ x = torch.rand(3, 1, 32, 32, device=device, dtype=dtype)
+ with torch.no_grad():
+ with _ConvolutionLayouts() as eager:
+ expected_out = net(x)
+ scripted = torch.jit.script(net)
+ scripted(x)
+ with _ConvolutionLayouts() as script:
+ actual = scripted(x)
+ assert {layout for layout in eager.layouts if layout != "b"} == {expected}
+ assert script.layouts == eager.layouts
+ self.assert_close(actual, expected_out)
+
@pytest.mark.parametrize("name", NETWORKS)
def test_layout_keeps_outputs(self, name, device, dtype, monkeypatch):
torch.manual_seed(0)