Pranav Srivastava
Learning tracks
publishedIntermediate10 chapters

Attention & Transformers

The single idea — letting a model decide what to pay attention to — that fixed the memory problem in older networks and became the architecture behind every modern AI. Built from true first principles: the actual query/key/value maths, worked by hand, plus positional encoding, multi-head attention, and the full transformer block — explained so clearly a 15-year-old could follow every step.

Updated September 11, 2026

AttentionTransformersSelf-AttentionLLMsPositional EncodingMulti-Head Attention

Almost every AI you have heard of — ChatGPT, Claude, Gemini, image generators, translation, even the tool folding proteins in a lab — runs on one architecture: the transformer. And the transformer is built from one idea, repeated and stacked: attention. This course does not wave its hands at that idea. It builds it from the ground up — the actual arithmetic, worked by hand with numbers small enough to check yourself — until you could, if you wanted to, explain the whole thing to a curious 14-year-old without lying to them once.

What you will learn
  • Feel, in your gut, exactly why older networks struggled with long sentences
  • Understand attention as a mechanism, not a metaphor — Query, Key, Value, worked by hand
  • Read a real attention pattern and explain why it changes with context
  • Know why a model needs to be told word order separately, and how positional encoding does it
  • Understand multi-head attention and why one "spotlight" was never going to be enough
  • See the complete transformer block — every piece, and what each one is for
  • Explain why speed and quality together, not either alone, is what let this architecture take over
  • Know the difference between an encoder and a decoder, and why ChatGPT writes one word at a time
  • Recognise the same idea at work outside text — vision, audio, biology
112 min

The problem: a sentence read through a straw

Before attention existed, the standard way to have a neural network read a sentence was a recurrent neural network, or RNN — covered in the Deep Learning course. Picture it like someone reading a book one word at a time through a cardboard tube, jotting a short note in the margin after every word to remind themselves what mattered so far, then covering that word up and moving to the next. The note is all they carry forward. Everything not captured in the note is gone.

That "note" is called the hidden state, and it has a fixed size — the same number of numbers, no matter how long the sentence gets. Try to picture what that means: a two-word sentence and a two-hundred-word paragraph get squeezed into the exact same amount of memory. Something has to get dropped, and it's usually whatever came first.

Here's where that actually bites. Read this sentence and answer instantly, without thinking about it:

"The trophy did not fit in the brown suitcase because it was too big."

What does "it" refer to? You knew before you finished reading — the trophy, obviously; a suitcase being "too big" wouldn't stop something fitting inside it. Now read this one:

"The trophy did not fit in the brown suitcase because it was too small."

Change one word — "big" to "small" — and "it" now means the suitcase. You didn't even notice yourself doing this. Your brain silently reached all the way back across ten words, picked out exactly the right noun, and updated its answer the instant "small" appeared. That's not a party trick. Linguists call this exact kind of sentence a Winograd schema, and it's used as a genuine test of whether a system understands language or is just pattern-matching, because getting it right requires holding the whole sentence in mind at once, not reading it through a straw.

Chapter summary
  • RNNs read one word at a time and compress everything into a fixed-size "note" (the hidden state)
  • Long sentences overflow that note — early words fade as new ones arrive
  • Winograd sentences (the trophy/suitcase pair) prove real understanding requires the whole sentence at once, not a summary of it
  • This is precisely the problem attention was invented to solve
Check your understanding
  1. Why does changing "big" to "small" flip the meaning of "it" — and why is that hard for an RNN specifically?
  2. In your own words, what is a "hidden state," and why is its fixed size the actual source of the problem?
210 min

The core idea: what 'paying attention' really means

Before any maths, let's get the feeling of attention right, because the feeling is the whole idea — the arithmetic in the next chapter is just a way of making the feeling precise enough for a computer to do it.

You already do this constantly. At a noisy party, dozens of conversations are hitting your ears at once, but the moment someone across the room says your name, you hear it instantly — your brain was quietly monitoring everything, ready to snap focus onto whatever mattered. Psychologists call this the cocktail party effect, and it's a genuinely good description of what attention does inside a model: it isn't reading one thing at a time and forgetting the rest. It's looking at everything at once, and deciding, for whatever it's currently focused on, which of all the other things actually matter — and by how much.

