Attention mechanisms
Overview
Mohit Iyyer explains how self-attention addresses recurrent neural networks' vanishing-gradient, information-bottleneck, and sequential-computation problems. He derives query, key, and value projections, causal masking, and the matrix operations that let Transformers compute all token representations in parallel during training, while noting that autoregressive generation remains sequential.
Key takeaways
- Softmax cross-entropy gives a logit gradient of Q minus P: gradient descent increases the correct next token's probability and decreases probability assigned to incorrect tokens.
- An RNN's repeated hidden-state transitions create vanishing gradients and compress long contexts into a single state, while attention provides direct paths from a prediction position to earlier token representations.
- Self-attention uses learned projections qᵢ = WQcᵢ, kᵢ = WKcᵢ, and vᵢ = WVcᵢ; query-key dot products choose how strongly each value contributes to a token representation.
- Causal masks must replace future-token logits with negative infinity before softmax, because zero logits would still receive nonzero attention probability.
- The matrix computation softmax(QKᵀ) V computes all sequence positions in parallel during training, but autoregressive inference remains left-to-right because each generated token depends on previous outputs.
- The basic self-attention equations need positional information: without it, token order is not explicitly represented, motivating positional encodings in the Transformer.
Chapters
- The upcoming lectures move from Transformer attention to language-model scaling, pre-training, post-training, and mixture-of-experts models.
- Project groups should develop ideas early and ask instructors or TAs about feasibility during office hours.
- Project evaluation emphasizes sustained effort and diagnosing failures, not necessarily achieving the best results.
- Groups should independently seek compute credits rather than waiting for course-level support.
- A training step runs an input sequence through a model, computes its loss, obtains gradients with backpropagation, and updates parameters.
- The forward architecture could be an RNN or fixed-window model; the course will transition to Transformers.
- Gradient descent updates parameters in the direction opposite the loss gradient.
- PyTorch, JAX, and TensorFlow automate differentiation, so model code can define the forward computation without manually deriving every gradient.
- For next-token prediction, the model produces vocabulary logits and cross-entropy compares them with the observed next-token index.
- Calling the loss's backward function chains derivatives through layers such as linear projections, softmax, and attention.
- An optimizer such as stochastic gradient descent or Adam applies parameter updates after backpropagation; the lecture also mentions Muon.
- Training typically repeats a loop over batches, for example processing thousands of tokens before moving to the next batch.
- Large language-model runs often make one pass over enormous datasets because fresh text can be more valuable than repeatedly seeing the same tokens.
- Data can be reweighted: math textbooks may be upsampled while noisy internet text is downweighted.
- For logits Z, softmax cross-entropy gives the output-layer gradient Q minus P, where Q is the model distribution and P is the target.
- With a one-hot target, the correct token has P equal to 1, so gradient descent pushes its predicted probability upward.
- Incorrect tokens have P equal to 0, so their probabilities are pushed downward.
- The output-weight gradient combines Q minus P with the hidden state, and this error signal propagates through earlier network parameters.
- In a simplified linear RNN, repeated updates give hₙ = Wₕⁿ⁻¹h₁, exposing a long chain of repeated matrix multiplications.
- Repeated multiplication can make values grow or shrink toward zero, and gradients in long sequences commonly vanish.
- A vanishing gradient can prevent a prediction thousands of time steps later from learning dependencies on early tokens.
- An RNN compresses an entire prefix into one d-dimensional hidden state, such as h₁₀₀₀₀ for a 10,000-token document.
- That single state may not preserve every useful detail, and a left-to-right RNN cannot directly revisit an earlier token when making a later prediction.
- The recurrence hₜ = f(Wₕhₜ₋₁ + Wₓcₜ) requires hₜ₋₁ before hₜ, limiting parallel computation across positions.
- Parallelizable linear recurrent models such as Mamba are mentioned as alternatives, though the lecture says they had not matched Transformers on text at comparable public scale.
- Attention forms a weighted average of token representations, allowing a position to draw information directly from earlier positions.
- These shortcut connections let gradients reach an early token without passing through thousands of recurrent updates.
- Attention was first added to RNN-based systems to ease the information bottleneck, but those systems still had sequential RNN computation.
- The 2017 Transformer paper replaced recurrence with self-attention to enable parallel computation across positions.
- Each token embedding cᵢ is mapped through learned linear layers to qᵢ = WQcᵢ, kᵢ = WKcᵢ, and vᵢ = WVcᵢ.
- Queries represent what a position seeks, keys represent what each position offers for matching, and values carry information into the resulting representation.
- The same WQ, WK, and WV matrices are shared across sequence positions, while each token produces different query, key, and value vectors.
- At this stage, each token's projections depend only on its own embedding, so cross-token information has not yet been combined.
- At position 3 in the example, the query q₃ is dotted with keys k₁, k₂, and k₃ to score the available prefix tokens.
- Softmax converts those query-key scores into attention probabilities, such as illustrative weights of 0.5, 0.2, and 0.3.
- The position's representation is the weighted sum of values, for example h₃ = 0.5v₁ + 0.2v₂ + 0.3v₃.
- Queries and keys determine the weights, while value vectors contribute the content of the resulting representation; the standard Transformer also scales dot products.
- A position's representation must exclude later tokens so the model cannot see its next-word target during training.
- For h₂, attention uses q₂k₁ and q₂k₂ but excludes the third token, which is the target word in the example.
- The resulting h₂ is a weighted combination of v₁ and v₂ only, while h₂ and h₃ can be computed independently in parallel.
- This restriction is causal masking, which ensures each prediction uses only its prefix.
- Stacking queries as rows and keys as columns produces all pairwise scores in one matrix multiplication, QKᵀ.
- The score matrix contains future-token entries that must be masked before softmax.
- Setting masked logits to negative infinity, for example with a PyTorch mask-fill operation, makes their softmax probabilities exactly zero; simply setting logits to zero would not.
- Multiplying the resulting attention matrix by the value matrix computes every token representation H together, enabling parallel training subject to GPU memory.
- Training data contains complete sequences, so all input tokens are available and causal self-attention can calculate positions in parallel.
- At inference, the model generates a response one token at a time because each new token depends on the previously generated output.
- Both RNNs and autoregressive Transformers therefore decode left to right, even though Transformers parallelize token computations during training.
- Learned parameters include WQ, WK, WV, the output projection WO, and the embedding matrix E; vectors such as q₁ and k₁ are input-specific activations, not parameters.
- Masked future positions receive no probability and do not pass gradients through those attention connections.
- The basic attention equations shown do not encode token order, so sequences such as “my favorite LLM is” and a reordered version would lack explicit positional distinctions.
- The next lecture will introduce positional information, stacked Transformer layers, and multiple attention heads.
Transcript excerpt
0:11 Okay. So let's get started everyone. Today we are going to start um talking about the basics underlying transformer language models um specifically the attention mechanism which is kind of the centerpiece of this architecture. we will kind of transition from recurrent neural networks which we talked about last time to um uh transformers and by the end of class on Wednesday hopefully we will have completed um you know everything we need to know about a transformer and we will move on to different ways that we can apply this architecture to training language models. we'll start talking about
0:58 scaling and um pre-training, post-training, a mixture of experts, things like that. So, that's kind of where we're going um in the next coming weeks. Uh before that, just a reminder that um the project groups have been formed now. So, um, we highly encourage you to get together with your group as quickly as possible to try and come up with some initial ideas and, um, you know, come discuss with anyone of, uh, the instructors, TAs or myself in our office hours if you have any questions on whether your project is appropriate, feasible, whatever. I just wanted to make a note that because we did get uh
1:46 quite a few questions about this in the office hours um that uh like a good project doesn't necessarily have to work like your idea doesn't have to get the greatest results or anything like that. We are mainly looking for effort like your does your project reflect an appropriate amount of work through the course of a semester? Um, and also kind of did you take the effort to try and understand in the case that you got a poor result, why your model is failing, what you would need to do um to address
This is the start of the transcript. Save this video free for the whole transcript, searchable and time-coded.
In this course
Related notes
Summary, takeaways, and chapters were generated by AI from the video's transcript and may contain errors. The video belongs to its creator, Mohit Iyyer.