← All notes
Course chapters
On this page

Lesson 21 · Large language models

The Transformer architecture

Assemble attention, feed-forward networks and positional information into a Transformer. Follow a token through stacked blocks and distinguish parallel training from step-by-step generation.

1. Attention is useful. What is still missing?

The previous lessons gave us a way to select context and combine information from several learned spaces. A token can now receive information from other positions without passing it through a recurrent hidden state one step at a time.

But attention is a component, rather than a complete language model. How do we turn it into a system that predicts the next token?

Start with a small prompt:

“I am a small ___”

Imagine that “I”, “am”, “a” and “small” are four tokens. We will assemble a simplified causal language model around this example, then identify the details that make a standard Transformer block complete.

The original 2017 Transformer was an encoder-decoder model for sequence-to-sequence tasks. Our next-token example follows a decoder-only pattern to make the main operations easier to follow. These are related architectures, not identical models.

2. Start with attention alone

A first attempt might be:

  1. Look up a vector for each token.
  2. Apply attention several times.
  3. Use the last position's vector to predict a continuation.

Attention lets the last position collect information from “I”, “am”, “a” and “small”. For one head, the final value-mixing step is:

h=∑jαjvj,αj≥0,∑jαj=1.\mathbf h=\sum_j\alpha_j\mathbf v_j, \qquad \alpha_j\geq0,\qquad\sum_j\alpha_j=1.
ABC0.5A + 0.3B + 0.2Ch=0.5vA+0.3vB+0.2vC\mathbf h=0.5\mathbf v_A+0.3\mathbf v_B+0.2\mathbf v_C
Figure 21-1. A single head's weighted sum lies in the convex hull of its value vectors. This geometric statement does not apply unchanged after output projections and residual additions.

This weighted sum selects and mixes existing value vectors. We also want a dedicated operation that transforms the resulting contextual features at each position.

Be careful with the distinction: attention is not simply a linear average of the original embeddings. Its weights depend on queries and keys through Softmax, its values come from learned projections, and multi-head outputs have another projection. Attention already performs input-dependent nonlinear computation.

The motivation for adding an FFN is therefore not that attention can never compute a new feature. It is that a standard Transformer separates communication across positions from a flexible nonlinear transformation of each position's features.

Pause and think

Once attention has brought context into the last position, what familiar component can transform that contextual representation?

I've thought about it — show the answerHide answer

A feed-forward network. It can combine coordinates through a linear map, apply a nonlinearity and map the result back to the model width.

This is similar to the feed-forward language model in Lesson 16, but here the input to the FFN is already contextualised through attention.

3. Add a position-wise feed-forward network

The FFN operates on each row separately, using the same parameters at every position. With row-vector notation:

FFN⁡(x)=ReLU⁡(xW1+b1)W2+b2.\operatorname{FFN}(\mathbf x) =\operatorname{ReLU}(\mathbf xW_1+\mathbf b_1)W_2+\mathbf b_2.

Attention · exchange information across positions

cat
Shared FFN
Updated row
chases
Shared FFN
Updated row
dog
Shared FFN
Updated row
Figure 21-2. Attention mixes information across allowed positions. The same FFN then transforms each contextual row separately; its parameters are shared across positions.

“Separately” describes this operation's direct inputs. The rows have already received context from attention, so it does not mean that their representations are unrelated or that they use different FFN weights.

In the original model, the FFN used a 512→2048→512512\rightarrow2048\rightarrow512 arrangement:

W1∈R512×2048,W2∈R2048×512.W_1\in\mathbb R^{512\times2048},\qquad W_2\in\mathbb R^{2048\times512}.
  1. Contextual input · 512 coordinates
  2. First linear map · 2048 coordinates
  3. ReLU · coordinate-wise nonlinearity
  4. Second linear map · 512 coordinates
Figure 21-3. The original model expands each row from 512 to 2048 coordinates, applies ReLU, and projects back to 512. Fourfold expansion is a model choice, not a requirement.

Expanding the hidden width provides more intermediate nonlinear features. The second projection combines them and returns to the width expected by the next sublayer and residual connection.

For “small”, it is helpful to imagine features responding to contextual clues about size, animals or a description of the speaker. These are intuitions, not guaranteed meanings of individual hidden coordinates. Features can be distributed across coordinates and overlap.

