Self-Attention and Transformers


Self-Attention and Transformers

Simon
Welcome back to CS224N. Today we're focusing on self-attention and Transformers, ideas that form the foundation of many modern advances in natural language processing and AI more broadly. Before we get into the technical material, there are a few course reminders.

Corey
The new lecture notes are available, and they follow today's material while going into considerably more detail. Assignment four is due a week from today. Because the Azure issues are continuing, students without a GPU can use Colab; the teaching assistants have tested that the machine translation training will fit within a Colab session.

Simon
The course staff is also working on obtaining more GPUs for assignment five and the final project. The final project proposal is important because you'll receive feedback about whether your idea is feasible or whether it should be adjusted, and the proposal is scheduled to be released tonight.

Corey
Now let's look back at the standard NLP strategy before Transformers. For a strong sequence-to-sequence system, we might use a bidirectional LSTM to encode the source sentence, a unidirectional LSTM to generate an output one step at a time, and attention to give the decoder flexible access to the encoder's memory.

Simon
That setup worked exceptionally well, especially for machine translation. Attention helped solve a bottleneck: instead of forcing the entire source sentence into one fixed-size vector, the decoder could look back at different parts of the encoded sentence when generating each target word.

Corey
So the goal of today's lecture is similar, but the building blocks change. Instead of relying on recurrence through LSTMs, we'll use self-attention and Transformers, which avoid several limitations of recurrent neural networks and support much more efficient computation.

Simon
The first limitation is linear interaction distance. An RNN processes a sequence from left to right or right to left, so nearby words can interact through only a few recurrent steps. That locality is sometimes useful, because words such as “tasty” and “pizza” often influence each other's meaning.

Corey
But long-distance dependencies are harder. In a sentence like “The chef who went to the stores and picked up the ingredients and loves garlic was...” the words “chef” and “was” need to be related, even though many steps separate them. In an RNN, information and gradients have to pass through every intervening recurrent operation.

Simon
LSTMs handle gradients across long distances better than simple RNNs, but they do not eliminate the problem. Ideally, words that are related anywhere in a sentence or document should be able to interact more directly instead of being forced to communicate through a linearly long chain.

Corey
The second limitation is the dependence on sequence position, or time, during computation. To calculate the hidden state at step five, an RNN must first calculate the states at steps four, three, and earlier. That creates a sequence-length number of operations that cannot be parallelized.

Simon
GPUs are excellent at performing many independent operations simultaneously, but recurrence creates dependencies between time steps. As the sequence gets longer, the amount of computation that must happen sequentially also grows, preventing the GPU from processing the whole sequence at once.

Corey
Attention helps with the first issue, but in the Transformer we also remove recurrence entirely. Each word can independently produce an embedding, and attention can then allow every word to interact with the other words in one large parallel operation.

Simon
A useful way to understand attention is as a fuzzy lookup in a key-value store. In an ordinary dictionary, a query exactly matches a key and returns its value. Attention instead compares a query with every key, assigns a soft similarity weight to each one, and returns a weighted sum of the corresponding values.

Corey
The lookup is therefore soft rather than exact. A query can be somewhat similar to many keys, and a softmax turns those similarity scores into weights, usually between zero and one that sum to one. The output is the weighted average of the value vectors.

Simon
For self-attention, begin with a sequence of words from a vocabulary. Each word has a non-contextual embedding produced by an embedding matrix. Then three different learned matrices transform that embedding into a query vector, a key vector, and a value vector.

Corey
For word i, the query is formed by multiplying its embedding by the query matrix, the key by multiplying it by the key matrix, and the value by multiplying it by the value matrix. Every word participates in all three roles, but the three learned transformations allow those roles to behave differently.

Simon
Next, calculate every query-key similarity. The score between word i and word j is the dot product of query i and key j. After applying a softmax across all possible j values, we obtain the attention weight from word i to word j.

Corey
Finally, the representation for word i is the weighted sum of all the value vectors, using those attention weights. So when representing a word such as “learned” in “I went to Stanford's CS224N and learned,” the model can decide how much information to draw from “Stanford,” “CS224N,” or the other words.

Simon
The query and key matrices also let the model learn whether a word should attend strongly to itself. If the matrices were identities, a word's representation would naturally have a high similarity with itself, but learned transformations can make self-attention behave differently. The model learns these patterns from data.

Corey
There is an important problem, though: self-attention by itself has no notion of word order. If we use only word embeddings and attention, the sequence “Zuko made his uncle” could receive the same representations as “his uncle made Zuko,” even though the meanings differ.

Simon
To fix that, we add position representations to the input word embeddings. A position vector represents the sequence index, so the input now encodes both what the word is and where it occurs. This positional information can be added at the beginning of the network rather than repeatedly at every layer.

Corey
One early approach uses sinusoidal position representations. Different dimensions use sine or cosine functions with different periods, producing a pattern that varies across sequence positions. The intuition is that periodic signals might represent positions and perhaps help with longer sequences, although in practice that extrapolation does not work.

Simon
Another approach is to learn the position representations directly. If the maximum sequence length is n, the model learns a matrix with one learned vector for each position and adds those vectors to the word embeddings. This is flexible, but a model using a fixed maximum length cannot directly handle sequences longer than that length.

Corey
Sequence length remains a practical issue even for large language models. Self-attention computes interactions between every pair of positions, so its memory and computation grow quadratically with sequence length. A context of several thousand words may be possible, but that still does not cover an entire novel or a full Wikipedia page.

Simon
A second problem is that basic self-attention has no nonlinearities. Repeatedly applying it mainly re-averages value vectors. The usual fix is to apply a position-wise feed-forward network after attention, processing each output vector independently with matrix transformations and nonlinearities.