Or think about skimming a long legal contract. You hit the phrase "the aforementioned party" and your eyes don't re-read the whole document from the top — they flick back to the exact clause that defined who that was, ignore everything else on the page, and return. That flick — precise, selective, instant — is attention. Not reading everything with equal care. Reading everything, but unevenly, on purpose, based on what's relevant right now.

Chapter summary
  • Attention looks at the whole input at once, then decides what to focus on — like the cocktail-party effect
  • It isn't "read everything equally." It's "read everything, but weight it by relevance"
  • Self-attention: words in a sentence deciding how much to focus on other words in that same sentence
320 min

Query, Key, Value — the actual mechanism

Here is the part almost every "attention explained simply" article skips, and it's the part that actually matters. The cocktail-party feeling is nice, but how does a model actually compute "focus on this word 70% and that one 20%"? This chapter builds it from scratch, with a library-desk analogy and numbers small enough to check by hand.

Imagine a librarian's front desk. Every word in the sentence, as it's processed, does three things:

  • It writes a Query — a short description, as a list of numbers, of what it's looking for to complete its own meaning.
  • It writes a Key — a short tag describing what kind of information it offers to anyone searching.
  • It carries a Value — its actual content, what gets handed over if it's chosen.

Query, Key and Value are the same idea a search engine uses: your search box is the Query, the index tags on every webpage are the Keys, and the actual page content is the Value. Attention is a search, run separately for every single word, against every other word in the sentence, all at once.

Query, Key, Value — the whole mechanism, five small steps

1. The Query

What is the word “it” looking for?

Think of a librarian's desk. Every word, as it's processed, writes down a Query — a short description, as a list of numbers, of what kind of information it needs to fully understand itself.

Query(“it”) = [1.4, 0.5] — leaning toward “big, physical object” things

These are toy 2-number vectors so the arithmetic stays checkable by hand. A real model uses hundreds of numbers per word — same five steps, just much wider.

Walk through what just happened, because every one of those five steps has a name worth knowing: the model computed a score for how well the Query matched each Key (a dot product — just "multiply and add," a way of measuring how alike two lists of numbers are); it ran those scores through softmax, which is a clean mathematical way of turning any list of numbers into honest percentages that add up to exactly 1; and it used those percentages to blend the Values into one new, context-aware meaning. That entire five-step recipe — Query, Key, Score, Softmax, weighted Value — is attention. Everything else in this course is either preparing inputs for that recipe or stacking many copies of it together.

tiny_attention.py
import numpy as np

def softmax(x):
    x = x - np.max(x)  # for numerical stability
    e = np.exp(x)
    return e / e.sum()

def self_attention(X, Wq, Wk, Wv):
    """
    X:  (seq_len, d_model) — one embedding row per word
    Wq, Wk, Wv: (d_model, d_k) — learned projection matrices
    Returns: (seq_len, d_k) — one new, context-aware vector per word
    """
    Q = X @ Wq                          # every word's Query
    K = X @ Wk                          # every word's Key
    V = X @ Wv                          # every word's Value

    d_k = K.shape[-1]
    scores = (Q @ K.T) / np.sqrt(d_k)   # every Query vs. every Key
    weights = np.apply_along_axis(softmax, 1, scores)  # rows sum to 1

    return weights @ V                  # weighted blend of Values

# A toy sentence with 4 words, each an 8-number embedding
X = np.random.randn(4, 8)
Wq, Wk, Wv = (np.random.randn(8, 8) for _ in range(3))

output = self_attention(X, Wq, Wk, Wv)
print(output.shape)  # (4, 8) — one new, context-aware vector per word
Chapter summary
  • Every word produces a Query (what it needs), a Key (what it offers), and a Value (its actual content)
  • Score = Query · Key (a dot product — how alike two number-lists are)
  • Softmax turns scores into percentages that sum to 1
  • The output is a weighted blend of every word's Value, using those percentages
  • Q, K, V come from three matrices the model learns during training — nobody hand-writes them
Check your understanding
  1. In the worked example, why does "it" end up mostly blended with "trophy" rather than split evenly across all words?
  2. What would happen to the output if every Key were identical? (Hint: think about what softmax would produce.)
