The Full Transformer Architecture

Complete specification of the transformer: encoder and decoder stacks, the role of each sublayer (attention, FFN, normalization), residual streams, encoder-decoder cross-attention, and architectural variants (encoder-only, decoder-only).

Intermediate

Table of Contents

  1. Learning Objectives
  2. Notation
  3. Core Intuition
  4. The Encoder Block
  5. The Decoder Block
  6. Cross-Attention Mechanism
  7. The Feed-Forward Network
  8. The Residual Stream
  9. Encoder-Only Models (BERT)
  10. Decoder-Only Models (GPT)
  11. Parameter Count Analysis
  12. Common Pitfalls
  13. Summary
  14. Exercises

Learning Objectives

  1. Describe the full encoder-decoder transformer architecture from Vaswani et al. (2017).
  2. Explain the function of each sublayer and the order of operations.
  3. Derive the causal mask for autoregressive decoding.
  4. Compute the total parameter count as a function of dd, HH, dffd_{ff}, LL.
  5. Compare encoder-only, decoder-only, and encoder-decoder variants.

Notation

  • dd — model dimension
  • dffd_{ff} — feed-forward hidden dimension (typically 4d4d)
  • HH — number of attention heads
  • LL — number of layers (blocks)
  • TT — sequence length
  • VV — vocabulary size

Core Intuition

The transformer processes sequences through alternating attention (mixing information across positions) and feed-forward (transforming each position independently) layers. Residual connections and layer normalization enable training very deep stacks. The architecture's power comes from attention's ability to model arbitrary pairwise interactions in O(1)O(1) depth.

Transformer Block

Layer 1
residualInputLayerNormMHAAdd&NormFFNAdd&NormOutputToken at: Add&Norm×1
Depth
1
Step
3
Residual skipToken flow
Explore: Data flows through LayerNorm → MHA → Add&Norm → FFN → Add&Norm. Residual connections (dashed) preserve gradient paths. Stack depth layers for deeper models.

The Encoder Block

Each encoder layer applies two sublayers:

