Transformers & Attention

Generative & Agentic AI · AI Foundations · Intermediate · 16 min

The architecture behind every modern LLM, without the scary maths.

Every word in the sentence shines a flashlight on all the other words. The brighter the beam on a word, the more of its meaning flows back. 'it' shines brightest on 'cat'.

The idea in everyday words

Reading a mystery novel: when you see 'he hid the key', your brain instantly links 'he' to the butler from chapter 2. Attention lets every word 'look back' at all other words and decide which ones matter for its meaning.

The pipeline

  1. Tokenise text → token IDs.
  2. Embed: each token becomes a vector (+ position info).
  3. Transformer blocks (dozens of them): self-attention mixes information between tokens, then a small neural net processes each token.
  4. Output: a probability for every possible next token.

Attention = weighted average

Each token makes a query ("what am I looking for?"); every token offers a key ("what do I contain?") and a value. Score = query · key → softmax turns scores into weights that add to 1 → the output is the weighted mix of values.

import math
def softmax(scores):
    m = max(scores)                          # subtract the max: same answer, no overflow
    exps = [math.exp(s - m) for s in scores]
    total = sum(exps)
    return [round(e / total, 3) for e in exps]

words = ["The", "cat", "sat", "it"]
scores_for_it = [0.1, 2.5, 0.4, 0.8]      # how relevant each word is to "it"
for w, p in zip(words, softmax(scores_for_it)):
    print(w, p)

"it" pays most attention to "cat". Change the scores and run again. Try [1000, 1001, 999, 1000]: without the - m line, math.exp(1000) overflows.

In a real model the score is scaled: score = (q · k) / √d, where d is the length of the key vectors. Without it, dot products grow with d, softmax becomes almost one-hot, and the gradients vanish.

Why transformers won

  • Look at all tokens in parallel (fast on GPUs) instead of one by one (old RNNs).
  • Multi-head attention: many attention patterns at once (grammar, meaning, references).
  • Scale = more layers + more data → emergent abilities.
  • Cost: attention is O(n²) in context length: why long contexts are expensive.

The KV cache: why tokens after the first one are fast

When the model writes token 50, attention needs the keys and values of tokens 1 to 49. Those never change, so the model stores them in a KV cache and only computes Q, K and V for the newest token.

  • Prefill: the whole prompt is processed at once. This is the wait before the first word appears (time to first token). Longer prompts → longer wait.
  • Decode: every later token is one small step that reuses the cache. This is the streaming speed (tokens per second).
  • Memory: the cache grows with context length × layers × heads, and with every user served at the same time. That is why long contexts need a lot of GPU memory, and why serving engines like vLLM manage the cache carefully (PagedAttention).

Go deeper (engineer level): attention in matrix form, positions and the KV cache

Matrix form. Stack the n tokens as rows. With learned projections, Q = XW_Q, K = XW_K, V = XW_V (each n × d_k). Then

Attention(Q, K, V) = softmax(QKᵀ / √d_k + M) V

QKᵀ is an n × n score matrix, so time is O(n² · d) and a naive implementation stores n² scores per head. M is the causal mask: minus infinity above the diagonal, so token i cannot see tokens after it. Multi-head attention runs h smaller heads (d_k = d / h) in parallel, concatenates them and mixes them with W_O.

Why √d_k. If the parts of q and k are independent with variance 1, q · k has variance d_k. Dividing by √d_k keeps the scores near variance 1, so softmax does not saturate into a one-hot vector with near-zero gradients.

Positions. Attention alone ignores word order, so models add positions: sinusoidal or learned absolute embeddings (original transformer, BERT, GPT-2), RoPE, which rotates q and k so their dot product depends on the relative distance (used by Llama-style models), or ALiBi, a distance penalty added to the scores. Long-context versions stretch RoPE (for example YaRN); measure quality past the trained length.

Serving mechanics. FlashAttention computes the same result in tiles, so the n × n matrix never sits in GPU memory at once: same maths, far less memory traffic. Grouped-query attention (GQA) shares K and V across groups of query heads, which shrinks the KV cache:

layers, kv_heads, head_dim, bytes_per = 32, 8, 128, 2   # a Llama-3-8B-like shape in fp16
per_token = 2 * layers * kv_heads * head_dim * bytes_per  # K and V
print(per_token // 1024, "KiB per token;", round(per_token * 8192 / 2**30, 2), "GiB for 8k tokens, per sequence")

Failure modes: softmax overflow in fp16 (kernels compute it in fp32 with the max subtracted) and "lost in the middle" (facts mid-prompt are used less reliably).

Step by step

  1. Tokens:

    ['The', 'cat', 'sat', 'because', 'it', …]

  2. Query:

    'it' asks: who am I referring to?

  3. Scores:

    it·cat = high, it·sat = low

  4. Softmax:

    weights: cat 62%, others small

  5. Mix:

    'it' vector now carries 'cat' meaning

Code example

import math
def attention(query, keys, values):
    d = len(query)
    scores = [sum(q * k for q, k in zip(query, key)) / math.sqrt(d) for key in keys]   # scaled dot product
    m = max(scores)
    exps = [math.exp(s - m) for s in scores]       # stable softmax
    total = sum(exps)                              # computed ONCE, not inside the loop
    weights = [e / total for e in exps]
    return [round(sum(w * v[i] for w, v in zip(weights, values)), 3) for i in range(len(values[0]))]

keys = [[1, 0], [0, 1]]
values = [[10, 0], [0, 10]]
print(attention([3, 0], keys, values))   # mostly the first value

Interview tips

  • Explain Q, K, V in plain words.

  • Why is long context expensive? O(n²) attention + KV cache memory.

  • Encoder vs decoder vs encoder-decoder models.

Challenge: Implement Softmax

Return the softmax of a non-empty list of scores, each value rounded to 2 decimals: exp(s_i) / sum(exp(s_j)).

Scores can be negative or very large (attention logits often are). It must work for [1000, 1000] without overflowing: subtract the largest score first, which gives exactly the same answer.

Example: softmax([0, 0]) → [0.5, 0.5]

Solve it in the browser with tests, hints and an AI coach.

Practice problems

More in AI Foundations

Previous: Tokenization & Byte-Pair Encoding · Next: How LLMs Are Trained: Pretraining, SFT & RLHF