410 min

Seeing it work: a real attention pattern

Theory earns its keep once you can actually watch it happen. Here is the Winograd sentence from Chapter 1, with attention weights laid out exactly the way a real trained model's would look — pick a word, see where its attention goes, and watch what happens when one word in the sentence changes.

Click a word — see what it's paying attention to

Attention weight from “it” → every word (darker = stronger, all weights sum to 1)

The
0.03
trophy
0.62
did
0.02
not
0.02
fit
0.03
in
0.02
the
0.02
suitcase
0.08
because
0.05
it
0.05
was
0.02
too
0.02
big
0.02

“It” attends most strongly to “trophy” — a trophy is the kind of thing that can be too big to fit.

These specific numbers are illustrative — set by hand to make the pattern easy to see — but the shape is exactly how a trained model's attention weights actually behave.

Sit with the second example for a second, because it's the whole argument in one click. Nothing about where "it" sits in the sentence changed — same position, ninth word, every time. The only thing that changed was meaning — "big" swapped for "small" — and the model's attention followed the meaning, not the position. That is the entire case for attention over the old straw-reading approach, made concrete: it isn't tracking distance. It's tracking relevance.

Chapter summary
  • Attention weights are context-sensitive, not position-sensitive
  • Swapping one word can completely change where attention flows, even though word position stays fixed
  • This is direct evidence attention captures meaning, not just "look nearby"
512 min

Multiple spotlights: multi-head attention

One attention "search" is already powerful — but a sentence has many kinds of relationships happening simultaneously. "Quick" describes "fox." "Fox" is the subject of "jumps." "Fox" and "dog" are quietly linked as the two animals in the scene. Asking one single Query/Key/Value setup to capture all of that at once is asking a lot from one spotlight.

So transformers don't use one. They run several attention "heads" in parallel — each with its own learned Query, Key and Value matrices — so each head is free to specialise in a different kind of relationship, entirely on its own, during training.

Multiple heads, watching the same sentence differently
Thequickfoxjumpsoverthelazydog

Head 1 specialises in:

Adjective → noun (which word describes which)

In practice a model runs many of these — GPT-3-scale models use 96 heads per layer — each with its own Query/Key/Value, all computed in parallel and then combined. Nobody hand-assigns what each head learns; it falls out of training, and researchers finding these interpretable patterns after the fact is one of the more genuinely delightful discoveries in the field.

Nobody tells Head 1 "you're in charge of adjectives" or Head 4 "you handle animal pairs." Those specialisations emerge from training, purely because splitting the work that way happens to make the model better at predicting language. Researchers going back into trained models afterward and finding heads that cleanly track syntax, or coreference, or position, is one of the genuinely delightful discoveries in this whole field — a bit like performing an autopsy and finding the patient had quietly organised their own internal departments.

Chapter summary
  • One attention head can only really specialise in one kind of relationship at a time
  • Multi-head attention runs several heads in parallel, each with its own learned Q/K/V
  • Specialisation (syntax, coreference, position…) emerges from training — it's never hand-assigned
  • Heads' outputs get combined by one more small learned layer
Check your understanding
  1. Why might a single attention head struggle to capture both "which adjective describes which noun" and "which word is far away but still related"?
  2. What does it mean that head specialisation "emerges" rather than being programmed in?
612 min

Teaching the model about order

Here's a gap in everything we've built so far, and it's a genuinely important one: nothing about Query, Key, Value or softmax mentions order. Attention compares every word to every other word as an unordered set — as far as the maths in Chapter 3 is concerned, "the dog bit the man" and "the man bit the dog" contain exactly the same words attending to exactly the same words. Obviously those two sentences mean opposite things. Something has to tell the model which word came first.

The fix, called positional encoding, is one of the more elegant ideas in the whole architecture. Before attention ever runs, every position in the sentence gets its own unique numeric fingerprint, generated from waves — and it's added directly onto that word's embedding.

Why the model needs to be told where each word sits

Attention compares every word to every other word — but nothing about that comparison mentions order. On its own, attention would read “the dog bit the man” and “the man bit the dog” as the exact same bag of words. So before anything else happens, every position gets its own unique numeric fingerprint — generated from waves like a clock's hands, some ticking fast, some slow — and that fingerprint is added onto the word.

