Transformers Learn Two Competing Sorting Algorithms, and Only One Length-Generalizes
Khashayar Gatmiry, Nathan W. Henry, Chloe H. Su, Emmanuel Abbe, Samy Bengio, Melanie Weber, Jonathan A. Kelner, Peter L. Bartlett
Key points
From the paper's conclusion- We show that two-layer transformers trained to near-zero loss on a sorting task converge to one of two mechanistically distinct solution classes depending on their initialization.
Abstract
We show that two-layer transformers trained to near-zero loss on a sorting task converge to one of two mechanistically distinct solution classes depending on their initialization. One solution class consists of solutions that do not use the second attention layer to sort, but also fail to length-generalize. The other, which uses both attention layers, length-generalizes perfectly, despite only being trained to sort sequences of a fixed length. By carefully choosing the weight initialization, we demonstrate that we can steer the model toward learning one solution or the other. We identify input types that are rare at the training length but increasingly common at longer sequence lengths as a source of this disparity in length-generalization, and find that layer-wise specialization of the second class of solutions allows them to handle these rare sequences more accurately. In the second class, we discover a mechanism by which the second layer attention can use the contextual information gathered by the first layer attention to reduce its search space. On the related task of finding the minimum of a sequence, we find a similar two solution-type phenomenon, but with the opposite generalization pattern, where a different form of layer-wise specialization causes the two-layer solution to length-generalize worse than the single-attention solution.
Read the paper
Discussion
Science Skim's AI key points, plus readers' public thoughts
Readers' thoughts
No reader thoughts yet.
Related papers
- Transformers Provably Learn Graph Search: Training Dynamics and the Exponential Power of DeptharXiv · 2026
- Training Dynamics of Transformers on Unbounded Inputs: Attention Learning Can Lag Output Layer LearningarXiv · 2026
- Grammar Sparsity Sets How Transformers Learn Random LanguagesarXiv · 2026
- Attention Is Only as Good as Its Witnesses: When Higher-Order Layers Help, and When They Do NotarXiv · 2026
- Quantitative Generalization Bounds for Multi-Layer Transformers: A Few Long Strings can Beat Many Short OnesarXiv · 2026
- Distinct mechanisms underlying in-context learning in transformersPhysical Review X · 2026