Attention Mechanism & Transformer Overview
Understand attention and the transformer stack that powers modern NLP models.
In plain words
Attention lets each word look at all the other words in the sentence and decide which ones matter most for understanding it, then mix in their information.
Think of it like…
A meeting where every participant can ask everyone else a question and weigh the answers by relevance. A token's query is its question, each other token's key advertises what it knows and the value is what it actually says; the answer is a relevance-weighted blend.
Where you’ve seen it
A single query token with q = (1, 0) attends over three tokens with keys k₁ = (1, 0), k₂ = (0, 1) and k₃ = (1, 1) and d_k = 2. The dot products are 1, 0 and 1; dividing by √2 = 1.414 gives 0.707, 0 and 0.707; softmax gives weights 2.028 / 5.056 = 0.401, 1 / 5.056 = 0.198 and 0.401, which add to 1. With values v₁ = (2, 0), v₂ = (0, 4) and v₃ = (2, 2) the output is 0.401 × (2, 0) + 0.198 × (0, 4) + 0.401 × (2, 2) = (1.604, 1.593). The √d_k scaling matters at realistic sizes: with d_k = 64, raw dot products of random unit-variance vectors have a standard deviation of 8, which would push softmax into near one-hot saturation. A transformer layer with d_model = 512 and 8 heads has per-head size 64; its attention projections hold 4 × 512² = 1,048,576 weights and its feed-forward network (512 → 2,048 → 512) holds 2 × 512 × 2,048 = 2,097,152, so about 12 × d² = 3,145,728 parameters per layer ignoring biases and norms, or about 18.9 million for six layers. The cost that matters for practitioners is the score matrix: 2,048 tokens produce 4,194,304 attention scores per head per layer, and 4,096 tokens produce 16,777,216, four times as many, which is why context length is expensive. A data science team picks an encoder model for ticket classification (cheap, strong), a decoder LLM for summarisation and an embedding model for search, using each architecture for what it was built for.
Words you’ll hear
- Query, key, value
- Projections of each token: what it looks for, what it offers and what it passes on.
- Multi-head attention
- Several attention operations in parallel on smaller subspaces, then concatenated.
- Causal mask
- A mask that stops a token attending to later positions, used for text generation.
- Positional encoding
- Added information about token order, since attention itself is order-blind.
Visual diagram
Theory & deep dive
Attention step by step
Each token is projected into a query (what it is looking for), a key (what it contains) and a value (what it contributes). Scores are dot products between the query and every key, divided by √d_k to keep their variance near 1 (with d_k = 64 the raw dot products have a standard deviation of 8, so without scaling the softmax would be nearly one-hot and gradients would vanish). A softmax turns the scores into weights that sum to 1, and the output is the weighted sum of values. For q = (1, 0), keys (1, 0), (0, 1), (1, 1) and values (2, 0), (0, 4), (2, 2): scores 1, 0, 1 → scaled 0.707, 0, 0.707 → weights 0.401, 0.198, 0.401 → output (1.604, 1.593).
Multi-head attention runs h attention operations in parallel on d_model / h-dimensional slices (for 512 and 8 heads, 64 each), letting different heads specialise in different relations (syntax, coreference, position), then concatenates and projects the results. Self-attention takes Q, K and V from the same sequence; cross-attention (in encoder–decoder models) takes queries from the decoder and keys and values from the encoder. Because attention ignores order, positional encodings (sinusoidal, learned or rotary) are added to the token embeddings.
Scores (1, 0, 1) ÷ 1.414 = (0.707, 0, 0.707). exp = (2.028, 1, 2.028), sum 5.056. Weights (0.401, 0.198, 0.401). Output = 0.401 × (2, 0) + 0.198 × (0, 4) + 0.401 × (2, 2) = (1.604, 1.593).
The transformer block, architectures and costs
A block is: self-attention → add residual → layer norm → feed-forward network (two linear layers with GELU, usually expanding to 4 × d_model) → add residual → layer norm. Parameters per block are about 4d² for the attention projections (Q, K, V and output) plus 8d² for the feed-forward network, 12d² in total: for d = 512 that is 3,145,728, and six layers make about 18.9 million. Encoder-only models (BERT, RoBERTa) use bidirectional attention and are the workhorses for classification, NER and embeddings; decoder-only models (GPT-style LLMs) apply a causal mask and generate text; encoder–decoder models (T5, BART) suit translation and summarisation.
Attention compares every token with every other, so the score matrix has n² entries per head per layer: 2,048 tokens give 4,194,304, and 4,096 give 16,777,216, four times as many. This is why context windows are limited and long documents are chunked, and why efficient-attention variants and KV caching exist. Practical consequences for a data scientist: choose the smallest architecture that meets the task (an encoder for classification is far cheaper than an LLM), watch the maximum sequence length (typically 512 for older encoders; longer for newer ones), batch by length to cut padding and remember that pretraining is what makes transformers useful, so fine-tune rather than train from scratch.
Sequence 2,048: 2,048² = 4,194,304 scores per head per layer. Sequence 4,096: 16,777,216 (4×). With 12 heads and 12 layers in float16 the stored score matrices for one example at 4,096 tokens would be 16,777,216 × 144 × 2 bytes ≈ 4.8 GB if all were kept, which is why implementations recompute or fuse them.
How it works, step by step
Step 1 of 41. Embed tokens and add positions
Convert subword tokens to vectors and add positional information so order is available.
- Limit
- max sequence length
When to use it & trade-offs
What it is
Attention lets a model compute each token's representation as a weighted average of other tokens' values, where the weights come from how well the token's query matches every other token's key: Attention(Q, K, V) = softmax(QKᵀ / √d_k) V. A transformer stacks blocks of multi-head self-attention and a position-wise feed-forward network, each wrapped in residual connections and layer normalisation, with positional encodings to supply word order. Encoder-only models (BERT-style) read the whole input and suit classification and tagging, decoder-only models (GPT-style) use a causal mask and generate text one token at a time, and encoder–decoder models (T5-style) map one sequence to another.
Why it matters: Transformers replaced recurrent networks for language because attention lets every token see every other token in one step and trains in parallel across positions, which scales to huge datasets. Almost every modern NLP tool a data scientist touches (embeddings, fine-tuned classifiers, LLMs, RAG) is built on them. Understanding the formula, the cost of attention and the three architecture families helps you choose a model, estimate memory and context limits and read model documentation.
When to reach for it
- Encoders for ticket classification and entity extraction
- Embedding models for semantic search
- Decoder LLMs for summarisation and question answering
When to avoid or be careful
- Using a large decoder LLM where a small encoder suffices
- Feeding documents longer than the context window without chunking
- Training a transformer from scratch on a small dataset
Transformer families
Strengths: Bidirectional context; small and fast.
Watch out: Doesn't generate free text.
Strengths: General-purpose; strong few-shot behaviour.
Watch out: Large; costly per token.
Strengths: Clear input and output separation.
Watch out: Two stacks to serve.
Interview signals & numbers to know
When this topic comes up
- “Explain self-attention”
- Why divide by √d_k
- Encoder versus decoder models
- The quadratic cost of attention
- Role of positional encodings
Benchmarks & rules of thumb
- softmax(QKᵀ/√d_k) V
- scaled dot-product attention
- 12 d²
- approximate parameters per transformer block
- n²
- attention scores per head per layer; 4,096 tokens → 16.8M
Common mistakes & follow-ups
Common interview mistakes
- Ignoring truncation when documents exceed the model's maximum length.
- Assuming attention weights are a complete explanation of a prediction.
- Forgetting that decoder models need a causal mask during training.
Likely interviewer follow-ups
- Why are positional encodings needed?
- What does multi-head attention add over a single head?
- How does context length affect cost?
Knowledge check
Put it into practice
Practice related interview Q&A
Apply Attention Mechanism & Transformer Overview with data science interview Q&A and hands-on practice.