LLM_log #003 Understanding Large Language Models – Transformers illustrative explanation
๐ Understanding Large Language Models: A Complete Visual Guide
๐ฏ What You’ll Learn
Large Language Models like GPT-4, Claude, and Llama have transformed how we interact with AI, but understanding what actually happens when you type “The cat sat on the” and the model predicts “mat” can feel like opening a black box.
In this comprehensive guide, we’ll demystify the entire process by following a single example through every step of a Transformer’s architecture. You’ll learn exactly how text becomes numbers, how those numbers flow through 12 sequential processing blocks, and how mathematical operations like attention and matrix multiplication work together to generate intelligent predictions.
We’ll use GPT-2 as our reference model (117 million parameters, 768 dimensions, 12 Transformer blocks) because it’s well-documented and represents the core architecture used in modern LLMs.
Tutorial Overview
- The Three Main Components – Tokenizer, Transformer Stack, and Language Modeling Head
- The Forward Pass – How text flows through the model to generate predictions
- Positional Encodings – Teaching the model about word order
- Inside Transformer Blocks – Self-attention and feedforward networks
- The Feedforward Network – Where 48% of parameters live
- Self-Attention in Action – How context influences predictions
- Mathematical Deep Dive – Real numbers through attention
- Multi-Head Attention – Why we split into 12 parallel heads
1. The Three Main Components
When you ask ChatGPT a question or have Claude write code for you, your text goes through three major processing stages. Understanding this high-level architecture is essential before we dive into the details.
Every Transformer LLM follows the same basic pipeline: Tokenizer โ Transformer Stack โ LM Head
Figure 3-4: The Three Main Components of a Transformer LLM
TOKENIZER
” cat” โ 3857
” sat” โ 3332
” on” โ 319
” the” โ 262
STACK OF TRANSFORMER BLOCKS
LM HEAD
One selected token
The three-component design elegantly separates concerns. The tokenizer handles text-to-numbers conversion, the Transformer stack does the computational heavy lifting, and the LM Head converts refined representations back into probabilities over words.
By the time text reaches the Transformer blocks, it’s already converted into dense vectors of 768 numbers each. The model never sees actual words after tokenization – only numerical representations.
2. The Forward Pass
Let’s trace exactly what happens to “The cat sat on the” as it flows through the model.
GPT-2 Specifications
- Vocabulary: 50,257 tokens
- Embedding dimension: 768
- Number of blocks: 12
- Context window: 1,024 tokens
- Total parameters: ~117 million
Step 1: Tokenization
Figure 3-5: Tokenizer Vocabulary & Token Embeddings
(e.g., 3,072 dimensions)
[0.23, -0.45, …, 0.89]
[-0.11, 0.78, …, 0.23]
[0.12, 0.56, -0.89, …, 0.34]
โ “the”
[0.67, -0.34, 0.12, …, -0.56]
โ “on”
[0.45, 0.23, -0.67, …, 0.12]
โ “The”
[-0.89, 0.45, 0.23, …, 0.78]
โ “sat”
[-0.23, 0.89, 0.34, …, -0.45]
โ “cat”
[0.34, 0.56, …, 0.67]
” cat”
” sat”
” on”
” the”
โข Unique IDs: Each token has a numeric identifier
โข Dense vectors: Each ID maps to 1000s of dimensions (e.g., 3072)
โข Learned representations: Trained to capture semantic meaning
The embedding for “cat” in GPT-2 is completely different from “cat” in GPT-3 or Claude. Each model learns its own embeddings during training. You cannot transfer embeddings between models.
Step 2: Through Transformer Stack
Figure 3-6: Complete Forward Pass & Probability Distribution
โ Only LAST position (“the”) used for prediction
| Token | Probability | Visual |
|---|---|---|
| ! | 0.01% | |
| “ | 0.02% | |
| … | … | |
| mat | 45% ๐ |
HIGHEST
|
| floor | 18% | |
| couch | 12% | |
| rug | 8% | |
| chair | 5% | |
| … | 12% | (49,995 other tokens) |
2. Last Position Matters: Only output of “the” position used for prediction
3. Full Distribution: Model scores ALL 50,000 tokens
4. Highest Score Wins: “mat” (45%) is most likely next token
All 5 tokens process in parallel through each block. They don’t go one-by-one – imagine 5 separate streams flowing simultaneously. Each stream can “look at” the others (that’s attention), but all move forward together.
Step 3: Decoding Strategies
Figure 3-7: Choosing a Token – Decoding Strategies
| Token | Probability | Visual |
|---|---|---|
| mat | 45% |
๐ฏ HIGHEST
|
| floor | 18% | |
| couch | 12% | |
| rug | 8% | |
| chair | 5% | |
| … | 12% | (49,995 other tokens) |
2. Greedy = Predictable: Always picks highest probability (deterministic)
3. Sampling = Creative: Picks based on probabilities (varied output)
4. Temperature: Controls randomness (0 = greedy, higher = more random)
5. Real LLMs: Often use advanced strategies (top-k, top-p) for best results
3. Positional Encodings
There’s a critical problem: the model has no idea about word order. “The cat chased the dog” would look identical to “The dog chased the cat” without position information.
Figure 3-8: Positional Encodings – Teaching the Model About Order
โข “You love me” โ “You love me?”
Word order matters in language! The model must know which token comes first, second, third, etc.
Final Embedding = Token Embedding + Position EncodingThis way, the model can distinguish between “cat at position 2” vs “cat at position 5”
โข Separate embedding table for positions
โข Position 0 โ vector [0.23, -0.45, …]
โข Position 1 โ vector [0.12, 0.67, …]
โข …
โข Position 1023 โ vector [-0.34, 0.89, …]
Cons: Fixed maximum length (1024 for GPT-2)
โข Mathematical function, not learned
โข sin/cos waves of different frequencies
โข Applied during attention computation
โข Can handle any length!
Cons: More complex implementation
2. Added at input: Token embedding + Position encoding = Final embedding
3. Two approaches: Learned (GPT-2) vs Sinusoidal/RoPE (modern models)
4. Context limit: GPT-2 can handle max 1,024 tokens (positions 0-1023)
5. Once and done: Position info flows through the network but isn’t re-added
Positional information is added ONCE at the very beginning, right after token embedding lookup. It’s not re-added at each block. The position info flows through the network encoded in the vectors themselves.
4. Inside Transformer Blocks
Now let’s see what happens inside those 12 Transformer blocks.
The Stack
Figure 3-11: Inside the Transformer – Stack of Processing Blocks
โข GPT-3: 96 blocks
โข Llama 2: 32-80 blocks (depending on size)
โข Original Transformer: 6 blocks
Inside One Block
Figure 3-12: Inside a Transformer Block
โข Combines information from relevant positions
โข Example: Understanding “it” in “The cat sat on the mat because it…”
โข Uses Query, Key, Value matrices
โข Factual knowledge (e.g., “Paris” after “France”)
โข Language patterns and relationships
โข Enables both memorization & generalization
Feedforward: Recalls from training data that “Redemption” often follows
Result: High probability for “Redemption”
5. The Feedforward Network
Let’s zoom into the feedforward component – it contains 48% of the model’s parameters!
Figure 3-13: Feedforward Neural Network – Where Knowledge Lives
Allows network to learn complex patterns
GeLU(x) = x ยท ฮฆ(x)
| Component | Parameters | Percentage |
|---|---|---|
| Token Embeddings | 38.6M | 33% |
| 12 ร Feedforward Layers | 56.6M | 48% ๐ |
| 12 ร Attention Layers | 28.3M | 24% |
| Other (LayerNorm, etc.) | ~1M | ~1% |
| TOTAL | ~117M | 100% |
The feedforward network is the model’s primary knowledge store. That 4ร expansion (768 โ 3,072 โ 768) provides massive capacity to encode patterns learned from billions of training tokens.
6. Self-Attention in Action
Now let’s see attention working with our example sentence.
Figure 3-14: Self-Attention Incorporates Relevant Context
โข Should we focus on “cat”? ๐ฑ
โข Or on “sat”? ๐บ
โข Or on “on”? ๐
5%
25%
58% ๐ฏ
12%
โ Predicts: “mat” (common object to sit on)
โข “The dog sat on the floor”
โข “She sat on the chair”
The model learned that after “sat on the“, common completions are furniture/surfaces. The attention mechanism learned to focus on the verb “sat” to understand what type of word should come next.
The model doesn’t have hardcoded rules saying “attend to ‘sat’ when predicting furniture.” These patterns emerge through training on billions of tokens. The attention weights are learned parameters that get adjusted to minimize prediction error.
7. Mathematical Deep Dive
Let’s follow real numbers through the attention mechanism using a simplified 4D example.
Part 3: Attention Mechanism – Mathematical Deep Dive
โข Sentence: “The cat sat on the”
โข Vector dimension: 4 (instead of GPT-2’s 768)
โข Focus: Processing the last token “the” to predict “mat”
โข Real numbers: Actual matrix multiplications you can verify!
[0.1 0.4 0.2 0.5]
[0.3 0.1 0.5 0.2]
[0.2 0.3 0.1 0.4]
[0.2 0.5 0.1 0.2]
[0.3 0.1 0.4 0.5]
[0.1 0.2 0.3 0.4]
[0.3 0.5 0.3 0.1]
[0.2 0.3 0.4 0.5]
[0.4 0.2 0.1 0.3]
[0.1 0.4 0.2 0.5]
[0.3 0.1 0.5 0.2]
[0.2 0.3 0.1 0.4]
[0.59,0.41,0.56,0.43] ยท
[0.58,0.55,0.47,0.61]
[1.13/2, 1.09/2, 1.28/2, 1.15/2] = [0.565, 0.545, 0.640, 0.575]
vโ = [0.67, 0.58, 0.47, 0.54]
vโ = [0.79, 0.48, 0.56, 0.75]
vโ = [0.68, 0.55, 0.44, 0.61]
0.240ร[0.67, 0.58, 0.47, 0.54] +
0.265ร[0.79, 0.48, 0.56, 0.75] +
0.249ร[0.68, 0.55, 0.44, 0.61]
NO context
COLORED by “sat” (26.5%)
24.0% of vโ (“cat”) +
26.5% of vโ (“sat”) โ MOST
24.9% of vโ (“on”)
โข Keys (kโ, kโ, kโ, kโ) โ to compute attention scores
โข Values (vโ, vโ, vโ, vโ) โ to combine in weighted sum
โข Query (qโ ) โ to determine what to attend to
All tokens must be processed simultaneously to generate their K and V vectors. This is why Transformers process tokens in parallel – not for speed, but because the math requires it!
2. Token “sat” got highest attention (26.5%): This is why the model predicts furniture/surfaces
3. All operations are differentiable: The model can learn optimal WQ, WK, WV through backpropagation
4. In real GPT-2: Vectors are 768-dimensional, not 4, but the math is identical!
5. This happens in parallel: All 5 tokens are processed simultaneously
โ Feedforward Neural Network
โ More Transformer blocks (repeat 11 more times in GPT-2)
โ LM Head to predict “mat”
The weighted sum formula needs value vectors from ALL previous tokens simultaneously. To compute output for position 5, we need vโ, vโ, vโ, vโ all at once. This is why Transformers are inherently parallel – the math requires it!
8. Multi-Head Attention
GPT-2 actually runs attention 12 times in parallel using different learned matrices.
Figure 3-17: Complete Flow Through One Transformer Block
โ
LM Head matrix (768 ร 50,257)
โ
50,257 logits
โ
Softmax โ probabilities
โ
Select token (e.g., “mat”)
MultiHead(Q,K,V) = Concat(head1,…,head12)WO
Where each head:
headi = Attention(QWQi, KWKi, VWVi)
Each head sees dimensions 0-63, 64-127, etc. But information isn’t neatly separated – it’s distributed across all dimensions. Each head sees a partial, blurred view of everything. Through learned Q/K/V projections, different heads learn to emphasize different patterns.
๐ Final Synthesis
The Complete Flow
- Text โ Tokenizer โ Token IDs
- Token IDs โ Embedding Lookup โ 768-dim vectors
- Add positional encodings (once, at the start)
- Flow through 12 Transformer blocks sequentially
- Each block: Self-attention + Feedforward + Residual connections
- Final output โ LM Head โ 50,257 logits
- Softmax โ Probabilities โ Pick next token
Key Takeaways
Everything is learned: Token embeddings, attention weights, feedforward parameters – all learned from data, not hand-designed.
Parallel processing: All tokens flow simultaneously. This isn’t just for speed – the math requires it.
Context is key: Same word has different representations depending on context, thanks to attention.
Scale matters: GPT-2’s 117M parameters enable good performance, but GPT-3 (175B) and GPT-4 (rumored 1.7T) achieve dramatically better results.
It’s predictive: Despite seeming intelligent, LLMs do next-token prediction based on learned patterns.
๐ You’ve Completed the Guide!
You now understand how Large Language Models work from input to output. You’ve seen the architecture, followed numbers through calculations, and learned why design choices were made.
This knowledge applies to GPT-4, Claude, Llama, and virtually all modern LLMs.
Reference Model: GPT-2 (50,257 tokens โข 768 dimensions โข 12 blocks โข 117M parameters)
Consistent Example: “The cat sat on the” โ “mat”
Colors: Google Material Design Palette
All figures: Self-contained with inline CSS
๐ Appendix: Complete Mathematical Reference
This appendix provides all key mathematical formulas used in Transformer language models, with proper LaTeX notation.
1. Attention Mechanism
Single-Head Attention
Where:
- Q = Query matrix (what we’re looking for)
- K = Key matrix (what each token offers)
- V = Value matrix (actual information to combine)
- dk = dimension of keys (64 per head in GPT-2)
- โdk = scaling factor to prevent large dot products
For each attention head: dk = 64, so โdk = โ64 = 8
Multi-Head Attention
Where each head is computed as:
Parameters:
- WQi โ โdmodel ร dk = Query projection for head i
- WKi โ โdmodel ร dk = Key projection for head i
- WVi โ โdmodel ร dv = Value projection for head i
- WO โ โhdv ร dmodel = Output projection matrix
- h = number of heads (12 in GPT-2)
- dmodel = 768 (GPT-2)
- dk = dv = dmodel/h = 64 (GPT-2)
2. Softmax Function
Properties:
- Output range: (0, 1) for each element
- Sum constraint: ฮฃi softmax(xi) = 1
- Monotonic: preserves ordering of inputs
- Differentiable: enables gradient-based learning
In attention context:
Where scorei = (q ยท ki) / โdk
3. Layer Normalization
Where:
- ฮผ = (1/d) ฮฃi=1d xi (mean)
- ฯยฒ = (1/d) ฮฃi=1d (xi – ฮผ)ยฒ (variance)
- ฮณ, ฮฒ = learnable parameters (scale and shift)
- ฮต = 10-5 (small constant for numerical stability)
- โ = element-wise multiplication
- d = feature dimension (768 for GPT-2)
4. Residual Connections
Post-normalization (original Transformer):
Pre-normalization (modern Transformers, including GPT-2):
5. Feedforward Neural Network
Parameters:
- W1 โ โdmodel ร dff = First layer weights
- b1 โ โdff = First layer bias
- W2 โ โdff ร dmodel = Second layer weights
- b2 โ โdmodel = Second layer bias
- dff = feedforward hidden dimension (typically 4 ร dmodel)
GPT-2 Configuration:
- dmodel = 768
- dff = 3,072 (exactly 4 ร 768)
6. GeLU Activation Function
Gaussian Error Linear Unit:
Where ฮฆ(x) is the cumulative distribution function of standard normal distribution:
Approximation (commonly used in practice):
7. Positional Encoding
Learned Positional Embeddings (GPT-2)
Where:
- Etoken โ โ50,257 ร 768 = token embedding matrix
- Epos โ โ1,024 ร 768 = position embedding matrix
- t = token ID
- p = position (0 to 1,023)
Sinusoidal (Original Transformer)
Where:
- pos = position in sequence
- i = dimension index
- dmodel = model dimension (768)
8. Language Modeling Head
Project to vocabulary:
Apply softmax to get probabilities:
Where:
- xfinal โ โ768 = output from last Transformer block
- WLM โ โ768 ร 50,257 = LM head weight matrix
- V = 50,257 (vocabulary size)
- logits โ โ50,257 = scores for each token
9. Temperature Scaling
Temperature parameter controls randomness in sampling:
Temperature effects:
- T = 0: Greedy decoding (always pick highest probability)
- T = 1: Sample from raw distribution
- T > 1: More random (flattens distribution)
- T < 1: More confident (sharpens distribution)
10. Parameter Count Formulas
Per Transformer block:
Multi-head attention:
Feedforward network:
Total per block:
Full GPT-2 model:
Where:
- V = 50,257 (vocabulary size)
- dmodel = 768 (embedding dimension)
- L = 12 (number of blocks)
GPT-2 breakdown:
- Token embeddings: 50,257 ร 768 = 38,597,376
- Position embeddings: 1,024 ร 768 = 786,432
- 12 Transformer blocks: 12 ร 7.1M = 85.2M
- Total: ~117M parameters
11. Training Loss Function
Cross-entropy loss for next-token prediction:
Per-token loss:
Where:
- xi = token at position i
- P(xi+1 | x1, …, xi) = predicted probability for next token
- logittarget = score for the actual next token
๐ Formula Summary
| Attention | softmax(QKT/โdk) V |
| Multi-Head | Concat(heads) WO |
| Feedforward | GeLU(xW1)W2 |
| Layer Norm | ฮณ(x-ฮผ)/โ(ฯยฒ+ฮต) + ฮฒ |
| Residual | x + Sublayer(LayerNorm(x)) |
| Position | Etoken + Epos |
| LM Head | softmax(xยทWLM) |
๐ References
- “Attention Is All You Need” (Vaswani et al., 2017) – Original Transformer
- “Language Models are Unsupervised Multitask Learners” (Radford et al., 2019) – GPT-2
- “Layer Normalization” (Ba et al., 2016)
- “Gaussian Error Linear Units (GELUs)” (Hendrycks & Gimpel, 2016)
- “RoFormer” (Su et al., 2021) – Rotary Position Embeddings