acceptodds
Published as a conference paper at NeurIPS 2026

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 Li2024One 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.

Keywords:
Sydney

Reviews

Among:
Shape:
123456this paper, Bottom 4%
Figure 1. Mean review rating of the reviewed papers at NeurIPS 2026. This paper averages 3.67 over 3 reviews, above 4% of the others.
Reviewer_USTLOpenReview ↗
Rating
3
Clarity
4
Confidence
3
Originality
2
Quality
3
Significance
3
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

Paper formatting concerns

Na

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 kk-NN.

  • Regarding the discussion on kk-NN, I find it difficult to believe that scaling up the model does not help in learning kk-NN for larger values of kk 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 kk-NN.

1 comment

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, KK-NN is conventionally formulated as a direct top-KK retrieval-and-aggregation rule rather than as an iterative process. Our work identifies a non-obvious sequential realization of KK-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 KK-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 W(t)=diag⁡(α(t)Id,0,β(t)IN+1)W^{(t)}=\operatorname{diag}(\alpha^{(t)}I_d,0,\beta^{(t)}I_{N+1}). After this reduction, the parameters do not converge to finite values: Appendix E.3 proves α(t)→+∞\alpha^{(t)}\to+\infty and β(t)→−∞\beta^{(t)}\to-\infty through contradiction and compactness arguments, while Appendices E.5-E.6 prove that their relative scale converges, −β(t)/α(t)→2-\beta^{(t)}/\alpha^{(t)}\to2, 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 N=40N=40, d=10d=10, 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 KK. These results suggest that both multi-head and multi-layer Transformers can learn the proposed sequential KK-NN mechanism, indicating that the mechanism is not empirically restricted to the one-layer architecture analyzed in the paper.

ModelTraining loss, 2kTraining loss, 4kTraining loss, 6kTraining loss, 8kTraining loss, 10kTest acc. K=1K=1Test acc. K=3K=3Test acc. K=5K=5
4-head, 1-layer0.144650.107370.099300.086580.08927100.099.798.2
1-head, 2-layer0.232580.156140.152730.140340.15023100.099.192.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

Reviewer_RhHpOpenReview ↗
Rating
4
Clarity
3
Confidence
4
Originality
3
Quality
3
Significance
3
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 KK-nearest-neighbor (KK-NN) (binary) classification. In the process, it constructs a negative result showing that direct inference by a one-layer transformer fails for odd K>1K > 1 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 λ\lambda 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 K>1K > 1.

