PIXELBANKv9.1.0
Menu
Back to LLM Study Plan
Week 3-4

Chapter 3: Transformer Architecture

Dive deep into the architecture that powers every modern LLM. Understand self-attention---the mechanism that allows tokens to attend to each other regardless of distance---multi-head attention for capturing different relationship types, feed-forward networks, layer normalization, residual connections, and how they combine into a full transformer block.

Chapter Overview

The Transformer architecture (Vaswani et al., 2017) is the foundation of all modern LLMs. Its key innovation---self-attention---allows every token to directly interact with every other token in a sequence, eliminating the information bottleneck of recurrent architectures.

A transformer block consists of two main sub-layers: a multi-head self-attention mechanism and a position-wise feed-forward network. Each sub-layer is wrapped with a residual connection and layer normalization. Stacking dozens (or hundreds) of these blocks creates the deep networks we call LLMs.

Understanding the transformer at a mathematical level is essential for: debugging model behavior, implementing efficient inference, designing architectural improvements, and understanding why certain prompting strategies work. Each component has a clear purpose, and their interplay creates a system far more powerful than the sum of its parts.

This chapter covers:

  • Self-Attention: The core mechanism that enables tokens to exchange information
  • Multi-Head Attention: Running multiple attention patterns in parallel
  • Feed-Forward Networks: Per-token nonlinear transformations
  • Layer Normalization: Stabilizing training of deep networks
  • Residual Connections: Enabling gradient flow through many layers
  • Full Transformer Block: How all components fit together

Chapter Roadmap

Click any topic to jump in

1
Self-Attention

The core mechanism — every token computes weighted attention over all other tokens via queries, keys, and values.

Queries, Keys, and ValuesScaled Dot-Product AttentionCausal (Masked) AttentionAttention Complexity
Parallel heads and per-token processing

Multi-head attention captures diverse patterns; FFN stores and transforms knowledge

2
Multi-Head Attention

Parallel attention heads that each learn different relationship types — syntax, semantics, position.

Multi-Head Attention FormulaWhat Different Heads LearnGrouped Query Attention (GQA)Multi-Query Attention (MQA)
3
Feed-Forward Networks

Per-token nonlinear transformations that store factual knowledge and apply complex feature mappings.

Position-wise FFNActivation FunctionsSwiGLU ActivationFFN as Knowledge Storage
Training stability mechanisms

Normalization and skip connections make deep stacking possible

4
Layer Normalization

Stabilizing deep network training by normalizing activations — LayerNorm, RMSNorm, Pre-Norm vs Post-Norm.

Layer NormalizationPre-Norm vs Post-NormRMSNormWhy Not BatchNorm?
5
Residual Connections

Skip connections that enable gradient flow through 100+ layers by preserving the identity path.

Residual Connection FormulaGradient FlowResidual Stream Interpretation
Complete architecture
6
Full Transformer Block

Assembling all components into the Pre-Norm block that gets stacked dozens of times in modern LLMs.

Pre-Norm Transformer BlockParameter Count BreakdownKV Cache for InferenceScaling Depth vs Width

A word's meaning depends on other words, often far away. In "The trophy did not fit in the suitcase because it was too big", the word "it" refers to the trophy eight words earlier, and only the final word "big" settles it. A recurrent network must carry that clue forward step by step through one hidden vector, and the signal fades over long distances. It also cannot process the positions in parallel, which makes training slow on modern hardware.

The previous chapter, Tokenization & Embeddings, turned text into a sequence of vectors with positions attached. This topic covers the operation that lets every one of those vectors look directly at every other one in a single step.

We start with queries, keys, and values, the three roles each token plays. Then we build scaled dot-product attention and explain why the scores are divided by dk\sqrt{d_k}. Next comes the causal mask that stops a decoder from reading the future. We finish with the cost: attention compares every pair of tokens, so it grows with the square of sequence length.

Definition

Self-attention is a sequence operation in which every position computes a query, a key, and a value by linear projection. It scores its query against every key with scaled dot products, turns the scores into weights with a softmax, and outputs the weighted sum of the values. The result is a context-dependent representation for each position, computed for all positions in parallel.

In this topic

1Queries, Keys, and Values
2Scaled Dot-Product Attention
3Causal (Masked) Attention
4Attention Complexity
1 of 4
Queries, Keys, and Values

Q=XWQ,K=XWK,V=XWVQ = XW_Q, \quad K = XW_K, \quad V = XW_V

Self-attention gives each token three roles, each produced by a learned matrix. The query qi=xiWQq_i = x_i W_Q describes what token ii is looking for. The key kj=xjWKk_j = x_j W_K describes what token jj offers to be matched against. The value vj=xjWVv_j = x_j W_V is the content token jj passes along if it is chosen. Here xix_i is the input embedding and WQ,WK,WV∈Rd×dkW_Q, W_K, W_V \in \mathbb{R}^{d \times d_k}. Separating matching (keys) from content (values) lets a token be easy to find for one reason and contribute something different. The roles are learned, not assigned, so no head is guaranteed to learn a clean grammatical role.

Mathematical Intuition

