Training Dynamics of Transformers to Recognize Word Co-occurrence via Gradient Flow Analysis

Understanding the training dynamics of transformers is important to explain the impressive capabilities behind large language models. In this work, we study the dynamics of training a shallow transformer on a task of recognizing co-occurrence of two designated words. In the literature of studying training dynamics of transformers, several simplifications are commonly adopted such as weight reparameterization, attention linearization, special initialization, and lazy regime. In contrast, we analyze the gradient flow dynamics of simultaneously training three attention matrices and a linear MLP layer from random initialization, and provide a framework of analyzing such dynamics via a coupled dynamical system. We establish near minimum loss and characterize the attention model after training. We discover that gradient flow serves as an inherent mechanism that naturally divide the training process into two phases. In Phase 1, the linear MLP quickly aligns with the two target signals for correct classification, whereas the softmax attention remains almost unchanged. In Phase 2, the attention matrices and the MLP evolve jointly to enlarge the classification margin and reduce the loss to a near minimum value. Technically, we prove a novel property of the gradient flow, termed \textit{automatic balancing of gradients}, which enables the loss values of different samples to decrease almost at the same rate and further facilitates the proof of near minimum training loss. We also conduct experiments to verify our theoretical results.

Paper

Similar papers

Peer review

Reviewer cFaT6/10 · confidence 3/52024-07-11

Summary

This paper investigates the training dynamics of a single-layer transformer followed by a single MLP layer on a synthetic binary classification task, where the objective is to identify the co-occurrence of two specific tokens in the input sequence. They analyze the gradient flow dynamics for the case that all the attention parameters (key, query, value) and the linear layer all trainable and show that the model can achieve low loss despite the non-convexity of the objective. They identify two phases in the training, 1) the MLP aligns with the two target tokens at the start of the training and the model learns to classify all the samples correctly, 2) the attention and MLP parameters update to increase the classification margin and drive the loss to zero. They also run a small scale numerical experiment in their synthetic setup tp confirm their analysis.

Strengths

The paper makes no restricting assumptions on the weights of the transformer model and performs the analysis on the joint optimization of all the parameters. Although the paper and its proof are notation-heavy, the authors have broken down the complexity of the proof and notation in the main body to clarify the steps needed to prove the results.

Weaknesses

There are some restrictive assumptions on the synthetic data model: The vocabulary set $d$ is considered to be larger than the number of training tokens, which is not the case in realistic setups. Thus, some tokens are not visited at training time. Also, they assume, apart from the two target tokens, the remaining tokens appear at maximum once in the training set. The proof outline in the main body helps in understanding the high-level steps involved. However, it could still benefit from additional clarifications on some intermediate steps. For instance, in phases 1 and 2, it's mentioned how the alignment of the MLP with the target tokens $G^{(t)}(\mu_{1,2})$ behaves during training. However, it's not clear how this connects to the evolution of the attention scores in phase 2 as stated in Lemma 4.7.

Questions

1. As far as I understand, in your synthetic task, in the first phase of training, effectively only the MLP weights are learning the task. That is, the model can achieve 100% accuracy only by aligning the MLP weights with the relevant tokens $\mu_1,\mu_2$. So, the attention layer is not needed for identifying the co-occurrence of the tokens in this setup? 2. Can you also report validation and accuracy plots in your synthetic experiments? Does the validation loss decay at the same rate as the training loss as stated in Thm 3.3? 3. Regarding the proof sketch: a) The alignment of parameters with the target tokens is discussed in the main body. Can you also clarify how the gradients related to irrelevant tokens evolve? In particular, regarding the tokens that do not appear in the training set (since $nL\leq d$), does the model learn not to attend to them at test time? b) I find it confusing that the softmax output remains close to $1/L$ long in the training (line 320) and assigns uniform attention to all tokens in the sequence. Does this statement hold for all training samples? If yes, then how does the model learn to attend to the target tokens?

Rating

6

Confidence

3

Soundness

3

Presentation

3

Contribution

3

Limitations

Yes

Reviewer ritc6/10 · confidence 3/52024-07-12

Summary

This paper studies the training dynamics of a single hidden layer transformer network (self-attention + linear MLP) trained on a binary word cooccurrence task. Specifically, given a data matrix $X \in R^{d \times L}$ representing L "words" (each column of X is a word vector of dimension d), the model must output +1 if words 1 and 2 both occur in X, and -1 otherwise. The paper shows that a transformer layer is able to learn this task, and that the training occurs in two stages: First, the linear MLP layer learns to classify data points correctly by positively aligning with the embeddings for words 1 and 2 (but without making large changes to attention matrices). Second, it drives the loss down further by using the attention matrices to positively correlate q,k,v for words 1 and 2, and anti-correlate the q,k,v for a common word (denoted word "3" in the paper) relative to words 1,2. After these phases, both the training and generalization losses go to zero (as long as embedding dimension is large enough). Overall, I found the results interesting and insightful, though not very surprising, and the practical implications of these results were not very clear to me. Thus, I currently recommend weak accept. Importantly, my primary research area is not learning theory, so my knowledge of the related work is relatively limited, and thus my review confidence is relatively low.