H=LayerNorm(H+MHA(H,H,H))(1)\mathbf{H}' = \text{LayerNorm}(\mathbf{H} + \text{MHA}(\mathbf{H}, \mathbf{H}, \mathbf{H})) \tag{1} H=LayerNorm(H+FFN(H))(2)\mathbf{H}'' = \text{LayerNorm}(\mathbf{H}' + \text{FFN}(\mathbf{H}')) \tag{2}

The encoder uses bidirectional self-attention — every position can attend to every other position. After LL layers, the encoder output ZRTsrc×d\mathbf{Z} \in \mathbb{R}^{T_{\text{src}} \times d} encodes the full input context.


The Decoder Block

Each decoder layer applies three sublayers:

H=LayerNorm(H+MaskedMHA(H,H,H))(3)\mathbf{H}' = \text{LayerNorm}(\mathbf{H} + \text{MaskedMHA}(\mathbf{H}, \mathbf{H}, \mathbf{H})) \tag{3} H=LayerNorm(H+CrossMHA(H,Z,Z))(4)\mathbf{H}'' = \text{LayerNorm}(\mathbf{H}' + \text{CrossMHA}(\mathbf{H}', \mathbf{Z}, \mathbf{Z})) \tag{4} H=LayerNorm(H+FFN(H))(5)\mathbf{H}''' = \text{LayerNorm}(\mathbf{H}'' + \text{FFN}(\mathbf{H}'')) \tag{5}

Masked self-attention prevents position tt from attending to future positions t>tt' > t.

Causal mask. The attention scores are masked:

A=softmax(QKTdk+M),Mij={0iji<j.(6)\mathbf{A} = \text{softmax}\left(\frac{\mathbf{Q}\mathbf{K}^T}{\sqrt{d_k}} + \mathbf{M}\right), \quad M_{ij} = \begin{cases}0 & i \geq j \\ -\infty & i < j\end{cases}. \tag{6}

Adding -\infty before softmax ensures those positions receive zero attention weight.


Cross-Attention Mechanism

In cross-attention, queries come from the decoder and keys/values from the encoder:

CrossAttn(Hdec,Zenc)=softmax(HdecWQ(ZencWK)Tdk)ZencWV.(7)\text{CrossAttn}(\mathbf{H}_{\text{dec}}, \mathbf{Z}_{\text{enc}}) = \text{softmax}\left(\frac{\mathbf{H}_{\text{dec}}\mathbf{W}^Q(\mathbf{Z}_{\text{enc}}\mathbf{W}^K)^T}{\sqrt{d_k}}\right)\mathbf{Z}_{\text{enc}}\mathbf{W}^V. \tag{7}

This allows each decoder position to attend to all encoder positions — the mechanism by which the decoder "reads" the input.


The Feed-Forward Network

Applied identically and independently to each position:

FFN(x)=W2ϕ(W1x+b1)+b2,(8)\text{FFN}(\mathbf{x}) = \mathbf{W}_2\,\phi(\mathbf{W}_1\mathbf{x} + \mathbf{b}_1) + \mathbf{b}_2, \tag{8}

where W1Rdff×d\mathbf{W}_1 \in \mathbb{R}^{d_{ff} \times d}, W2Rd×dff\mathbf{W}_2 \in \mathbb{R}^{d \times d_{ff}}, and ϕ\phi is the activation (ReLU in original, GELU in GPT/BERT).

Parameters per FFN layer: 2ddff+dff+d8d22d \cdot d_{ff} + d_{ff} + d \approx 8d^2 (for dff=4dd_{ff} = 4d).

Interpretation: The FFN acts as a position-wise "memory lookup" — it stores and retrieves factual knowledge. Attention routes information; FFN processes it.


The Residual Stream

The residual stream interpretation (Elhage et al., 2021): The hidden state h\mathbf{h} is a "residual stream" that accumulates contributions from each sublayer:

h(L)=h(0)+l=1LAttn(l)+l=1LFFN(l).(9)\mathbf{h}^{(L)} = \mathbf{h}^{(0)} + \sum_{l=1}^L \text{Attn}^{(l)} + \sum_{l=1}^L \text{FFN}^{(l)}. \tag{9}

Each attention and FFN layer reads from and writes to this stream. This view makes gradient flow transparent: the gradient flows directly from loss to any layer through the identity path.


Encoder-Only Models (BERT)

  • Remove the decoder entirely.
  • Bidirectional attention over the full input.
  • Pre-trained with Masked Language Modeling (MLM): predict randomly masked tokens.
  • Used for: classification, NER, sentence similarity, retrieval.

Decoder-Only Models (GPT)

  • Remove the encoder and cross-attention.
  • Causal (masked) self-attention only.
  • Pre-trained with next-token prediction: p(xtx1,,xt1)p(x_t \mid x_1, \ldots, x_{t-1}).
  • Used for: text generation, in-context learning, reasoning.
  • Most modern LLMs (GPT-4, LLaMA, Claude) are decoder-only.

Why decoder-only dominates: Simpler architecture; scales better; naturally supports generation; in-context learning emerges at scale.


Parameter Count Analysis

For a decoder-only transformer:

Per layer:

  • Self-attention: 4d24d^2 (Q, K, V, O projections)
  • FFN: 2ddff8d22d \cdot d_{ff} \approx 8d^2
  • LayerNorm: 4d4d (negligible)
  • Total per layer: 12d2\approx 12d^2

Full model:

  • Embedding: VdV \cdot d
  • LL layers: 12Ld212Ld^2
  • Final LN + output head: Vd\approx V \cdot d (often tied with embedding)
N12Ld2+2Vd.(10)\boxed{N \approx 12Ld^2 + 2Vd.} \tag{10}

Example (GPT-3 175B): L=96,d=12288,H=96,dff=49152,V=50257L=96, d=12288, H=96, d_{ff}=49152, V=50257. This gives 12×96×122882174B\approx 12 \times 96 \times 12288^2 \approx 174\text{B}.


Common Pitfalls

Pitfall 1. Thinking the FFN is unimportant. It contains 2/3\sim 2/3 of all parameters and stores most learned "knowledge." Attention just routes information.

Pitfall 2. Not using the causal mask for generation. Without it, the model sees future tokens during training — the loss becomes trivially low but the model cannot generate.

Pitfall 3. Confusing Pre-Norm with Post-Norm. Modern models use Pre-Norm (LN\text{LN} before attention/FFN) for training stability. The original paper used Post-Norm.


Summary

  • The transformer alternates multi-head attention (inter-position mixing) and FFN (per-position transformation).
  • Residual connections + LayerNorm enable training deep stacks.
  • Causal masking enforces autoregressive structure for generation.
  • Cross-attention connects encoder outputs to decoder queries.
  • Decoder-only is the dominant architecture for modern LLMs.
  • Total parameters scale as 12Ld2\sim 12Ld^2.

Exercises

Exercise 1. For a transformer with L=12,d=768,dff=3072,V=30000L=12, d=768, d_{ff}=3072, V=30000, compute the total parameter count.

Exercise 2. Derive the causal mask and show that position tt's output depends only on positions 1,,t1, \ldots, t.

Exercise 3. Prove that the encoder-decoder cross-attention computes the same function as a retrieval operation: the decoder "queries" the encoder "database."

Exercise 4. Compute the FLOPs for one forward pass through a single transformer layer with sequence length TT and model dimension dd.

Exercise 5. Explain why weight tying (sharing embedding and output projection matrices) is valid and compute the parameter savings.