Chapter 2 · Foundations

Transformer Architecture

Chapter 1 treated the model as a black box. This chapter opens it. By the end you will understand attention well enough to explain why doubling the context window used to quadruple the cost, and why that single fact shaped the entire industry.

Builds on Chapter 1 1986 to 2017 Retail examples 14 interview drills Reading time ~50 min

2.1 Why open the box

You can build a working AI product knowing only Chapter 1. Plenty of people do. But three questions keep coming back, and none of them can be answered from outside the box.

  • Why did a 4K context window cost so much more than 2K, rather than twice as much?
  • Why can the model read a long prompt quickly but write a long answer slowly?
  • Why did everything in AI suddenly accelerate after 2017?

All three have the same answer: attention. This chapter builds that mechanism from nothing, with no mathematics beyond multiplication and addition.

[i] What you need from Chapter 1

Three things: text is split into tokens; the model produces a probability for every possible next token; and generation is a loop that runs the model once per output token. If any of those feel shaky, re-read sections 1.10 and 1.12 first — everything here builds directly on them.

2.2 The problem: order carries meaning

Start with the actual difficulty. Language is a sequence, and the same words in a different order mean different things.

Same words, opposite meaningstext
"the jacket is under the coat"
"the coat is under the jacket"

"return the item I bought"
"I bought the item, return"

A system that treats a sentence as an unordered bag of words cannot tell these apart. That was a genuine limitation of the statistical methods described in section 1.5 — they counted words without modelling arrangement.

There is a second, harder problem. Meaning depends on relationships between distant words, not just neighbouring ones.

[retail] The pronoun problem

Consider a customer message:

"I ordered the blue running shoes last Tuesday but they arrived scuffed, so I would like to return them."

To handle this, a model must connect "they" and "them" back to "shoes" — nine and fifteen words earlier respectively. Not to "Tuesday", which is closer. Not to "blue". Resolving which earlier word a later word refers to is the core skill, and the distance between them can be arbitrary.

2.3 What came before: recurrent networks

The pre-2017 answer was the recurrent neural network, or RNN, an idea dating to the 1980s and made practical by the LSTM variant in 1997.

[def] Recurrent neural network

An RNN reads a sequence one item at a time, maintaining a hidden state: a fixed-size bundle of numbers acting as memory. At each word it combines the new word with the current memory to produce updated memory. The same operation repeats for every word, which is what "recurrent" means.

The intuition is close to how a person reads: left to right, carrying a running sense of the sentence. That is genuinely appealing, and it worked well enough to power Google Translate from 2016.

How a recurrent network processes a sentence Five boxes in a row, one per word, connected left to right by arrows carrying a hidden state. Each box must wait for the previous one to finish, so processing is strictly sequential. A note shows that information from the first word has been compressed through four separate updates by the time the last word is reached. STRICTLY SEQUENTIAL: each step waits for the one before it step 1 "blue" state step 2 "shoes" state step 3 "arrived" state step 4 "scuffed" "they" to connect "they" back to "shoes", information must survive 4 rewrites of a fixed-size memory Two consequences. Training cannot be parallelised, because step 4 needs step 3's output. And early words fade, because every step overwrites the same fixed-size memory. Both problems get worse as sentences get longer.
Figure 2.1 — The recurrent approach. Reading left to right with a running memory is intuitive, but it forces every step to wait for the previous one and squeezes all earlier context through a fixed-size bottleneck.

2.4 The two walls RNNs hit

Recurrent networks were the state of the art for years. They were abandoned almost overnight because of two limitations that no amount of engineering could remove. Both are visible in Figure 2.1.

Wall one: information decay over distance

All memory of the sentence so far lives in one fixed-size bundle of numbers. Every new word overwrites part of it. By the time the model reaches "they", the trace of "shoes" has survived four rewrites and been diluted each time.

The LSTM, introduced in 1997, was designed specifically to slow this decay with learned gates controlling what to keep and what to discard. It genuinely helped, and it is why RNNs remained viable into the 2010s. But it delayed the problem rather than removing it. Beyond roughly 50 to 100 words, early context still faded.

[retail] What decay looked like in practice

A 2016-era support classifier reading a long customer complaint would frequently latch onto the emotional tone of the final sentence and miss the actual product mentioned in the first. Customers learned to put the important part last, which is a clear sign the technology was shaping the behaviour rather than serving it.

Wall two: training could not be parallelised

This is the one that actually killed the architecture, and it is an engineering constraint rather than a quality one.

Step 4 cannot begin until step 3 has produced its output. That dependency is inherent to the design. A GPU has thousands of cores that can work simultaneously, and a strictly sequential algorithm leaves nearly all of them idle.

[!] Why this mattered so much

