English

Finding Clustering Algorithms in the Transformer Architecture

Machine Learning 2025-06-25 v1 Artificial Intelligence

Abstract

The invention of the transformer architecture has revolutionized Artificial Intelligence (AI), yielding unprecedented success in areas such as natural language processing, computer vision, and multimodal reasoning. Despite these advances, it is unclear whether transformers are able to learn and implement precise algorithms. Here, we demonstrate that transformers can exactly implement a fundamental and widely used algorithm for kk-means clustering: Lloyd's algorithm. First, we theoretically prove the existence of such a transformer architecture, which we term the kk-means transformer, that exactly implements Lloyd's algorithm for kk-means clustering using the standard ingredients of modern transformers: attention and residual connections. Next, we numerically implement this transformer and demonstrate in experiments the exact correspondence between our architecture and Lloyd's algorithm, providing a fully neural implementation of kk-means clustering. Finally, we demonstrate that interpretable alterations (e.g., incorporating layer normalizations or multilayer perceptrons) to this architecture yields diverse and novel variants of clustering algorithms, such as soft kk-means, spherical kk-means, trimmed kk-means, and more. Collectively, our findings demonstrate how transformer mechanisms can precisely map onto algorithmic procedures, offering a clear and interpretable perspective on implementing precise algorithms in transformers.

Keywords

Cite

@article{arxiv.2506.19125,
  title  = {Finding Clustering Algorithms in the Transformer Architecture},
  author = {Kenneth L. Clarkson and Lior Horesh and Takuya Ito and Charlotte Park and Parikshit Ram},
  journal= {arXiv preprint arXiv:2506.19125},
  year   = {2025}
}
R2 v1 2026-07-01T03:30:22.929Z