One-Layer Transformers Provably Learn In-Context K-Nearest Neighbor Prediction with Chain-of-Thought

Lyumin Wu, Yuan CaoNeurIPS 2026

TL;DR

Everyone knows that asking a Large Language Model to "think step-by-step" via Chain-of-Thought (CoT) dramatically boosts its reasoning abilities, yet how gradient descent actually wires this skill into a model remains largely mysterious. Using the classic $K$-nearest-neighbor ($K$-NN) classification task as a theoretical laboratory, this paper proves that while a single-layer transformer fundamentally fails at direct $K$-NN prediction (for odd $K > 1$), giving it $K-1$ intermediate CoT steps unlocks a clever "find-and-mask" loop that solves the task. Even better, the authors prove that standard gradient descent naturally discovers this exact multi-step algorithm from scratch using only single-step supervision.

What Problem Does This Paper Address?

Why does generating intermediate tokens allow shallow transformers to solve problems they otherwise can't touch—and how do they learn to do it during training?

Consider in-context $K$-NN: you feed a model $N$ labeled data points plus one unlabeled query point, and ask for the majority label among the $K$ closest points. Prior work proved that a one-layer transformer can easily learn $1$-NN without CoT. Softmax attention is essentially a smooth argmax—crank up the temperature, and it naturally spotlights the single closest neighbor based on feature dot products.

However, softmax is terrible at cleanly grabbing the 2nd, 3rd, or $K$-th closest items all at once in a single forward pass. First, the authors prove mathematically that a one-layer transformer doing direct, single-step inference cannot reliably solve $K$-NN for odd $K > 1$, even when data points are cleanly separated. The central question then becomes: can CoT turn this parallel bottleneck into a solvable sequential problem, and will gradient descent actually converge to that solution?

Methods

Following standard theoretical simplifications, the authors analyze a one-layer self-attention transformer with merged key-query ($W$) and projection-value ($V$) matrices. Each input token is a column vector stacking three things: its $d$-dimensional feature vector, its binary label ($\pm 1$, or $0$ for the query), and a stochastic positional encoding (a randomly permuted, randomly signed one-hot vector ensuring all tokens have mutually orthogonal IDs).

To solve $K$-NN sequentially over $K-1$ CoT steps, the authors construct a specific block-diagonal weight matrix $W$ governed by two scalar parameters: a positive feature-matching weight $\alpha$, and a negative positional-penalty weight $\beta$.

  • What's novel: When the model retrieves the 1st nearest neighbor, the residual connection adds both that neighbor's label and its orthogonal positional ID onto the newly generated CoT token. In the next step, because $\beta$ is negative, the attention mechanism looks at that accumulated positional ID and slaps a massive penalty on the already-visited neighbor (as well as previous CoT tokens), effectively masking them out so softmax can cleanly pick the next closest neighbor!
  • Training setup: Keeping $V$ fixed, the authors initialize $W = 0$ and train it via gradient descent on the population loss. Crucially, instead of supervising an entire $K$-step rollout, they only supervise the first step—training the model to output the $1$-NN state vector (query features, 1st neighbor's label, and the sum of the query and 1st neighbor's positional IDs).

Datasets

Because this is primarily a theoretical work, no standard empirical benchmarks are used. Instead, the authors validate their math using synthetic datasets:

  • Training: Feature vectors ($d \in \{5, 10, 20\}$) and queries are sampled uniformly from the unit sphere $\mathbb{S}^{d-1}$ with context lengths $N \in \{20, 40\}$, paired with independent, random $\pm 1$ (Rademacher) labels.
  • Evaluation: A separate synthetic test set of 1,000 well-separated instances generated via rejection sampling to guarantee a minimum distance margin ($\gamma = 0.1$) between neighbors.

