Attention & Transformers

The architecture behind modern AI — queries, keys and values, scaled dot-product attention, self-attention, multi-head attention, positional encodings, the transformer block (residuals, layer norm, feed-forward), encoder vs decoder models, causal masking, and the cost of attention.

Advanced 5 min readLesson 11 of 14 Interview Q&A

The transformer (Vaswani et al., 2017, "Attention Is All You Need") is the architecture behind GPT, Claude, Gemini, LLaMA, BERT, Whisper, vision transformers and protein models. Its core operation — attention — lets every position in a sequence directly gather information from every other position, in parallel.

The intuition

In "The animal didn't cross the street because it was too tired", what does "it" refer to? To build a good representation of "it", the model should pull in information from "animal". Self-attention does this: each token computes how relevant every other token is, then takes a weighted mix of their information.

Queries, keys and values

Each token's vector xi\mathbf{x}_i is projected into three vectors with learned matrices:

VectorRoleAnalogy
Query qi=WQxi\mathbf{q}_i = W_Q \mathbf{x}_iWhat this token is looking forA search query
Key kj=WKxj\mathbf{k}_j = W_K \mathbf{x}_jWhat each token offers to be matched onDocument titles
Value vj=WVxj\mathbf{v}_j = W_V \mathbf{x}_jThe information each token passes on if attended toDocument contents

The attention weight from token i to token j is the (scaled) dot product of qi\mathbf{q}_i and kj\mathbf{k}_j, normalised with softmax across j. The output for token i is the weighted sum of values.

Scaled dot-product attention

In matrix form for a whole sequence:

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 × n matrix of scores — every query against every key.
  2. Divide by dk\sqrt{d_k} so scores don't grow with dimension and saturate the softmax.
  3. Softmax each row → attention weights that sum to 1.
  4. Multiply by V: each output row is a weighted average of value vectors.
thecatitsatthecatitsat0.70.050.10.150.10.60.20.10.550.050.30.10.40.10.10.4
Toy attention weights: each row sums to 1 (rows = queries, columns = keys)
Python
import torch
import torch.nn.functional as F

def attention(Q, K, V, mask=None):
    d_k = Q.size(-1)
    scores = Q @ K.transpose(-2, -1) / d_k ** 0.5      # (…, n, n)
    if mask is not None:
        scores = scores.masked_fill(mask == 0, float("-inf"))
    weights = F.softmax(scores, dim=-1)
    return weights @ V, weights

Multi-head attention

One attention pattern can't capture everything (syntax, coreference, nearby words, topic). Multi-head attention runs h attention operations in parallel, each with its own smaller WQ,WK,WVW_Q, W_K, W_V (dimension d/hd/h), then concatenates and projects the results:

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

Different heads learn different relationships. (Efficient variants used in LLMs: multi-query and grouped-query attention share keys and values across heads to shrink the inference cache.)

Positional information

Attention is permutation-invariant: shuffle the tokens and each gets the same output. Order must be injected:

  • Sinusoidal or learned absolute position embeddings added to token embeddings (original transformer, BERT, GPT-2).
  • Rotary position embeddings (RoPE): rotate query and key vectors by position-dependent angles, so attention scores depend on relative distance — used by most modern LLMs; extendable to longer contexts.
  • ALiBi: a distance-based bias added to attention scores.

The transformer block

Inputtoken embeddings + positional informationLayerNorm → Multi-head self-attention → + residualtokens exchange informationLayerNorm → Feed-forward MLP → + residualeach token processed independently (most of the parameters)× N blocks12 in BERT-base, 32–120+ in large LLMs
  • Attention mixes information across positions.
  • The feed-forward network (two linear layers with GELU or SwiGLU, ~4× wider) transforms each position independently — it's where much of the model's knowledge is stored.
  • Residual connections and layer normalisation (pre-norm, often RMSNorm) keep deep stacks trainable (Neural networks).
Python
from torch import nn