Training a language model means processing a very large amount of text. If your architecture forces one word at a time, training time scales with the total number of words and cannot be reduced by adding hardware. That put a hard ceiling on model size. The scaling story of 2020 onward, where bigger models unlocked new capabilities, was simply not reachable with recurrent architectures. Not expensive — unreachable.

The bottleneck, stated plainly
Aspect Recurrent networks What was needed
Processing order Strictly one word at a time All words at once
Path between two distant words Grows with the distance Constant, however far apart
Memory of earlier context Fixed size, overwritten each step Direct access to every word
Use of GPU hardware Poor, mostly idle cores Saturated
In plain English: reading word by word means the beginning fades by the end, and it wastes the hardware. The fix has to let the model look at every word directly, all at the same time.

2.5 Attention, invented as a patch

Attention did not arrive as a replacement for recurrent networks. It arrived in 2014 as a fix for one of their symptoms, and only later turned out to be strong enough to stand alone.

[hist] 2014: Bahdanau attention

Bahdanau, Cho and Bengio were working on machine translation. The standard design squeezed an entire source sentence into a single fixed-size vector before starting to translate, and quality collapsed on long sentences for exactly the decay reason above. Their fix: instead of one summary vector, keep the representation of every source word, and let the translator look back at all of them, choosing what to focus on at each output step. They called that choosing attention.

The intuition is worth sitting with, because it is the whole idea. When a human translates "the shoes arrived scuffed" into another language, they do not memorise the sentence and then recite. They keep the sentence in front of them, and while writing each word they glance at the parts that matter for that word.

Attention is that glance, made mathematical: a weighted lookup where the model decides how much each other word matters right now.

[retail] Attention as a search over your own sentence

You already understand attention if you understand search. Processing the word "them" in our customer message, the model effectively runs a query:

"I am a plural pronoun in object position. Which earlier word am I standing in for?"

Every other word in the sentence is scored against that query. "Shoes" scores highly because it is a plural noun that can be returned. "Tuesday" scores low despite being closer. "Blue" scores moderately, because it modifies the thing in question. The model then builds its representation of "them" mostly from "shoes", a little from "blue", and almost nothing from "Tuesday".

Two properties fall out of this immediately, and they are exactly the two walls:

  • Distance stops mattering. Scoring "them" against "shoes" is one operation regardless of whether they are 3 words or 300 apart. No information has to survive intermediate rewrites.
  • Every word can be scored simultaneously. The score between "them" and "shoes" does not depend on the score between "them" and "Tuesday", so all of them can be computed at once, in parallel, on a GPU.

[hist] 2015: the simplification

Luong et al. simplified the scoring to a plain dot product between vectors, which is both cheaper and, as it turned out, sufficient. This is the direct ancestor of the scaled dot-product attention used in every model today.

For three years attention was an add-on: recurrent networks with an attention mechanism bolted alongside. Then someone asked the obvious question.

2.6 2017: attention is all you need

If attention already lets a model look directly at every word, what is the recurrence actually contributing? In June 2017, eight researchers at Google published a paper whose title answered that: Attention Is All You Need.

[hist] The paper that reset the field

Vaswani, Shazeer, Parmar, Uszkoreit, Jones, Gomez, Kaiser and Polosukhin removed recurrence entirely. No hidden state passed along, no sequential reading. Just attention, repeated in layers. They named the architecture the transformer.

It beat the best translation systems of the day while training in a fraction of the time, because it could finally use a GPU properly. Every major language model since — GPT, BERT, Claude, Gemini, Llama — is a transformer.

Recurrent, before 2017

  • Reads one word at a time, in order
  • Carries a fixed-size memory forward
  • Distant words connected through many steps
  • Training cannot be parallelised
  • Practical limit around 100 words

Transformer, 2017 onward

  • Reads every word simultaneously
  • No carried memory; direct access to all words
  • Any two words are one step apart
  • Training saturates GPU hardware
  • Limit set by compute, not by decay

[!] The cost of removing recurrence

Nothing is free. Reading sequentially gave the old models word order for nothing — step 3 obviously came after step 2. Look at every word simultaneously and you have thrown that away. To a bare attention mechanism, "the coat is under the jacket" and "the jacket is under the coat" are the same set of words. Section 2.10 covers positional encoding, which is how that gets fixed.

In plain English: transformers replaced "read the sentence word by word, remembering as you go" with "look at the whole sentence at once and decide what relates to what". That change is why models could suddenly be trained at scale.

2.7 Query, key and value

This is the heart of the chapter. Three terms that sound abstract until you see where the names come from, at which point they become obvious.

The names are borrowed from databases. Think about looking something up in a dictionary, or a product lookup in a shop system:

[def] The database analogy

  • Query — what you are looking for. "Show me waterproof jackets."
  • Key — the label on each stored item, used for matching. Each product's searchable attributes.
  • Value — the content you actually get back once something matches. The full product record.

