Skip to content
Road to Intelligence

Concept · Chapter 7: Transformers

Self-Attention

Must knowImplement45 minDifficulty

Self-attention lets every token in a sequence look at every other token, decide how relevant each one is, and update itself with a weighted mix of what it finds.

The problem

In a recurrent network, information between distant words must travel step by step through every word in between — slow to compute and easy to lose.

The solution

Let each token compare itself to all tokens at once (via dot products of learned queries and keys), convert the scores into weights with softmax, and take a weighted sum of their values.

The consequence

Any two tokens interact in a single step, the whole sequence is processed in parallel, and the cost grows with the square of sequence length — which later drives work like KV caching and FlashAttention.

You should understand first

  1. Vectors
  2. Dot Product
  3. Embeddings
  4. Attention
  5. Probability and Distributions
  6. Softmax
  7. Self-Attention

Start from the simplest version

Forget Q, K and V for a moment. Take one sentence:

the cat sat because it was tired

To understand "it", a reader looks back and connects it to "cat". Self-attention gives the model a way to do the same thing: each word asks "which other words matter to me?" and pulls in information from them.

We already have the tools:

  1. Every word is a vector (an embedding).
  2. The dot product scores how aligned two vectors are.
  3. Softmax turns a list of scores into weights that sum to 1.
  4. A weighted sum mixes vectors according to those weights.

That's attention. Build it one step at a time:

Try it · toy model

Attention from Scratch

One short sentence, one question: which words should each word pay attention to? Build attention step by step — similarity, softmax, weighted sum, then queries and keys.

Know well10 min

Why queries, keys and values?

Scoring raw embeddings against each other has a flaw: a word is always most similar to itself, and "what I'm looking for" is forced to be the same as "what I am". So each token makes three different vectors, each through its own learned matrix:

VectorRoleAnalogy
Query q=xWQq = xW_Qwhat this token is looking forthe search box
Key k=xWKk = xW_Kwhat this token offers to othersthe item's index card
Value v=xWVv = xW_Vthe information actually passed alongthe item's contents

The model learns WQ,WK,WVW_Q, W_K, W_V during training, so it learns what to look for and what to advertise.

The equation

Attention(Q,K,V)=softmax⁡ ⁣(QK⊤dk)V\text{Attention}(Q, K, V) = \operatorname{softmax}\!\left(\frac{QK^\top}{\sqrt{d_k}}\right) V

Causal masking

A GPT-style model predicts the next token, so while training, position 5 must not peek at positions 6, 7, 8. We set those scores to −∞-\infty before the softmax, which makes their weights exactly 0. The attention matrix becomes lower-triangular.

The price: O(n²)

Every token scores every other token, so a sequence of nn tokens needs an n×nn \times n table. Doubling the context length quadruples that work and memory. Much modern engineering — KV caches, FlashAttention, grouped-query attention — exists to live with this cost.

Why should I care?

As a researcher

It's the core operation of the Transformer. Most architecture papers since 2017 modify some part of it: positions, heads, masking, cost or memory.

As an engineer

Its quadratic cost in context length is why long contexts are expensive, why KV caches exist, and why inference is often memory-bound.

Modern systems that depend on it

  • Transformer blocks
  • BERT and GPT
  • Every modern LLM
  • KV cache
  • FlashAttention
  • Vision Transformers

Historical context

Before

RNNs and LSTMs passed information along the sequence one step at a time; attention existed, but as an add-on connecting a decoder to an encoder.

After

Multi-head attention, the Transformer, and eventually efficiency variants (multi-query and grouped-query attention, FlashAttention, sparse and linear attention).

Used today

Every layer of every Transformer-based model: GPT-style chat models, BERT-style encoders, embedding models, vision and speech Transformers.

What to remember

  • Each token produces a query, a key and a value by multiplying its vector with three learned matrices.
  • Score = query · key: how relevant that token is to this one.
  • Scores are divided by √d to keep softmax from saturating, then softmaxed into weights.
  • Output = weighted sum of the values.
  • Causal masking hides future tokens in GPT-style models.
  • Cost is O(n²) in sequence length n.

Key papers

Essential

Neural Machine Translation by Jointly Learning to Align and Translate

Dzmitry Bahdanau, Kyunghyun Cho, Yoshua Bengio · 2014 · ICLR 2015

Introduced attention in neural networks for language: instead of squeezing a sentence into one vector, the decoder looks back at every input word and decides which ones matter right now.

How to read it: Figure 3's alignment heat-maps are the best picture of 'attention' ever drawn — look at them first.

~1 h readarXiv:1409.0473✓ verified 2026-09-26
Essential

Attention Is All You Need

Ashish Vaswani, Noam Shazeer et al. · 2017 · NeurIPS 2017

Introduced the Transformer — the architecture behind BERT, GPT and nearly every modern large language model, and later adapted to vision, audio and more.

How to read it: Section 3 is the architecture — read it with Figure 1 open. Sections 3.2.1–3.2.2 contain the attention equation. You can skim the training details on a first pass.

~1 h 15 min readarXiv:1706.03762✓ verified 2026-09-26

Watch