The Transformer, Explained for Engineers
By the Katkat team · Updated · 8 min read
Quick overview
Learn how a decoder-only transformer works: self-attention, multi-head attention, feed-forward blocks, residuals and layer norm, with the parameter math.
After this lesson you should be able to walk through one transformer block on a whiteboard and say what each part does and why it is there. You should be able to explain how a decoder-only model trains on all positions at once but generates one token at a time. You should also be able to estimate where a model's parameters and its attention cost come from, using a few lines of arithmetic.
The big picture: one block, repeated
A decoder-only transformer, the design behind most modern chat LLMs, is a stack of identical blocks. Text is first split into tokens (see Tokenization), and each token becomes a vector of size d_model. Positional information is added or applied inside attention (see Positional Information). The vectors then flow through N blocks. Each block has two sublayers:
| Sublayer | What it does | Mixes information across tokens? |
|---|---|---|
| Self-attention | Each token gathers information from earlier tokens | Yes |
| Feed-forward network (FFN) | Transforms each token's vector on its own | No |
Both sublayers are wrapped in a residual connection and a normalisation layer. After the last block, a final norm and a linear "unembedding" layer turn each vector into one score (logit) per vocabulary entry. A softmax over those logits gives the next-token distribution, which decoding then samples from.
The key mental model: attention moves information between positions, the FFN processes information within a position, and the residual stream carries everything forward.
Self-attention: the mechanism
For each token's input vector x, the layer computes three vectors using learned matrices:
- Query
q = x·W_q: what this token is looking for. - Key
k = x·W_k: what this token offers to others. - Value
v = x·W_v: the content that gets passed along.
Stack these into matrices Q, K, V (one row per token). The output is:
Attention(Q, K, V) = softmax(Q·Kᵀ / √d_k + mask) · V
Step by step:
Q·Kᵀgives an n×n matrix of dot products: how well each token's query matches every token's key.- Dividing by
√d_kkeeps the scores in a sane range. If query and key components have roughly unit variance, a dot product overd_kterms has standard deviation about√d_k. Without scaling, large scores push softmax into near one-hot outputs with tiny gradients. - The causal mask sets scores for future positions to negative infinity, so softmax gives them zero weight. Token 5 can see tokens 1 to 5, never 6.
- Softmax turns each row into weights that sum to 1.
- Multiplying by V produces, for each token, a weighted average of value vectors.
Without positional information, attention treats its input as an unordered set. That is why positions must be injected separately.
Multi-head attention
One attention computation gives each token a single weighted average. Multi-head attention runs h smaller attentions in parallel. Each head has its own W_q, W_k, W_v projecting from d_model down to d_head = d_model / h. The head outputs are concatenated back to d_model and mixed by an output matrix W_o.
Heads can specialise: one may track the previous token, another may link a pronoun to its noun. Do not claim every head has a clean, interpretable role, because many do not. The compute cost is about the same as a single full-width head, since the dimensions are split rather than multiplied. For a code walkthrough, see Implement Multi-Head Attention.
A common production variation is sharing key/value heads across several query heads (multi-query or grouped-query attention). Queries stay at h heads, but there are fewer K/V heads, which shrinks the KV cache used during generation. For example, going from 32 K/V heads to 8 makes the cache 4x smaller.
The feed-forward block
The FFN is applied to every token independently with the same weights. In the classic design it is two linear layers with a nonlinearity between them: expand from d_model to 4·d_model, apply an activation (GELU or ReLU in early models), then project back down. Many recent models use a gated variant such as SwiGLU, which has three matrices and usually a smaller hidden size, so the parameter count stays comparable.
Without the FFN, a stack of attention layers would be a weak function approximator, since attention mostly computes weighted averages. The FFN adds the nonlinear, per-token computation. It also holds a large share of the parameters, and it is often hypothesised to store much of the model's factual knowledge, though this is an interpretation rather than a settled fact.
Residuals and layer norm
Each sublayer is applied as x + Sublayer(x). This residual connection gives gradients a direct path from the loss back to early layers, which makes deep stacks trainable. It also means each layer writes a small update into a shared "residual stream" instead of rewriting the representation from scratch.
Layer normalisation rescales each token's vector across its feature dimension to zero mean and unit variance, then applies a learned scale and shift. It normalises per token, not across the batch, so it works with any batch size and sequence length. Many LLMs use RMSNorm, a simplified version that skips mean subtraction.
Placement matters:
- Post-norm (original paper):
x = Norm(x + Sublayer(x)). It can be unstable in very deep models without careful warmup. - Pre-norm (common in modern LLMs):
x = x + Sublayer(Norm(x)). The residual path stays clean, which usually trains more stably.
Decoder-only versus other layouts
The original transformer had an encoder and a decoder. Today's LLMs mostly use only the decoder side.
| Layout | Attention pattern | Typical use |
|---|---|---|
| Encoder-only (BERT-style) | Bidirectional: every token sees every token | Classification, embeddings, retrieval |
| Encoder-decoder (T5-style) | Encoder is bidirectional; decoder is causal and cross-attends to the encoder | Translation, summarisation |
| Decoder-only (GPT-style) | Causal: each token sees only earlier tokens | General text generation, chat |
Decoder-only models train with next-token prediction. Because of the causal mask, one forward pass over a sequence of n tokens yields n predictions at once, so training is fully parallel across positions. Generation, however, is sequential: each new token depends on the previous one. To avoid recomputing keys and values for earlier tokens, serving systems store them in a KV cache (see Prefill, Decode and the KV Cache and Implement a KV Cache).
Worked example: where the parameters and the cost go
Take a model with d_model = 4096, 32 heads (d_head = 128), 32 layers, classic FFN with hidden size 4 × 4096, and a vocabulary of 32,000. Ignore biases and norm parameters, which are tiny.
Attention per layer: four matrices (W_q, W_k, W_v, W_o), each 4096 × 4096.
4 × 4096² = 4 × 16,777,216 = 67,108,864 parameters.
FFN per layer: two matrices, 4096 × 16,384 and 16,384 × 4096.
2 × 4096 × 16,384 = 134,217,728 parameters.
Per layer: 67,108,864 + 134,217,728 = 201,326,592 (this is 12·d²).
32 layers: 201,326,592 × 32 = 6,442,450,944, about 6.44B.
Embedding table: 32,000 × 4096 = 131,072,000, about 0.13B. If the unembedding is separate, add the same again.
Total: roughly 6.6B parameters (about 6.7B with an untied output layer). The FFN holds two thirds of each block's parameters.
Attention cost: at sequence length 2,048, one head produces 2,048² = 4,194,304 scores. Across 32 heads that is 134,217,728 scores per layer. At 2 bytes each, materialising them would take about 268 MB per layer. Doubling the length to 4,096 makes this 4x larger, which is the quadratic cost of attention. Kernels such as FlashAttention avoid storing this full matrix in GPU memory.
Real models differ (gated FFNs, grouped-query attention), so treat this as an estimate, not an exact count for any named model.
Trade-offs to know
- Quadratic attention cost: compute and memory for scores grow with n². This drives long-context cost.
- Parallel training, serial decoding: great for training throughput, but generation latency scales with the number of output tokens.
- More heads versus head size: more heads give more diverse patterns, but each head has fewer dimensions.
- KV cache size versus quality: fewer K/V heads save memory but can slightly reduce quality.
- Depth versus width: deeper models can compose more steps; wider models parallelise better. Parameter count alone does not decide which is better.
How does this come up in interviews?
1. Why do we divide attention scores by √d_k?
Dot products of d_k-dimensional vectors grow in magnitude with d_k; their standard deviation is about √d_k for unit-variance inputs. Large inputs saturate softmax, producing near one-hot weights and very small gradients. Dividing by √d_k keeps the score scale roughly constant regardless of head size.
2. Why use multiple heads instead of one large attention?
Multiple heads let the model compute several different weighted averages over the sequence in parallel, each in its own learned subspace. A single head produces only one attention pattern per token and layer. The cost is similar because each head works in d_model / h dimensions. Be honest that individual heads are not always interpretable.
3. Roughly how many parameters are in a transformer block, and where are they?
With classic sizing, attention has about 4d² parameters and the FFN about 8d², so a block has about 12d². Multiply by the number of layers and add the embedding table (vocab × d). Mention that gated FFNs and grouped-query attention change the exact numbers.
4. How can a decoder-only model train in parallel but generate sequentially? In training, the full sequence is known, and the causal mask stops each position from seeing the future. One pass therefore computes the next-token loss at every position. At inference the future tokens do not exist yet, so each token must be sampled before the next step, and a KV cache avoids redoing earlier work.
5. What do residual connections and layer norm do, and what is the pre-norm versus post-norm difference? Residuals give gradients a direct path through the stack and let each layer add a refinement to a shared stream. Layer norm keeps activations at a stable scale per token. Pre-norm puts the norm inside the residual branch, leaving the main path as an identity, which generally trains more stably at depth than post-norm.
Common mistakes
- Saying attention "looks at" tokens without mentioning that weights come from query-key dot products and are then applied to values.
- Forgetting the causal mask, or describing decoder-only models as bidirectional.
- Claiming the FFN mixes tokens. It operates on each position independently.
- Describing attention cost as linear in sequence length. The score matrix is n × n.
- Forgetting that attention alone has no sense of order, so positional information is required.
- Confusing training (parallel across positions) with generation (one token per step).
- Quoting parameter counts as exact for a named model when the real architecture uses gated FFNs, grouped-query attention or tied embeddings.
- Stating that each head has a clean human-readable role as if it were proven.