One-Layer Transformers Provably Learn In-Context K-Nearest Neighbor Prediction with Chain-of-Thought
Lyumin Wu, Yuan Cao
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 -nearest-neighbor (-NN) prediction with a one-layer transformer. Earlier work has demonstrated that one-layer transformers can be trained to perform -NN without CoT [26] by having the softmax attention attend to the nearest neighbor in context. However, this result on -NN cannot be extended to -NN for , as softmax attention is much less naturally suited to attending to the 2nd through -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 . We then give an explicit construction of a one-layer transformer, and show that it can solve -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 -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.
Are you an author? Claim this paper to see who's reading it, with views and other statistics, and to write about it here.
Claim this paperedit · history
NeurIPS 2026
Accept (poster) · 3 reviews · OpenReview
Updated 25 Nov 2026, 03:44 UTC.
- Decision
- Accept (poster)
Read decision
Meta-review
Initial Meta-Review
I would like the rebuttal to focus on the following prioritized points:
- ffVj-W1 (one-layer Transformer) ~USTL-W3
- I think it is acceptable, but provide some discussion.
- ffVj-W2 (stochastic position encoding) ~RhHp-W1, USTL-W2
- All reviewers identified this as a significant weakness. Please provide a discussion addressing this concern.
- ffVj-W3 (limited convergence analysis)
- Please provide some discussion.
- RhHp-W2/3 (restrictive assumptions: Fixing V; training distribution)
- This is also a crucial point. Please provide more discussion.
- RhHp-W4 (multiclass setup)
- I think it is acceptable to focus on the binary setting, but please provide some discussion on a multiclass setup.
- USTL-W1 (Need for broader comparison with prior work)
- Please provide a broader comparison with prior work.
Final Meta-Review
The most important reason for the decision is that this paper establishes an expressiveness gap between direct inference and CoT: a one-layer transformer without CoT cannot perform K-NN via direct inference, whereas the same architecture can solve K-NN via CoT. The authors well responded to the concerns raised by the reviewers, particularly as described below. Overall I recommend accept.
- ffVj-W2 (stochastic position encoding) ~RhHp-W1, USTL-W2
- RhHp-W2/3 (restrictive assumptions: Fixing V; training distribution)
- After the rebuttal, the reviewers think the settings and the assumptions are overall necessary or acceptable as they are used to simplify the complicated theoretical analysis of GD with transformers.
Final justification
See the Meta-Review.
- Final justification
- See the Meta-Review.
Read meta-review
Meta-review
Initial Meta-Review
I would like the rebuttal to focus on the following prioritized points:
- ffVj-W1 (one-layer Transformer) ~USTL-W3
- I think it is acceptable, but provide some discussion.
- ffVj-W2 (stochastic position encoding) ~RhHp-W1, USTL-W2
- All reviewers identified this as a significant weakness. Please provide a discussion addressing this concern.
- ffVj-W3 (limited convergence analysis)
- Please provide some discussion.
- RhHp-W2/3 (restrictive assumptions: Fixing V; training distribution)
- This is also a crucial point. Please provide more discussion.
- RhHp-W4 (multiclass setup)
- I think it is acceptable to focus on the binary setting, but please provide some discussion on a multiclass setup.
- USTL-W1 (Need for broader comparison with prior work)
- Please provide a broader comparison with prior work.
Final Meta-Review
The most important reason for the decision is that this paper establishes an expressiveness gap between direct inference and CoT: a one-layer transformer without CoT cannot perform K-NN via direct inference, whereas the same architecture can solve K-NN via CoT. The authors well responded to the concerns raised by the reviewers, particularly as described below. Overall I recommend accept.
- ffVj-W2 (stochastic position encoding) ~RhHp-W1, USTL-W2
- RhHp-W2/3 (restrictive assumptions: Fixing V; training distribution)
- After the rebuttal, the reviewers think the settings and the assumptions are overall necessary or acceptable as they are used to simplify the complicated theoretical analysis of GD with transformers.
1 comment
- Rating
- 3/6
- Confidence
- 3/5
- Quality
- 3/4
- Clarity
- 4/4
- Significance
- 3/4
- Originality
- 2/4
- Contribution type
- theory
- Ethical concerns
- NO or VERY MINOR ethics concerns only
Read review
Summary
This paper studies the expressivity and learning guarantees of a one-layer transformer with and without Chain of Thought (CoT). The authors show that a one-layer transformer fails to implement k-Nearest Neighbors (kNN) even for well-separated cases when k is odd, and show that a single-layer, transformer-only network can implement kNN with CoT. Further, they show that gradient descent applied to the population loss recovers the parameters that implement the intermediate tokens that realize kNN.
Strengths and weaknesses
Strengths.
- The paper is very well-written, and its core ideas are communicated effectively.
- It presents a clear operational view of transformers, both with and without Chain of Thought (CoT).
Weaknesses
- Need for broader comparison with prior work: The core idea, that a recursively applied transformer circuit can express iterative algorithms, is very close to recent studies such as Huang et al. (2025) [15], which explored single-step versus multi-step gradient descent. In this paper, the algorithm implements k-NN through a sequential nearest-neighbor selection procedure (Lines 171–173). Given this conceptual similarity, could you explicitly compare your work with this earlier literature to clarify your exact contributions?
- Unclear embedding construction: The embedding construction used in this setting is not fully explained and feels somewhat ad hoc. For example, why are stochastic positional encodings necessary?
- Limited scope of experiments: The simulation results focus exclusively on one-layer transformers. Further experiments are needed to determine if the proposed mechanism scales to larger models and more realistic datasets.
In light of these points, I urge the authors to expand the comparison with prior work to better isolate their conceptual contributions. Additionally, extending the experimental section to demonstrate the applicability of the presented mechanism in larger models would significantly strengthen the paper.
Questions
NA
Limitations
Yes
Final justification
Based on our discussion, I have decided to keep my score the same. My justification is as follows:
-
From what I could follow, the proof idea and the conceptual approach (implementing iterative methods with CoT) have already been covered in earlier literature, which means that the paper's primary potential contribution should lie in the context of implementing and learning -NN.
-
Regarding the discussion on -NN, I find it difficult to believe that scaling up the model does not help in learning -NN for larger values of in practice. Therefore, it is still not obvious to me how the CoT approach implemented here will help at a larger scale. Ultimately, the discussion and the experiments need to be expanded to establish a clearer picture of how CoT improves -NN.
Formatting concerns
Na
10 comments
Rebuttal
We sincerely appreciate your thoughtful feedback. Below, we respond to the weaknesses you identified and provide detailed answers to your questions.
W1. Comparison with Huang et al. (2025) [3]. Could you explicitly compare your work with this earlier literature to clarify your exact contributions?
A1. Thank you for pointing out this important connection. Both our work and Huang et al. [3] study how a learned single-step Transformer computation can be recursively applied to produce a multi-step algorithm. The underlying tasks and mechanisms, however, are substantially different.
Huang et al. [3] consider linear regression, for which gradient descent is already a canonical iterative algorithm. Each CoT step is trained to reproduce one gradient-descent update, and repeatedly applying the same update rule naturally yields a multi-step optimization procedure. By contrast, -NN is conventionally formulated as a direct top- retrieval-and-aggregation rule rather than as an iterative process. Our work identifies a non-obvious sequential realization of -NN: at each step, the Transformer retrieves the nearest context point that has not yet been selected, while the generated positional state records the selected neighbors and suppresses them in subsequent attention computations. Recursively applying this transition therefore converts a nominally non-iterative prediction rule into a sequential retrieval algorithm.
A second distinction concerns supervision. Huang et al. [3] supervise the intermediate computation step by step, whereas our training objective supervises only the first target state. At test time, the learned transition is applied autoregressively to generate the remaining intermediate states and recover the full -NN prediction. Thus, our result shows that first-step supervision can be sufficient to identify a reusable transition rule whose repeated application implements a longer reasoning process. We view this as an interesting observation.
Moreover, Huang et al. [3] analyze linear attention, which is a simplification of softmax attention, and establish convergence to a finite parameter limit. The nonlinearity of softmax commonly makes the corresponding loss and gradient difficult to express in a tractable closed form. In our setting, we must first use distributional symmetries to prove that gradient descent remains on the invariant manifold . After this reduction, the parameters do not converge to finite values: Appendix E.3 proves and through contradiction and compactness arguments, while Appendices E.5-E.6 prove that their relative scale converges, , using drift estimates and crossing arguments. Therefore, although both works establish convergence results, characterizing the divergent softmax dynamics and identifying its limiting direction is technically more involved.
We will revise the related-work discussion to make this comparison explicit.
W2. Embedding construction is not fully explained and feels somewhat ad hoc. Why are stochastic positional encodings necessary?
A2. We thank the reviewer for this comment.
Regarding the embedding construction, please note that our setting is consistent with existing work on in-context learning [4–7], where the embedding consists of a feature block, a label block, and a positional encoding block.
Regarding the positional encoding, our use of stochastic positional encodings follows [1-2]. Specifically, [1] introduces stochastic positional encodings as an alternative to fixed absolute positional encodings, which may generalize poorly to unseen sequence lengths. More closely related to our setting, [2] theoretically analyzes the training dynamics of one-layer Transformers with near-orthogonal stochastic positional encodings.
A key observation in [2] is that stochastic positional encoding improves length generalization while inducing distributional symmetry that simplifies the characterization of gradient-descent trajectories. Our analysis builds on the same principle: randomness in the positional encodings induces a signed-permutation symmetry in the positional block, allowing us to show in Appendix E.2 that gradient descent remains confined to a low-dimensional invariant manifold.
Our expressive power guarantees (Theorem 3.1, Proposition 3.2) can be directly extended to any mutually orthogonal positional encodings, since the proof primarily uses orthogonality and is otherwise unchanged. However, our training analysis relies on the signed-permutation symmetry of stochastic positional encodings used in Appendix E.2; without this symmetry, an analogous guarantee would require a substantially different analysis of the full positional block. We will clarify this distinction in the revision.
W3. Limited scope of experiments.
A3. We conduct additional experiments with , , replacing the single-head, single-layer Transformer with either a four-head, one-layer model or a single-head, two-layer model. Both variants are successfully optimized, exhibiting substantial decreases in training loss and achieving high test accuracy across different values of . These results suggest that both multi-head and multi-layer Transformers can learn the proposed sequential -NN mechanism, indicating that the mechanism is not empirically restricted to the one-layer architecture analyzed in the paper.
| Model | Training loss, 2k | Training loss, 4k | Training loss, 6k | Training loss, 8k | Training loss, 10k | Test acc. | Test acc. | Test acc. |
|---|---|---|---|---|---|---|---|---|
| 4-head, 1-layer | 0.14465 | 0.10737 | 0.09930 | 0.08658 | 0.08927 | 100.0 | 99.7 | 98.2 |
| 1-head, 2-layer | 0.23258 | 0.15614 | 0.15273 | 0.14034 | 0.15023 | 100.0 | 99.1 | 92.8 |
References:
[1] Positional description matters for transformers arithmetic. ArXiv 2023
[2] Transformers Provably Learn Sparse Token Selection While Fully-Connected Nets Cannot. ICML 2024
[3] Transformers Learn to Implement Multi-step Gradient Descent with Chain of Thought. ICLR 2025
[4] One-Layer Transformer Provably Learns One-Nearest Neighbor In Context. NeurIPS 2024
[5] Transformers as Statisticians: Provable In-Context Learning with In-Context Algorithm Selection
[6] In-context Learning on Function Classes Unveiled for Transformers. ICML 2024
[7] In-Context Deep Learning via Transformer Models. ICML 2025
I thank the authors for their detailed responses. Regarding A3, before I finalize my score, could the authors compare how the models in their updated experiment perform with and without CoT training? Currently, it is difficult to assess from the provided table exactly how CoT contributes to generalization.
Thank you for your response and suggestion. Below, we compare the performance of the four-head, one-layer model and the single-head, two-layer model in our updated experiments, with and without CoT training.
Specifically, for , , we train a separate direct-prediction baseline for each for iterations. During training, each model receives only the initial input and is supervised to predict the final -NN target state directly in a single forward pass.
At inference time, each trained model performs only a single forward pass on the initial input, without intermediate-state generation or autoregressive rollout. Each model is tested only at the value of for which it was trained, using the same test protocol as in the CoT experiments.
We summarize the new experiments and compare them with the CoT results in the following table.
| Model | Training setup | Inference | Test acc. | Test acc. | Test acc. |
|---|---|---|---|---|---|
| 4-head, 1-layer | CoT | CoT rollout | 100.0 | 99.7 | 98.2 |
| 4-head, 1-layer | Direct model trained for | Single-pass | 100.0 | ||
| 4-head, 1-layer | Direct model trained for | Single-pass | 75.1 | ||
| 4-head, 1-layer | Direct model trained for | Single-pass | 68.5 | ||
| 1-head, 2-layer | CoT | CoT rollout | 100.0 | 99.1 | 92.8 |
| 1-head, 2-layer | Direct model trained for | Single-pass | 100.0 | ||
| 1-head, 2-layer | Direct model trained for | Single-pass | 74.7 | ||
| 1-head, 2-layer | Direct model trained for | Single-pass | 69.2 |
These comparisons show a clear advantage of CoT training and rollout over direct single-pass training for both architectures. Although all models solve the -NN task perfectly, a substantial performance gap emerges at and . In particular, despite being trained separately for a specific value of , the direct baselines exhibit markedly lower accuracy as increases. By contrast, a single CoT-trained model maintains high accuracy across different values of by varying only the rollout length. This suggests that CoT enables models to use a sequential retrieval mechanism for -NN prediction that generalizes across reasoning depths. Moreover, both this mechanism and the overall -NN task for appear difficult to handle via direct inference alone.
We hope these additional experimental results help resolve your concerns, and we would be happy to address any further questions. Thank you again for your careful review of our paper.
- Rating
- 4/6
- Confidence
- 4/5
- Quality
- 3/4
- Clarity
- 3/4
- Significance
- 3/4
- Originality
- 3/4
- Contribution type
- theory
- Ethical concerns
- NO or VERY MINOR ethics concerns only
Read review
Summary
The paper provides a rigorous theoretical analysis of how Chain-of-Thought (CoT) reasoning enables one-layer transformers to perform in-context -nearest-neighbor (-NN) (binary) classification. In the process, it constructs a negative result showing that direct inference by a one-layer transformer fails for odd on well-separated inputs. The paper's central claim, demonstrating CoT enables K-NN via sequential nearest-neighbor selection using stochastic positional encodings, comes with a training dynamics result showing that gradient descent on a one-step supervision objective recovers their underlying construction, with loss converging to zero.
Strengths and weaknesses
Strengths
- The paper is well-written, easy to follow, and well-organized. The proof machinery is substantial and carefully executed. The training dynamics analysis (Appendix E) is particularly impressive. The authors reduce the full matrix gradient descent problem to a @D scalar system via symmetry arguments, specifically by exploiting rotational invariance in feature space, label sign symmetry, and the signed-permutation symmetry of the stochastic positional encodings.
- I found the boundary-layer asymptotic analysis in Section E.5, treating the logistic kernels as approximate identities concentrating around the critical threshold quite interesting.
- In terms of overall impact, it is fair to say that this work addresses the central challenge that [1] left open; their 1-NN result relied on softmax attention, naturally concentrating on the single maximum-inner-product token, a property that breaks for .
[1] Li, Z., Cao, Y., Gao, C., He, Y., Liu, H., Klusowski, J.M., Fan, J. and Wang, M., 2024. One-layer transformer provably learns one-nearest neighbor in context. Advances in Neural Information Processing Systems, 37, pp.82166-82204.
Weaknesses
-
The paper's central technical device: stochastic positional encodings with random signed permutations, is non-standard and seems only to serve the theoretical construct. The authors attempt to justify its relatability in practice by enabling the symmetry arguments for training analysis; however, the encoding scheme raises serious questions. It is not clear how sensitive the results are to the specific structure of these encodings. Would natural alternatives (learned positional encodings, RoPE, etc.) support an analogous mechanism?
-
Fixing throughout training (Section 4) is a significant constraint (though commonly referred to in literature). It pre-encodes the output structure (the label and positional components are automatically passed through), which makes the model do less work than a real transformer, where must also be learned.
-
The training distribution requires uniform on the sphere, labels satisfying for , and specific rotation and sign symmetries. This is quite restrictive. The condition covers the case where labels are i.i.d. uniform independent of features: arguably a setting where -NN prediction is nearly vacuous (the label of is independent of its neighbors).
-
The construction and following arguments of the paper hinge on the binary classification problem, with little discussion regarding generalizability towards a multi-class setup.
Questions
- The value seems to emerge from the geometry of the unit sphere. Is this ratio stable, in the sense that if the data lived on a sphere of radius or were drawn from a different distribution, would the critical ratio change correspondingly? How generalizable is the approach?
- The training objective supervises the full target vector . This includes the positional component, which encodes which neighbor was selected. At test time, this target vector is not available, and the model must generate it autoregressively. How does the training objective guarantee that the positional component learned during training generalizes to the autoregressive rollout?
- Figure 2 shows that the learned converges to the theoretical construction. Does the joint training converge at the same rate as fixed- training?
- Can the authors comment on the tightness/lower bound on the CoT steps required (as in Theorem 3.1: )?
Limitations
The paper does a good job of pointing out technical limitations throughout the discussion.
Final justification
Based on the author's responses to my questions and taking into consideration other discussions, the merit of the paper outweighs the concerns raised. Hence, I stand by my initial score.
Formatting concerns
There are no immediate formatting lapses.
3 comments
Rebuttal
Thank you for the careful review. Below, we address your concerns regarding the weaknesses and provide detailed answers to your questions.
W1. Stochastic positional encodings are non-standard. Sensitivity to these encodings? Alternatives?
A1. Thanks for the comment. Below we clarify the motivation for using the stochastic positional encodings and discuss potential alternatives.
- Our use of stochastic positional encodings follows [1-2]. Specifically, [1] introduces stochastic positional encodings as an alternative to fixed absolute positional encodings, which may generalize poorly to unseen sequence lengths. More closely related to our setting, [2] theoretically analyzes the training dynamics of one-layer Transformers with near-orthogonal stochastic positional encodings.
- A key observation in [2] is that stochastic positional encoding improves length generalization while inducing distributional symmetry that simplifies the characterization of gradient-descent trajectories. Our analysis builds on the same principle: randomness in the positional encodings induces a signed-permutation symmetry in the positional block, allowing us to show in Appendix E.2 that gradient descent remains confined to a low-dimensional invariant manifold.
- Our expressive power guarantees (Theorem 3.1, Proposition 3.2) can be directly extended to any mutually orthogonal positional encodings, since the proof primarily uses orthogonality and is otherwise unchanged. However, the training-dynamics result is more restrictive: Appendix E.2 relies on the signed-permutation symmetry of stochastic positional encodings to reduce the dynamics to a few scalar variables. This symmetry is generally absent for fixed, learned, and rotary encodings, so extending the training guarantee would require different proof techniques.
W2. Fixing is a limitation.
A2. Fixing throughout training is indeed a limitation of our theoretical analysis. Nevertheless, it is a standard simplification in the literature on Transformer training dynamics [3–6], commonly used to isolate the learning dynamics of attention.
We would like to point out that the mechanism underlying CoT reasoning identified in our work is governed primarily by . The positive amplifies similarity differences and selects the nearest context point, while the negative coefficient penalizes previously selected tokens, effectively acting as a learned mask. Thus, fixing preserves the central learning problem: gradient descent must recover the invariant structure of , drive and , and establish the limiting ratio required to balance nearest-neighbor selection against suppression of previously retrieved points. Characterizing these coupled dynamics remains highly nontrivial.
We also provide experiments (Appendix F) in which and are jointly trained from random initialization. The model still develops the predicted parameter structure and achieves high CoT -NN accuracy, suggesting that fixing is primarily an analytical device rather than an empirical requirement. Extending the theory to jointly learned and would require analyzing a more complex coupled matrix dynamical system, which we leave for future work.
W3. training distribution is restrictive, covering i.i.d. uniform labels independent of features where -NN prediction is nearly vacuous
A3. These training assumptions are adapted from [4], which studies the in-context 1-NN problem, and also covers the setting of i.i.d. uniform labels independent of features.
We would like to clarify that -NN prediction is not vacuous in this setting. Even when and are independent, the context dataset they form still gives a well-defined -NN prediction task, as the -NN predictor relies on feature proximity, rather than label-feature correlations, to make predictions.
In fact, this special case where and are independent is useful for isolating the learning of a clean nearest-neighbor prediction rule. If the data contain more complex feature-label dependencies, the Transformer may reduce the population loss by exploiting those dependencies directly rather than learning pure nearest-neighbor retrieval. For example, it may learn a mixture of in-context regression and in-context nearest-neighbor prediction. Such behavior may be practically meaningful, but it would make the specific CoT retrieval mechanism studied here more difficult and less clean. We believe this is the main reason why previous work [4] and our work both cover such settings.
We will add more discussion in the revision.
W4. Extensions to a multi-class setup?
A4. We agree that extending our analysis to multi-class classification is an important direction. The binary-label setting is not essential to the CoT expressivity results in Theorem 3.1 and Proposition 3.2. For a -class problem, can be replaced by a one-hot encoding , with the label block adjusted accordingly. Then, Theorem 3.1 and Proposition 3.2 still hold with , . Since neighbor selection depends primarily on the feature and positional blocks, the attention mechanism remains unchanged. After steps, the accumulated label state yields the standard plurality-vote -NN prediction through its largest coordinate.
Extending the training-dynamics theorem requires additional work, as the binary sign-flip symmetry must be replaced by class-permutation symmetry and the reduced dynamics rederived for vector-valued labels. We will discuss this multi-class extension in the revision.
Q1. Does the value emerge from the unit sphere setting? If the data lived on a sphere of radius or were drawn from a different distribution, would the ratio change? How generalizable is the approach?
A5. You are right that emerges from the geometry of the unit sphere. Our analysis can be directly extended to the case when all inputs lie on a sphere of radius , and we can expect the same argument to give the critical ratio . We also expect the analysis to extend approximately to high-dimensional isotropic Gaussian data, whose norms concentrate around a common value. After appropriate rescaling, concentration bounds and perturbation analysis may recover the spherical threshold. For more general distributions, however, the critical ratio may depend on additional geometric properties and may not reduce to a single universal ratio. A rigorous treatment is left for future work.
Q2. How does the training objective guarantee that the positional component learned during training generalizes to the autoregressive rollout?
A6. The guarantee follows from the parameter structure recovered by gradient descent. Theorem 4.2 shows training yields , where and . This structure implements an attention rule that selects the context vector of the nearest unselected neighbor, including its positional component.
At test time, given the initial input embedding matrix, the first step identifies through attention and selects its entire context vector; the generated state is then used to select the vector corresponding to , and this process continues autoregressively. Thus, neither the target vector nor the indices are required to be known at test time. Lemma 3.3 formalizes this autoregressive rollout using the model’s own generated states.
Q3. Does the joint training converge at the same rate as fixed- training?
A7. The following table reports the training losses after 10000 iterations for joint training and fixed- training under the same experimental setup as in the paper.
| Joint Train | 0.084868 | 0.105870 | 0.135849 | 0.161082 |
| Fixed Train | 0.069993 | 0.078814 | 0.117389 | 0.139270 |
Joint training consistently gives slightly higher training loss than fixed- training under the same setup, suggesting slightly slower convergence. Intuitively, fixed- training starts from the correct value-projection structure, whereas joint training must first identify the appropriate pattern of while optimizing . After approaches the theoretical construction, the subsequent optimization behavior becomes similar to the fixed- case.
Q4. Tightness/lower bound on the CoT steps?
A8. Proposition 2.2 provides a weak lower bound: for odd , the one-layer transformer considered in our paper cannot uniformly solve -NN through direct single-pass inference. Thus, zero CoT steps are insufficient in this setting.
To our knowledge, a general lower bound on the CoT length is currently unknown. Determining whether is tight, or whether a different CoT mechanism can achieve sublinear reasoning length, is an interesting direction for future work.
References:
[1] Positional description matters for transformers arithmetic. ArXiv 2023
[2] Transformers Provably Learn Sparse Token Selection While Fully-Connected Nets Cannot. ICML 2024
[3] Multi-head Transformers Provably Learn Symbolic Multi-step Reasoning via Gradient Descent. NeurIPS 2025
[4] One-Layer Transformer Provably Learns One-Nearest Neighbor In Context. NeurIPS 2024
[5] Can Looped Transformers Learn to Implement Multi-step Gradient Descent for In-context Learning? ICML 2024
[6] How transformers learn diverse attention correlations in masked vision pretraining. ICML 2024 Workshop
I thank the authors for the detailed response. Based on the rebuttal, discussions from the other reviews, and my initial evaluation, I stand by my score. The added experimental results are very much appreciated.
Thank you for your support and for taking the time to respond to our rebuttal. We also greatly appreciate your positive assessment of the additional experimental results. We sincerely value the time and effort you have devoted to reviewing our work and engaging in the discussion.
- Rating
- 4/6
- Confidence
- 4/5
- Quality
- 3/4
- Clarity
- 3/4
- Significance
- 2/4
- Originality
- 3/4
- Contribution type
- theory
- Ethical concerns
- NO or VERY MINOR ethics concerns only
Read review
Summary
This work studies one-layer Transformers in learning In-context K nearest neighbors by Chain-of-Thought. The authors show that one-layer Transformers can be constructed to solve KNN problems by CoT, while without CoT, they cannot. The authors also provide a convergence analysis of the population loss for one-layer Transformers trained by gradient descent. Experiments are conducted to verify the consistency between the construction and the convergence analysis.
Strengths and weaknesses
Strengths:
-
The theoretical analysis is solid and impressive. The studied problem is a reasonable extension from 1-NN using ICL to K-NN using CoT.
-
The paper is easy to follow and well-organized, from expressive power to convergence analysis. Figure 1 (b) verifies the constructed Transformer, which bridges the gap between the two parts of the analysis.
Weaknesses:
-
The experiments are only for one-layer Transformers together with the theoretical analysis. It may restrict the significance of this work.
-
The setting of the stochastic positional encoding looks strange and requires motivation and explanation. I have a similar concern for the training based on the first-step target supervision.
-
The convergence analysis only deals with limiting cases without a characterization of the required number of iterations.
Please see Questions for more details.
Questions
-
Can your theoretical analysis be extended to multi-layer or multi-head Transformers?
-
What happens if you use multi-layer or multi-head Transformers for training empirically? Will the results be different?
-
Why do you consider stochastic positional encodings, which may differ between different training iterations if my understanding is correct (line 103)? Is there any existing theoretical work or practical setting that uses this formulation?
-
The convergence analysis only characterizes when . Can you characterize the required number of iterations or the convergence rate?
-
The authors seem to treat the supervision on the first-step target state vector (lines 66 and 205) as a contribution. However, how is it motivated by practice or existing works? I know in practice people may use the LAST-step as supervision, like the CoT-I in https://arxiv.org/pdf/2305.18869. This is somehow more reasonable since people care about the final output of reasoning. In your problem setting, the task will become whether we can learn the -th nearest neighbor by learning the list of the first nearest neighbors. Can your analysis be extended to consider the last-step supervision?
-
Can ICL learn K-NN empirically? Can you discuss the comparison between ICL and CoT in your problem setting empirically and theoretically?
Limitations
Yes.
Final justification
After the rebuttal, I think most of the concerns have been addressed. Although I still think supervising the first-step outcome for K-NN task is a little strange, I agree that this work has an additional theoretical contribution compared to [1], and this work especially characterizes the mechanism of selecting the relevant token and masking previously selected tokens. Therefore, I have increased my rating to 4.
[1] One-Layer Transformer Provably Learns One-Nearest Neighbor In Context. NeurIPS 2024
Formatting concerns
N/A
4 comments
Rebuttal
Thank you for your thoughtful feedback, and we sincerely appreciate your comments.
W1&Q1&Q2. Only one-layer Transformers. Extensions to multi-layer or multi-head Transformers and empirical results?
A1. We acknowledge that focusing on the one-layer case is a limitation of the present work.
Nevertheless, most existing training-theoretic studies of CoT reasoning [3–5] and in-context 1-NN prediction [6] also focus on one-layer Transformer architectures. As our work builds directly on these two lines of research and establishes a direct comparison with [6] in Proposition 2.2, we consider the one-layer softmax Transformer a natural and well-motivated setting for isolating the mechanism studied here.
Moreover, from an expressivity perspective, the extension to multi-layer or multi-head Transformers is immediate. A multi-layer, multi-head Transformer can reproduce our one-layer, one-head construction by using a single layer and a single head to implement the proposed mechanism while setting the remaining components to be inactive. Therefore, our positive expressivity result continues to hold for these richer architectures.
Extending the training-dynamics analysis is beyond the scope of the current proof. In a multi-head Transformer, different heads may interact or specialize in different functions. In a multi-layer Transformer, each layer transforms the representations passed to subsequent layers, introducing additional dependencies across layers. These interactions are not captured by our current analysis and would require different proof techniques.
While extending the training analysis to more practical architectures is an important direction, we believe that the present contribution should be assessed in the context of comparable theoretical studies on the training dynamics of Transformers, most of which likewise focus on the one-layer setting [3-6].
Regarding experiments, we conduct experiments with , , replacing the single-head, single-layer Transformer with either a four-head, one-layer model or a single-head, two-layer model. Both variants are successfully optimized, exhibiting substantial decreases in training loss and achieving high test accuracy across different values of . These results suggest that both multi-head and multi-layer Transformers can learn the proposed sequential -NN mechanism, indicating that our theoretical setting captures key aspects of more diverse architectures.
| Model | Training loss, 2k | Training loss, 4k | Training loss, 6k | Training loss, 8k | Training loss, 10k | Test acc. | Test acc. | Test acc. |
|---|---|---|---|---|---|---|---|---|
| 4-head, 1-layer | 0.14465 | 0.10737 | 0.09930 | 0.08658 | 0.08927 | 100.0 | 99.7 | 98.2 |
| 1-head, 2-layer | 0.23258 | 0.15614 | 0.15273 | 0.14034 | 0.15023 | 100.0 | 99.1 | 92.8 |
W2&Q3&Q5. stochastic positional encoding? existing theoretical work or practical setting using it? First-step target supervision? How about last-step supervision [7]?
A2. Thank you for these thoughtful questions. We address them in detail as follows.
-
stochastic positional encoding:
- Our use of stochastic positional encodings follows [1-2]. Specifically, [1] introduces stochastic positional encodings as an alternative to fixed absolute positional encodings, which may generalize poorly to unseen sequence lengths. More closely related to our setting, [2] theoretically analyzes the training dynamics of one-layer Transformers with near-orthogonal stochastic positional encodings.
- A key observation in [2] is that stochastic positional encoding improves length generalization while inducing distributional symmetry that simplifies the characterization of gradient-descent trajectories. Our analysis builds on the same principle: randomness in the positional encodings induces a signed-permutation symmetry in the positional block, allowing us to show in Appendix E.2 that gradient descent remains confined to a low-dimensional invariant manifold.
- Our expressive power guarantees (Theorem 3.1, Proposition 3.2) can be directly extended to any mutually orthogonal positional encodings. However, our training analysis relies on the signed-permutation symmetry of stochastic positional encodings used in Appendix E.2; without this symmetry, an analogous guarantee would require a substantially different analysis of the full positional block. We will clarify this distinction in the revision.
-
first-step target supervision: The motivation for considering first-step target supervision is two-fold:
- First, our work directly extends [6], which shows that a one-layer Transformer without CoT can be trained to perform 1-NN. The setting of first-step target supervision essentially also directly teaches the model to perform 1-NN retrieval, and therefore makes our setting more comparable with [6].
- Second, prior theoretical studies of one-layer Transformers with CoT [3–5] typically supervise multiple intermediate states through teacher forcing, and multi-step supervision essentially provides repeated examples of a shared transition rule. We observe that such supervision may help optimization analysis, but may not be necessary to identify the rule itself. Our result shows that, for -NN, supervising only the first target state is sufficient to learn a mechanism that can be applied autoregressively over multiple steps. We view this result as a theoretically interesting observation.
-
last-step supervision:
- We also thank the reviewer for suggesting the practically relevant alternative of last-step supervision [7], which is more directly aligned with the final prediction objective. We will cite and discuss [7] in the revision. In our setting, given , the model would similarly be trained to predict , effectively identifying the -th nearest neighbor after excluding the first . This relies on the same mechanism as our current analysis—feature similarity ranks the context points, while the accumulated positional state suppresses previously selected neighbors. We therefore expect that a similar analysis may yield an analogous reduced parameterization of , although a formal proof requires additional work.
W3&Q4. No characterization of the required number of iterations.
A3. You are right that Theorem 4.2 is asymptotic and does not provide an explicit iteration-complexity bound. This asymptotic formulation enables a clean characterization of the limiting parameter regime selected by gradient descent.
Several key steps in the proof rely on qualitative arguments that do not yield finite-time estimates. Specifically, Appendix E.3 establishes the divergence of and through contradiction and compactness arguments, while Appendices E.5-E.6 prove the convergence of to 2 using asymptotic drift and crossing arguments (see also the proof sketch in Section 5). We believe that these two key steps are technically challenging, and our current proof techniques for the asymptotic results are already highly involved. Extending these results to the non-asymptotic regime would require additional theoretical tools and an even more complex proof.
We will revise the paper to clarify that Theorem 4.2 provides an asymptotic characterization of the recovery of the sharp-attention CoT regime and does not establish a finite-time optimization guarantee.
Q6. Can ICL learn K-NN empirically? Comparison between ICL and CoT, empirically and theoretically?
A4. We thank the reviewer for this question. We clarify that both settings studied in our paper are forms of in-context learning: at test time, the model receives labeled context examples and a query and predicts without parameter updates. The relevant distinction is between direct-answer ICL, which predicts in a single forward pass, and CoT-augmented ICL, which autoregressively generates intermediate states before producing the final prediction.
Theoretically, Proposition 2.2 shows that direct-answer ICL cannot uniformly implement odd- NN over the well-separated class : for any fixed finite parameter setting, there exists an input on which it fails. In contrast, Theorem 3.1 and Proposition 3.2 show that the same one-layer architecture can implement -NN using CoT steps.
Empirically, we remove CoT supervision and train the Transformer to predict the final state in a single forward pass. Across all evaluated configurations, the training loss remains approximately between and and shows no consistent decrease over steps. Under the same experimental protocol, the direct-answer model therefore fails to learn the -NN target, whereas the CoT-augmented model converges successfully, consistent with our theoretical separation.
| Step 2000 | Step 4000 | Step 6000 | Step 8000 | Step 10000 | |
|---|---|---|---|---|---|
| 1.617138 | 1.692581 | 1.674053 | 1.630763 | 1.663558 | |
| 1.682409 | 1.700712 | 1.695117 | 1.743311 | 1.677553 | |
| 1.670989 | 1.703986 | 1.705789 | 1.753437 | 1.736894 | |
| 1.766365 | 1.745283 | 1.713068 | 1.766397 | 1.754815 |
References:
[1] Positional description matters for transformers arithmetic. ArXiv 2023
[2] Transformers Provably Learn Sparse Token Selection While Fully-Connected Nets Cannot. ICML 2024
[3] Transformers Learn to Implement Multi-step Gradient Descent with Chain of Thought. ICLR 2025
[4] Transformers Provably Learn Chain-of-Thought Reasoning with Length Generalization. NeurIPS 2025
[5] Multi-head Transformers Provably Learn Symbolic Multi-step Reasoning via Gradient Descent. NeurIPS 2025
[6] One-Layer Transformer Provably Learns One-Nearest Neighbor In Context. NeurIPS 2024
[7] Dissecting Chain-of-Thought: Compositionality through In-Context Filtering and Learning. NeurIPS 2023
Dear Reviewer ffVj,
We sincerely appreciate the time and effort you have devoted to reviewing our work. As the discussion period is ending in less than one day, we would like to take this opportunity to follow up on our responses and ensure that we have adequately addressed your comments and concerns. If any points remain unclear or require further explanation, we will try our best to provide additional clarification.
In addition, we would like to present some additional experiments conducted during the discussion period in response to Reviewer USTL’s follow-up questions, as these experiments provide a further complement to our responses A1 and A4 to your comments and questions.
These additional experiments are designed to further evaluate the performance of models with multiple heads or multiple layers, and to compare direct-inference models with CoT models. Specifically, for and , we train a separate direct-inference baseline for each for iterations. During training, each model receives only the initial input and is supervised to predict the final -NN target state directly in a single forward pass.
At inference time, each trained direct-inference model performs only a single forward pass on the initial input, without intermediate-state generation or autoregressive rollout. We evaluate each direct model on the test task corresponding to the value of for which it was trained. In addition, for the models trained with and , we also evaluate their predictions on the test set. This additional evaluation allows us to examine whether models trained for larger nevertheless retain behavior close to -NN prediction.
We summarize the new experiments and compare them with the CoT results in the following table.
| Model | Training setup | Inference | Test acc. | Test acc. | Test acc. |
|---|---|---|---|---|---|
| 4-head, 1-layer | CoT | CoT rollout | 100.0 | 99.7 | 98.2 |
| 4-head, 1-layer | Direct model trained for | Single-pass | 100.0 | ||
| 4-head, 1-layer | Direct model trained for | Single-pass | 100.0 | 75.1 | |
| 4-head, 1-layer | Direct model trained for | Single-pass | 99.9 | 68.5 | |
| 1-head, 2-layer | CoT | CoT rollout | 100.0 | 99.1 | 92.8 |
| 1-head, 2-layer | Direct model trained for | Single-pass | 100.0 | ||
| 1-head, 2-layer | Direct model trained for | Single-pass | 100.0 | 74.7 | |
| 1-head, 2-layer | Direct model trained for | Single-pass | 97.9 | 69.2 | |
| 1-head, 1-layer | CoT | CoT rollout | 100.0 | 99.8 | 98.3 |
| 1-head, 1-layer | Direct model trained for | Single-pass | 100.0 | ||
| 1-head, 1-layer | Direct model trained for | Single-pass | 100.0 | 74.7 | |
| 1-head, 1-layer | Direct model trained for | Single-pass | 99.6 | 68.8 |
Based on these experiments, we have several observations:
First, direct-inference learning of -NN remains difficult even with additional heads or layers: the direct models solve -NN well, but their accuracies remain far below those of the CoT models for and .
Second, the training of direct-inference models converges toward suboptimal -NN-like solutions. Specifically, these models achieve nearly perfect -NN accuracy but low -NN and -NN accuracies, even when supervised by -NN or -NN prediction rules. Since we use i.i.d. labels in the experiments, we can verify that the theoretical accuracies of a -NN predictor on the -NN and -NN prediction tasks are and , respectively. These values are close to our experimental results and explain the test accuracies achieved by the direct-inference models on the -NN and -NN tasks.
These results suggest that, during training, direct-inference models with additional heads or layers may continue to attend to the same context data point rather than retrieve multiple distinct neighbors. In contrast, CoT not only provides a natural sequential mechanism for the models to express -NN prediction rules, but also helps training successfully converge to such predictors. These results are consistent with both our expressive-power results and our training guarantees.
We find these additional experimental results particularly informative and will include them, together with a more detailed discussion, in the revised manuscript. For further details, please also refer to our discussion with Reviewer USTL.
Thank you again for your time and consideration.
Best regards,
Authors of Submission 30429
Thank you for your response. Most of my concerns have been addressed. The additional experiments look great. Regarding stochastic positional encoding, it makes sense to list several existing works as the motivation for the formulation. However, only some papers consider this. Is it because the problem or the task itself is a good fit for stochastic positional encoding? Moreover, I still think using first-step supervision is strange. From the training objective, we only have the first-step outcome, and never appears, but the target is to learn the -th nearest neighbors. If training with the first-step outcome is enough for K-NN inference, does it mean that one can also use ICL to learn 1-NN and then recursively implement the inference for times to find the -th nearest neighbor? If so, the theoretical contribution is weakened, since you are learning 1-NN, which is the same as the existing work on 1-NN.
Thank you for confirming that most of your concerns have been addressed. Below we answer your follow-up questions.
Q1. Is it because the problem or the task itself is a good fit for stochastic positional encoding?
A1. We do not view stochastic positional encoding as an intrinsic requirement of -NN. As we mentioned, our expressive power guarantees can be directly extended to any mutually orthogonal positional encodings.
However, we do believe that stochastic positional encoding is a good fit for our problem. Stochasticity in the positional encodings induces a signed-permutation symmetry in the positional block. As shown in Appendix E.2, this symmetry ensures that gradient descent remains confined to a low-dimensional invariant manifold, thereby making the training dynamics tractable.
Q2. I still think using first-step supervision is strange. From the training objective, we only have the first-step outcome, and never appears, but the target is to learn the -th nearest neighbors. One can also use ICL to learn -NN and then recursively implement the inference for times to find the -th nearest neighbor? If so, the theoretical contribution is weakened, since you are learning 1-NN, which is the same as the existing work on 1-NN.
A2. We believe this is a misunderstanding.
1. We would like to clarify that our setting is indeed an ICL task. In our formulation, CoT serves as an explicit mechanism for carrying out multi-step in-context inference. Therefore, we do not view the CoT formulation as separate from ICL.
2. “Using the models to learn -NN target-state prediction and then recursively implementing the inference times can identify the -th nearest neighbor” is precisely one of our key findings. Therefore, this observation itself constitutes part of our contribution, rather than a reason to discount our contribution.
More specifically, our work highlights an interesting phenomenon: supervising the model to perform -NN target-state prediction suffices to ensure that the trained model implements -NN with CoT. We do not claim that one-step supervision is universally sufficient for CoT, but we believe it is useful to give a concrete theoretical demonstration of the existence of such behavior in certain settings.
3. We want to clarify that our finding in 2. does not weaken our theoretical contribution. Our setting is different from existing work on 1-NN [1], and the results in [1] cannot naturally imply that autoregressive implementations of the model performs -NN:
-
A key difference from [1] in the problem setting is that we supervise the target state vector , rather than only the scalar target . This is crucial for implementing the CoT process: in addition to predicting the correct nearest-neighbor label, the model must also learn the correct positional component, which is needed to penalize neighbors selected in earlier reasoning steps. Moreover, we consider the initialization , while [1] requires that one of the entries in is initialized with a small enough negative value. These differences make our analysis more challenging.
-
More importantly, our work introduces a sequential mechanism that reformulates the conventionally non-sequential -NN task as a sequential procedure, thereby enabling CoT-based prediction. This is clearly not covered in the study of 1-NN in [1].
-
From a technical perspective, demonstrating that transformers can perform -NN requires showing that softmax attention can simultaneously implement two coupled mechanisms: selecting the relevant token and masking previously selected tokens. This differs substantially from the -NN task, which primarily requires only the nearest-neighbor selection mechanism.
-
Our proof shows that the training dynamics remain on the invariant manifold , where drives selection of the nearest context point, while penalizes previously selected tokens and hence implements a learned mask. A key novelty of our analysis is to prove the coupled asymptotic behavior of these two coefficients: and , together with a precise characterization of their limiting ratio. This joint characterization is essential for showing that CoT implements -NN, and notably, the results in [1] are not sufficient to show this.
-
We prove the divergence of using contradiction and compactness arguments, and then establish the limiting ratio between them via drift and crossing arguments. These proof techniques are novel and not covered in [1] either.
We hope that our clarification above addresses your concerns. Thank you for your careful reading and helpful feedback.
[1] One-Layer Transformer Provably Learns One-Nearest Neighbor In Context. NeurIPS 2024
From OpenReview, CC BY 4.0. Authors as signed there; shown unedited.
Loading the discussion…
Dear AC,
Thank you for your effort in handling our paper. We have posted our rebuttal responses.
We understand the concerns regarding our single-layer, fixed-V setting. But we note that this is a common setting in theoretical studies [3,4,8].
Even in this setting, the study of K-NN via CoT remains highly nontrivial. We develop novel proof techniques, including contradiction and compactness arguments for proving parameter divergence without closed-form GD updates, and asymptotic drift/crossing arguments for characterizing limiting ratios among diverging parameters. To our knowledge, these technical tools are unique in the literature.
While we agree that more general settings are important future directions, we sincerely hope that our work can be evaluated based on its technical novelty and within the context of comparable theoretical studies.
Below we briefly summarize our response to the six prioritized points.
We believe that our responses have clarified the reviewers’ concerns, and we are happy to provide further clarification during the discussion period.
[1] Transformers Learn to Implement Multi-step Gradient Descent with Chain of Thought. ICLR 2025
[2] Transformers Provably Learn Chain-of-Thought Reasoning with Length Generalization. NeurIPS 2025
[3] Multi-head Transformers Provably Learn Symbolic Multi-step Reasoning via Gradient Descent. NeurIPS 2025
[4] One-Layer Transformer Provably Learns One-Nearest Neighbor In Context. NeurIPS 2024
[5] Positional description matters for transformers arithmetic. ArXiv 2023
[6] Transformers Provably Learn Sparse Token Selection While Fully-Connected Nets Cannot. ICML 2024
[7] Can Looped Transformers Learn to Implement Multi-step Gradient Descent for In-context Learning? ICML 2024
[8] How transformers learn diverse attention correlations in masked vision pretraining. ICML 2024 Workshop