A normal database lookup is exact: the key either matches or it does not, and you get back one item. Attention is a soft lookup: every key matches to some degree, and you get back a blend of all the values, weighted by how well each key matched.

Now the part that trips people up. In self-attention, every word produces all three. Each word simultaneously asks a question, advertises what it offers, and carries content to contribute.

What each role means for a single word in a sentence
Role The question it answers Example: the word "them"
Query What am I looking for? "I am a plural object pronoun. What noun do I refer to?"
Key What do I offer to others? "I am a pronoun, object position, plural."
Value What content do I contribute? The actual meaning representation of "them".

[+] Where the three come from

Each word starts as a single vector, a list of numbers representing it. That vector is multiplied by three separate matrices of learned weights, producing three different vectors: the query, the key and the value. Those three matrices are learned during training and shared across every word. So "what makes a good question" and "what makes a good advertisement" are not designed by a human — they are discovered from data.

[retail] Why one vector is not enough

A reasonable objection: why not just compare the word vectors directly and skip the three projections?

Because what a word seeks and what a word offers are different things. In "waterproof jacket", the word "jacket" is looking for adjectives that describe it, while simultaneously offering itself as a noun for adjectives to attach to. One vector cannot represent both roles cleanly. Splitting into query and key lets the model learn asymmetric relationships: "them" strongly seeks "shoes", but "shoes" does not particularly seek "them".

2.8 Attention scores, step by step

Time to actually compute one. We will use the sentence fragment "the blue shoes arrived scuffed" and work out what the word "scuffed" pays attention to. The numbers are illustrative but the procedure is exactly what runs inside every model.

  1. Produce a query, key and value for every word Five words in, so five queries, five keys and five values. Each is a list of numbers. We are computing the output for "scuffed", so we take its query and score it against every key, including its own.
  2. Score the query against each key with a dot product A dot product multiplies two vectors element by element and sums the result. It is large when two vectors point in a similar direction and small when they do not. That single number is how well this key answers this query.
  3. Scale the scores down Divide each score by the square root of the vector length. Without this, long vectors produce large dot products, and large numbers make the next step behave badly — probability collapses onto a single word and learning stalls. This is why the technique is called scaled dot-product attention.
  4. Softmax into weights Convert the scaled scores into positive numbers that sum to 1, exactly as in section 1.12. These are the attention weights: how much of each word to use.
  5. Blend the values Multiply each word's value vector by its weight and add them all up. The result replaces the representation of "scuffed" — now enriched with context from the words that mattered.
The entire mechanism, in five linespython
import numpy as np

def attention(Q, K, V):
    scores  = Q @ K.T # 1. every query against every key
    scores  = scores / np.sqrt(K.shape[-1]) # 2. scale
    weights = softmax(scores, axis=-1) # 3. to probabilities
    return weights @ V # 4. weighted blend of values

That is genuinely the whole thing. Every language model you have used is this operation, repeated across many heads and many layers, with a few supporting pieces covered in section 2.11.

Computing attention weights for one word The query vector for the word "scuffed" is scored against the key of every word in the sentence. Raw dot-product scores are scaled, then converted by softmax into weights that sum to one. The word "shoes" receives the largest weight at 0.52, followed by "arrived" at 0.21, while "the" receives almost nothing. QUERY FROM: "scuffed" — asking "what am I describing?" word raw score scaled weight after softmax "the" 1.2 0.42 0.03 "blue" 3.1 1.10 0.14 "shoes" 4.4 2.42 0.52 "arrived" 3.6 1.52 0.21 "scuffed" 2.8 0.99 0.10 weights always sum to exactly 1.00 The new representation of "scuffed" is now: 0.52 x value("shoes") + 0.21 x value("arrived") + 0.14 x value("blue") + 0.10 x value("scuffed") + 0.03 x value("the") "scuffed" now carries the information that it describes shoes. It has been contextualised.
Figure 2.2 — One attention operation for one word. Note that the model discovered "scuffed relates to shoes" from data alone; nobody wrote a grammar rule. Note also that "shoes" is three positions away and that cost nothing extra — the same computation would apply at three hundred positions.
In plain English: each word asks a question, every other word answers with how relevant it is, those answers are turned into percentages, and the word rebuilds itself as a weighted mixture of the words that mattered. That is attention.

2.9 Multi-head attention

One attention operation produces one set of weights, which means it can express one kind of relationship at a time. That is a real limitation, because words relate to each other in several ways simultaneously.

[retail] One sentence, several kinds of relationship

Take: "the blue shoes I ordered arrived scuffed"

  • Grammatical: "arrived" needs its subject, which is "shoes".
  • Descriptive: "blue" and "scuffed" both modify "shoes".
  • Referential: "I" is the customer, and connects to "ordered".
  • Sentiment: "scuffed" is the negative signal, and it attaches to the product rather than the delivery.