dim 0
dim 1
dim 2
dim 3
dim 4
dim 5
dim 6
dim 7

Row 3 selected — click any row to compare fingerprints. Notice: dim 0 changes almost every row (the fast-ticking hand — great for telling neighbours apart), while the columns further right barely move over these 12 rows (the slow-ticking hands — great for telling distant positions apart). Together, every position — near or far — ends up with a fingerprint no other position shares.

A bonus this buys almost for free: positions 3 and 4 end up with very similar fingerprints (both fast-hand columns are close), while position 3 and position 11 look quite different. The encoding doesn't just say which position a word is at — it says how far it is from every other position too.

The clock analogy is worth sitting with, because it explains why waves specifically. Picture a clock with several hands moving at very different speeds. The fastest hand distinguishes this second from the last one — perfect for telling neighbouring positions apart, useless for anything far away, since it loops back round constantly. The slowest hand barely moves at all over a short span — useless for nearby positions, perfect for telling position 3 apart from position 300. Positional encoding uses a whole family of these hands, each ticking at a different frequency, and together they give every single position in a sentence — however long — its own fingerprint that no other position shares, while also making nearby positions look naturally similar to each other. That second property matters: the model doesn't just learn "this is position 9." It learns "this position is close to position 8 and far from position 40," which turns out to be exactly the kind of information attention can put to good use.

Chapter summary
  • Attention alone has no concept of word order — it treats the sentence as an unordered set of comparisons
  • Positional encoding adds a unique numeric "fingerprint" to each position, before attention runs
  • Built from waves at many frequencies — fast ones distinguish neighbours, slow ones distinguish distant positions
  • Nearby positions end up with naturally similar fingerprints — a useful side effect, not an accident
Check your understanding
  1. Without positional encoding, why would "the dog bit the man" and "the man bit the dog" look identical to self-attention?
  2. Why use many different wave frequencies instead of just one?
714 min

Putting it all together: one transformer block

Time to assemble every piece into the actual architecture. A single transformer block is smaller than it sounds once you've built each part — it's multi-head attention, plus a couple of standard neural-network habits that make deep networks trainable at all.

One transformer block, start to finish
This block gets stacked N times — GPT-3 stacks it 96 times — each layer refining the meaning built by the last.

Two pieces here weren't covered yet, and both exist purely to make very deep networks actually trainable:

The residual connection ("Add") is simple and important: alongside the attention layer's output, the block also adds back the original input, unchanged. Think of it as a highway running straight through the block, with attention as an off-ramp that adds a correction rather than replacing the signal entirely. Without this, stacking 96 layers tends to make training unstable — small errors compound layer after layer until the signal is unrecognisable. The highway means even if one layer contributes almost nothing useful, information can still flow cleanly past it.

Layer normalisation ("Normalise") rescales the numbers flowing through the network so they stay in a sane, consistent range at every layer — roughly, it keeps the "volume" from drifting too loud or too quiet as data passes through dozens of stacked blocks, which again keeps training stable.

The feed-forward network is the one genuinely new piece: after attention has gathered context from other words, each word passes through its own small, ordinary neural network — the same one, reused for every word — giving the model extra capacity to process what attention just found, on a word-by-word basis, before passing everything to the next block.

Chapter summary
  • A transformer block: positional encoding → multi-head attention → add & normalise → feed-forward → add & normalise
  • Residual connections let information skip past a layer cleanly, keeping deep networks trainable
  • Layer normalisation keeps the numbers flowing through the network in a stable range
  • The feed-forward network gives each word extra "thinking" capacity after attention gathers context
  • Stacking many blocks lets understanding build in layers, simple patterns first, abstract ones later
Check your understanding
  1. What problem do residual connections solve, and why does it get worse with more layers?
  2. Put the five pieces of a transformer block in the correct order, from memory.
810 min

Why this one idea won

There were plenty of clever sequence-processing ideas before and around the transformer. Why did this one take over so completely? Because it hit a genuinely rare combination: it was better at understanding long-range meaning (any word can attend directly to any other, no matter the distance — the straw is gone entirely) and, separately, cheaper to scale.

