1. Home
  2. Explore
  3. Computer Science
  4. Attention and Transformers

Study methods

Flashcards
Quiz
Fill in the blanks
Written test
Lesson
Notes
Podcast
Content

Attention and Transformers

Speaker 1Speaker 2

Attention and Transformers

12:59
0:00-12:59
  1. Simon

    Welcome back to lecture eight. Today we're moving from recurrent neural networks into attention and transformers. Last time, recurrent networks showed us how to process sequences, which expanded neural networks beyond one-to-one tasks like taking an image and producing a classification.

  2. Hope

    Right. Once we can process sequences, we can handle one-to-many problems, such as taking an image and generating a caption; many-to-one problems, such as classifying a sequence of video frames; and sequence-to-sequence problems, such as translating one sentence into another language.

  3. Simon

    And transformers are important because they now form the basis of almost all large, state-of-the-art deep-learning applications. They are used for generating and classifying text and images, working with audio, and many other tasks. But historically, the ideas behind transformers grew out of attempts to improve recurrent neural networks.

  4. Hope

    So let's begin with translation. Suppose the input is an English sentence and the output is an Italian sentence. We cannot assume the two sentences have the same number of words or that corresponding words appear in the same order, which makes translation a natural sequence-to-sequence problem.

  5. Simon

    The original recurrent approach uses an encoder and a decoder. The encoder is a recurrent neural network that processes the input one token at a time. At each step, it receives the current input vector and the previous hidden state, then produces a new hidden state.

  6. Hope

    After the encoder has processed the complete English sentence, its final hidden state is treated as a context vector. The idea is that, because the recurrent computation has passed through every word, this last state summarizes the entire input sequence.

  7. Simon

    A second recurrent network, the decoder, then generates the translated sentence one word at a time. At each step, it uses the previous output token, its previous hidden state, and the context vector from the encoder. The decoder can have the same basic architecture as the encoder, but it can have different learned parameters.

  8. Hope

    The problem is that the entire input must communicate with the decoder through one fixed-length vector. That may be reasonable for a short sentence like 'we see the sky,' but the vector's size does not grow when the input becomes a paragraph, a book, or a large corpus.

  9. Simon

    That creates a communication bottleneck. Asking one fixed-size vector to preserve everything needed from an increasingly long input becomes unreasonable. The motivating idea behind attention is therefore: instead of forcing the decoder to rely on one summary, let it look back at the whole input sequence whenever it produces an output.

  10. Hope

    The encoder can remain unchanged. At a particular decoder step, we take the current decoder hidden state and compare it with every hidden state produced by the encoder. Each comparison gives a scalar alignment score indicating how well that decoder state matches one input position.

  11. Simon

    One way to calculate an alignment score is with a learned linear function. We concatenate the decoder state with one encoder state, apply the function, and obtain a single number. The function is learned along with the rest of the network through gradient descent.

  12. Hope

    Those raw scores can be arbitrary real numbers, so we pass them through a softmax. The result is a set of attention weights: every weight lies between zero and one, and all the weights sum to one. In other words, for the current decoder state, the network produces a probability distribution over the input positions.

  13. Simon

    We then use those weights to form a weighted linear combination of the encoder hidden states. That combination is a new context vector for the current decoder step. If the decoder is trying to produce the translated word corresponding to 'we see,' it can learn to assign larger weights to those input words and smaller weights to unrelated words such as 'sky.'

  14. Hope

    Crucially, nobody has to label the correct alignment for the network. The entire mechanism is differentiable, and the model is trained using the usual output-token objective, such as cross-entropy. While learning to predict the target sentence, it learns for itself how to set the attention weights.

  15. Simon

    The decoder still works recurrently: it uses its previous hidden state, the current context vector, and the previous output token to compute its next state and output. But the context vector is no longer fixed for the whole sentence. At every decoder step, the model recomputes attention over the entire input sequence.

  16. Hope

    That solves the bottleneck because each output can access a fresh summary of the input. It also gives us a way to inspect what the model is using. If we visualize the attention weights in a grid, each output word corresponds to a distribution over the input words.

  17. Simon

    For example, in English-to-French translation, a row might place most of its weight on the English word 'the' when producing the corresponding French word. Another row might focus on 'agreement.' Diagonal patterns suggest that words align in the same order, while backward diagonals or small blocks can reveal reordering or cases where several words correspond to one another.

  18. Hope

    And the model was not explicitly taught grammar or word alignment. It received input-output sentence pairs and learned through gradient descent. The designers supplied an architecture that made looking back at relevant input positions possible, and the network learned how to use that mechanism for translation.

  19. Simon

    The next step is to separate attention from recurrent networks entirely. In the recurrent example, the encoder hidden states acted as data to summarize, and each decoder hidden state acted as a query asking what information was relevant at that moment.

  20. Hope

    So an attention operator takes data vectors and query vectors. For each query, it compares the query with all the data vectors, converts the similarities into attention weights, and uses those weights to produce an output vector that summarizes the data in a query-specific way.

  21. Simon

    In principle, the similarity function could be any function of two vectors that returns a scalar. A simple and useful choice is the dot product. Because larger vector dimensions can make dot products grow in scale and cause the softmax to become too sharp, we divide the dot product by the square root of the vector dimension.

  22. Hope

    That is called scaled dot-product attention. The scaling helps maintain better gradient flow across different vector dimensions and helps prevent vanishing gradients as models become larger.

  23. Simon

    We can also process many queries at once. Let the query vectors form a matrix and the data vectors form another matrix. All pairwise dot products can then be computed with a matrix multiplication, followed by a softmax along the appropriate dimension so that each query receives a distribution over the data vectors.

  24. Hope

    The output for every query is a weighted combination of the data vectors. That entire collection of weighted combinations can also be computed with a matrix multiplication. So attention is not just conceptually useful; it maps naturally onto highly optimized parallel hardware.

  25. Simon

    There is one refinement: instead of using each data vector directly both to calculate similarity and to construct the output, we project it into two different vectors. The key is used for matching against queries, while the value is used to construct the output.

  26. Hope

    The key and value projections are learned linear transformations. The model learns how to represent each data vector for matching and, separately, how to represent the information that should be retrieved. A search engine is a useful intuition: the query matches against keys, but the result returned is the value, which need not look like the query.

  27. Simon

    With queries, keys, and values, the attention layer works as follows: project data vectors into keys and values, compare every query with every key using scaled dot products, apply softmax to obtain attention weights, and use those weights to combine the value vectors.

  28. Hope

    When the queries and data come from two different sources, this is called cross-attention. Translation is one example: decoder states query encoder states. Image captioning can also have this structure, with generated words attending to information from an image.

  29. Simon

    Self-attention is the case where there is only one set of input vectors. Each input vector is projected into a query, a key, and a value, and the set of vectors attends to itself. The output has the same number of positions as the input, although the vectors have been updated using information from one another.

  30. Hope

    Self-attention has an important symmetry. If we shuffle the input vectors, the resulting outputs are the same outputs, shuffled in the same way. This property is called permutation equivariance, and it means that the computation itself does not depend on the order in which the vectors are presented.

  31. Simon

    That is useful when the inputs are naturally a set, but it can be a problem for sequences, where position matters. A common solution is to concatenate positional information, called a positional embedding, to each input vector so the network can distinguish the first position from the second, third, and so on.

  32. Hope

    Another option is masked self-attention. After calculating alignment scores, we replace scores for forbidden interactions with negative infinity. Softmax turns those entries into zero, so the corresponding value vectors cannot influence that output.

  33. Simon

    Masking is especially useful for language modeling. When predicting the first word, the model should only use the first input position. When predicting the second, it may use the first two, but it must not look ahead at future words and cheat.

  34. Hope

    Self-attention is also commonly extended to multi-headed self-attention. We run several independent copies, or heads, in parallel. Each head has the same architecture but different weights, so the heads can learn different ways of comparing and combining the inputs. Their outputs are then combined with another learned linear projection.

  35. Simon

    Although the equations can look complicated, the operation is mostly a small number of large, batched matrix multiplications: one to produce queries, keys, and values; one to calculate query-key similarities; one to combine values using attention weights; and one output projection to mix information across heads.

  36. Hope

    This makes attention highly parallelizable. Recurrent networks are sequential because each hidden state depends on the previous one. Convolution is parallelizable over a grid, but it mixes information locally, so large receptive fields may require large kernels or many stacked layers.

  37. Simon

    Self-attention operates on sets of vectors and lets every vector interact with every other vector in one layer. Its main cost is that a sequence of length n requires roughly n-squared computation and memory for the pairwise interactions. That cost is substantial for extremely long sequences, but the operation's scalability across processors makes it attractive for large models.

  38. Hope

    Parallelizability matters because making one processor faster has become difficult, while using many processors together is practical. An algorithm that can distribute its work across GPUs or many other processors can scale to much larger computations.

  39. Simon

    The transformer puts self-attention at the center of a neural-network architecture. A transformer block first applies multi-headed self-attention, uses a residual connection, and applies layer normalization. It then applies a small multilayer perceptron, also called an MLP or feed-forward network, independently to each vector.

  40. Hope

    The MLP complements self-attention. Self-attention lets the vectors communicate and compare with one another, while the MLP performs separate processing on each vector. The MLP is also wrapped with a residual connection and layer normalization, and this complete structure is called a transformer block.

  41. Simon

    A transformer is simply a sequence of these blocks. The architecture has scaled dramatically: early transformers had around a dozen blocks and hundreds of millions of parameters, while later systems have used hundreds of blocks and trillions of parameters.

  42. Hope

    Transformers are not limited to language. For images, we can divide an image into patches and project each patch into a vector. Those patch vectors become the transformer's inputs. If we want image classification, we can pool the output vectors and pass the result through a linear layer to produce class scores.

  43. Simon

    So the key ideas are now connected. Attention began as a way for a recurrent decoder to look back at relevant encoder states instead of relying on one fixed context vector. It became a general operator based on queries, keys, values, softmax weights, and weighted combinations.

  44. Hope

    And self-attention applies that operator to one set of vectors, with positional information added when order matters. Masking controls which positions may interact, and multiple heads provide several learned patterns of interaction in parallel.

  45. Simon

    Finally, transformers organize these ideas into a scalable architecture built from self-attention, residual connections, normalization, and per-vector feed-forward networks. That combination is why transformers have become the dominant architecture for large, modern deep-learning systems across text, images, audio, and other data types.

  46. Hope

    That brings us to the main takeaway: attention removes the recurrent bottleneck, self-attention lets vectors communicate directly, and transformers make that communication the core of a highly parallelizable neural network. It is a powerful shift from processing sequences one step at a time to letting the whole collection of representations interact efficiently.

Ask anything

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

FlashcardsQuizFill in the blanksWritten testLessonNotesPodcastContent