class Block(nn.Module):
    def __init__(self, d_model=768, n_heads=12):
        super().__init__()
        self.ln1 = nn.LayerNorm(d_model)
        self.attn = nn.MultiheadAttention(d_model, n_heads, batch_first=True)
        self.ln2 = nn.LayerNorm(d_model)
        self.mlp = nn.Sequential(nn.Linear(d_model, 4 * d_model), nn.GELU(), nn.Linear(4 * d_model, d_model))

    def forward(self, x, causal_mask):
        h = self.ln1(x)
        x = x + self.attn(h, h, h, attn_mask=causal_mask, need_weights=False)[0]   # residual
        x = x + self.mlp(self.ln2(x))                                              # residual
        return x

Encoders, decoders and both

TypeAttentionPretraining taskExamplesGood for
Encoder-onlyBidirectional: every token sees all tokensMasked language modelling (fill in blanks)BERT, RoBERTa, embedding modelsClassification, search embeddings, NER
Decoder-onlyCausal: each token sees only earlier tokensNext-token predictionGPT, Claude, LLaMA, GeminiText generation, chat — today's LLMs
Encoder–decoderEncoder bidirectional; decoder causal + cross-attention to encoder outputsSpan corruption, translationOriginal Transformer, T5, WhisperTranslation, summarisation, speech recognition

Causal masking

For generation, a token must not see the future during training (otherwise predicting the next token is trivial). A causal mask sets scores above the diagonal to −∞ before the softmax, so position i attends only to positions ≤ i. This lets the model train on every position of a sequence in parallel while learning to predict each next token.

Why transformers won

  • Parallelism: all positions are processed at once — training saturates GPUs, unlike sequential RNNs (RNNs).
  • Direct long-range connections: any two tokens interact in one step.
  • Scaling: performance improves predictably with more parameters, data and compute (scaling laws), which justified building ever-larger models (LLMs).
  • Generality: the same block works for text, images (ViT), audio, video, code, proteins — and combinations (multimodal models).

The cost of attention

The n × n score matrix makes attention O(n²) in sequence length for compute and (naively) memory. Doubling context quadruples attention cost. Solutions:

TechniqueIdea
FlashAttentionExact attention computed in tiles in fast on-chip SRAM, never materialising the full matrix — far less memory traffic
KV cacheDuring generation, store past keys and values so each new token costs O(n), not O(n²)
Sparse / sliding-window attentionAttend to a local window plus selected global tokens
Grouped-query attentionFewer key/value heads → a smaller KV cache
State-space and linear-attention hybridsSub-quadratic sequence mixing for very long contexts
Key takeaways
  • Attention computes softmax(QKᵀ/√d)V: each token takes a weighted mix of all tokens' values based on query–key similarity.
  • Multi-head attention learns several relationship types in parallel.
  • Positions are injected with position embeddings, now mostly RoPE.
  • A transformer block = attention + feed-forward MLP, each with layer norm and a residual connection, stacked N times.
  • Encoder-only (BERT) for understanding, decoder-only with causal masks (GPT-style LLMs) for generation, encoder–decoder for translation and speech.
  • Transformers parallelise and scale well; attention is quadratic in length, mitigated by FlashAttention, KV caches and sparse variants.
Interview questions
QWhy is the dot product divided by the square root of d_k in attention?hard

For random vectors with unit-variance components, the dot product of two d_k-dimensional vectors has variance d_k, so scores grow with dimension. Large scores push the softmax into a near one-hot regime where its gradients are tiny, slowing or stalling learning. Dividing by √d_k keeps the scores' variance around 1 regardless of head size, so the softmax stays in a range with useful gradients.

QWhat is the KV cache and why does it matter?medium

In autoregressive generation, each new token attends to all previous tokens. Recomputing keys and values for the whole prefix at every step would be wasteful, so the model caches the keys and values of past tokens for every layer and only computes them for the new token. This makes each step linear in context length, but the cache grows with batch size, sequence length, layers and heads, so it often limits how many requests and how much context a server can handle — motivating grouped-query attention, quantised caches and paged memory management.