TL;DR
k-means clustering has quietly graduated from a dusty offline analytics tool to an online component inside modern LLMs and video diffusion models—except existing GPU implementations are still agonizingly slow. By redesigning how k-means moves data across GPU memory hierarchies rather than changing the underlying math, Flash-KMeans delivers exact clustering up to 17.9× faster than the strongest baselines (and over 200× faster than FAISS). It turns out the secret to faster clustering isn’t fewer calculations; it’s respecting GPU plumbing.
What Problem Does This Paper Address?
Historically, k-means ran offline on CPUs, where shaving off floating-point operations (FLOPs) via clever math approximations made sense. Today, AI pipelines invoke k-means dynamically on GPUs during forward passes—for sparse attention routing, KV-cache compression, and token permutation in generative video models.
On modern GPUs, raw compute is cheap, while moving data is expensive. Standard k-means (Lloyd’s algorithm) hits two massive hardware walls:
- The Memory Wall (Assignment Stage): Assigning $N$ points to $K$ centroids usually involves writing a gigantic $N \times K$ distance matrix to main GPU memory—High Bandwidth Memory (HBM)—only to immediately read it back to find the minimum distance.
- Traffic Jams (Update Stage): Updating centroids requires summing up points in each cluster. Standard GPU code uses "scatter-style" atomic additions, where thousands of threads try to update the same popular centroid’s memory address simultaneously, forcing hardware serialization and stalling bandwidth down to a trickle.
Add in out-of-VRAM batch sizes and dynamic input shapes triggering slow kernel recompilations, and k-means becomes a major online bottleneck.
Methods
Flash-KMeans keeps the exact mathematics of Lloyd’s algorithm intact, restructuring only the hardware execution path through three innovations:
- FlashAssign (Materialization-Free Assignment): Taking a page out of FlashAttention’s playbook, FlashAssign tiles data into ultra-fast on-chip SRAM and registers. As it streams centroid tiles through, it computes distances and maintains a running minimum (
online argmin) right in the registers. The massive $N \times K$ intermediate matrix is never written to HBM, slashing memory traffic from $O(NK)$ to $O(Nd + Kd)$. - Sort-Inverse Update: Instead of threads chaotically scattering updates to HBM, Flash-KMeans runs an
argsorton the lightweight 1D cluster-assignment vector (leaving the heavy data matrix untouched in memory). Now grouped into contiguous cluster segments, thread blocks gather features, sum them locally on-chip, and write to HBM just once per segment—eliminating atomic lock contention.
- System Co-Design: For massive datasets exceeding GPU memory, asynchronous CUDA streams overlap CPU-to-GPU PCIe transfers with computation. For dynamic shapes, a cache-aware heuristic picks kernel tile sizes based on L1/L2 cache specs, skipping exhaustive auto-tuning.
Datasets
The authors evaluate Flash-KMeans across:
- Synthetic Sweeps: Extensive grids varying data points ($N$ up to $10^9$ out-of-core), clusters ($K$ up to 256K), dimensions ($D$ up to 1024), and batch sizes ($B$).
- SIFT1M: A standard 1-million-vector benchmark used here to test real-world IVF-Flat and IVF-PQ index construction.
- Video Diffusion Workloads: Live token-clustering workloads inside a 50-step Diffusion Transformer (DiT) video generation pipeline ($B=32, N=75.6\text{K}, K=1000$).
No new datasets were introduced.
Key Insights and Ideas
- Partial fusion isn't enough: NVIDIA’s cuVS library does fuse distance calculation and reduction (
fusedL2NN), yet it is actually slower than unfused operations on large workloads (51.8 ms vs. 28.5 ms on H100). Why? Because it stores the running minimum in global HBM under locks. Keeping states strictly in registers—as FlashAssign does—is what unlocks real speed. - Amdahl's Law in action: In ablation tests, applying Sort-Inverse Update alone yields a negligible 1.04× end-to-end speedup because the assignment bottleneck completely dominates runtime. Once FlashAssign clears the assignment bottleneck (9.89× alone), Sort-Inverse Update slashes the remaining time nearly in half, jumping total speedup to 16.77×.
- Sorting beats colliding: Paying the upfront cost of sorting a 1D array of IDs seems like extra work, but trading $O(Nd)$ contested atomic writes for clean, localized on-chip reductions vastly outweighs the sorting overhead.
Key Results
Evaluated primarily on NVIDIA H200 (plus H100 and B200) GPUs in FP32:
- End-to-End Speedups: Up to 17.9× faster than
fast_pytorch_kmeans, 5.4× faster than Triton-basedfastkmeanson high-$K$ workloads (where PyTorch runs out of memory), 33× faster than NVIDIA cuML, and >200× faster than FAISS. - Kernel Microbenchmarks: FlashAssign hits up to 21.2× speedup; Sort-Inverse Update hits up to 6.3× speedup.
- Real Pipelines: Accelerates SIFT1M index building by 5.3–5.6× over cuVS, batched PQ codebook fitting by 10.7×, and cuts clustering time in a 50-step Video DiT generation from ~14 seconds down to 2 seconds (6.5× speedup).
- Deployability: Scales out-of-core to 1 billion points (6.3× faster than
fastkmeans) and cuts compilation time-to-first-run by 175× with negligible runtime loss.
Limitations and Future Work
- Hardware Specificity: Flash-KMeans is tailored for NVIDIA GPUs; adapting the dataflow to TPUs or AWS Trainium remains future work.
- High Dimensions: As feature dimension $D$ grows very large (e.g., $D = 1024$), distance math becomes more compute-bound, narrowing FlashAssign’s advantage to 3.95×.
- Sorting Overhead at Scale: At massive point counts ($N = 33\text{M}$), the
argsortstep itself begins to take a noticeable bite, accounting for 24.5% of the update stage's runtime.
Summary updated