solulubeta
Sign in
Machine Learning / Transformers & LLMs
04.01 · Lesson

Attention and the Transformer

Scaled dot-product attention from scratch, queries, keys and values, multi-head attention, positional encodings, and the encoder and decoder blocks.

4 min Quiz Free

The transformer (Vaswani et al., 2017, “Attention Is All You Need”) replaced recurrence with attention. It underlies BERT, GPT, Claude, Gemini, Llama, vision transformers and more.

The idea of attention

To understand a word, look at the other words that matter for it. In “The animal didn’t cross the street because it was too tired”, the representation of “it” should draw mostly from “animal”.

Each token produces three vectors from its embedding x\mathbf{x} via learned matrices:

  • Query q=WQx\mathbf{q} = W_Q\mathbf{x}: what this token is looking for.
  • Key k=WKx\mathbf{k} = W_K\mathbf{x}: what this token offers to be matched against.
  • Value v=WVx\mathbf{v} = W_V\mathbf{x}: the information it passes on if attended to.

Scaled dot-product attention

For all tokens at once (rows of QQ, KK, VV):

Attention(Q,K,V)=softmax ⁣(QK⊤dk)V\text{Attention}(Q, K, V) = \text{softmax}\!\left(\frac{QK^\top}{\sqrt{d_k}}\right)V
  1. QK⊤QK^\top: an n×nn \times n matrix of scores, how well each query matches each key.
  2. Divide by dk\sqrt{d_k} so that the scores don’t grow with dimension and saturate the softmax.
  3. Softmax each row into weights that sum to 1.
  4. Multiply by VV: each output is a weighted average of the values.
flowchart LR
  X[Token embeddings] --> Q[Q = XW_Q] & K[K = XW_K] & V[V = XW_V]
  Q & K --> S["scores = QKᵀ/√dₖ"] --> M["(mask)"] --> SM[softmax] --> O["weights × V"]
  V --> O

Every token can directly use information from every other token, regardless of distance, and the whole computation is matrix multiplications that parallelise across the sequence. Training no longer has to step through time like an RNN.

Cost: the score matrix is n×nn \times n, so time and memory are O(n2)O(n^2) in sequence length. Long-context models use tricks like FlashAttention (memory-efficient exact attention), sliding windows and sparse attention.

Multi-head attention

One attention pattern can’t capture everything (syntax, coreference, nearby words). Multi-head attention runs hh attentions in parallel with smaller dimensions (dk=dmodel/hd_k = d_\text{model}/h), concatenates the results and mixes them:

MultiHead(X)=Concat(head1,…,headh) WO\text{MultiHead}(X) = \text{Concat}(\text{head}_1, \dots, \text{head}_h)\,W_O

Positional information

Attention by itself ignores order: shuffle the tokens and the outputs shuffle the same way. Position must be injected:

  • Sinusoidal encodings (original paper): fixed sin/cos waves added to embeddings.
  • Learned position embeddings (BERT, GPT-2).
  • Rotary embeddings (RoPE): rotate queries and keys by position, so attention depends on relative positions. Used by most modern LLMs.

The transformer block

flowchart TB
  IN[x] --> LN1[LayerNorm] --> MHA[Multi-head self-attention] --> ADD1(("+"))
  IN --> ADD1
  ADD1 --> LN2[LayerNorm] --> FFN["Feed-forward:<br/>Linear → GELU → Linear"] --> ADD2(("+"))
  ADD1 --> ADD2
  ADD2 --> OUT[to next block]

Each block has self-attention (tokens exchange information) and a position-wise feed-forward network (each token is processed independently, typically 4× wider), each wrapped with a residual connection and layer normalisation (pre-norm, as drawn, is standard now). Models stack dozens of these blocks.

Three families

FamilyAttentionTrained toExamplesGood for
Encoder-onlyBidirectional (sees all tokens)Fill in masked tokensBERT, RoBERTaClassification, embeddings, extraction
Decoder-onlyCausal (only earlier tokens)Predict the next tokenGPT, Llama, ClaudeText generation, chat, code
Encoder–decoderEncoder bidirectional; decoder causal + cross-attention to the encoderMap input sequence → output sequenceT5, original transformerTranslation, summarisation

The causal mask sets future scores to −∞-\infty before the softmax, so position tt only sees positions ≤t\le t. Cross-attention takes queries from the decoder and keys and values from the encoder.

Check yourself

Question 1 of 3

Why divide QKᵀ by √d_k in attention?

Question 2 of 3

What does the causal mask in a decoder do?

Question 3 of 3

Self-attention's cost grows with sequence length n as…

Mark this as done when you are finished.

Item 18 of 24 · updated 2026-10-12