-
Notifications
You must be signed in to change notification settings - Fork 1.5k
Perf: Use a KDTree on CPU instead of full EDT for 1.5x to 16x faster metric computation #8910
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: dev
Are you sure you want to change the base?
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change | ||||||||||||||||||||||||||||||||||||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
|
|
@@ -16,8 +16,10 @@ | |||||||||||||||||||||||||||||||||||||||||||||
| import numpy as np | ||||||||||||||||||||||||||||||||||||||||||||||
| import torch | ||||||||||||||||||||||||||||||||||||||||||||||
| from parameterized import parameterized | ||||||||||||||||||||||||||||||||||||||||||||||
| from scipy.ndimage import distance_transform_edt | ||||||||||||||||||||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||||||||||||||||||||
| from monai.metrics import SurfaceDistanceMetric | ||||||||||||||||||||||||||||||||||||||||||||||
| from monai.metrics.utils import get_mask_edges, get_surface_distance | ||||||||||||||||||||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||||||||||||||||||||
| _device = "cuda:0" if torch.cuda.is_available() else "cpu" | ||||||||||||||||||||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||||||||||||||||||||
|
|
@@ -182,5 +184,43 @@ def test_nans(self, input_data): | |||||||||||||||||||||||||||||||||||||||||||||
| np.testing.assert_allclose(0, not_nans, rtol=1e-5) | ||||||||||||||||||||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||||||||||||||||||||
| KDTREE_SPACINGS = [["isotropic_default", None], ["isotropic", (1.0, 1.0, 1.0)], ["anisotropic", (1.0, 2.5, 0.5)]] | ||||||||||||||||||||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||||||||||||||||||||
| def _edge_masks(seed=0): | ||||||||||||||||||||||||||||||||||||||||||||||
| # two offset spheres plus a few scattered false positives in the prediction, so the | ||||||||||||||||||||||||||||||||||||||||||||||
| # surfaces are non-trivially apart and an outlier expands the cropped bounding box. | ||||||||||||||||||||||||||||||||||||||||||||||
| gt = create_spherical_seg_3d(radius=20, centre=(30, 30, 30)) | ||||||||||||||||||||||||||||||||||||||||||||||
| pred = create_spherical_seg_3d(radius=20, centre=(32, 31, 30)) | ||||||||||||||||||||||||||||||||||||||||||||||
| rng = np.random.RandomState(seed) | ||||||||||||||||||||||||||||||||||||||||||||||
| for _ in range(5): | ||||||||||||||||||||||||||||||||||||||||||||||
| pred[tuple(rng.randint(0, s) for s in pred.shape)] = 1 | ||||||||||||||||||||||||||||||||||||||||||||||
| edges_pred, edges_gt = get_mask_edges(pred, gt) | ||||||||||||||||||||||||||||||||||||||||||||||
| return np.asarray(edges_pred, dtype=bool), np.asarray(edges_gt, dtype=bool) | ||||||||||||||||||||||||||||||||||||||||||||||
|
Comment on lines
+190
to
+199
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Add Google-style docstring. Missing docstring violates coding guidelines. Document the 📝 Example docstring def _edge_masks(seed=0):
+ """Generate test edge masks from offset spheres with random false positives.
+
+ Args:
+ seed: Random seed for reproducible false positive placement.
+
+ Returns:
+ Tuple of (edges_pred, edges_gt) as boolean numpy arrays.
+ """
# two offset spheres plus a few scattered false positives in the prediction, so the🤖 Prompt for AI AgentsSource: Coding guidelines |
||||||||||||||||||||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||||||||||||||||||||
| class TestSurfaceDistanceKDTreeMatchesEDT(unittest.TestCase): | ||||||||||||||||||||||||||||||||||||||||||||||
| @parameterized.expand(KDTREE_SPACINGS) | ||||||||||||||||||||||||||||||||||||||||||||||
| def test_cpu_kdtree_euclidean_distances_match_dense_edt(self, _name, spacing): | ||||||||||||||||||||||||||||||||||||||||||||||
| edges_pred, edges_gt = _edge_masks() | ||||||||||||||||||||||||||||||||||||||||||||||
| result = np.asarray(get_surface_distance(edges_pred, edges_gt, distance_metric="euclidean", spacing=spacing)) | ||||||||||||||||||||||||||||||||||||||||||||||
| reference = distance_transform_edt(~edges_gt, sampling=spacing)[edges_pred] | ||||||||||||||||||||||||||||||||||||||||||||||
| # same multiset of distances (downstream metrics only use max/percentile/mean) | ||||||||||||||||||||||||||||||||||||||||||||||
| np.testing.assert_allclose(np.sort(result), np.sort(reference), rtol=1e-5, atol=1e-5) | ||||||||||||||||||||||||||||||||||||||||||||||
| self.assertEqual(result.dtype, np.float32) | ||||||||||||||||||||||||||||||||||||||||||||||
| self.assertEqual(result.shape, reference.shape) | ||||||||||||||||||||||||||||||||||||||||||||||
|
Comment on lines
+204
to
+211
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Add Google-style docstring. Test method lacks required docstring. Document the test purpose and parameters. 📝 Example docstring `@parameterized.expand`(KDTREE_SPACINGS)
def test_cpu_kdtree_euclidean_distances_match_dense_edt(self, _name, spacing):
+ """Verify CPU KDTree euclidean distances match dense EDT reference.
+
+ Args:
+ _name: Test case name (from parameterized).
+ spacing: Voxel spacing for distance computation.
+ """
edges_pred, edges_gt = _edge_masks()📝 Committable suggestion
Suggested change
🤖 Prompt for AI AgentsSource: Coding guidelines |
||||||||||||||||||||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||||||||||||||||||||
| def test_torch_input_preserves_type_device_and_matches_dense_edt(self): | ||||||||||||||||||||||||||||||||||||||||||||||
| edges_pred, edges_gt = _edge_masks() | ||||||||||||||||||||||||||||||||||||||||||||||
| spacing = (1.0, 2.5, 0.5) | ||||||||||||||||||||||||||||||||||||||||||||||
| seg_pred, seg_gt = torch.as_tensor(edges_pred), torch.as_tensor(edges_gt) | ||||||||||||||||||||||||||||||||||||||||||||||
| result = get_surface_distance(seg_pred, seg_gt, distance_metric="euclidean", spacing=spacing) | ||||||||||||||||||||||||||||||||||||||||||||||
| self.assertIsInstance(result, torch.Tensor) | ||||||||||||||||||||||||||||||||||||||||||||||
| self.assertEqual(result.dtype, torch.float32) | ||||||||||||||||||||||||||||||||||||||||||||||
| self.assertEqual(result.device, seg_pred.device) | ||||||||||||||||||||||||||||||||||||||||||||||
| reference = distance_transform_edt(~edges_gt, sampling=spacing)[edges_pred] | ||||||||||||||||||||||||||||||||||||||||||||||
| np.testing.assert_allclose(np.sort(result.cpu().numpy()), np.sort(reference), rtol=1e-5, atol=1e-5) | ||||||||||||||||||||||||||||||||||||||||||||||
|
Comment on lines
+213
to
+222
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Add Google-style docstring. Test method lacks required docstring. Document the test purpose. 📝 Example docstring def test_torch_input_preserves_type_device_and_matches_dense_edt(self):
+ """Verify torch inputs preserve type/device/dtype and match EDT reference."""
edges_pred, edges_gt = _edge_masks()🤖 Prompt for AI AgentsSource: Coding guidelines |
||||||||||||||||||||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||||||||||||||||||||||
| if __name__ == "__main__": | ||||||||||||||||||||||||||||||||||||||||||||||
| unittest.main() | ||||||||||||||||||||||||||||||||||||||||||||||
Uh oh!
There was an error while loading. Please reload this page.