Skip to content

Commit 70e9727

Browse files
Perf: single-pass remap_instance_id (unique + bincount + LUT gather) (#9009)
### Description Replaces the per-instance loops in `remap_instance_id` (which scanned the full volume once per instance id — twice with `by_size=True` — for `O(instances * volume)` work) with a single `torch.unique(return_inverse=True)` + `bincount` + LUT-gather pass, computing the same relabeling in `O(volume)`. Same approach as #8978; `by_size` tie-breaking (stable, ascending-id) and the int32 output dtype are preserved exactly. ### Benchmark Synthetic instance masks (random sparse ids, `by_size=True`), median of repeated runs, `OMP_NUM_THREADS=8`. **2D** | Input (H×W, #inst) | CPU speedup | CUDA speedup | | --- | --- | --- | | 128×128, 40 | ~4.2× | ~8.2× | | 256×256, 80 | ~10.8× | ~10.4× | | 512×512, 150 | ~9.1× | ~17.9× | | 512×512, 300 | ~18× | ~36× | | 1024×1024, 150 | ~5.7× | ~16.6× | | 1024×1024, 500 | ~18.7× | ~54.6× | **3D** | Input (D×H×W, #inst) | CPU speedup | CUDA speedup | | --- | --- | --- | | 64×64×64, 30 | ~2.4× | ~3.8× | | 96×96×96, 50 | ~2.8× | ~5.8× | | 128×128×128, 80 | ~3.6× | ~8.9× | | 128×128×128, 200 | ~8.6× | ~21.6× | | 160×160×160, 120 | ~5.8× | ~13× | Numerics are bit-identical (`torch.equal`) at every size. The old implementation was slowest on GPU (e.g. 2720 ms for 1024×1024 with 500 instances, vs 262 ms on CPU) because the per-instance masked scans serialize; that inversion is gone (49.8 ms). System: 12th Gen Intel Core i7-12800H (20 threads, `OMP_NUM_THREADS=8`); NVIDIA RTX A1000 Laptop GPU (4 GB); Linux 6.8.0-124-generic x86_64; Python 3.10.12; PyTorch 2.12.1+cu130. ### Types of changes - [x] Non-breaking change (fix or new feature that would not break existing functionality). - [x] New tests added to cover the changes. - [x] The metrics tests passed locally (490 passed, including new parameterized cases for non-contiguous ids, size ties, no-background and empty inputs, and randomized 2D/3D equivalence against the previous implementation), along with `black`/`isort`/`ruff`/`mypy`. --------- Signed-off-by: Soumya Snigdha Kundu <soumya_snigdha.kundu@kcl.ac.uk> Signed-off-by: Soumya Snigdha Kundu <soumyawork15@gmail.com> Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
1 parent b087a1b commit 70e9727

2 files changed

Lines changed: 107 additions & 15 deletions

File tree

‎monai/metrics/utils.py‎

Lines changed: 14 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@
1212
from __future__ import annotations
1313

1414
import warnings
15-
from collections.abc import Iterable, Sequence
15+
from collections.abc import Sequence
1616
from functools import cache, partial
1717
from types import ModuleType
1818
from typing import Any, overload
@@ -515,23 +515,22 @@ def remap_instance_id(pred: torch.Tensor, by_size: bool = False) -> torch.Tensor
515515
value of the tensor should be an integer, and represents the prediction of its corresponding instance id.
516516
by_size: if True, largest instance will be assigned a smaller id.
517517
518+
Returns:
519+
tensor of the same shape as ``pred`` with ids remapped to ``1..K`` (``torch.int`` dtype),
520+
or ``pred`` unchanged (original dtype) when it contains no foreground ids.
518521
"""
519-
pred_id: Iterable[Any] = list(pred.unique())
520-
# the original implementation has the limitation that if there is no 0 in pred, error will happen
521-
pred_id = [i for i in pred_id if i != 0]
522-
523-
if not pred_id:
522+
uniq, inverse = torch.unique(pred, return_inverse=True)
523+
order = torch.nonzero(uniq != 0).flatten()
524+
if order.numel() == 0:
524525
return pred
525526
if by_size:
526-
instance_size = [(pred == instance_id).sum() for instance_id in pred_id]
527-
pair_data = zip(pred_id, instance_size)
528-
pair_list = sorted(pair_data, key=lambda x: x[1], reverse=True)
529-
pred_id, _ = zip(*pair_list)
530-
531-
new_pred = torch.zeros_like(pred, dtype=torch.int)
532-
for idx, instance_id in enumerate(pred_id):
533-
new_pred[pred == instance_id] = idx + 1
534-
return new_pred
527+
counts = torch.bincount(inverse.flatten(), minlength=uniq.numel())[order]
528+
# stable sort keeps ascending-id order for equal-size instances, matching the
529+
# original python `sorted` tie-breaking
530+
order = order[torch.argsort(counts, descending=True, stable=True)]
531+
lut = torch.zeros(uniq.numel(), dtype=torch.int, device=pred.device)
532+
lut[order] = torch.arange(1, order.numel() + 1, dtype=torch.int, device=pred.device)
533+
return lut[inverse]
535534

536535

537536
def prepare_spacing(
Lines changed: 93 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,93 @@
1+
# Copyright (c) MONAI Consortium
2+
# Licensed under the Apache License, Version 2.0 (the "License");
3+
# you may not use this file except in compliance with the License.
4+
# You may obtain a copy of the License at
5+
# http://www.apache.org/licenses/LICENSE-2.0
6+
# Unless required by applicable law or agreed to in writing, software
7+
# distributed under the License is distributed on an "AS IS" BASIS,
8+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
9+
# See the License for the specific language governing permissions and
10+
# limitations under the License.
11+
12+
from __future__ import annotations
13+
14+
import unittest
15+
16+
import torch
17+
from parameterized import parameterized
18+
19+
from monai.metrics.utils import remap_instance_id
20+
21+
_device = "cuda:0" if torch.cuda.is_available() else "cpu"
22+
23+
TEST_CASES = [
24+
# (description, input, by_size, expected)
25+
["non_contiguous_ids", [[0, 2, 2], [5, 5, 0]], False, [[0, 1, 1], [2, 2, 0]]],
26+
["already_contiguous", [[0, 1], [2, 2]], False, [[0, 1], [2, 2]]],
27+
# id 7 covers 3 pixels, id 3 covers 2, id 9 covers 1 -> sizes decide new ids
28+
["by_size_largest_first", [[7, 7, 7, 0], [3, 3, 9, 0]], True, [[1, 1, 1, 0], [2, 2, 3, 0]]],
29+
# equal sizes: ascending original id order wins (stable tie-breaking)
30+
["by_size_ties_stable", [[5, 5, 0], [2, 2, 0]], True, [[2, 2, 0], [1, 1, 0]]],
31+
["no_background", [[4, 4], [6, 6]], False, [[1, 1], [2, 2]]],
32+
["single_instance", [[0, 0], [3, 3]], True, [[0, 0], [1, 1]]],
33+
]
34+
35+
36+
def _reference_remap(pred: torch.Tensor, by_size: bool = False) -> torch.Tensor:
37+
"""The original per-instance-loop implementation, kept as the behavioral reference."""
38+
pred_id = [i for i in pred.unique() if i != 0]
39+
if not pred_id:
40+
return pred
41+
if by_size:
42+
instance_size = [(pred == instance_id).sum() for instance_id in pred_id]
43+
pair_list = sorted(zip(pred_id, instance_size, strict=True), key=lambda x: x[1], reverse=True)
44+
pred_id = [p[0] for p in pair_list]
45+
new_pred = torch.zeros_like(pred, dtype=torch.int)
46+
for idx, instance_id in enumerate(pred_id):
47+
new_pred[pred == instance_id] = idx + 1
48+
return new_pred
49+
50+
51+
class TestRemapInstanceId(unittest.TestCase):
52+
"""Tests for `remap_instance_id` covering expected values, pass-through cases, and reference equivalence."""
53+
54+
@parameterized.expand(TEST_CASES)
55+
def test_expected_value(self, _, pred, by_size, expected):
56+
"""Remapping produces the hand-computed contiguous ids, including `by_size` ordering and ties."""
57+
result = remap_instance_id(torch.as_tensor(pred, device=_device), by_size=by_size)
58+
torch.testing.assert_close(result.cpu(), torch.as_tensor(expected, dtype=torch.int), check_dtype=False)
59+
60+
@parameterized.expand([["all_background_2d", (4, 4)], ["all_background_3d", (2, 3, 4)], ["empty", (0,)]])
61+
def test_passthrough(self, _, shape):
62+
"""Inputs without foreground ids are returned unchanged, keeping their original dtype."""
63+
pred = torch.zeros(shape, dtype=torch.int64, device=_device)
64+
result = remap_instance_id(pred, by_size=True)
65+
# assert_close checks dtype as well as values, so the original dtype is verified here
66+
torch.testing.assert_close(result, pred)
67+
68+
def test_output_dtype(self):
69+
"""Remapped outputs use the `torch.int` dtype regardless of input dtype."""
70+
pred = torch.as_tensor([[0, 9]], dtype=torch.int64, device=_device)
71+
self.assertEqual(remap_instance_id(pred).dtype, torch.int)
72+
73+
@parameterized.expand(
74+
[
75+
["2d", (64, 64), 20, False],
76+
["2d_by_size", (64, 64), 20, True],
77+
["3d_by_size", (16, 16, 16), 12, True],
78+
["sparse_ids_by_size", (48, 48), 7, True],
79+
]
80+
)
81+
def test_matches_reference(self, name, shape, n_inst, by_size):
82+
"""Randomized inputs produce output identical to the previous per-instance-loop implementation."""
83+
generator = torch.Generator().manual_seed(0)
84+
pred = torch.randint(0, n_inst + 1, shape, generator=generator).to(_device)
85+
if name.startswith("sparse"):
86+
pred = pred * 1000 + 17 # large, non-contiguous, no-background ids
87+
result = remap_instance_id(pred, by_size=by_size)
88+
expected = _reference_remap(pred, by_size=by_size)
89+
torch.testing.assert_close(result, expected)
90+
91+
92+
if __name__ == "__main__":
93+
unittest.main()

0 commit comments

Comments
 (0)