Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

fix ScaleSpaceDetector dynamo config scope (#4134)

X-mo78d2fe3bff071
diff --git a/.github/workflows/pr_test_cpu.yml b/.github/workflows/pr_test_cpu.yml
index d08daaa44..ffaa97605 100644
--- a/.github/workflows/pr_test_cpu.yml
+++ b/.github/workflows/pr_test_cpu.yml
@@ -166,7 +166,7 @@ jobs:
pytorch-version: '["2.14.0"]'
pytorch-dtype: float32
optimizer: inductor
- pytest-extra: 'tests/augmentation tests/enhance tests/filters tests/color tests/geometry tests/losses tests/morphology -k "dynamo or compile"'
+ pytest-extra: 'tests/augmentation tests/enhance tests/feature tests/filters tests/color tests/geometry tests/losses tests/morphology -k "dynamo or compile"'
cache-path: weights/
cache-key: model-weights-${{ needs.pre-tests.outputs.hash }}
cache-restore-keys: |
diff --git a/CHANGELOG.md b/CHANGELOG.md
index e1b7446f0..5947e57e8 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -238,6 +238,9 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### Bug fixes
+* Constructing `ScaleSpaceDetector` with `compile_modules` no longer permanently mutates the process-global
+ `torch._dynamo.config.capture_dynamic_output_shape_ops` setting. (#4134)
+
* `Boxes3D.to_tensor` and `Boxes3D.get_boxes_shape` are differentiable again (#1396). Both reduce a box's 8
vertices to its min/max corner with `amin`/`amax`, which is a genuine kink -- not differentiable in the
classical sense -- wherever multiple vertices exactly tie for an axis extremum. Every face of an
diff --git a/kornia/feature/scale_space_detector.py b/kornia/feature/scale_space_detector.py
index 4a0e456bd..692b714a7 100644
--- a/kornia/feature/scale_space_detector.py
+++ b/kornia/feature/scale_space_detector.py
@@ -16,7 +16,8 @@
#
import math
-from typing import List, Optional, Tuple, Union
+from contextlib import nullcontext
+from typing import ContextManager, List, Optional, Tuple, Union
import torch
import torch.nn.functional as F
@@ -249,15 +250,10 @@ class ScaleSpaceDetector(nn.Module):
if unknown:
raise ValueError(f"Unknown module names in compile_modules: {unknown}. Valid: {_all_names}")
- if _compile_set:
- # Allow torch.compile to keep data-dependent shape ops (torch.where / nonzero)
- # inside the compiled graph as unbacked symbols, avoiding graph breaks and the
- # 0/1-specialization recompilations that would otherwise fire whenever an octave
- # first encounters zero NMS maxima (blurry/extreme-viewpoint images).
- torch._dynamo.config.capture_dynamic_output_shape_ops = True
+ self._compile_set: frozenset[str] = frozenset(_compile_set)
def _maybe_compile(mod: nn.Module, name: str) -> nn.Module:
- return torch.compile(mod, dynamic=True) if name in _compile_set else mod
+ return torch.compile(mod, dynamic=True) if name in self._compile_set else mod
if scale_pyr_module is None:
extra_levels = 3 if scale_space_response else 2
@@ -284,6 +280,15 @@ class ScaleSpaceDetector(nn.Module):
# like Difference-of-Gaussians
self.scale_space_response = scale_space_response
+ def _dynamo_config_patch(self, modules: Tuple[str, ...]) -> ContextManager[None]:
+ if self._compile_set.intersection(modules):
+ # Allow torch.compile to keep data-dependent shape ops (torch.where / nonzero)
+ # inside the compiled graph as unbacked symbols, avoiding graph breaks and the
+ # 0/1-specialization recompilations that would otherwise fire whenever an octave
+ # first encounters zero NMS maxima (blurry/extreme-viewpoint images).
+ return torch._dynamo.config.patch(capture_dynamic_output_shape_ops=True)
+ return nullcontext()
+
def __repr__(self) -> str:
return (
f"{self.__class__.__name__}("
@@ -320,9 +325,11 @@ class ScaleSpaceDetector(nn.Module):
# Run response function
if self.scale_space_response:
- oct_resp = self.resp(octave, sigmas_oct.view(-1)) # (B, 1, Ldog, H, W)
+ with self._dynamo_config_patch(("resp",)):
+ oct_resp = self.resp(octave, sigmas_oct.view(-1)) # (B, 1, Ldog, H, W)
else:
- level_resp = self.resp(octave.permute(0, 2, 1, 3, 4).reshape(B * L, CH, H, W), sigmas_oct.view(-1))
+ with self._dynamo_config_patch(("resp",)):
+ level_resp = self.resp(octave.permute(0, 2, 1, 3, 4).reshape(B * L, CH, H, W), sigmas_oct.view(-1))
KORNIA_CHECK(
level_resp.dim() == 4
and level_resp.shape[0] == B * L
@@ -371,17 +378,18 @@ class ScaleSpaceDetector(nn.Module):
if mask.is_floating_point():
oct_mask = resampled
- if self.minima_are_also_good:
- if is_iterative_subpix:
+ with self._dynamo_config_patch(("subpix",)):
+ if self.minima_are_also_good:
+ if is_iterative_subpix:
+ coord_max, response_max = self.subpix(oct_resp, precomputed_nms_mask=max_nms_mask)
+ coord_min, response_min = self.subpix(-oct_resp, precomputed_nms_mask=min_nms_mask)
+ else:
+ coord_max, response_max = self.subpix(oct_resp)
+ coord_min, response_min = self.subpix(-oct_resp)
+ elif is_iterative_subpix:
coord_max, response_max = self.subpix(oct_resp, precomputed_nms_mask=max_nms_mask)
- coord_min, response_min = self.subpix(-oct_resp, precomputed_nms_mask=min_nms_mask)
else:
coord_max, response_max = self.subpix(oct_resp)
- coord_min, response_min = self.subpix(-oct_resp)
- elif is_iterative_subpix:
- coord_max, response_max = self.subpix(oct_resp, precomputed_nms_mask=max_nms_mask)
- else:
- coord_max, response_max = self.subpix(oct_resp)
# Zero responses at scale border levels so they never reach top-K.
# (nms3d_minmax already sets the masks False at these positions.)
@@ -509,7 +517,8 @@ class ScaleSpaceDetector(nn.Module):
_check_mask(mask, img)
dev = img.device
dtype: torch.dtype = img.dtype
- sp, sigmas, _ = self.scale_pyr(img)
+ with self._dynamo_config_patch(("scale_pyr",)):
+ sp, sigmas, _ = self.scale_pyr(img)
# ── Hoist loop invariants ────────────────────────────────────────────
if isinstance(self.scale_pyr.n_levels, torch.Tensor):
@@ -609,8 +618,10 @@ class ScaleSpaceDetector(nn.Module):
# zero-LAF padding contract rather than bypassing an override through `_detect`.
responses, lafs = self.detect(img, self.num_features, mask)
filled = lafs.ne(0).any(dim=-1).any(dim=-1)
- lafs = self.aff(lafs, img)
- lafs = self.ori(lafs, img)
+ with self._dynamo_config_patch(("aff",)):
+ lafs = self.aff(lafs, img)
+ with self._dynamo_config_patch(("ori",)):
+ lafs = self.ori(lafs, img)
return _zero_unfilled(lafs, filled), responses
diff --git a/tests/feature/test_scale_space_detector.py b/tests/feature/test_scale_space_detector.py
index 01a2a1144..3e4f481d1 100644
--- a/tests/feature/test_scale_space_detector.py
+++ b/tests/feature/test_scale_space_detector.py
@@ -28,8 +28,16 @@ from kornia.feature.scale_space_detector import (
get_default_detector_config,
)
from kornia.geometry.subpix import ConvQuadInterp3d
-
-from testing.base import BaseTester, supports_conv2d, supports_replicate_padding, supports_topk
+from kornia.geometry.transform import ScalePyramid
+
+from testing.base import (
+ DYNAMO_UNAVAILABLE_REASON,
+ BaseTester,
+ dynamo_is_available,
+ supports_conv2d,
+ supports_replicate_padding,
+ supports_topk,
+)
def _require_affine_orientation_kernels(device: torch.device, dtype: torch.dtype) -> None:
@@ -489,6 +497,64 @@ class TestScaleSpaceDetector(BaseTester):
# ... and the y-extent the same block hardcodes as `half_s` (max|cos| = 1).
assert abs(((pts[..., 1].max() - cy) / half_s).item() - 1.0) < 1e-6
+ @pytest.mark.skipif(not dynamo_is_available(), reason=DYNAMO_UNAVAILABLE_REASON)
+ def test_scale_space_detector_init_preserves_global_config_4095(self):
+ torch._dynamo.reset()
+ try:
+ with torch._dynamo.config.patch(capture_dynamic_output_shape_ops=False):
+ assert not torch._dynamo.config.capture_dynamic_output_shape_ops
+ _ = ScaleSpaceDetector(num_features=5, compile_modules=["resp"])
+ assert not torch._dynamo.config.capture_dynamic_output_shape_ops
+ finally:
+ torch._dynamo.reset()
+
+ @pytest.mark.skipif(not dynamo_is_available(), reason=DYNAMO_UNAVAILABLE_REASON)
+ def test_compile_modules_forward_restores_dynamo_config_4095(self):
+ torch._dynamo.reset()
+ try:
+ with torch._dynamo.config.patch(capture_dynamic_output_shape_ops=False):
+ det = ScaleSpaceDetector(
+ num_features=2,
+ scale_pyr_module=ScalePyramid(1, 1.6, 15, extra_levels=2),
+ compile_modules=["subpix"],
+ )
+ img = torch.zeros(1, 1, 16, 16)
+ lafs, resps = det(img)
+ assert lafs.shape == torch.Size([1, 2, 2, 3])
+ assert resps.shape == torch.Size([1, 2])
+ assert not torch._dynamo.config.capture_dynamic_output_shape_ops
+ finally:
+ torch._dynamo.reset()
+
+ @pytest.mark.skipif(not dynamo_is_available(), reason=DYNAMO_UNAVAILABLE_REASON)
+ def test_compile_modules_match_eager_4095(self):
+ torch._dynamo.reset()
+ try:
+ inp = torch.zeros(1, 1, 33, 33)
+ inp[:, :, 13:-13, 13:-13] = 1.0
+ with torch._dynamo.config.patch(capture_dynamic_output_shape_ops=False):
+ eager = ScaleSpaceDetector(
+ 1,
+ resp_module=kornia.feature.BlobHessian(),
+ subpix_module=ConvQuadInterp3d(10),
+ mr_size=3.0,
+ )
+ compiled = ScaleSpaceDetector(
+ 1,
+ resp_module=kornia.feature.BlobHessian(),
+ subpix_module=ConvQuadInterp3d(10),
+ mr_size=3.0,
+ compile_modules=["resp", "subpix"],
+ )
+ lafs_eager, resps_eager = eager(inp)
+ lafs_compiled, resps_compiled = compiled(inp)
+ assert not torch._dynamo.config.capture_dynamic_output_shape_ops
+ assert bool((resps_compiled != 0).any())
+ self.assert_close(lafs_compiled, lafs_eager)
+ self.assert_close(resps_compiled, resps_eager)
+ finally:
+ torch._dynamo.reset()
+
def test_gradcheck(self, device):
batch_size, channels, height, width = 1, 1, 7, 7
patches = torch.rand(batch_size, channels, height, width, device=device, dtype=torch.float64)