Forcing all four through a single set of attention weights means compromising on all of them. The solution is straightforward: run several attention operations in parallel, each with its own learned query, key and value matrices.

[def] Multi-head attention

Multi-head attention runs several independent attention operations side by side. Each one is a head, with its own learned projections, so each can specialise in a different type of relationship. Their outputs are joined together and passed through one more learned matrix to combine them. The 2017 paper used 8 heads; modern large models use 32 to 128.

The detail people miss

Adding 8 heads does not make the model 8 times more expensive. The vector is divided among the heads rather than duplicated. If a model works with 512-number vectors and has 8 heads, each head operates on 64 numbers. Total work is roughly unchanged; it has simply been split into 8 specialised views instead of one general one.

[+] What heads actually learn

Nobody assigns roles to heads. They differentiate on their own during training, and researchers examining trained models have found heads that consistently track identifiable patterns:

  • Heads that link pronouns to the nouns they refer to
  • Heads that connect verbs to their subjects
  • Heads that attend to the immediately preceding word
  • Heads that match opening and closing brackets or quotes
  • Heads that appear to track topic across a whole passage

[!] Do not over-read the interpretations

It is tempting to say "head 7 is the grammar head". Reality is messier: most heads are polysemantic, handling several unrelated patterns depending on context, and many heads can be removed entirely with little effect on quality. Attention maps are suggestive rather than an explanation of the model's reasoning. Treat published visualisations as illustrative, not definitive.

In plain English: instead of one reader deciding what relates to what, you get several readers looking for different things at the same time, then their notes are merged. Same total effort, much richer result.

2.10 Positional encoding

Section 2.6 flagged a debt: removing recurrence threw away word order. Time to pay it.

Attention as described so far is order-blind. It computes scores between pairs of words, and nothing in that computation refers to where a word sits. Shuffle the input and you get the same set of attention scores, just rearranged.

[!] Why this is fatal without a fix

"Refund the customer for the damaged item" and "the customer damaged the item, refund for" contain identical words. Order is the only thing distinguishing a routine instruction from nonsense. A retail assistant that cannot tell them apart is worthless.

[def] Positional encoding

Positional encoding adds information about each token's position directly into its vector, before attention runs. The word "shoes" at position 3 gets a slightly different vector from "shoes" at position 17. Attention stays order-blind; the inputs simply arrive carrying their position with them.

Approaches, and why the obvious ones fail

Ways to encode position, from naive to current practice
Approach Idea Problem
Add the index Append 1, 2, 3 to each vector Unbounded. Position 4,000 produces a huge number that swamps the actual meaning.
Normalise to 0 through 1 Divide position by sentence length The same value means different things in different-length inputs, so the model cannot learn a stable rule.
Sinusoidal (2017) Overlay sine and cosine waves of many frequencies Bounded and extends beyond training lengths, but encodes absolute position when relative distance usually matters more.
Learned (BERT, GPT-2) Train a vector for each position Works well, but cannot handle positions longer than it was trained on.
RoPE (2021) Rotate query and key vectors by an angle proportional to position Encodes relative distance naturally and extends further. Used by Llama, and most current models.

[+] Why rotation was the clever move

Rotary Position Embedding rotates each word's query and key by an angle set by its position. When two rotated vectors are compared with a dot product, the result depends on the difference between their angles — that is, on how far apart the words are, not where they sit absolutely. That matches how language actually works: "not" matters because of what it sits next to, wherever in the document that happens to be. It is also a large part of why context windows could grow past a few thousand tokens.

In plain English: attention cannot see order, so position is stamped onto each word before attention runs. Modern models do this by rotating vectors, which makes the model care about distance between words rather than absolute slots.

2.11 The rest of the block

Attention is the interesting part, but it is not the whole layer. A transformer block has three supporting components, and each exists to solve a specific problem.

Feed-forward network: where thinking happens

Attention moves information between words. It does not do much processing of the information itself — it is fundamentally a weighted average. After attention, each word passes through a small neural network on its own.

[def] Feed-forward network

A two-layer network applied to each position independently. It expands the vector to roughly four times its size, applies a non-linear function, then compresses it back. Because it is applied separately to each word with no mixing, all positions run in parallel. Despite being conceptually simple, the feed-forward layers hold roughly two thirds of a transformer's parameters, and there is good evidence they are where most factual knowledge is stored.

A useful division of labour: attention decides what is relevant; the feed-forward network decides what that means.

Residual connections: keeping deep networks trainable

Modern models stack many layers — 32, 80, sometimes more. Stacking naively fails, because the signal used to adjust weights during training shrinks as it passes back through each layer, until the earliest layers stop learning altogether.

[hist] 2015: the residual connection

