Find a course

Module 5: Architectures That Changed AILesson 11 of 1116 min

Sequences, Attention and Transformers

Learn how embeddings represent words, why recurrent networks struggled with long text, and how attention and transformers power language models.

Step 1 of 12Learn

When order matters

Read this sentence: "The trophy didn't fit in the suitcase because it was too big." What was too big? The trophy. Now change one word: "...because it was too small." Now "it" is the suitcase. To understand language, a model has to use context, sometimes from far away in the sentence, and it has to respect word order: "dog bites man" and "man bites dog" contain the same words.

Text, speech, music, DNA and stock prices are all sequences. Before a network can process text, it needs numbers. Text is split into tokens, which are words or pieces of words, and each token is mapped to an embedding: a learned vector of, say, 512 numbers. Embeddings are learned during training so that tokens used in similar ways end up with similar vectors. "Cat" and "kitten" sit close together; "cat" and "carburetor" are far apart. Directions in this space can even capture relationships, like the difference between singular and plural.

A plain dense network is a poor fit for sequences. It expects a fixed number of inputs, while sentences vary in length, and it has no notion that position 5 follows position 4. Two families of architectures were built to handle this: recurrent networks and, more recently, transformers.

Step 2 of 12Practice · Choose one

What is an embedding in a language model?

Step 3 of 12Learn

Recurrent networks and their limits

A recurrent neural network (RNN) reads a sequence one token at a time and keeps a hidden state, a vector that acts as its running memory. At each step it combines the current token with the previous hidden state to produce a new hidden state:

h_t = tanh(W·x_t + U·h_(t−1) + b)

The same weights W and U are used at every step, which is weight sharing across time, just as CNNs share weights across space. After the last token, the hidden state summarizes the whole sequence and can feed a classifier, or the network can produce an output at every step.

RNNs have two serious problems. First, information from early tokens must survive being passed through every later step, and during training the gradient must flow back through all of them. Over long sequences it vanishes, so plain RNNs effectively forget anything more than a few dozen tokens back. LSTMs (long short-term memory, 1997) and GRUs added gates, small learned switches that decide what to keep, forget and output, which greatly extended their memory. They powered machine translation and speech recognition through the mid-2010s.

The second problem is speed. Step t can't start until step t − 1 finishes, so an RNN can't spread one sequence's work across thousands of GPU cores. That limit became decisive as datasets grew.

Step 4 of 12Practice · True or false

A recurrent neural network uses a different set of weights for each position in the sequence.

Step 5 of 12Learn

Attention: looking everywhere at once

Attention lets every token look directly at every other token and decide how much each one matters. Here's how self-attention works. Each token's embedding is turned, by three learned weight matrices, into three vectors:

  • a query: what this token is looking for,
  • a key: what this token offers,
  • a value: the information it passes on if chosen.

To update the token "it," the model compares its query with the key of every token using a dot product. A large dot product means a good match. The scores are divided by √d (d is the length of the key vectors, which keeps the numbers in a stable range), then softmax turns them into weights that sum to 1. The new representation of "it" is the weighted sum of all the value vectors. If "trophy" got 70% of the weight, the updated "it" now carries a lot of information about the trophy.

Two things make this powerful. Distance doesn't matter: token 3 can attend to token 3,000 as easily as to its neighbor. And every token's attention can be computed at the same time, as big matrix multiplications that GPUs handle superbly. Models use multi-head attention, several attention computations in parallel, so different heads can track different relationships, such as grammar in one head and meaning in another.

Self-attention: the word it attends strongly to trophy and weakly to the other words in the sentencethetrophydidn'tfitinthesuitcaseit

Step 6 of 12Practice · Work it out

In self-attention, a query and a key have a dot product of 8, and the key vectors have length d = 16. What is the scaled score, dot product divided by √d, before softmax?

Step 7 of 12Tap to reveal

Inside a transformer

  1. Token embeddings

    Each input token is converted into its learned embedding vector.

  2. Positional information

    Attention by itself ignores order, so position information is added to the embeddings (or built into the attention scores) so the model knows which token came first.

  3. Multi-head self-attention

    Every token gathers information from every other token, with several heads looking for different kinds of relationships.

  4. Feed-forward layer

    A small dense network, applied to each token separately, processes what attention gathered.

  5. Residual connections and normalization

    Each sub-layer's input is added to its output and normalized, which keeps training stable through many layers.

  6. Stack and repeat

    This block is repeated dozens of times. Language models end with a layer that turns the final vector into a probability for every token in the vocabulary.

Step 8 of 12Learn

From transformers to language models

The transformer was introduced in 2017 for machine translation. Researchers soon found that a stack of transformer blocks trained on one simple task, predicting the next token in huge amounts of text, learns a startling range of skills along the way: grammar, facts, translation, summarizing and even some reasoning. These are large language models (LLMs), with billions of parameters.

Training happens in stages. Pretraining on a vast text collection produces a model that continues text plausibly. Fine-tuning on curated examples of instructions and good answers, often followed by training with human or automated feedback, turns it into a helpful assistant. The same transformer design, with different inputs, now handles images (vision transformers), audio and protein structures.

Keep the mechanism in mind when you use these tools. An LLM generates text by repeatedly choosing likely next tokens, so it can produce fluent, confident statements that are false, often called hallucinations. It knows nothing after its training data was collected unless given tools or documents. And attention compares every token with every other token, so the cost grows with the square of the input length, which is why long documents are expensive to process.

Step 9 of 12Compare

Four architectures side by side

AspectDense networkCNNRNN / LSTMTransformer
Best suited toFixed-size tabular dataImages and grid-like dataShort-to-medium sequences, streaming dataText, long sequences, and increasingly everything
Key ideaEvery input connects to every neuronSmall shared filters slide across the inputA hidden state carries memory step by stepAttention lets every token look at every other token
Main weaknessToo many parameters for raw images or textCaptures long-range relationships only in deep layersSlow to train; forgets long-range contextCost grows with the square of input length

Step 10 of 12Practice · Match the pairs

Match each task to the architecture that is the most natural first choice.

Tap an answer, then tap the place where it belongs (or drag it there).

  1. Predicting house prices from 12 numeric features
  2. Detecting cracks in photos of bridges
  3. Summarizing long legal documents
  4. A small on-device model processing a live sensor stream step by step

Step 11 of 12Practice · What would you do?

What would you do?

A student asks a language model for sources on a history topic. It returns a neatly formatted citation to a journal article, but the student can't find the article anywhere. What best explains this?

Step 12 of 12Practice · Choose one

Why do transformers train much faster than RNNs on modern GPUs?