Transformer architecture

advanced 12 minarchitecturestransformersattention

Builds on:Attention mechanism

The idea

A transformer is a stack of identical blocks, each doing two things to a sequence of token vectors: mix across positions (multi-head attention), then process each position (a feed-forward network applied identically at every position). Everything else — residuals, layer norms, positional encodings — exists to make that stack trainable and order-aware. One pre-LN block:

x←x+MHA(LN(x)),x←x+FFN(LN(x))x \leftarrow x + \mathrm{MHA}(\mathrm{LN}(x)), \qquad x \leftarrow x + \mathrm{FFN}(\mathrm{LN}(x))

Multi-head attention. Rather than one attention pattern over full-width vectors, split into hh heads of dimension dk=dmodel/hd_k = d_{\text{model}}/h:

headi=Attention(XWiQ, XWiK, XWiV),MHA(X)=Concat(head1,…,headh) WO.\begin{aligned} \mathrm{head}_i &= \mathrm{Attention}(XW_i^Q,\, XW_i^K,\, XW_i^V), \\ \mathrm{MHA}(X) &= \mathrm{Concat}(\mathrm{head}_1, \ldots, \mathrm{head}_h)\, W^O. \end{aligned}

Same total projection dimensions as one big head, but hh separately normalized attention patterns per token. Some trained heads exhibit interpretable positional or syntactic behavior, but specialization is not guaranteed and many heads can be redundant or pruned.

Position-wise FFN. FFN(x)=W2 GELU(W1x+b1)+b2\mathrm{FFN}(x) = W_2\, \mathrm{GELU}(W_1 x + b_1) + b_2 with hidden width 4dmodel4d_{\text{model}}. It is where most parameters live, and it acts per token — attention is the only place information crosses positions.

Positional encodings. Attention is permutation-equivariant, so order must be injected. Sinusoidal encodings add a multi-wavelength sin/cos fingerprint of each position to its embedding:

PE(pos, 2i)=sin⁡ ⁣(pos100002i/d),PE(pos, 2i+1)=cos⁡ ⁣(pos100002i/d)PE_{(pos,\, 2i)} = \sin\!\left(\frac{pos}{10000^{2i/d}}\right), \qquad PE_{(pos,\, 2i+1)} = \cos\!\left(\frac{pos}{10000^{2i/d}}\right)

Learned absolute embeddings (BERT) and rotary embeddings (most modern LLMs) are the common alternatives.

Why not RNNs? Three answers an interviewer wants, in order: (1) parallelism — RNN training is sequential in tt because hth_t needs ht−1h_{t-1}; a transformer trains on all positions at once as dense matrix algebra; (2) path length — relating tokens nn apart takes nn recurrent hops (gradients decay across each) versus exactly one attention hop; (3) scaling — transformers kept converting more data and compute into better loss. The price: O(n2)O(n^2) attention versus O(n)O(n) recurrence, and O(n)O(n) inference memory (KV cache) versus an RNN's O(1)O(1) state.

Worked example

Parameter budget of one encoder block at dmodel=512d_{\text{model}} = 512, h=8h = 8, FFN width 2048 (the original base config):

ComponentCountParams
WQ,WK,WVW^Q, W^K, W^V3×512×5123 \times 512 \times 512786,432786{,}432
WOW^O512×512512 \times 512262,144262{,}144
FFN in512×2048512 \times 20481,048,5761{,}048{,}576
FFN out2048×5122048 \times 5121,048,5761{,}048{,}576
2 LayerNorms2×2×5122 \times 2 \times 5122,0482{,}048
Total≈3.15\approx 3.15M

Read off the structure: two thirds of every block is FFN, attention projections are the other third, norms are noise. A 6-block stack is ≈18.9\approx 18.9M parameters before embeddings; a 32k-token vocabulary at d=512d = 512 adds another ≈16.4\approx 16.4M — for small models the embedding table rivals the whole stack, which is why input/output embeddings are often tied.

Sanity-check the multi-head shapes on a 10-token sentence: input 10×51210 \times 512 → per head, Q,K,VQ, K, V are 10×6410 \times 64 → scores 10×1010 \times 10 per head (8 of them) → weighted values 10×6410 \times 64 → concat 10×51210 \times 512 → WOW^O → 10×51210 \times 512. The sequence length only ever appears in the 10×1010 \times 10 score matrices — that is the O(n2)O(n^2) core in the flesh.

Cheat sheet

Block (pre-LN): x+MHA(LN(x))x + \mathrm{MHA}(\mathrm{LN}(x)), then x+FFN(LN(x))x + \mathrm{FFN}(\mathrm{LN}(x)); FFN =W2 GELU(W1x)= W_2\,\mathrm{GELU}(W_1 x), width 4d4d.

MHA: hh heads of dk=d/hd_k = d/h; params 4d24d^2 (Q, K, V, O); compute ≈ one full-width head; heads = independent attention patterns.

Positional encodings: sinusoidal (fixed, extrapolates in principle, relative offsets are linear maps); learned absolute (BERT); rotary/RoPE (relative, inside the QK product — modern default).

RNN / LSTMTransformer
Training over length nnsequential, O(n)O(n) stepsparallel, O(1)O(1) depth
Max dependency pathO(n)O(n)O(1)O(1)
Compute per layerO(nd2)O(n d^2)O(n2d+nd2)O(n^2 d + n d^2)
Inference stateO(1)O(1)KV cache O(n)O(n)
Long-range gradientsdecay through gatesdirect