[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 VV 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 VV must also be learned.

  • The training distribution requires xi,xqx_i, x_q uniform on the sphere, labels satisfying E[yiyj∣x1:q]=0\mathbb{E}[y_i y_j | x_{1:q}] = 0 for i≠ji \neq j, and specific rotation and sign symmetries. This is quite restrictive. The condition covers the case where labels are i.i.d. uniform ±1±1 independent of features: arguably a setting where KK-NN prediction is nearly vacuous (the label of xqx_q 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 −2−2 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 r≠1r \neq 1 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 (xq⊤,yπ(1),pN+1⊤+pπ(1)⊤)⊤(x_q^\top, y_{\pi(1)}, p_{N+1}^\top + p_{\pi(1)}^\top)^\top. 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 VV converges to the theoretical construction. Does the joint training converge at the same rate as fixed-VV training?
  • Can the authors comment on the tightness/lower bound on the CoT steps required (as in Theorem 3.1: K−1K-1)?
Limitations

The paper does a good job of pointing out technical limitations throughout the discussion.

Paper formatting concerns

There are no immediate formatting lapses.

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.

1 comment

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 VV is a limitation.

A2. Fixing VV 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 W(t)=diag⁡(α(t)I,0,β(t)I)W^{(t)}=\operatorname{diag}(\alpha^{(t)}I,0,\beta^{(t)}I). The positive α(t)\alpha^{(t)} amplifies similarity differences and selects the nearest context point, while the negative coefficient β(t)\beta^{(t)} penalizes previously selected tokens, effectively acting as a learned mask. Thus, fixing VV preserves the central learning problem: gradient descent must recover the invariant structure of WW, drive α(t)→∞\alpha^{(t)}\to\infty and β(t)→−∞\beta^{(t)}\to-\infty, and establish the limiting ratio β(t)/α(t)→−2\beta^{(t)}/\alpha^{(t)}\to-2 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 WW and VV are jointly trained from random initialization. The model still develops the predicted parameter structure and achieves high CoT KK-NN accuracy, suggesting that fixing VV is primarily an analytical device rather than an empirical requirement. Extending the theory to jointly learned WW and VV 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 ±1\pm 1 labels independent of features where KK-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 ±1\pm 1 labels independent of features.

We would like to clarify that KK-NN prediction is not vacuous in this setting. Even when xix_i and yiy_i are independent, the context dataset they form still gives a well-defined KK-NN prediction task, as the KK-NN predictor relies on feature proximity, rather than label-feature correlations, to make predictions.

In fact, this special case where xix_i and yiy_i 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 CC-class problem, yi∈±1y_i \in \\{\pm1\\} can be replaced by a one-hot encoding eyi∈RCe_{y_i} \in \mathbb{R}^C, with the label block adjusted accordingly. Then, Theorem 3.1 and Proposition 3.2 still hold with V=diag⁡(0d×d,IC,IN+1)V=\operatorname{diag}(0_{d\times d},I_{C},I_{N+1}), W=diag⁡(αId,0C×C,βIN+1)W=\operatorname{diag}(\alpha I_d,0_{C\times C},\beta I_{N+1}). Since neighbor selection depends primarily on the feature and positional blocks, the attention mechanism remains unchanged. After KK steps, the accumulated label state ∑k=1Keyπ(k)\sum_{k=1}^{K} e_{y_{\pi(k)}} yields the standard plurality-vote KK-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 22 emerge from the unit sphere setting? If the data lived on a sphere of radius r≠1r\neq 1 or were drawn from a different distribution, would the ratio change? How generalizable is the approach?

A5. You are right that 22 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 rr, and we can expect the same argument to give the critical ratio 2r22r^2. 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 W(t)=diag⁡(α(t)Id,0,β(t)IN+1)W^{(t)}=\operatorname{diag}(\alpha^{(t)}I_d,0,\beta^{(t)}I_{N+1}), where α(t)→∞\alpha^{(t)}\to\infty and β(t)/α(t)→−2\beta^{(t)}/\alpha^{(t)}\to-2. This structure implements an attention rule that selects the context vector (xπ(k)⊤,yπ(k),pπ(k)⊤)⊤(x_{\pi(k)}^\top,y_{\pi(k)},p_{\pi(k)}^\top)^\top of the nearest unselected neighbor, including its positional component.

At test time, given the initial input embedding matrix, the first step identifies π(1)\pi(1) through attention and selects its entire context vector; the generated state is then used to select the vector corresponding to π(2)\pi(2), and this process continues autoregressively. Thus, neither the target vector nor the indices π(k)\pi(k) 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-VV training?

A7. The following table reports the training losses after 10000 iterations for joint W,VW,V training and fixed-VV training under the same experimental setup as in the paper.

(N,d)(N,d)(20,5)(20,5)(20,10)(20,10)(40,10)(40,10)(40,20)(40,20)
Joint Train0.0848680.1058700.1358490.161082
Fixed Train0.0699930.0788140.1173890.139270

Joint training consistently gives slightly higher training loss than fixed-VV training under the same setup, suggesting slightly slower convergence. Intuitively, fixed-VV training starts from the correct value-projection structure, whereas joint training must first identify the appropriate pattern of VV while optimizing WW. After VV approaches the theoretical construction, the subsequent optimization behavior becomes similar to the fixed-VV case.

Q4. Tightness/lower bound on the CoT steps?

A8. Proposition 2.2 provides a weak lower bound: for odd K>1K>1, the one-layer transformer considered in our paper cannot uniformly solve KK-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 K−1K-1 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

Reviewer_ffVjOpenReview ↗
Rating
4
Clarity
3
Confidence
4
Originality
3
Quality
3
Significance
2
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:

  1. The theoretical analysis is solid and impressive. The studied problem is a reasonable extension from 1-NN using ICL to K-NN using CoT.

  2. 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:

  1. The experiments are only for one-layer Transformers together with the theoretical analysis. It may restrict the significance of this work.

  2. 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.

  3. The convergence analysis only deals with limiting cases without a characterization of the required number of iterations.

Please see Questions for more details.

Questions
  1. Can your theoretical analysis be extended to multi-layer or multi-head Transformers?

  2. What happens if you use multi-layer or multi-head Transformers for training empirically? Will the results be different?

  3. 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?

  4. The convergence analysis only characterizes when t→∞t\rightarrow \infty. Can you characterize the required number of iterations or the convergence rate?

  5. 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 KK-th nearest neighbor by learning the list of the first KK nearest neighbors. Can your analysis be extended to consider the last-step supervision?

  6. Can ICL learn K-NN empirically? Can you discuss the comparison between ICL and CoT in your problem setting empirically and theoretically?

Limitations

Yes.

Paper formatting concerns

N/A

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

1 comment

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 N=40N=40, d=10d=10, 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 KK. These results suggest that both multi-head and multi-layer Transformers can learn the proposed sequential KK-NN mechanism, indicating that our theoretical setting captures key aspects of more diverse architectures.

ModelTraining loss, 2kTraining loss, 4kTraining loss, 6kTraining loss, 8kTraining loss, 10kTest acc. K=1K=1Test acc. K=3K=3Test acc. K=5K=5
4-head, 1-layer0.144650.107370.099300.086580.08927100.099.798.2
1-head, 2-layer0.232580.156140.152730.140340.15023100.099.192.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 KK-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 q(0),…,q(K−1)q^{(0)},\ldots,q^{(K-1)}, the model would similarly be trained to predict q(K)q^{(K)}, effectively identifying the KK-th nearest neighbor after excluding the first K−1K-1. 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 WW, 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 α(t)\alpha^{(t)} and β(t)\beta^{(t)} through contradiction and compactness arguments, while Appendices E.5-E.6 prove the convergence of λt=−β(t)/α(t)\lambda_t=-\beta^{(t)}/\alpha^{(t)} 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-KK NN over the well-separated class XγX_\gamma: 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 KK-NN using K−1K-1 CoT steps.

Empirically, we remove CoT supervision and train the Transformer to predict the final state q(K)=[xq⊤,∑i=1Kyπ(i),pN+1⊤+∑i=1Kpπ(i)⊤]⊤q^{(K)}=[x_q^\top,\sum_{i=1}^{K}y_{\pi(i)},p_{N+1}^\top+\sum_{i=1}^{K}p_{\pi(i)}^\top]^\top in a single forward pass. Across all evaluated configurations, the training loss remains approximately between 1.621.62 and 1.771.77 and shows no consistent decrease over 1000010000 steps. Under the same experimental protocol, the direct-answer model therefore fails to learn the KK-NN target, whereas the CoT-augmented model converges successfully, consistent with our theoretical separation.

(N,d)(N,d)Step 2000Step 4000Step 6000Step 8000Step 10000
(20,5)(20,5)1.6171381.6925811.6740531.6307631.663558
(20,10)(20,10)1.6824091.7007121.6951171.7433111.677553
(40,10)(40,10)1.6709891.7039861.7057891.7534371.736894
(40,20)(40,20)1.7663651.7452831.7130681.7663971.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

Comments on the paper

1 comment
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.

From OpenReview, CC BY 4.0. Authors as signed there; shown unedited.

Related papers

Loading the map…

Discussion (0)

Sign in to comment.