Zero Labs
Industry News / AI

Accelerating K-Means on Modern GPUs: An IO-Aware Approach via Flash-KMeans

Source · Towards AI By MrPickle

From the publisher’s feed, collected in the ZeroLabs newsroom.

This article analyzes the hardware-level constraints of parallelizing K-Means on modern GPUs — specifically DRAM bandwidth saturation and atomic memory write contention. We then examine the architectural principles of Flash-KMeans, an IO-aware exact clustering formulation inspired by memory hierarchy co-design, followed by empirical evaluation and performance trade-off analysis on a physical GPU.│ Note: Throughout my learning and debugging journey, I paired with Google Antigravity as my AI pair programmer, which helped me unravel the math and pinpoint subtle GPU memory pitfalls.1. Introduction: Performance Bottlenecks in GPU-Accelerated K-MeansK-Means remains one of the foundational clustering techniques in unsupervised learning. It iteratively alternates between two primary steps until convergence:Assignment Phase: For each data point xᵢ ∈ ℝᴰ (i = 1, …, N), compute its Euclidean distance to all K centroids Cⱼ ∈ ℝᴰ (j = 1, …, K), and assign it to the nearest cluster:Centroid Update Phase: Recompute each centroid as the arithmetic mean of all data points assigned to that cluster:​At first glance, the assignment phase exhibits embarrassing data parallelism: each point’s cluster index can be evaluated independently. Consequently, a canonical GPU implementation allocates one thread per data point.However, empirical measurements reveal that naive GPU implementations frequently fall short of peak theoretical compute throughput. The underlying bottleneck is not arithmetic capacity (ALU/FLOPs), but the GPU memory hierarchy:DRAM Bandwidth Saturation (Memory-Bound Assignment): During the assignment phase, each thread repeatedly fetches the full set of K centroids from off-chip DRAM. For large problems (N×K×D), the memory bus between DRAM and on-chip caches becomes fully saturated, forcing compute units into high-latency stall states.Atomic Memory Contention (Unstructured Reduction): During the update phase, thousands of distributed threads concurrently accumulate their point coordinates into a small number of centroids using atomicAdd instructions on DRAM. This concurrent access to identical memory addresses triggers severe thread serialization and stalls the memory controller.2. Theoretical Principles of Flash-KMeansParalleling the memory co-design principles established by FlashAttention (Dao et al., 2022) in transformer architectures, Flash-KMeans (Yang et al., 2026) restructures the data movement patterns of K-Means. The primary design objective is to minimize read/write transactions between off-chip DRAM and fast on-chip memory (SRAM / Shared Memory).The architecture consists of two foundational components:2.1. FlashAssign: Memory Tiling and Online ArgminTo alleviate DRAM bandwidth pressure during the assignment phase:SRAM Tiling via Shared Memory: The dataset X and centroid matrix C are partitioned into uniform two-dimensional tiles X_tile × D and K_tile × D matched to the capacity of the GPU’s Shared Memory. Centroid blocks are loaded once cooperatively by threads within a Thread Block and reused repeatedly across all points in that block.Online Argmin: Conventional workflows often materialize an intermediate N×K distance matrix before applying a reduction. FlashAssign maintains the running minimum distance and corresponding cluster identifier entirely within per-thread registers. Only the final cluster assignment is written to DRAM once per iteration, bypassing intermediate matrix materialization.2.2. Sort-Inverse Centroid Update: Contiguous Mapping & Tree ReductionTo address the serialization caused by scattered atomicAdd calls during the centroid update phase, Flash-KMeans converts unstructured write patterns into structured, contiguous reductions:Sort-by-Key Clustering:Upon completing the assignment step, point indices are sorted with respect to their newly assigned cluster labels.This reorders the data array such that points belonging to the same cluster reside consecutively in memory, forming contiguous segments.Block-Level Binary Tree Reduction:Thread blocks load these contiguous segments directly into Shared Memory.Cluster-level coordinate summation is performed locally using a binary tree reduction structure inside SRAM.Contention Mitigation: Instead of issuing M atomic writes to DRAM for M points in a block, coordinate sums are pre-aggregated in Shared Memory. A single designated thread (Thread 0) executes one atomicAdd per dimension to DRAM for the entire segment, reducing global atomic contention by orders of magnitude.3. Empirical Evaluation and Benchmark AnalysisTo assess real-world performance, the baseline and optimized kernels were benchmarked on a physical system with the following specifications:Hardware: NVIDIA GeForce RTX 4050 Laptop GPU (6,144 MiB VRAM).Workload Configuration: Points (N=10,000), Clusters (K=200), Dimensions (D=64), Iterations = 10.Table 1: Execution Time and Speedup ComparisonsImplementation Variant Time (10 iters) Speedup vs. CPU Speedup vs. Naive Label Match Rate Centroid Max Diff-------------------------------------------------------------------------------------------------------------------------------CPU Baseline (Single-Thread) 925.70 ms 1.00x — Reference (100%) 0.00GPU Naive (Baseline) 34.57 ms 26.78x 1.00x 100.00% 0.00GPU Tiled (FlashAssign Only) 12.34 ms 75.04x 2.80x 100.00% 0.00GPU Flash-KMeans (Full Pipeline) 20.32 ms 45.56x 1.70x 100.00% 0.00Discussion and Performance Trade-offsImpact of Tiling on DRAM Read Overhead: Applying Shared Memory tiling alone (GPU Tiled) yields an immediate 2.80x times speedup over GPU Naive and 75.04× times over the CPU baseline. This confirms that the distance computation phase in standard K-Means is predominantly DRAM bandwidth-bound, and that caching centroids in on-chip SRAM effectively unblocks compute units.Analysis of Sorting Overhead vs. Atomic Contention: At N=10,000, the full Flash-KMeans pipeline executes in 20.32 ms—significantly faster than GPU Naive (1.70× times), but slower than the pure Tiled implementation (12.34 ms).Root Cause: At moderate dataset sizes, the algorithmic overhead of the sorting phase (thrust::sort_by_key) represents a noticeable fraction of iteration latency.Scaling Characteristics: The primary advantage of Sort-Inverse reduction emerges as the workload scales (N ≥ 10⁵, 10⁶ and large K). In those regimes, naive atomic writes suffer severe serialization penalties that scale super-linearly with N. By contrast, the cost of radix/merge sorting scales quasi-linearly (O(N log N) or O(N) for fixed-width keys), making the elimination of DRAM atomic contention the decisive factor in sustaining throughput.4. ConclusionModern GPU optimization increasingly hinges on managing data movement through the memory hierarchy rather than raw arithmetic operation counts. By mitigating DRAM bandwidth saturation via SRAM tiling and eliminating atomic contention through structured tree reductions, Flash-KMeans demonstrates that classical unsupervised algorithms can achieve substantial speedups while maintaining mathematical exactness.5. ReferencesYang, S., Xi, H., et al. (2026). Flash-KMeans: Fast and Memory-Efficient Exact K-Means. arXiv preprint arXiv:2603.09229.Dao, T., Fu, D. Y., Ermon, S., Rudra, A., & Ré, C. (2022). FlashAttention: Fast and Memory-Efficient Exact Attention with IO-Awareness. Advances in Neural Information Processing Systems (NeurIPS 2022).Lloyd, S. (1982). Least squares quantization in PCM. IEEE Transactions on Information Theory, 28(2), 129–137.Accelerating K-Means on Modern GPUs: An IO-Aware Approach via Flash-KMeans was originally published in Towards AI on Medium, where people are continuing the conversation by highlighting and responding to this story.