A visual deep-dive
Inside the LLM
A visual deep-dive into how Large Language Models think, process, and generate — from raw text to output token.
What is a token?
Words break into colored pieces
A token is a subword unit — not always a full word.
Subword split of "unbelievable":
Algorithms
Three families
🔵 BPE — Byte Pair Encoding
GPT series. Merges most frequent character pairs iteratively.
🟢 WordPiece
BERT, DistilBERT. Maximizes language-model likelihood.
🟣 SentencePiece
LLaMA, T5, Mistral. Language-agnostic, works on raw bytes.
Token → ID → Embedding
Lookup table
| Model | Vocab |
|---|---|
| BERT | 30,522 |
| GPT-2 | 50,257 |
| GPT-4 | ~100,000 |
Token embeddings
A point in dmodel-dimensional space
Rows = tokens · Columns = dimensions.
BERT: dmodel = 768 · GPT-3: dmodel = 12,288
Positional encoding
Two ways to inject order
Sinusoidal
Original Transformer (2017).
RoPE
LLaMA, Mistral, Gemma.
Rotates Q and K vectors by an angle proportional to position.
RoPE generalizes better to longer contexts than fixed sinusoidal encodings.
Multi-Head Attention
Multiple parallel attention heads let the model attend to different relationships at once. See Chapter 5 →
Residual Connection
Gradients flow directly through the skip path — this is what makes deep stacks of 96+ layers trainable.
Layer Normalization
Stabilizes training by normalizing feature distributions per token.
Feed-Forward Network
Dimensions expand dmodel → 4·dmodel → dmodel.
Attention is the mechanism that lets every token decide which other tokens to focus on. It is the core innovation of the Transformer architecture.
Scaled Dot-Product
FoundationQ · K · V
- ① scores = Q · Kᵀ
- ② scores = scores / √dₖ
- ③ mask (if needed): scores[future] = −∞
- ④ weights = softmax(scores)
- ⑤ output = weights · V
Q asks "what am I looking for?", K says "what do I contain?", V says "what will I give you?". Attention finds which K matches Q best, then returns those V values.
Multi-Head Attention
GPT · BERT · LLaMA · ClaudeMany specialized views
MultiHead = Concat(head₁,…,headₕ) · Wᴼ
| Head | What it learns |
|---|---|
| 1 | Subject–verb agreement |
| 2 | Coreference (he/she/it → noun) |
| 3 | Positional patterns |
| 4 | Semantic similarity |
| 5–8 | Syntax, rare patterns… |
GPT-3 has 96 heads × 96 layers.
Masked Self-Attention
GPT · LLaMA · ClaudeCan only look LEFT — never the future
Set −∞ at masked positions before softmax → softmax(−∞) = 0 → those tokens get zero attention weight.
where M[i,j] = 0 if j ≤ i, else −∞
Like writing a story — you can only reference what you've already written.
Cross-Attention
T5 · BART · WhisperBridges encoder ↔ decoder
English "The cat sat" → Encoder → K, V. French Decoder Q → CrossAttn(Q, K, V) → "Le chat s'assit".
Grouped Query Attention
LLaMA 2/3 · Mistral · GemmaShare K/V across query heads
With 32 query heads you'd need 32 K/V pairs — the KV cache explodes during inference. GQA shares K/V across groups.
✅ 2–4× less KV cache memory
✅ Faster inference, same quality
✅ Enables longer context windows
LLaMA 3 70B uses 8 KV heads for 64 query heads (8:1).
Flash Attention
GPT-4 · Claude · Gemini · LLaMA 3Same math — way smarter memory
Standard attention stores the full N×N matrix in slow GPU HBM. For N=8192: 8192² × 4B ≈ 256MB per layer.
Flash Attention tiles Q, K, V into blocks and processes one at a time in fast SRAM — never materializing the full matrix.
| Standard | Flash | |
|---|---|---|
| Memory | O(N²) | O(N) |
| Speed | Baseline | 2–4× faster |
| Full matrix stored | ✅ Yes | ❌ No |
| Numerically identical | — | ✅ Yes |
Flash 1 (2022) → Flash 2 (2023) → Flash 3 (2024).
Architecture
Expand · activate · contract
Activation curves
Why it matters
FFN layers store world knowledge
Geva et al. (2021) showed individual FFN neurons activate for specific facts — "capital of France", "author of Hamlet", and so on.
| Layer | GPT-3 params |
|---|---|
| Total | 175B |
| FFN layers | ~113B (65%) |
| Attention | ~58B |
Remove the FFN and the model loses most of its factual knowledge.
LLaMA replaces GELU with SwiGLU for better empirical results.
Residual connections
Without residuals, gradients vanish in deep networks. The skip path keeps gradients alive through 96+ layers.
Layer normalization
Pre-norm (LN before sublayer) trains more stably than the original post-norm. GPT-3 and LLaMA use pre-norm.
Greedy
Always pick the top token
✅ Fast · ❌ Repetitive · ❌ Boring
Beam Search
Keep top-k candidate sequences
k=1 = Greedy · k=5 typical · k=10+ translation. ✅ Better quality · ❌ Slow
Top-k Sampling
Sample from the top k tokens
✅ Creative · ❌ k is context-sensitive
Top-p (Nucleus)
Smallest set covering p% mass
✅ Adapts to context · used by default in most LLMs · p=0.9–0.95
Temperature
Scale logits before softmax
T = 0.1 — spiky
T = 1.0 — natural
T = 2.0 — flat
Rule of thumb: Coding T=0.0–0.3 · Chat T=0.7 · Creative T=1.0–1.2
🔵 Encoder-Only
BERT · RoBERTa · DistilBERT · ELECTRA
Attention: Bidirectional — every token sees every other
Training: Masked Language Modeling (predict [MASK])
Best for: Classification · NER · QA · Embeddings
Not for generation
🟣 Decoder-Only
GPT-4 · LLaMA · Mistral · Claude · Gemini
Attention: Causal — lower triangular mask
Training: Next-token prediction (autoregressive)
Best for: Chat · Code · Reasoning · Generation
Context: 4k (GPT-3) → 128k (GPT-4) → 1M+ (Gemini 1.5)
🟢 Encoder–Decoder
T5 · BART · mT5 · Whisper · MarianMT
Attention: Encoder bidir + decoder causal + cross-attention
Training: Span corruption / seq-to-seq
Best for: Translation · Summarization · Speech-to-text
Heaviest of the three
Full comparison
| Feature | Encoder-Only | Decoder-Only | Enc–Dec |
|---|---|---|---|
| Sees context | Both directions | Left only | Both |
| Primary task | Understanding | Generation | Seq2Seq |
| KV cache needed | No | Yes | Yes |
| Cross-attention | No | No | Yes |
| Examples | BERT | GPT-4 | T5 |
Pre-Training
Common Crawl · Books · Wikipedia · GitHub · ArXiv.
Trillions of tokens, weeks on thousands of GPUs.
Output: a language model — but it doesn't follow instructions.
Supervised Fine-Tuning (SFT)
~10k–100k expert-written prompt → response pairs.
Output: model learns to follow instructions helpfully.
RLHF
- ① Collect human preference pairs (A vs B).
- ② Train a reward model on preferences.
- ③ Use PPO to maximize reward model score.
Output: aligned model, less harmful.
Modern Alternatives
DPO — skip the reward model, optimize preferences directly.
RLAIF — AI feedback (Claude / GPT-4) replaces humans.
Constitutional AI — model critiques and revises itself.
Chinchilla Scaling Law
For compute-optimal training: 20 tokens per parameter. LLaMA 2 7B → 140B tokens · 70B model → 1.4T tokens.
⚡ KV Cache
Never recompute the past
LLaMA 3 70B @ 8k context ≈ 16 GB just for KV cache.
RoPE
Rotary positional embeddings
- ✅ Relative positions preserved
- ✅ Extrapolates to longer contexts
- ✅ No learnable parameters
Used by LLaMA · Mistral · Gemma · GPT-NeoX · Falcon.
LoRA
Fine-tune billions on one GPU
Freeze W, add small trainable matrices A and B.
7B model → fine-tune only ~4M params instead of 7B.
Mixture of Experts (MoE)
Sparse — activate only 2–4 experts
Mixtral 8×7B: 8 experts, top-2 active, 13B active per token. GPT-4 (rumored): 8 experts, ~220B active of ~1.8T total.
Token
ArchitectureThe atomic unit of text a model processes — often a subword piece.
Embedding
ArchitectureA learned dense vector representation of a token.
Query (Q)
AttentionVector representing what a token is looking for.
Key (K)
AttentionVector representing what a token contains.
Value (V)
AttentionVector representing the content a token will contribute if attended to.
Attention Score
AttentionDot product Q·Kᵀ before softmax.
Attention Weight
AttentionSoftmax-normalized attention score in [0,1].
Attention Head
AttentionOne independent set of Q/K/V projections in a multi-head layer.
Transformer Block
ArchitectureA repeating unit: attention + residual + norm + FFN + residual + norm.
Encoder
ArchitectureStack that produces bidirectional representations of input.
Decoder
ArchitectureCausal stack that generates tokens one at a time.
Self-Attention
AttentionAttention where Q, K, V come from the same sequence.
Cross-Attention
AttentionDecoder Q attends to encoder K and V.
Masked Attention
AttentionCausal mask preventing tokens from seeing future positions.
Multi-Head Attention
AttentionSeveral attention heads run in parallel, then concatenated.
Grouped Query Attention
EfficiencyMultiple query heads share fewer K/V heads to shrink KV cache.
Flash Attention
EfficiencyTiled attention that avoids materializing the full N×N matrix.
Layer Normalization
ArchitectureNormalizes features per token to stabilize training.
Residual Connection
ArchitectureSkip connection y = x + Sublayer(x) that lets gradients flow.
Feed-Forward Network (FFN)
ArchitectureTwo-layer MLP applied position-wise after attention.
GELU
ArchitectureSmooth activation used in Transformer FFN layers.
SwiGLU
ArchitectureGated activation variant used by LLaMA-family FFNs.
Softmax
DecodingFunction that turns logits into a probability distribution.
Temperature
DecodingScalar that sharpens or flattens the next-token distribution.
Top-k Sampling
DecodingSample only from the k highest-probability tokens.
Top-p Sampling
DecodingSample from the smallest set covering p% of probability mass.
Beam Search
DecodingKeep the top-k partial sequences at every step.
Greedy Decoding
DecodingAlways pick the single highest-probability token.
Context Window
ArchitectureMaximum number of tokens the model can attend to at once.
KV Cache
EfficiencyStored K/V tensors from previous tokens reused at inference.
Positional Encoding
ArchitectureSignal that injects token order into embeddings.
RoPE
EfficiencyRotary positional encoding that rotates Q/K by angle ∝ position.
ALiBi
EfficiencyAdds a position-dependent bias to attention scores, no embeddings needed.
BPE
ArchitectureByte Pair Encoding — merges frequent character pairs into tokens.
WordPiece
ArchitectureTokenization that maximizes language-model likelihood.
SentencePiece
ArchitectureLanguage-agnostic tokenizer that operates on raw bytes.
Vocabulary
ArchitectureThe full set of tokens a tokenizer can produce.
Pre-training
TrainingSelf-supervised next-token prediction on massive corpora.
Fine-tuning
TrainingFurther training on a smaller, task-specific dataset.
SFT
TrainingSupervised fine-tuning on prompt → response pairs.
RLHF
TrainingReinforcement learning from human feedback via a reward model.
DPO
TrainingDirect Preference Optimization — optimize preferences without a reward model.
RLAIF
TrainingRL from AI feedback instead of human labels.
Reward Model
TrainingModel trained to predict human preference between two responses.
LoRA
EfficiencyLow-Rank Adapters fine-tune via small additive matrices.
MoE
EfficiencyMixture of Experts — sparsely activates a few FFN experts per token.
Router
EfficiencyGating function in MoE that picks experts per token.
Expert
EfficiencyOne of several parallel FFNs in an MoE layer.
Scaling Laws
TrainingEmpirical power-laws relating loss, data, parameters, compute.
Chinchilla Law
TrainingCompute-optimal training uses ~20 tokens per parameter.
dmodel
ArchitectureHidden dimension of token representations.
dff
ArchitectureInner dimension of the FFN — typically 4 × dmodel.
dₖ
AttentionPer-head dimension used inside attention.
Num Heads
AttentionNumber of parallel attention heads per layer.
Num Layers
ArchitectureDepth of the Transformer stack.
Batch Size
TrainingNumber of sequences processed in one training step.
Gradient
TrainingVector of partial derivatives of the loss w.r.t. parameters.
Backpropagation
TrainingChain-rule algorithm that computes gradients through the network.
Cross-Entropy Loss
TrainingLoss comparing predicted distribution to one-hot true label.
Perplexity
Trainingexp(loss) — average per-token uncertainty.