ReLU replaces negative pre-activations with zero. It does not literally decide which linguistic facts are true. The hidden width and activation are architecture choices; other Transformers can use different widths, activations or gated FFNs.

Without the nonlinearity, two consecutive affine maps could be collapsed into one affine map. The hidden transformation and activation give this component its expressive role.

FFNs contain many learned parameters and can contribute to stored associations. It would be too strong to claim that all model knowledge lives there: embeddings, attention and the rest of the network also contribute.

4. Stack blocks and predict a continuation

The simplified block now has two main operations: attention exchanges information across positions, then the FFN transforms each contextual row.

Both return the model width. For a sequence of nn tokens with width dd:

X(ℓ)∈Rn×d⟶X(ℓ+1)∈Rn×d.X^{(\ell)}\in\mathbb R^{n\times d} \quad\longrightarrow\quad X^{(\ell+1)}\in\mathbb R^{n\times d}.

In our four-token example, a width of 512512 gives 4×5124\times512 inputs and outputs. Four is the example sequence length, not a fixed requirement. The model's supported context length and available resources limit how much text we can process.

Each block has its own learned parameters. Matching shapes let us feed one block's output into the next, updating the representations repeatedly.

  1. Token embeddings + positional information · n × d
  2. Block 1 · masked attention → FFN · n × d
  3. Block 2 · masked attention → FFN · n × d
  4. Block 3 · masked attention → FFN · n × d
  5. Last position → vocabulary logits → Softmax

Three blocks illustrate stacking. This is not a specification of a particular trained model.

Figure 21-4. A simplified causal language-model backbone. Each attention + FFN stage keeps the sequence shape. Residual connections and normalisation are omitted here and shown in Figure 21-6.

For generation, project the last position's representation into vocabulary logits and apply Softmax:

z=hn−1Wvocab+b,pj=ezj∑kezk.\mathbf z=\mathbf h_{n-1}W_{\mathrm{vocab}}+\mathbf b, \qquad p_j=\frac{e^{z_j}}{\sum_k e^{z_k}}.

Here Wvocab∈Rd×∣V∣W_{\mathrm{vocab}}\in\mathbb R^{d\times|\mathcal V|}, where ∣V∣|\mathcal V| is the vocabulary size. The probabilities are over tokens, which need not be complete words.

A model might assign probability to continuations such as “cat”, “dog” or “bird”; no trained predictions are being made in these diagrams. A decoding rule selects a token, appends it to the prompt and repeats. Greedy selection and sampling are different choices, so there is not always one inevitable continuation.

A straightforward implementation recomputes the prefix at each generation step. Later we will see how a key-value cache can reuse work.

Parallel training does not remove causal order

During training, the sequence is already known. A causal mask prevents a position from attending to later positions, while matrix operations calculate the allowed outputs for many positions in parallel. Shifted targets let each position predict the following token.

This is different from generation: ordinary autoregressive decoding must obtain a new token before using it to predict the next one. Layers also still depend on the outputs of earlier layers.

5. Put order back into the input

Compare “cat chases dog” with “dog chases cat”. The words are the same, but their positions change the meaning.

Unmasked self-attention with no positional information is permutation-equivariant: if we reorder its input rows, its output rows reorder correspondingly. It does not by itself attach a distinct representation to “cat at position zero” versus “cat at position two”. Shared position-wise FFNs retain this property.

A causal mask introduces an order-dependent access pattern, so a masked model is not simply an unordered bag of words. Nevertheless, positional mechanisms give it information about positions or relative distances beyond which tokens are allowed to interact.

A familiar approach adds a position vector to each token embedding:

xp=etp+rp.\mathbf x_p=\mathbf e_{t_p}+\mathbf r_p.

The original Transformer scaled its embeddings by d\sqrt d before this addition. We omit that scaling in the small input-vector experiment so the two contributions are easy to inspect.

For the original sinusoidal position scheme:

PE⁡(p,2i)=sin⁡ ⁣(p100002i/d),PE⁡(p,2i+1)=cos⁡ ⁣(p100002i/d).\begin{aligned} \operatorname{PE}(p,2i)&=\sin\!\left(\frac{p}{10000^{2i/d}}\right),\\ \operatorname{PE}(p,2i+1)&=\cos\!\left(\frac{p}{10000^{2i/d}}\right). \end{aligned}
Coordinate →01234567pos 0pos 1pos 2pos 3pos 4pos 5pos 6pos 7sin / cos pairs · different frequencies
Figure 21-5. Computed sinusoidal encodings for eight positions and eight coordinates. Shade maps values from −1 (pale) to +1 (dark); it is not an attention probability.