Strengths

- It is interesting to see that the training dynamics for this word cooccurrence task can be analyzed rigorously, with relatively few assumptions. - The theoretical results are validated with a nice synthetic experiments, that demonstrates that the two phases predicted by the theory do occur in practice.

Weaknesses

- This word cooccurrence task is very simple, and thus it is not surprising that a single transformer layer can easily learn it. - Only full gradients are considered, whereas transformers are typically trained with mini-batch Adam(W).

Questions

- What other tasks (beyond word cooccurrence) do you think could be analyzed with this methodology? - What are the implications of this result to more complex/realistic tasks, like next token prediction? - If mini-batch Adam is used during training, do the two phases still occur? - Can you add more details about the experimental setup to the main paper? - Can you add more discussion about the automatic balancing of gradients, and its significance, in a more central part of the text (e.g., section 3, not 4)?

Rating

6

Confidence

3

Soundness

3

Presentation

3

Contribution

3

Limitations

Yes, limitations have been discussed.

Reviewer G3j55/10 · confidence 4/52024-07-13

Summary

This article delves into the gradient flow dynamics for detecting word co-occurrence, demonstrating that the gradient flow approach can achieve minimal loss. The training process commences with random initialization and can be delineated into two distinct phases.

Strengths

- This article noticed an interesting phase transition during training in this special setting and demonstrates it with solid calculation and experiments. - A new property of gradient flow is noticed and contributes to prove near minimum training loss together with the analysis of softmax.

Weaknesses

The setting of empirical experiments is also simple and ideal and readers may have no idea if this is a general phenomenon during training for detecting word co-occurrence.

Questions

- In line 151 and 152, it is confusing why concentration theorems lead to the specific probability in (i) of Assumption 2.3. - Lack of explanation for $\langle w_{j_1}^{(t)},w_{j_2}^{(t)} \rangle$ in line 194. - It is not obvious why "the samples with only one target signal may be classified incorrectly as co-occurence" in line 282. - The notation in line 169 is somewhat misleading.

Rating

5

Confidence

4

Soundness

3

Presentation

2

Contribution

3

Limitations

The semantic mechanism this article focuses on is not general enough in NLP and the the results cannot give instruction useful enough to guide the training process of Transformer.

Reviewer G3j52024-08-12

Thank you for your clarifications. Specifically, I have noticed the new experiment. However, these results remain preliminary and do not verify that the training dynamics of weights in this work can be generalized to broader cases. For example, the dynamics "first learning MLP and then learning Attention" cannot be adequately captured by the loss or accuracy presented. I will maintain my score.

Authorsrebuttal2024-08-13

We thank the reviewer very much for the highly inspiring question. To clarify the reviewer's concern, we note that the attention quantities that we study in one-layer case are the projections of attention to the input signals. In multi-layer transformers, the inputs to the middle layers are changing from iterations to iterations, and hence it is hard to find a fixed subspace to project on. Consequently, it is hard to find a natural and meaningful projection of the softmax attention in the middle layers to illustrate the phase change. Similarly, the inputs to the middle MLP layers are also changing, which makes it hard to find a fixed space for projection. This said, we still expect that the phase-wise learning (first MLP then attention) can occur for broader class of architectures. One feasible setting to demonstrate this is one-layer **multi-headed** transformer, which generalizes our original architecture and still maintains the meaningful projection of softmax attention to the fixed input space. We conducted additional experiments for one-layer 3-headed transformer. In our table below, we provide the values $G(\mu_1)$ of the MLP alignment with $\mu_1$ and the attention scores when the query is $\mu_1$ and key is $\mu_2$. The experiment results are all rounded to a tenth of decimal for better illustration. Take the first head as an example. The result clearly indicates a two-phase training process: (i) in phase 1 (during the first 250 steps), the MLP layer $G(\mu_1)$ grows quickly whereas the change in the attention score is very small compared to its later changes; and (ii) in phase 2 (after 250 steps), both MLP and attention score change substantially. | | Step | 0 | 250 | 500 | 750 | 1000 | 1250 | 1500 | 1750 | |---|---|---|---|---|---|---|---|---|---| | Head No.1 | score ($\times 10^{-2}$) |7.7 | 7.8 | 8.2 | 8.6 | 9.0 | 9.3 | 9.5 | 9.8 | | | $G(\mu_1)$ | 0.8 | 4.8 | 8.0 | 10.7 | 13.0 | 14.8 |16.4 | 17.6 | | Head No.2 | score ($\times 10^{-2}$) |2.1 | 2.2 | 2.6 | 3.0 | 3.3 | 3.6 | 3.9 | 4.1 | | | $G(\mu_1)$ | -0.1 | 2.5 | 4.6 | 6.6 | 8.3 | 9.7 |10.9 | 11.9 | | Head No.3 | score ($\times 10^{-2}$) |-12.4 | -12.2 | -11.7 | -11.1 | -10.6 | -10.2 | -9.9 | -9.6 | | | $G(\mu_1)$ | 0.7 | 4.6 | 7.6 | 10.2 | 12.4 | 14.2 | 15.6 | 16.8 | We further emphasize that the main contribution of this paper lies in the development of the **new techniques** for analyzing the training dynamics of transformers, especially the joint optimization analysis of all transformer parameters, as Reviewer cFaT pointed out. We expect that these mathematical techniques can be generalized to more complicated transformer architectures in the future. We thank the reviewer again for your time and efforts. If our response resolved your concerns, could you please kindly consider to increase your score. We are also more than happy to answer your further questions.

