Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

fix(geometry): apply ImageRegistrator tolerance within each pyramid level (#5074)

Dmytro Mishkin406e3958484a
diff --git a/changelog.d/5074.fixed.md b/changelog.d/5074.fixed.md
new file mode 100644
index 000000000..c957b77bf
--- /dev/null
+++ b/changelog.d/5074.fixed.md
@@ -0,0 +1 @@
+`ImageRegistrator.register` applies `tolerance` within each pyramid level, so every level takes at least its first optimization step. Previously the first loss of a finer level was compared with the final loss of the coarser level, and when the two differed by less than `tolerance` that level stopped before any update (#5073).
diff --git a/kornia/geometry/transform/image_registrator.py b/kornia/geometry/transform/image_registrator.py
index 3ad055595..55628ddf5 100644
--- a/kornia/geometry/transform/image_registrator.py
+++ b/kornia/geometry/transform/image_registrator.py
@@ -287,18 +287,19 @@ class ImageRegistrator(nn.Module):
# [::-1] because we have to register from coarse to fine
img_src_pyr = build_pyramid(src_img, self.pyramid_levels)[::-1]
img_dst_pyr = build_pyramid(dst_img, self.pyramid_levels)[::-1]
- prev_loss = 1e10
aux_models = []
if len(img_dst_pyr) != len(img_src_pyr):
raise ValueError("Cannot register images of different sizes")
for img_src_level, img_dst_level in zip(img_src_pyr, img_dst_pyr):
+ # tolerance compares successive losses of one level; a loss from the coarser level is not one of them
+ prev_loss: Optional[float] = None
for i in range(self.num_iterations):
# compute gradient and update optimizer parameters
opt.zero_grad()
loss = self.get_single_level_loss(img_src_level, img_dst_level, self.model())
loss += self.get_single_level_loss(img_dst_level, img_src_level, self.model.forward_inverse())
current_loss = loss.item()
- if abs(current_loss - prev_loss) < self.tolerance:
+ if prev_loss is not None and abs(current_loss - prev_loss) < self.tolerance:
break
prev_loss = current_loss
loss.backward()
diff --git a/tests/geometry/transform/test_image_registrator.py b/tests/geometry/transform/test_image_registrator.py
index 2196c8cb7..4c7d8f5bf 100644
--- a/tests/geometry/transform/test_image_registrator.py
+++ b/tests/geometry/transform/test_image_registrator.py
@@ -27,7 +27,7 @@ from kornia.geometry import transform_points
from kornia.geometry.conversions import denormalize_homography
from kornia.geometry.transform import ImageRegistrator
-from testing.base import BaseTester
+from testing.base import BaseTester, supports_bilinear_2d_grid_sample_backward, supports_reflect_padding
from testing.casts import dict_to
@@ -166,3 +166,27 @@ class TestImageRegistrator(BaseTester):
with pytest.warns(DeprecationWarning, match="`warp_dst_inro_src` is deprecated in favor of"):
via_alias = ir.warp_dst_inro_src(dst)
self.assert_close(via_alias, into_src)
+
+ def test_tolerance_is_per_level_5073(self, device, dtype):
+ # #5073: tolerance compares successive losses within one pyramid level, so every level takes its first
+ # optimizer step even when its first loss equals the coarser level's final loss (identical images make every
+ # loss equal). Comparing across levels stopped every finer level before its first update.
+ if not supports_bilinear_2d_grid_sample_backward(device, dtype):
+ pytest.skip(f"torch has no {dtype} bilinear grid_sample kernel with backward on {device.type}")
+ if not supports_reflect_padding(device, dtype):
+ pytest.skip(f"torch has no {dtype} reflection padding kernel on {device.type}")
+ steps = []
+
+ class CountingAdam(torch.optim.Adam):
+ def step(self, *args, **kwargs):
+ steps.append(1)
+ return super().step(*args, **kwargs)
+
+ image = torch.zeros(1, 1, 32, 48, device=device, dtype=dtype)
+ for levels in (1, 2, 3):
+ steps.clear()
+ ir = ImageRegistrator(
+ "translation", optimizer=CountingAdam, num_iterations=1, pyramid_levels=levels, tolerance=1e-4
+ ).to(device, dtype)
+ ir.register(image, image)
+ assert len(steps) == levels