🐍 Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
Vectorize KMeans centroid update to remove per-cluster host syncs (#4545)
prithvirajrh595c0c9c3264
diff --git a/changelog.d/4545.fixed.md b/changelog.d/4545.fixed.mdnew file mode 100644index 000000000..2bec0898f--- /dev/null+++ b/changelog.d/4545.fixed.md@@ -0,0 +1 @@+`KMeans.fit` no longer synchronises with the device once per cluster per iteration to update centroids; the update is now vectorised. This mainly benefits GPU backends where the per-cluster host syncs were expensive (e.g. MPS); on CPU the win is smaller and shrinks further at larger problem sizes, where the O(N·K·D) distance computation dominates. A fit that hits an empty cluster may now produce different (but equally valid) centers for the same seed, since the random reseed draws differ from before. Two more observable side effects of the old in-place update are also gone: `fit` no longer mutates a `cluster_centers` tensor passed in at construction, and calling `fit` a second time no longer warm-starts from the first call's result - neither was documented behavior, but code relying on either will now see a difference.diff --git a/docs/export_support/cases_models.py b/docs/export_support/cases_models.pyindex 27b164531..ea72b26ac 100644--- a/docs/export_support/cases_models.py+++ b/docs/export_support/cases_models.py@@ -1123,8 +1123,9 @@ A("contrib",_kmeans_fit,[torch.randn(20, 2) * 0.5 + torch.tensor([2.5, 2.5])],- note="max_iterations=5, tolerance=None (fixed iteration count) but fit() uses torch.nonzero + data-dependent "- "`if selected.shape[0] == 0` per cluster",+ note="max_iterations=5, tolerance=None (fixed iteration count); the centroid update has no "+ "data-dependent control flow, so torch.export and the ONNX export now succeed; the one remaining "+ "graph break is torch.manual_seed in __init__",))A(case("contrib.Lambda", "contrib", K.contrib.Lambda(K.color.rgb_to_grayscale), [IMG], note="wraps rgb_to_grayscale"))diff --git a/kornia/contrib/kmeans.py b/kornia/contrib/kmeans.pyindex d78e7fb26..92e28dd68 100644--- a/kornia/contrib/kmeans.py+++ b/kornia/contrib/kmeans.py@@ -55,6 +55,10 @@ class KMeans:# cluster_centers should have only 2 dimensionsif cluster_centers is not None:KORNIA_CHECK_SHAPE(cluster_centers, ["C", "D"])+ KORNIA_CHECK(+ cluster_centers.shape[0] == num_clusters,+ f"cluster_centers has {cluster_centers.shape[0]} rows but num_clusters={num_clusters}",+ )self.num_clusters = num_clustersself._cluster_centers = cluster_centers@@ -177,14 +181,29 @@ class KMeans:previous_centers = current_centers.clone()- for index in range(self.num_clusters):- selected = torch.nonzero(cluster_assignment == index).squeeze()- selected = torch.index_select(X, 0, selected)- # edge case when a certain cluster centre has no points assigned to it- # just choose a random point as it's update- if selected.shape[0] == 0:- selected = X[torch.randint(len(X), (1,), device=X.device)]- current_centers[index] = selected.mean(dim=0)+ # Vectorized per-cluster mean via a one-hot assignment matrix, instead of looping over+ # clusters with torch.nonzero/index_select (each iteration's dynamic output shape+ # forces a host sync). One-hot + matmul routes the reduction through a GEMM kernel;+ # scatter_add_ into the small (num_clusters, D) destination measured ~10x slower on+ # MPS for this shape (many threads racing to accumulate into few destination rows).+ #+ # Counts stay int64 (exact) and the sum accumulates in at least float32: X.dtype+ # itself overflows to inf in float16 past 65504, and loses precision in bfloat16,+ # for perfectly ordinary inputs (e.g. float16 image color quantization).+ one_hot = torch.nn.functional.one_hot(cluster_assignment, num_classes=self.num_clusters)+ cluster_counts = one_hot.sum(0)+ work_dtype = torch.float32 if X.dtype in (torch.float16, torch.bfloat16) else X.dtype+ X_work = X.to(work_dtype)+ cluster_sums = one_hot.to(work_dtype).t() @ X_work++ # edge case when a certain cluster centre has no points assigned to it:+ # just choose a random point as its update. A random index is drawn for every+ # cluster unconditionally and masked with torch.where, so the branch never depends+ # on a data-dependent Python bool (no host sync either way).+ empty_mask = (cluster_counts == 0).unsqueeze(1)+ means = cluster_sums / cluster_counts.clamp(min=1).unsqueeze(1).to(work_dtype)+ random_points = X_work[torch.randint(len(X), (self.num_clusters,), device=X.device)]+ current_centers = torch.where(empty_mask, random_points, means).to(X.dtype)# sum of distance of how much the newly computed clusters have moved from their previous positionscenter_shift = torch.sum(torch.sqrt(torch.sum((current_centers - previous_centers) ** 2, dim=1)))diff --git a/tests/contrib/test_kmeans.py b/tests/contrib/test_kmeans.pyindex 4f49a1602..d784baf90 100644--- a/tests/contrib/test_kmeans.py+++ b/tests/contrib/test_kmeans.py@@ -90,6 +90,58 @@ class TestKMeans(BaseTester):kmeans.predict(torch.rand((10, 7), dtype=dtype))assert "7 != 5" in str(errinfo)+ # case: num_clusters does not match the number of rows in an explicit cluster_centers+ with pytest.raises(BaseError) as errinfo:+ starting_centers = torch.rand((5, 2), device=device, dtype=dtype)+ kornia.contrib.KMeans(3, starting_centers, 1e-3, 100, 0)+ assert "cluster_centers has 5 rows but num_clusters=3" in str(errinfo.value)++ def test_empty_cluster_reseeds_to_a_data_point(self, device, dtype):+ # Both starting centers coincide, so every point ties to cluster 0 (argmin keeps the+ # first index on a tie) and cluster 1 gets no points assigned to it for the one update.+ x = torch.tensor([[0.0, 0.0], [1.0, 0.0], [0.0, 1.0], [1.0, 1.0]], device=device, dtype=dtype)+ starting_centers = torch.tensor([[0.5, 0.5], [0.5, 0.5]], device=device, dtype=dtype)++ kmeans = kornia.contrib.KMeans(2, starting_centers, tolerance=None, max_iterations=1, seed=0)+ kmeans.fit(x)+ centers = kmeans.cluster_centers++ self.assert_close(centers[0], x.mean(dim=0))+ # the empty cluster is reseeded to *some* row of x, not left at the stale starting center+ assert any(torch.allclose(centers[1], row) for row in x)++ @pytest.mark.parametrize(+ ("x", "starting_centers", "expected"),+ [+ (+ (50 + torch.arange(3200) % 4).reshape(1600, 2).float(),+ None,+ torch.tensor([[51.0, 52.0]]),+ ),+ (+ torch.cat([torch.full((400, 3), 200.0), torch.full((400, 3), 20.0)]),+ torch.tensor([[190.0, 190.0, 190.0], [30.0, 30.0, 30.0]]),+ torch.tensor([[200.0, 200.0, 200.0], [20.0, 20.0, 20.0]]),+ ),+ ],+ )+ def test_large_cluster_sum_stays_finite(self, device, dtype, x, starting_centers, expected):+ # Regression test for accumulating sums/counts in X.dtype: in float16 a per-cluster sum+ # over hundreds of points routinely exceeds 65504 and overflows to inf; in bfloat16 the+ # count and sum both lose precision well before that. One update should still match the+ # exact float64 mean.+ x = x.to(device=device, dtype=dtype)+ centers = starting_centers.to(device=device, dtype=dtype) if starting_centers is not None else None+ num_clusters = expected.shape[0]++ kmeans = kornia.contrib.KMeans(num_clusters, centers, tolerance=None, max_iterations=1, seed=0)+ kmeans.fit(x)++ assert torch.isfinite(kmeans.cluster_centers).all()+ # exact in every dtype on the fixed implementation - a nonzero tolerance would let the+ # pre-fix bfloat16 error (0.25, well under BaseTester's default bfloat16 tolerance) pass+ self.assert_close(kmeans.cluster_centers, expected.to(device=device, dtype=dtype), rtol=0.0, atol=0.0)+@staticmethoddef _create_data(device, dtype):# create example dataset