The paired coordinates use different frequencies. The vector changes with position, allowing the model to use order alongside token content. A deterministic encoding alone does not guarantee reliable generalisation to arbitrary lengths.

Position 0 · cat

Embedding: [1, 0, 0, 0]

Position vector: [0.000, 1.000, 0.000, 1.000]

Input: [1.000, 1.000, 0.000, 1.000]

Position 1 · chases

Embedding: [0, 1, 0, 0]

Position vector: [0.841, 0.540, 0.010, 1.000]

Input: [0.841, 1.540, 0.010, 1.000]

Position 2 · dog

Embedding: [0, 0, 1, 0]

Position vector: [0.909, -0.416, 0.020, 1.000]

Input: [0.909, -0.416, 1.020, 1.000]

Fixed four-coordinate teaching embeddings; no trained language model runs here. With positions disabled, each word keeps the same vector wherever it moves. Adding positions changes the vector attached to that word.

Experiment 21-A. Swap the subject and object and compare input vectors with and without positional information.

Learned position embeddings are another option. Rotary position embeddings, or RoPE, encode position through rotations of queries and keys rather than adding the same position vector to token embeddings. The implementation differs, but both provide positional structure for attention.

6. Assemble the complete backbone

We can now trace the journey from an input token to a continuation:

| Component | Role | | --- | --- | | Embedding lookup | Map token IDs to learned vectors. | | Positional mechanism | Represent position or relative order. | | Attention | Exchange information across permitted positions. | | FFN | Transform each contextual row with shared nonlinear processing. | | Stacked blocks | Repeat these updates with different parameters. | | Vocabulary projection and Softmax | Convert representations into next-token probabilities. |

Two more components belong in a standard block: residual connections and layer normalisation. A residual branch adds the sublayer's input to its output. Normalisation changes the scale and distribution of coordinates within a row using a defined normalisation operation and learned parameters.

For a post-norm causal self-attention block, omitting dropout:

A=LayerNorm⁡ ⁣(X+MHA⁡causal(X)),Y=LayerNorm⁡ ⁣(A+FFN⁡(A)).\begin{aligned} A&=\operatorname{LayerNorm}\!\left(X+\operatorname{MHA}_{\mathrm{causal}}(X)\right),\\ Y&=\operatorname{LayerNorm}\!\left(A+\operatorname{FFN}(A)\right). \end{aligned}
  1. Token IDs → embedding lookup + position encoding
  2. Masked multi-head self-attention
  3. Residual addition + LayerNorm
  4. Position-wise FFN
  5. Residual addition + LayerNorm
  6. Repeat blocks → final position representation
  7. Vocabulary projection → Softmax → select next token
  8. Append selected token → next generation step

Residual branches add each sublayer's input to its output. Many later models place normalisation before sublayers; this diagram uses post-norm to keep the historical example explicit.

Figure 21-6. A causal decoder-only overview using the original post-normalisation ordering for illustration. The original encoder-decoder Transformer also includes encoder output and cross-attention in its decoder.

This uses the original post-norm ordering to introduce the roles. Later architectures often normalise before sublayers, and some use other normalisation variants. We will examine residual paths and normalisation in their own lesson.

The original encoder-decoder model also has a separate encoder and an extra decoder cross-attention sublayer. Cross-attention lets decoder queries access encoder representations. Our decoder-only overview does not include that extra source sequence; the architecture comparison will come in Lesson 23.

7. What you have discovered

  • Attention exchanges contextual information, while an FFN transforms each contextual position through shared nonlinear processing.
  • Blocks keep the sequence's model width, making them straightforward to stack.
  • Position mechanisms supply structure beyond token identity.
  • Residual connections and normalisation are part of a standard block, rather than optional labels on an attention-only diagram.
  • Training can calculate known sequence positions in parallel under a causal mask. New tokens are ordinarily generated step by step.

We have assumed that text can be turned into token IDs. Next, we will examine the missing entrance to this pipeline: the tokenizer.

Check your understanding

1. Which components make up a standard Transformer block?
2. What does removing recurrent state updates make possible?