Introduced in ResNet for image recognition, the fix is almost embarrassingly simple: add each layer's input to its output. The layer therefore only has to learn the change it wants to make, not reproduce everything it received. This gives the training signal a direct path back through the whole network, and it is what made networks deeper than about 20 layers practical. Transformers use it around both the attention and feed-forward sub-layers.

Layer normalisation: keeping numbers in range

With many layers each transforming numbers, values can drift steadily larger or smaller until training becomes unstable. Layer normalisation rescales each vector to a consistent statistical range before it enters the next sub-layer. It is plumbing rather than intelligence, but without it deep transformers do not train reliably.

Inside one transformer block A vertical flow diagram. Input enters, passes through layer normalisation and multi-head attention, then a residual connection adds the original input back. The result passes through layer normalisation again and a feed-forward network, followed by another residual add. The output feeds the next identical block. input from previous block layer normalisation MULTI-HEAD ATTENTION moves information between words + residual connection FEED-FORWARD NETWORK processes each word on its own + x 32 to 80 identical blocks stacked in series
Figure 2.3 — One transformer block. Attention mixes information across words; the feed-forward network processes each word individually; residual connections give the training signal a clear path; normalisation keeps the numbers stable. Stack this dozens of times and you have a language model.

2.12 Encoder, decoder, or both

The original 2017 transformer had two halves: an encoder that read the source sentence and a decoder that wrote the translation. That made sense for translation. It turned out you can use either half on its own, and which half you keep determines what the model is good at.

The three transformer families
Family Sees Good at Examples
Encoder only The whole input at once, both directions Understanding: classification, search, sentiment, embeddings BERT (2018), RoBERTa, most embedding models
Decoder only Only tokens before the current position Generating text GPT series, Claude, Llama, Gemini
Encoder-decoder Full input, generates output separately Transforming one text into another Original transformer, T5, BART

[+] Why decoder-only won for chat

Around 2020 it became clear that almost any task can be phrased as text continuation. Translation becomes "English: ... French:". Classification becomes "Sentiment:". Summarisation becomes "Summary:". One decoder-only model trained to continue text handles all of them, which is far simpler than maintaining a separate architecture per task. That realisation is what made the general-purpose assistant possible.

[retail] Both types in one storefront

A production retail stack usually runs both. An encoder model converts product descriptions and search queries into vectors for semantic search, and classifies incoming support tickets — it is small, fast and cheap, and it never writes text. A decoder model writes the assistant's replies and generates product copy. Using a large generative model for classification is a common and expensive mistake, as Chapter 1's drill 14 covered.

2.13 Causal attention

There is a problem with training a generative model. If the model can see the entire text at once, then when learning to predict word 5 it can simply look at word 5. It would score perfectly during training and produce nonsense in use, because at generation time the future does not exist yet.

[def] Causal masking

Causal masking, also called masked self-attention, blocks each position from attending to any later position. Before the softmax step, the scores for future tokens are set to negative infinity, which makes their weights exactly zero. Position 3 can attend to positions 1, 2 and 3, and nothing beyond.

The payoff is subtle and important. Because every position is masked independently, the model can be trained on an entire document in one parallel pass while still learning to predict each token from only its predecessors. A 1,000-token document provides 1,000 separate prediction exercises, all computed simultaneously.

[+] This is the parallelism win, concretely

An RNN learning from a 1,000-word document must take 1,000 sequential steps. A masked transformer learns the same 1,000 predictions in a single parallel pass. That difference — not any cleverness about language — is the practical reason transformers scaled and recurrent networks did not.

[!] Why encoder models are better at search

BERT-style encoders have no mask, so every word sees the full sentence in both directions. For understanding a query you already have in full, that is strictly better. It is also why encoders cannot generate: they have never learned to work from a prefix alone. The mask is the entire difference between the two families.

In plain English: generative models are deliberately blindfolded to the future during training, so they learn to predict rather than copy. That blindfold is applied to every position at once, which is what makes training fast.

2.14 Why context costs what it does

Now the question from section 2.1 can be answered properly.

Attention scores every token against every other token. With 10 tokens that is 100 comparisons. With 1,000 tokens it is 1,000,000. Double the input and the work quadruples, because you are filling a square grid.

Attention comparisons grow with the square of the input
Tokens in context Pairwise comparisons Relative to 1K
1,0001 million1x
2,0004 million4x
8,00064 million64x
32,0001.2 billion1,024x
128,00017.4 billion16,384x

[!] This is why long context was rationed

Early context limits were not arbitrary product decisions. Going from 2K to 32K tokens meant 256 times the attention computation, and the memory to hold that grid grew the same way. Memory was usually the binding constraint before speed was.

How the industry escaped the squeeze

Modern models handle 128K or more, which the table suggests should be impossible. Three developments changed the picture.

