Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

fix(feature): apportion MultiResolutionDetector quotas with largest remainder (#4156)

Mohansree Vijayakumarff67574ceccb
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 7d2e75e60..82de68a58 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -129,6 +129,16 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### Bug fixes
+* `MultiResolutionDetector.detect` apportions `num_features` across pyramid levels with largest-remainder
+ (Hamilton) apportionment instead of flooring each level's fractional share independently (#4101). The floors
+ used to discard every fractional part, so a small `num_features` could round the whole apportionment down: with
+ the default configuration the six shares are `0.508 .. 0.016`, and every level but the finest lost its entire
+ quota to truncation, so the detector effectively searched a single scale. The shortfall -- `num_features` minus
+ the sum of the floors -- is now handed to the levels with the largest fractional remainder, one slot each, so
+ the quotas always sum to exactly `num_features` and stay spread across scales. #4098's narrower `num_features=1`
+ fallback, which handed the request's one slot to the largest-share level when every quota floored to zero, is
+ the special case where the shortfall equals `num_features` and is superseded by the general apportionment.
+
* Make YUV and XYZ transformations compute integer inputs in `float32` instead of truncating their kernels, and
preserve directly constructed `float64` coefficients. This makes `rgb_to_yuv(uint8)` return `float32` on the
input's original 0--255 scale, fixes signed-integer YUV results, and removes the existing float32 coefficient loss
diff --git a/kornia/feature/scale_space_detector.py b/kornia/feature/scale_space_detector.py
index 1a36796c7..4a0e456bd 100644
--- a/kornia/feature/scale_space_detector.py
+++ b/kornia/feature/scale_space_detector.py
@@ -839,15 +839,19 @@ class MultiResolutionDetector(nn.Module):
nf = self.num_features * factor_points ** (-1 * (idx_level - self.num_upscale_levels))
num_features_per_level.append(nf)
shares: List[float] = [x / tmp for x in num_features_per_level]
+ # Largest-remainder (Hamilton) apportionment: `shares` sums to `self.num_features` (up to
+ # float error), but flooring each one independently discards every fractional part, so the
+ # floors can sum to well under `self.num_features` -- to zero at `num_features=1`, where the
+ # default six shares are 0.508 .. 0.016. The finest level's quota also dominates every other
+ # one's, so a small request degenerates to querying a single scale. Hand the shortfall --
+ # `self.num_features` minus the sum of floors -- to the levels with the largest fractional
+ # remainders, one slot each, so the quotas always sum to exactly `self.num_features` and stay
+ # spread across scales instead of collapsing onto the finest level.
num_features_per_level = [int(x) for x in shares]
- # Each quota truncates independently, so a small `num_features` can round the whole
- # apportionment to zero: with the default configuration that happens at `num_features=1`,
- # where the six shares are 0.508 .. 0.016. Every level would then be queried for zero
- # candidates and the result padded with a dummy, on an image full of real maxima. Hand the
- # one slot to the level with the largest share. This fires only when truncation lost
- # everything -- an apportionment that already gives out a slot is left exactly as it was.
- if self.num_features > 0 and sum(num_features_per_level) == 0:
- num_features_per_level[max(range(len(shares)), key=shares.__getitem__)] = 1
+ shortfall = self.num_features - sum(num_features_per_level)
+ by_remainder = sorted(range(len(shares)), key=lambda i: shares[i] - num_features_per_level[i], reverse=True)
+ for idx_level in by_remainder[:shortfall]:
+ num_features_per_level[idx_level] += 1
_, _, h, w = img.shape
img_up = img
@@ -889,9 +893,10 @@ class MultiResolutionDetector(nn.Module):
responses = torch.cat(all_responses, 1)
lafs = torch.cat(all_lafs, 1)
# The levels can produce fewer slots than requested β€” a level is capped at its own pixel
- # count, and the per-level quotas round down, to zero for a small `num_features`. Pad up
- # so the returned shape is always `num_features`, the same way `ScaleSpaceDetector.detect`
- # does; the padding is the zero response and zero LAF used everywhere else here.
+ # count, so a deep enough pyramid level runs out of positions before it fills its quota.
+ # Pad up so the returned shape is always `num_features`, the same way
+ # `ScaleSpaceDetector.detect` does; the padding is the zero response and zero LAF used
+ # everywhere else here.
if lafs.shape[1] < self.num_features:
pad = self.num_features - lafs.shape[1]
responses = F.pad(responses, (0, pad))
diff --git a/tests/feature/test_scale_space_detector.py b/tests/feature/test_scale_space_detector.py
index 905dc60b9..b9bf864b4 100644
--- a/tests/feature/test_scale_space_detector.py
+++ b/tests/feature/test_scale_space_detector.py
@@ -853,6 +853,28 @@ class TestMultiResolutionDetector(BaseTester):
self.assert_close(resps_one[0, 0], resps_two[0].max())
self.assert_close(lafs_one[0, 0], lafs_two[0, int(resps_two[0].argmax())])
+ def test_small_request_spreads_across_scales(self, device, dtype):
+ # `detect` used to apportion `num_features` across pyramid levels by flooring each level's
+ # fractional share independently (`int(x) for x in shares`). The shares favor the finest
+ # level so heavily (0.508 .. 0.016 with the default config) that a small `num_features`
+ # truncated every other level's quota to zero: five well-separated, equally strong blobs and
+ # `num_features=3` returned three near-duplicate detections of the single strongest blob
+ # instead of covering several of them. Largest-remainder (Hamilton) apportionment hands the
+ # shortfall to the levels with the largest fractional remainder instead, so a small request
+ # still reaches more than one scale and covers more than one blob.
+ img = torch.zeros(1, 1, 96, 96, device=device, dtype=dtype)
+ centers = [(20, 20), (20, 70), (48, 48), (76, 20), (76, 70)]
+ for y, x in centers:
+ img[:, :, y - 2 : y + 3, x - 2 : x + 3] = 1.0
+
+ det = self._make_detector(num_features=3).to(device, dtype)
+ _, lafs = det.detect(img)
+ laf_centers = lafs[0, :, :, 2]
+ covered = sum(
+ 1 for y, x in centers if bool(((laf_centers - laf_centers.new_tensor([x, y])).abs().amax(dim=1) < 4).any())
+ )
+ assert covered >= 2, f"expected the 3-feature request to reach at least 2 of the 5 blobs, got {covered}"
+
def test_negative_score_threshold_is_rejected(self, device, dtype):
# NMS writes an exact zero at every suppressed position, so a negative threshold would
# admit all of them -- and collide with the zero response that marks an unfilled slot.