That second part is easy to undervalue, so it's worth spelling out. An RNN has to process word 1, then word 2, then word 3 — strictly in order, because each step needs the previous one's result. That's a hard ceiling on how much you can speed things up with more hardware. Attention has no such requirement: every word's Query, Key and Value can be computed simultaneously, and every attention score can be computed in parallel too. That maps almost perfectly onto how GPUs work — thousands of small calculations happening at once — which meant transformers could be trained on vastly more text, vastly faster, for a given amount of hardware.

Chapter summary
  • Transformers combine two advantages usually traded off against each other: better long-range understanding and cheaper, parallel training
  • RNNs are stuck processing one step at a time; attention computes everything at once
  • Parallel training is why transformers could scale to enormous datasets affordably
  • Scale, once affordable, turned out to reliably improve quality — which is the direct cause of today's large language models
Check your understanding
  1. Name the transformer's two advantages, and explain why having both together (not just one) mattered so much.
  2. Why couldn't RNNs simply be trained on more hardware in parallel the same way?
912 min

Reading vs. writing: why ChatGPT writes one word at a time

One more piece completes the picture, and it explains something that might otherwise seem strange: if attention lets every word see every other word at once, why does ChatGPT still visibly type its answer out one word at a time, left to right?

The transformer architecture actually comes in three shapes, depending on the job:

  • An encoder reads an entire input and lets every word attend freely to every other word, including ones that come after it — good for understanding a full piece of text at once (translation input, classification, search).
  • A decoder generates text one step at a time, and uses causal (masked) attention: when producing word 12, it's mathematically forbidden from attending to words 13 onward, because they don't exist yet. This is precisely why ChatGPT, Claude, and essentially every modern chat model write left to right — it isn't a UI choice, it's baked into how the model is allowed to attend.
  • An encoder-decoder pairs both: an encoder fully understands the input (say, a French sentence), and a decoder generates the output (the English translation) one word at a time, attending both to its own previous words and, separately, to the encoder's full understanding of the input — this second kind of attention, pointing at a different piece of text entirely, is called cross-attention.
Chapter summary
  • Encoders let every word see every other word — good for understanding a complete input
  • Decoders use causal (masked) attention — a word can only attend to itself and earlier words, forcing left-to-right generation
  • Encoder-decoders combine both, with cross-attention letting the decoder consult the encoder's understanding
  • Most modern LLMs are decoder-only — one flexible training objective (predict the next word) turned out to be enough
Check your understanding
  1. Why can't a decoder attend to words that come after the one it's currently generating?
  2. What's the difference between self-attention and cross-attention?
108 min

One idea, everywhere

The remarkable postscript to all of this: attention was invented for language, and it turned out not to care what kind of data it was looking at.

1

Vision

Vision Transformers (ViT) slice an image into a grid of small patches, treat each patch the way a word gets treated, and run the exact same attention mechanism across them. A patch of a cat's ear can attend directly to a patch of its whisker on the other side of the image — no need to scan pixel by pixel the way older vision networks did.

2

Biology

DeepMind's AlphaFold, which cracked the fifty-year-old problem of predicting a protein's 3D shape from its amino-acid sequence, leans heavily on attention-style mechanisms to model which distant parts of a long protein chain influence each other — the exact same "any position can attend to any other position" idea, applied to biology instead of language.

3

Audio

OpenAI's Whisper transcribes speech using a transformer that treats a sound wave, chopped into short time-slices, the same way a text model treats words — attending across the whole clip to disambiguate what a mumbled or noisy moment probably said, using everything around it.

Chapter summary
  • Vision Transformers apply attention to image patches instead of words
  • AlphaFold uses attention-style mechanisms to model relationships across a protein chain
  • Whisper applies the same idea to chopped-up audio for speech recognition
  • One architecture, discovered for language, turned out to be a general tool for "which parts of this relate to which other parts" — which is most of intelligence
Check your understanding
  1. What do a sentence, an image, a protein, and an audio clip have in common that makes attention work on all of them?
  2. In your own words, explain to a friend what a Vision Transformer does differently from an older image-recognition network.
All tracksQuestions? Get in touch →