Techniques that made long context affordable
Technique Year What it changes
FlashAttention 2022 Never builds the full grid in memory. Computes it in tiles that fit in fast on-chip memory. Same mathematics, dramatically less memory traffic. The single biggest practical unlock.
Sparse and sliding-window attention 2019 onward Each token attends to a subset rather than everything. Cheaper, at some cost to quality on tasks needing genuinely global reasoning.
Grouped-query attention 2023 Several query heads share one set of keys and values, cutting the memory needed during generation.

[retail] What this means for your prompt design

The quadratic cost is why Chapter 1 recommended retrieving 5 relevant policy paragraphs rather than pasting the entire 40-page handbook. It is not only about the per-token price on your invoice: the attention work itself grows with the square of what you send, so the long prompt is slower as well as dearer. Retrieval is cheaper than context in both currencies.

[i] And why generation is slower than reading

The second question from section 2.1. Reading your prompt is one parallel pass over all tokens at once. Writing the reply is a loop: one full pass through the model per output token, because each token depends on the one before it. Input is parallel; output is inherently sequential. That asymmetry is why streaming exists as a user experience — and note the irony that generation is sequential for exactly the reason RNNs were.

2.15 Why transformers won

It is worth being precise about this, because the popular explanation is wrong. Transformers did not win because attention is a uniquely brilliant model of language. They won because of hardware.

[+] The actual reason

Attention is a large pile of matrix multiplications with no sequential dependency between positions. GPUs are machines built to do exactly that, thousands of operations at once. Recurrent networks had a dependency chain that left GPUs idle. The transformer was the first strong language architecture that could absorb as much hardware as you could afford to point at it.

That unlocked the sequence everything else followed from: train bigger models, on more data, in reasonable time. Which produced the scaling behaviour of 2020 onward, which produced the capabilities that made products like chat assistants viable.

Summary of the comparison
Property RNN / LSTM Transformer
Parallel over positionsNoYes
Path length between distant tokensProportional to distanceConstant
Cost per tokenConstantGrows with context length
Memory during generationFixedGrows with context
Scales with more hardwarePoorlyExtremely well

[!] Note rows three and four

RNNs are better on per-token cost and memory. A recurrent model processes token 50,000 as cheaply as token 5. The transformer trade was to accept worse per-token economics in exchange for parallel training. That was overwhelmingly the right trade, but it was a trade — which is precisely why the architectures in the next section are being actively researched.

2.16 Transformer limitations

Transformers are dominant, not perfect. Knowing the sharp edges is what separates understanding from repetition.

Limitation 1

Quadratic attention cost

Doubling context quadruples the work. Mitigated by FlashAttention and sparse variants, but not eliminated.

Limitation 2

Growing memory during generation

Keys and values for every previous token must be held in memory. Long conversations consume GPU memory steadily, which limits how many users a server can host.

Limitation 3

Sequential generation

One forward pass per output token. Long answers are inherently slow, no matter how much hardware you add.

Limitation 4

No memory between requests

Everything must fit in the context window. This is the statelessness from section 1.11, and it is architectural rather than an oversight.

Limitation 5

Fixed compute per token

The same work is spent on a trivial token as on a hard one. There is no built-in way to think longer about a difficult passage.

Limitation 6

Data hunger

Removing recurrence also removed a built-in assumption about sequence structure, so transformers must learn it from very large volumes of data.

[hist] What might come next

State space models such as Mamba (2023) revive the recurrent idea of constant per-token cost, while restructuring the mathematics so training still parallelises. They are promising for very long sequences. Mixture of experts activates only a fraction of parameters per token, cutting cost at a given capacity, and is already in production use. Neither has displaced the transformer, and betting on a successor is a way to sound confident and be wrong. The honest position: transformers dominate today, their limitations are well understood, and alternatives are credible but unproven at frontier scale.

2.17 Key takeaways

  1. Order carries meaning, and modelling relationships between distant words is the central difficulty in language.
  2. RNNs read sequentially, carrying a fixed-size memory. Intuitive, and the basis of the field until 2017.
  3. They hit two walls: early context decayed, and training could not be parallelised. The second one was fatal.
  4. Attention arrived in 2014 as a patch for translation quality, letting a model look back at every source word.
  5. In 2017 the recurrence was removed entirely. Attention alone was enough, and the transformer was named.
  6. Query, key and value come from database vocabulary. Every word produces all three; attention is a soft lookup returning a weighted blend.
  7. The computation is four steps: dot-product scores, scale, softmax, weighted sum of values.
  8. Multi-head attention runs several attention operations in parallel on split vectors, so different heads capture different relationships at no extra total cost.
  9. Positional encoding is required because attention is order-blind. Modern models use rotation, which encodes relative distance.
  10. A block is attention plus a feed-forward network, wrapped in residual connections and normalisation. The feed-forward layers hold most of the parameters and most of the factual knowledge.
  11. Encoder models understand, decoder models generate. The only real difference is the causal mask.
  12. Causal masking lets a whole document be trained on in one parallel pass while still learning genuine prediction.
  13. Cost grows with the square of context length, which is why long prompts are expensive in both money and latency.
  14. Transformers won on hardware efficiency, not on being a superior theory of language. They accepted worse per-token economics for parallel training.