Authorsrebuttal2024-08-13

A gentle reminder

Dear Reviewer G3j5, It occurs to us that we uploaded our response earlier and OpenReview didn't send out notification. This message serves as a gentle reminder for the reviewer to look at our most recent response. We once again appreciate the reviewer's time and effort. If our response resolved your concerns, could you please kindly consider to increase your current score accordingly? We are happy to hear your response. Best, Authors

Reviewer cFaT2024-08-12

Thanks for your response. Given that the data setup is simple, the findings on the efficient learnability of this task are not particularly surprising, and might not provide much insight on practical tasks. However, the minimal assumptions on the model weights and the joint optimization analysis of all transformer parameters could make the techniques valuable for future transformer analyses. Thus, I will increase my score to weak accept. Since the main contribution of the paper lies in the proof technique, I suggest enhancing the presentation of the proof outline in the final manuscript.

Authorsrebuttal2024-08-12

Thank you

We thank the reviewer very much for your further feedback. We will follow the reviewer's suggestion and enhance the presentation of the proof outline in the revision. We also highly appreciate that you increased the rating of the paper.

Area Chair X85Y2024-08-12

Please respond to rebuttal

Dear reviewers, The author-reviewer discussion period will end soon. Please make sure you read the authors' rebuttal and respond to it. If you have additional questions after reading the rebuttal please discuss with the authors. For those who have done so, thank you! AC

Reviewer ritc2024-08-13

Thank you very much for your response. I keep my score unchanged, due to what I perceive to be the limited impact/scope of the work. Regarding my question: "If mini-batch Adam is used during training, do the two phases still occur?" ---> Could you add an experiment to check this?

Authorsrebuttal2024-08-14

Thank you very much for your feedback. As we mentioned in our rebuttal, we expect the training phases of Adam will exhibit some differences from gradient descent considered in our work. This is due to the coordinate-wise normalization operation uniquely occurring in Adam but not in GD. Our experiments confirmed our thoughts. We provide the experiment results on AdamW with default parameter setup below, where we show the changes in $G(\mu_1)$, which is the MLP alignment with the signal $\mu_1$, and the attention score when the query is $\mu_1$ and the key is $\mu_2$. All the values are rounded to a tenth of decimal. As you can see from the experiment results below, both the MLP and score change dramatically in the first 50 steps and then the changes slow down. The behavior thus is very different from gradient descent, where only MLP changes rapidly in the initial training and then both MLP and score jointly change substantially. | Step | 0 | 50 | 100 | 150 | 200 | 250 | | --- | --- | --- | --- | --- | --- | --- | | $G(\mu_1)$ | 0.2 | 50.8 | 56.8 | 59.7 | 62.0 | 64.0 | | Score $(\times 10^{-1})$ | -0.8 | 3.0 | 3.5 | 3.8 | 4.1 | 4.3 | We further emphasize that the main contribution of this paper lies in the development of the **new techniques** for analyzing the training dynamics of transformers, especially the joint optimization analysis of all transformer parameters, as Reviewer cFaT pointed out. We expect that these mathematical techniques can be generalized to more complicated transformer architectures in the future. We thank the reviewer for the time and efforts. We hope that our response answers your question.

Program Chairsdecision2024-09-25

Decision

Accept (poster)

© 2026 NYSGPT2525 LLC