The projection matrices WQ,WK,WV∈Rd×dkW_Q, W_K, W_V \in \mathbb{R}^{d \times d_k} transform each token into three roles. The attention score qiTkj=xiTWQTWKxjq_i^T k_j = x_i^T W_Q^T W_K x_j is a bilinear form that measures compatibility between tokens ii and jj through the learned metric WQTWKW_Q^T W_K. This is more expressive than simple dot-product similarity because the model learns what aspects of tokens should determine attention.

Example:

In "The cat sat on the mat", how does the word "sat" use Q, K, V?

2 of 4
Scaled Dot-Product Attention

Attention(Q,K,V)=softmax(QKTdk)V\text{Attention}(Q, K, V) = \text{softmax}\left(\frac{QK^T}{\sqrt{d_k}}\right)V

The attention function runs in four steps. First compute all query-key dot products at once as QKTQK^T, an n×nn \times n score matrix for nn tokens. Then divide by dk\sqrt{d_k}, where dkd_k is the key dimension. Then apply a softmax to each row, so each token's weights are positive and sum to 1. Finally multiply by VV to mix the values. The scaling matters because a dot product of two random dkd_k-dimensional vectors with unit-variance entries has variance dkd_k. Unscaled, large scores push the softmax into a near one-hot regime where its gradients almost vanish, and learning stalls.

Mathematical Intuition

Self-attention computes softmax(QKT/dk)V\text{softmax}(QK^T/\sqrt{d_k})V. The dk\sqrt{d_k} scaling prevents dot products from growing with dimension, keeping softmax gradients useful. Without scaling, if qq and kk are random vectors with entries ∼N(0,1)\sim N(0,1), then qTkq^T k has variance dkd_k. For dk=64d_k = 64: std ≈8\approx 8, and softmax([8,−8,2,...])\text{softmax}([8, -8, 2, ...]) is nearly one-hot, producing vanishing gradients for all but the top-scoring key.

Example:

Why divide by dk\sqrt{d_k}? What happens without scaling when dk=512d_k = 512?

3 of 4
Causal (Masked) Attention

maskij={0if j≤i−∞if j>i\text{mask}_{ij} = \begin{cases} 0 & \text{if } j \leq i \\ -\infty & \text{if } j > i \end{cases}

A decoder-only model such as GPT or Llama is trained to predict each next token, so position ii must not see positions after it. The causal mask enforces this by adding −∞-\infty to every score where the key position jj is greater than the query position ii, as in the formula, before the softmax. Since e−∞=0e^{-\infty} = 0, those weights become exactly zero and the remaining weights still sum to 1. One forward pass then trains every position at once without leaking the answer. Forgetting the mask is a classic bug: training loss collapses toward zero while generation is useless.

Mathematical Intuition

The causal mask Mij=−∞⋅1[j>i]M_{ij} = -\infty \cdot \mathbb{1}[j > i] ensures softmax(…+M)ij=0\text{softmax}(\ldots + M)_{ij} = 0 for j>ij > i, because e−∞=0e^{-\infty} = 0. This enforces the autoregressive property: P(xt∣x<t)P(x_t \mid x_{<t}) cannot depend on x>tx_{>t}. The mask is the only difference between encoder (bidirectional) and decoder (causal) attention — the same attention mechanism with a different mask produces fundamentally different model capabilities.

Example:

In the sequence "I love cats", which tokens can "love" attend to?

4 of 4
Attention Complexity

Time: O(n2⋅d),Memory: O(n2+n⋅d)\text{Time: } O(n^2 \cdot d), \quad \text{Memory: } O(n^2 + n \cdot d)

Attention's cost comes from the score matrix. Every one of the nn queries is compared with all nn keys, and each comparison is a dd-dimensional dot product, so time grows as O(n2⋅d)O(n^2 \cdot d), as in the formula. A naive implementation also stores the n×nn \times n matrix, so memory grows as O(n2)O(n^2) as well. The feedforward layers, by contrast, are linear in nn. At short lengths the feedforward layers dominate, but at long lengths attention takes over. FlashAttention removes the quadratic memory by computing in tiles, but the quadratic compute remains. Sparse, sliding-window, and linear attention trade exactness for lower cost.

Mathematical Intuition

Computing the n×nn \times n attention matrix QKTQK^T requires n2dn^2 d multiply-adds. Storing this matrix takes n2n^2 floats. For n=128,000n = 128{,}000 (Llama's context): the matrix has 1.64×10101.64 \times 10^{10} entries, requiring ∼64\sim 64 GB in FP32. FlashAttention avoids materializing this matrix by computing attention in tiles that fit in SRAM, reducing memory from O(n2)O(n^2) to O(n)O(n) while maintaining exact computation.

Example:

A model processes 8K tokens with d=4096d = 4096. How does doubling context to 16K affect attention compute?

Theory Exercise

Problem:

Explain why self-attention can capture long-range dependencies that RNNs cannot, using a concrete example.

Hints:
  • Think about the path length between distant tokens
  • Consider the vanishing gradient problem in RNNs
  • Think about the attention matrix as a shortcut