[i] Vocabulary check

You should now be able to explain, without notes: attention, query, key, value, softmax, multi-head, attention head, positional encoding, RoPE, feed-forward network, residual connection, layer normalisation, encoder, decoder, causal mask, self-attention, quadratic scaling, FlashAttention. If any are hazy, the section number is in the sidebar.

2.18 Interview drills

Transformer questions separate people who have read a blog post from people who understand the mechanism. The tell is usually whether you can explain why a design choice exists, not just name it.

1. Explain attention to someone non-technical.

When you read a sentence, you do not weigh every word equally. Reading "the blue shoes arrived scuffed", to understand "scuffed" you automatically look back at "shoes", because that is the thing being described. You mostly ignore "the".

Attention is that, made mathematical. Every word asks a question, every other word scores how well it answers, the scores become percentages, and the word rebuilds its meaning as a weighted mixture of the words that mattered. Crucially nobody wrote those rules — the model learned which words matter from data.

What is tested: whether you can teach. Leading with a familiar experience rather than "queries and keys" is what a good answer sounds like.

2. What are query, key and value?

Database terms. The query is what a word is looking for, the key is what each word advertises about itself for matching, and the value is the content that gets returned. In self-attention every word produces all three by multiplying its vector by three separate learned matrices.

The difference from a database is that the lookup is soft. Rather than one exact match, every key matches to some degree and you get back a weighted blend of all the values.

Likely follow-up: "Why three projections instead of comparing word vectors directly?" Because what a word seeks and what it offers are different things, and one vector cannot represent both. Splitting them allows asymmetric relationships.

3. Why divide by the square root of the dimension?

To keep the softmax in a usable range. Dot products of longer vectors produce larger values, and large values make softmax extremely peaked — nearly all the weight lands on one token.

That hurts twice. The model loses the ability to blend information from several words, and during training the gradients through a saturated softmax become vanishingly small, so learning stalls. Scaling by the square root of the key dimension keeps the variance of the scores roughly constant regardless of vector size.

Signal: mentioning gradients. Many candidates know the formula but not that the reason is trainability.

4. Why is positional encoding necessary?

Because attention is order-blind. It computes scores between pairs of words and nothing in that computation references position, so shuffling the input produces the same scores rearranged. "The coat is under the jacket" and "the jacket is under the coat" would be identical.

Recurrent models got order for free by reading sequentially. Transformers gave that up in exchange for parallelism, so position has to be added back explicitly — stamped into each token's vector before attention runs.

Follow-up: "Which method?" Sinusoidal in 2017, learned in BERT and GPT-2, and RoPE in most current models because rotation naturally encodes relative distance rather than absolute position.

5. Why multiple attention heads?

One set of attention weights can only express one kind of relationship at a time, but words relate in several ways simultaneously — grammatical subject, descriptive modifier, coreference, sentiment. Forcing all of that through one head means compromising on all of it.

The important detail is that heads are not extra cost. The vector is divided among them rather than duplicated: 512 dimensions across 8 heads means 64 each. You get several specialised views for roughly the price of one general one.

Depth marker: adding that head interpretations are messier than the popular visualisations suggest — most heads are polysemantic and many can be pruned with little loss.

6. Why does context length increase cost quadratically?

Because every token is scored against every other token. That is a square grid: n tokens produce n-squared comparisons. A thousand tokens is a million comparisons; two thousand is four million. Double the input, quadruple the work.

In practice memory bound this before speed did, since the grid had to be held during computation. FlashAttention in 2022 was the major unlock: it computes the same result in tiles that fit in fast on-chip memory, so the full grid is never materialised. Sparse attention and grouped-query attention attack the same problem from different angles.

7. Why is generating a long answer slower than reading a long prompt?

Reading is one parallel pass. Every input token is processed simultaneously, because they are all available at once.

Generating is a loop. Each output token requires a complete forward pass through the model, and cannot start until the previous token exists, because it becomes part of the input. Input is parallel, output is inherently sequential. That is why time-to-first-token and tokens-per-second are separate metrics, and why streaming matters so much for perceived speed.

Nice observation to add: generation is sequential for exactly the reason RNNs were slow. Transformers solved the training bottleneck, not the generation one.

8. What is the difference between BERT and GPT?