Corey
That feed-forward network provides the traditional deep-learning expressivity. It also contains a large amount of computation that can be performed efficiently and in parallel on GPUs. So the basic block becomes self-attention followed by a feed-forward network.

Simon
For language modeling and other autoregressive generation tasks, there is one more issue: the model must not look at future words when predicting the next word. We still compute the full matrix of pairwise attention scores in parallel, but we mask future positions by assigning their scores a very large negative value, effectively negative infinity.

Corey
When the softmax is applied, those masked scores become weights of zero. Thus, the representation at a position can attend to itself and earlier positions, but not to later ones. This preserves parallel computation while preventing the model from cheating by seeing the answer.

Simon
The masking rule depends on the architecture. An encoder processing a source sentence usually uses bidirectional attention, because every source word can benefit from seeing the whole source sentence. A decoder generating a sequence uses masked attention, because it must obey the left-to-right information constraint.

Corey
Putting those pieces together gives a minimal self-attention architecture: start with word embeddings, add position representations, apply self-attention, pass each output through a position-wise feed-forward network, and use masking when future information must be hidden. These operations can be repeated in multiple layers.

Simon
The Transformer adds several important details to this minimal design. The most significant is masked multi-head self-attention. Instead of performing one attention operation, the model performs several attention operations with separate query, key, and value matrices.

Corey
The motivation is that a word may need to attend to different parts of a sequence for different reasons. One attention head might focus on information related to entities or topics, while another might capture syntactic relationships. The heads are not guaranteed to specialize perfectly, but in practice they often learn different patterns.

Simon
For efficient implementation, represent all word embeddings as one matrix X with shape n by d, where n is sequence length and d is model dimensionality. Multiplying X by the key, query, or value matrix transforms every word at once instead of using a loop over positions.

Corey
The matrix product XQ multiplied by the transpose of XK produces an n-by-n matrix of all query-key scores. Applying softmax across each appropriate row normalizes the scores, and multiplying that matrix by XV performs all the weighted sums at once.

Simon
Multi-head attention reshapes these computations so the head dimension acts somewhat like a batch dimension. Each head works in a lower-dimensional space, usually with the model dimensionality divided among the heads, and the resulting head outputs are concatenated and passed through a final linear transformation.

Corey
This is not intended to guarantee that every head learns a completely unique function. Some redundancy can occur. The practical result, though, is much better than using only one head, because the model can examine multiple relationships and locations in the sequence simultaneously.

Simon
Another standard detail is scaled dot-product attention. As the dimensionality of the vectors grows, dot products between even random vectors tend to become large. Large inputs to the softmax can make its gradients small, so the attention scores are divided by a factor based on the head dimensionality, typically the square root of that dimensionality.

Corey
Transformers also use residual connections and layer normalization. With a residual connection, the output of a layer is added to its input, so the layer only needs to learn a residual transformation. This gives gradients a direct path through the network and can make optimization easier.

Simon
Residual connections can also make the network behave somewhat like the identity function at initialization, which can provide a useful starting point. In a Transformer diagram, the residual addition is commonly grouped with layer normalization in an “add and norm” component.

Corey
Layer normalization standardizes an individual word vector across its dimensions. It computes the mean and standard deviation of the values in that vector, subtracts the mean, divides by the standard deviation with a small epsilon for stability, and may then apply learned scaling and shifting parameters.

Simon
The purpose is to reduce uninformative variation in the values passed between layers. Importantly, layer normalization computes these statistics independently for each word vector; it does not share the statistics across the words in a sequence or across examples in a batch.

Corey
A Transformer block therefore consists of attention followed by add-and-norm, then a feed-forward network followed by another add-and-norm. This block can be repeated many times, with separate parameters in different blocks, and the final representations can be used for tasks such as predicting the next word or classifying sentiment.

Simon
The Transformer encoder is almost the same structure without future masking. It uses multi-head self-attention with bidirectional context, so every input position can attend to every other input position.

Corey
The original Transformer architecture also combines an encoder and a decoder, as in the paper “Attention Is All You Need.” The encoder reads a source sequence, such as “I like pizza,” using unmasked attention. The decoder generates the target sequence using masked self-attention.

Simon
The decoder then uses a second attention operation called cross-attention. Its queries come from the decoder representations, while its keys and values come from the output of the encoder. That lets each generated target word look across the encoded source sentence.

Corey
So in machine translation, the encoder can build a fully contextual representation of the source, and the decoder can generate the target from left to right. At each target position, masked self-attention handles the already-generated target words, while cross-attention accesses the source-side information.

Simon
Transformers initially produced strong machine translation results and were significantly more efficient to train than recurrent systems because their operations could be parallelized. They later became central to document generation and many other NLP systems.

Corey
Their efficiency also enabled the rise of large-scale pretraining. Because Transformers can process enormous amounts of data and make better use of powerful GPUs, they moved ahead of LSTMs on many modern NLP benchmarks and applications.

Simon
That does not mean the architecture is perfect. The clearest limitation is still the quadratic sequence-length cost caused by all pairs of interactions. Researchers have explored ways to reduce that cost, along with better position representations and many other modifications.

Corey
So the main lesson is not that the original Transformer is the final possible architecture. It is that replacing recurrence with attention gives direct long-distance interaction and much more parallel computation, while position information, nonlinear feed-forward layers, masking, multi-head attention, scaling, residual connections, and normalization make the system practical.

Simon
And that is the foundation for the next topic: pretraining, which we'll cover in the next lecture. Good luck with assignment four, watch for the final project proposal announcement, and remember that Colab is available if you do not have a GPU.

Ask anything
We've read this whole study set, so questions about it get the best answers.