Core Pattern · Interactive Simmedium•DECEMBER 2026•8 MIN
Vectorized Pairwise L2 & Batched K-Means: GEMM Without 3D OOM
Use ||x - c||² = ||x||² + ||c||² - 2 x·c to compute all-pairs distances in one BLAS matmul without (N, K, D) allocation.
gemm-l2k-meansvectorizationmlembeddingsnumpy
The problem
Compute all-pairs squared Euclidean distances between X of shape (N, D) and centroids C of shape (K, D), then iterate Lloyd's K-Means updates until centroid shift falls below tolerance.
Watch it run
Step through Lloyd's iterations and adjust K to see how the GEMM distance matrix drives cluster assignments until maxShift == 0.
LOADING VECTORIZED K-MEANS SIM...
Reference implementation
import numpy as np
def pairwise_sq_l2(X: np.ndarray, C: np.ndarray) -> np.ndarray:
x2 = np.sum(X * X, axis=1, keepdims=True) # (N, 1)
c2 = np.sum(C * C, axis=1)[None, :] # (1, K)
return np.maximum(0.0, x2 + c2 - 2.0 * (X @ C.T))
def kmeans(X: np.ndarray, k: int, max_iters: int = 50, tol: float = 1e-4):
C = X[:k].copy()
for _ in range(max_iters):
labels = np.argmin(pairwise_sq_l2(X, C), axis=1)
C_new = np.array([
X[labels == j].mean(axis=0) if np.any(labels == j) else C[j]
for j in range(k)
])
if np.max(np.linalg.norm(C_new - C, axis=1)) < tol:
return C_new, labels
C = C_new
return C, labels