Structurally, one thing: the causal mask. BERT is encoder-only with no mask, so every token sees the whole input in both directions. GPT is decoder-only with a mask, so each token sees only what came before it.

That single difference determines everything else. Bidirectional context makes BERT better at understanding text you already have — classification, search, embeddings. But it cannot generate, because it never learned to work from a prefix alone. GPT gives up seeing the future and gains the ability to continue text, which turned out to subsume almost every task.

Retail framing: BERT-family models embed your catalogue and route tickets; GPT-family models write the replies. Most production stacks run both.

9. What does the feed-forward network contribute?

Attention only moves information between positions — it is a weighted average, so it does not do much transformation. The feed-forward network processes each position independently, expanding the vector roughly fourfold, applying a non-linearity, and compressing back.

The clean summary is: attention decides what is relevant, the feed-forward network decides what it means. Worth knowing that these layers hold about two thirds of the parameters, and there is good evidence they are where factual knowledge lives.

10. Why do transformers need residual connections?

Because deep networks otherwise fail to train. The signal used to update weights shrinks as it propagates back through layers, so in a stack of 80 the earliest layers receive almost nothing and stop learning.

Adding each sub-layer's input to its output gives that signal a direct path backwards through the entire network. It also reframes what each layer does: it only has to learn the modification it wants to make, rather than reconstructing everything it was given. The idea came from ResNet in 2015 and is why networks deeper than about 20 layers became practical at all.

11. What are the main limitations of the transformer architecture?

I would name four, in order of practical impact.

Quadratic attention cost. Doubling context quadruples the work. Mitigated by FlashAttention, not removed.

Memory growth during generation. Keys and values for every prior token must be retained, so long conversations consume GPU memory and limit how many users a server can hold.

Sequential generation. One forward pass per output token; hardware cannot fix it.

Fixed compute per token. The same work is spent on an easy token as a hard one, with no built-in way to think longer where it matters.

Strong close: note that RNNs beat transformers on per-token cost and memory. The transformer accepted worse inference economics to get parallel training, and that trade is why state space models are being explored.

12. Could something replace transformers?

Possibly, and there are credible candidates. State space models such as Mamba from 2023 recover the constant per-token cost of recurrence while restructuring the mathematics so training still parallelises, which is attractive for very long sequences. Mixture-of-experts activates only a fraction of parameters per token and is already in production.

But nothing has displaced the transformer at frontier scale, and there is an enormous accumulated investment in tooling, hardware and technique around it. I would say the limitations are well understood and actively worked on, and I would be sceptical of anyone confidently naming the successor.

What is tested: calibration. Both "transformers are eternal" and "Mamba is about to win" are wrong answers.

13. A customer complains your assistant is slow. How does architecture inform your diagnosis?

I would separate the two phases, because they have different causes and different fixes.

Slow to start responding points at input processing. The prompt is likely too long — and because attention is quadratic, an oversized prompt hurts more than proportionally. The fix is retrieving fewer, better passages rather than padding the context.

Slow while responding points at generation, which is one forward pass per token and cannot be parallelised. Fixes are a smaller model, shorter outputs, or streaming so the user sees progress immediately. If nothing changed on our side, I would also check whether the provider silently updated the model version.

Signal: splitting time-to-first-token from tokens-per-second unprompted. That is the first thing an experienced person measures.

14. Walk me through what happens to the sentence "return my order" inside a transformer.

Tokenise into subwords, then look up an embedding vector for each, and add positional information so the model knows the order.

Then, per block: layer-normalise, run multi-head attention so each token gathers relevant information from the others — "return" attending to "order" to establish what is being returned — add the residual, then pass each token through the feed-forward network and add the residual again.

Repeat for every block. Early layers tend to capture local syntax, later layers more abstract meaning.

At the end, the final position's vector is projected onto the vocabulary to produce a score for every possible next token, softmax turns those into probabilities, and one is sampled according to the temperature settings. Then the whole thing repeats with that token appended.

This is the synthesis question. Being able to narrate the full path end to end, without notes, is the clearest demonstration that the pieces have connected.

[+] Preparation advice

If you can only rehearse two, make them question 1 and question 14. Explaining attention simply proves you understand it; narrating the full forward pass proves you understand how the parts fit. Most other questions are subsets of those two.

2.19 Where this leads

The box is open. You know what happens between prompt and response, and you can explain the cost and latency behaviour of any model you use from first principles.

One thing was assumed throughout this chapter and never justified: that words can be turned into vectors where mathematical operations correspond to meaning. Attention compares query and key vectors with a dot product and treats a high value as "relevant" — but why should arithmetic on lists of numbers have anything to do with meaning at all?

Chapter 3 answers that. Embeddings are the bridge between language and mathematics, and they are also the foundation of semantic search, which is the first genuinely useful AI feature most retail teams ship.