Key Insights and Ideas

  • Turning parallel failure into sequential masking: Previous CoT theories showed transformers emulating gradient descent or tree traversal. Here, CoT implements an iterative selection and masking algorithm, using orthogonal positional encodings as a scratchpad memory to cross items off a list.
  • Magic ratio of $-2$: Why must $\beta/\alpha \to -2$? For points on a unit sphere, the dot product between a query and any neighbor lies in $(-1, 1]$, meaning the gap between the best and worst possible dot products is at most $2$. If $\beta/\alpha \to -2$, previously selected neighbors get penalized by $\approx -2\alpha$, pushing their attention logits strictly below any unselected neighbor, without accidentally over-penalizing or letting the query attend to itself.
  • One-step supervision generalizes to $K$ steps: You don't need multi-step teacher forcing. Teaching the model just to retrieve the 1st neighbor and record its ID forces gradient descent (from zero initialization!) to push $\alpha \to +\infty$, $\beta \to -\infty$, and lock onto $\beta/\alpha \to -2$. At test time, you can unroll this single learned step for any $K \le N$.
  • Out-of-distribution generalization: Training assumes random, independent labels to prevent the model from taking shortcuts (like learning linear regression instead of true nearest-neighbor lookup). Once trained, however, the learned retrieval circuit works on any feature-label distribution on the sphere.

Key Results

  • Theoretical Convergence: Under zero initialization ($W^{(0)}=0$), with $N = \Omega(\sqrt{d})$ and learning rate $\eta = O(N^{-2})$, population loss provably converges to $0$, and parameters diverge cleanly with $\beta^{(t)}/\alpha^{(t)} \to -2$.
  • Empirical Validation: Even when relaxing theoretical assumptions—using random Gaussian initialization (variance $0.5$) and online SGD (batch size 1,000, 10,000 iterations) for $d=10, N=20$—the learned $W$ heatmap recovers the exact predicted diagonal block structure.
  • CoT vs. Direct Inference: On the test set ($d=10, N=20$), the single-step-trained model rolled out with CoT hits nearly 100% test accuracy for $K = 1, 3,$ and $5$. Meanwhile, identical baseline transformers trained specifically for direct single-pass $K=3$ and $K=5$ prediction plateau at substantially lower accuracies (roughly ~70–85%).

Limitations and Future Work

The authors openly note that their setup trades realism for mathematical tractability:

  • Architectural simplifications: Merging key-query matrices ($W$) and freezing the value-projection matrix ($V$) during the theoretical proof (though an appendix experiment shows joint training of $W$ and $V$ empirically works too).
  • Idealized data and optimization: Proofs rely on exact population gradients rather than finite-sample SGD, and assume spherically symmetric inputs with independent labels during training.
  • Future directions: Extending these training-dynamics proofs to multi-head, multi-layer transformers with unmerged weights, realistic finite-sample regimes, and asymmetric data distributions.

Summary updated

Abstract

Chain-of-Thought (CoT) enables transformers to solve complex reasoning tasks by generating intermediate reasoning steps. Despite strong empirical success, the mechanisms by which such reasoning abilities emerge during training remain poorly understood, particularly from a theoretical perspective. In this work, we study this question in a stylized yet fully analyzable setting: in-context $\mathrm{K}$-nearest-neighbor ($\mathrm{K}$-NN) prediction with a one-layer transformer. Earlier work has demonstrated that one-layer transformers can be trained to perform $1$-NN without CoT [26] by having the softmax attention attend to the nearest neighbor in context. However, this result on $1$-NN cannot be extended to $\mathrm{K}$-NN for $K>1$, as softmax attention is much less naturally suited to attending to the 2nd through $K$-th nearest neighbors. We first give a rigorous negative result showing that this limitation already appears on a well-separated class of binary classification tasks for odd $K>1$. We then give an explicit construction of a one-layer transformer, and show that it can solve $\mathrm{K}$-NN via CoT reasoning. We further prove that, under a stylized training setup, gradient descent can recover this construction, thereby showing that transformers can acquire the capability to solve $\mathrm{K}$-NN through training. In addition, we show that the resulting trained model applies to a broader test class than that assumed in the training analysis. Our results shed light on how CoT expands the ability of transformers to learn and solve tasks that are otherwise hard to solve.
BibTeX
@inproceedings{wu2026one,
  author = {Lyumin Wu and Yuan Cao},
  title = {{One-Layer Transformers Provably Learn In-Context K-Nearest Neighbor Prediction with Chain-of-Thought}},
  booktitle = {Advances in Neural Information Processing Systems},
  year = {2026},
  url = {https://openreview.net/forum?id=KRMF9RmzSJ},
}
Figure