Every number a transformer engineer needs to derive from scratch. Parameter counts, attention arithmetic, memory budgets, KV caches, throughput — all solvable in-browser with instant feedback.
You're reviewing a pull request that claims to add a "small" 125M parameter model. How do you verify that number? You need to count every learnable weight in the transformer — every matrix, every bias, every embedding vector. Off-by-one on a dimension means off-by-millions on the parameter count.
A standard decoder-only transformer (GPT-style) has these learnable components:
GPT-2 Small: d=768, L=12, V=50257, T=1024 (learned position embeddings, tied LM head). How many total parameters?
Compute: 12 × L × d² + V×d + T×d + final_LN. Ignore per-layer LN and biases for now.
GPT-2 Small is reported as "124M parameters." Add the per-layer LayerNorms and the attention and FFN biases (119,808 more) and you get 124,439,808 ≈ 124.4M. The embedding dominates the non-layer parameters (38.6M of the 39.4M non-layer params).
LLaMA 7B: d=4096, L=32, V=32000. Uses RoPE (no learned position embeddings), untied LM head, SwiGLU FFN with dff=11008 (not 4d). RMSNorm instead of LayerNorm (only γ, no β).
SwiGLU has 3 matrices: Wgate[d, dff], Wup[d, dff], Wdown[dff, d]. So FFN params = 3 × d × dff.
The SwiGLU FFN is 3d×dff instead of 8d² — that's why LLaMA uses dff = 11008 instead of the standard 4d = 16384. The choice dff ≈ ⅔ × 4d = 10,923, rounded up to 11,008 (a multiple of 256), keeps the FFN near the standard 8d² while adding the gate.
At 70B scale, the embedding table is less than 1% of total params. The 12Ld² approximation becomes extremely accurate. This is why "70B parameters" essentially means "70 billion weights in the attention and FFN layers."
You need approximately 1 billion parameters. All four (d, L) shapes below give the same 0.8B in the layers by the 12Ld² rule. Which is the sensible design?
All options give ~0.8B from layers alone, but architecture design is about balance. Too few layers (L=4) means very shallow — poor reasoning capability. Too many layers with tiny d (L=256, d=512) means each layer has very little capacity and you pay huge activation memory.
The sweet spot for ~1B is d=2048, L=16-24. TinyLlama (1.1B) uses d=2048, L=22. Kaplan et al. (2020) found that loss depends only weakly on shape over a wide range of d/L, but extreme shapes like L=4 or d=512 fall off that range.
Write a function that computes the parameter count of a standard GPT-style transformer. Assume tied embeddings, standard 4d FFN, and ignore biases/LayerNorm.
javascript function paramCount(d, L, V) { const perLayer = 12 * d * d; // 4d² attn + 8d² FFN const embedding = V * d; // tied, so counted once return L * perLayer + embedding; }
This parameter counting function has a bug. Someone is getting 2x the expected count. Click the buggy line.
function paramCount(d, L, V) { const attn = 4 * d * d; // Q, K, V, O projections const ffn = 8 * d * d; // W1 and W2 const perLayer = attn + ffn; // 12d^2 total const layers = L * perLayer; const embed = V * d; // token embedding const head = V * d; // LM head (tied!) return layers + embed + head; }
Line 7 is the bug. The comment says "tied!" but the code still adds V * d for the LM head. If the embedding is tied (shared) with the LM head, the LM head adds zero extra parameters — the same weight matrix is reused. The line should be const head = 0; or simply removed.
This is a real mistake people make: they know the weights are tied but still count them twice. It inflates the count by Vd, which for V=50257 and d=768 is 38.6M — a 31% overcount for GPT-2 Small.
Mixtral 8x7B uses Mixture of Experts. Each layer has 8 expert FFNs (each d×dff×3 SwiGLU with dff=14336), but only top-2 are active per token. The attention layers are shared (not duplicated) and use GQA: 32 query heads and 8 KV heads, dk=128. d=4096, L=32, V=32000, untied LM head.
Total params = shared attention params + 8 × per-expert FFN params + embeddings. (The "7B" refers roughly to the active params per token, not total.)
Mistral reports 46.7B total parameters. Each token uses only attention (42M) + 2 experts (352M) = 394M per layer: 32 × 394M + 0.26B embeddings ≈ 12.9B active. It computes like a 13B dense model but stores 47B weights. If you used 4d² for attention (forgetting GQA), you would get 47.5B.
You're debugging a transformer and the attention outputs look wrong. Is it the scaling? The masking? A dimension mismatch? You need to be able to trace the full attention computation by hand — input to output, with exact shapes and values.
For a single attention head with seq_len=2048, d_k=d_v=128: how many FLOPs for the QKT matmul alone? (Count multiply+add as 2 FLOPs per output element.)
This is a [seq, d_k] × [d_k, seq] matmul, producing a [seq, seq] attention matrix. The FLOPs scale as O(seq² × d_k) — quadratic in sequence length. This is the bottleneck that motivates FlashAttention and linear attention variants.
Now count the total FLOPs for the FULL self-attention of one layer: Q/K/V projections + QKT + softmax×V + output projection. d=4096, h=32 heads, d_k=d_v=128, seq=2048, batch=1.
Projections: 4 matmuls of [seq, d] × [d, d]. QKT and attn×V: per head, then sum across heads.
The full self-attention FLOPs formula is: 8sd² + 4s²d where the first term covers the 4 projection matmuls and the second covers QKT + attn×V.
The projections dominate when s < d (which is typical for s=2048, d=4096). The QKT and attn×V terms grow as s² — they overtake projections only when s > 2d. At s = 8192 = 2d, both terms are about 1.1 trillion FLOPs, so the attention core is half the total.
The attention weight matrix (after softmax) has shape [batch, heads, seq, seq]. For batch=1, heads=32, seq=8192, stored in FP32: how much memory does this matrix alone consume?
8.6 GB for a single attention matrix of a single layer! This is why FlashAttention is essential — it avoids materializing this O(s²) matrix entirely, computing attention in tiles that fit in SRAM. Training keeps one per layer for the backward pass: 32 layers would need 275 GB.
If Q and K vectors have entries drawn i.i.d. from N(0, 1), and d_k = 128, what is the expected variance of a single dot product q · k before scaling?
After dividing by √dk = √128 ≈ 11.3, the variance becomes 128/128 = 1. This keeps the softmax inputs in a stable range regardless of head dimension.
In practice, naive implementations still compute the full QKT and then mask. FlashAttention's causal variant actually skips these computations by processing only the lower-triangular tiles, so it does about half the work of non-causal attention.
Implement scaled dot-product attention for 1D arrays representing a single query and set of keys/values. No batch, no heads — just the core math.
javascript function scaledDotProduct(q, keys, values) { const dk = q.length; const scale = Math.sqrt(dk); // 1-2. Scaled dot products const scores = keys.map(k => k.reduce((s, ki, i) => s + ki * q[i], 0) / scale ); // 3. Softmax (numerically stable) const maxS = Math.max(...scores); const exps = scores.map(s => Math.exp(s - maxS)); const sumE = exps.reduce((a, b) => a + b, 0); const weights = exps.map(e => e / sumE); // 4. Weighted sum of values const dv = values[0].length; const out = new Array(dv).fill(0); for (let i = 0; i < weights.length; i++) for (let j = 0; j < dv; j++) out[j] += weights[i] * values[i][j]; return out; }
A single attention head can only learn one type of relationship at a time — maybe syntactic structure, or maybe semantic similarity, but not both simultaneously. Multi-head attention (MHA) runs multiple independent attention heads in parallel, each with its own Q/K/V projections, then concatenates and projects the results.
For MHA with d=4096, h=32 heads: how many parameters in WQ, WK, WV, WO combined (one layer, no biases)?
This is the 4d² from the parameter counting formula. Each W matrix maps from d to d. The multi-head split is a reshaping operation: WQ produces [s, d] which is reshaped to [s, h, d_k] where d_k = d/h = 128. The parameter count is the same regardless of the number of heads.
LLaMA 2 70B uses GQA with h=64 query heads and g=8 KV groups. d=8192. How many parameters are in K and V projections combined (one layer)?
Each group has its own K and V projection of size [d, d_k] where d_k = d/h = 128.
Compare to full MHA: K+V would be 2 × 8192 × 8192 = 134.2M. GQA with g=8 saves 8× on K/V parameters: 16.8M vs 134.2M. The Q projection and O projection remain full-size (h=64 heads), so the total attention params drop from 4d² = 268.4M to d² + d² + 2d×g×d_k = 134.2M + 16.8M = 151.0M per layer.
Most transformers use d_k = 64 or d_k = 128 per head. For d=4096, how many heads do you get with d_k=64 vs d_k=128? What is the ratio of the total QKT FLOPs for the whole layer (all heads, seq=2048)?
Each d_k=64 head does half the work of a d_k=128 head, but there are twice as many heads. The total is the same. What changes is the number of [s, s] score matrices: 64 against 32. Without FlashAttention, d_k=64 doubles that activation memory.
Put these GQA operations in the correct order for a forward pass. (The Q and K,V projections are independent, so they are one step.)
The correct order is: Project Q and K,V → Repeat K,V → QKT/√dk → Softmax × V → Concat + WO
The key GQA-specific step is "Repeat K,V" — each of the g KV groups is broadcast (repeated) to serve h/g query heads. In LLaMA 2 70B with h=64, g=8: each KV group serves 8 query heads. expand makes the repeat a view with no copy; many implementations then reshape, which does copy. Fused kernels index the shared K,V directly.
You have an 80GB A100. Can you fit a 7B model for training? What about inference? The answer depends on exactly what lives in GPU memory simultaneously. There are four categories of memory consumers, and they behave very differently between training and inference.
LLaMA 7B has 6.74B parameters. Using mixed-precision Adam (16 bytes/param), how much memory for weights + gradients + optimizer states? Will it fit on a single A100 80GB?
107.8 GB > 80 GB, so no, it does not fit on a single A100. And this is BEFORE activations! With activations (even with gradient checkpointing), you'd need ~130-150 GB. You need either: (a) 2+ GPUs with FSDP/ZeRO-3, or (b) quantized training (QLoRA), or (c) CPU offloading.
For inference, you only need the weights (no gradients or optimizer states). How much memory does LLaMA 7B need in BF16? In INT4 (4-bit quantization)?
BF16 inference of a 7B model fits comfortably on a single RTX 4090 (24GB). INT4 needs about 3.4 GB, so it fits on a 6–8 GB laptop GPU with room for the KV cache.
During training, activations must be stored for backprop. For a single transformer layer with d=4096, seq=2048, batch=8: estimate the activation memory for the attention output + FFN output (BF16, ignoring intermediate FFN activations).
Each layer produces: attention output [b, s, d] + FFN output [b, s, d] = 2 × b × s × d elements.
268 MB per layer × 32 layers ≈ 8.6 GB for these two tensors. The real activation memory is far larger: you also store Q, K, V, the attention scores (s² per head), FFN intermediates and norm inputs. Korthikanti et al. (2022) estimate s·b·d·(34 + 5hs/d) bytes per layer: about 7.7 GB per layer here, 245 GB for 32 layers. FlashAttention removes the s² term and brings it to about 73 GB.
LLaMA 2 70B has ~70B parameters. With mixed-precision Adam (16 bytes/param), how much total memory for weights+gradients+optimizer? How many A100 80GB GPUs minimum (just for these, ignoring activations)?
14 GPUs just for these states (sharded with ZeRO-3 or FSDP), before activations. Real runs use far more GPUs for speed: LLaMA 65B was trained on 2048 A100 80GB GPUs. The extra GPUs add data parallelism, not memory.
LoRA freezes the base model and adds low-rank adapters. For a 7B model (6.74B params), you add rank-16 adapters to Q and V projections only. Each adapter pair (A, B) has shapes [d, r] and [r, d]. With d=4096, r=16, L=32 layers: how many trainable parameters? What's the ratio to full model?
Only 0.12% of the base model size! Training memory for LoRA: base weights (BF16, frozen) = 13.5 GB + gradients for 8.4M params = 16.8 MB + Adam states for 8.4M = 67 MB. Total ≈ 13.6 GB plus activations, so it fits on a single 24 GB consumer GPU.
During autoregressive generation, each new token needs to attend to all previous tokens. Without caching, you'd recompute K and V projections for the entire context at every step. The KV cache stores the K and V vectors from all previous positions, so each step only computes K,V for the new token and appends to the cache.
LLaMA 7B: d=4096, L=32, h=32 (MHA, g=h). At context length 4096, in BF16: how much memory for the full KV cache?
2.15 GB of KV cache on top of 13.5 GB of weights = 15.6 GB total. This fits on a 24GB RTX 4090 with room to spare. But watch what happens at longer contexts...
Same LLaMA 7B model, but now at context length 128K (131072 tokens). KV cache in BF16?
68.7 GB for the KV cache alone, about 5× the weights. On an A100 80GB: 13.5 + 68.7 = 82.2 GB. It does not fit, even for one user. This is why long-context models use GQA, and why KV cache quantization (INT8 or INT4) and sliding window attention exist.
LLaMA 2 70B uses GQA with g=8, h=64, d=8192, L=80. KV cache at context=4096, BF16. Compare to full MHA (g=h=64).
GQA with 8 groups saves 8× on KV cache memory. This matters enormously for serving: at 128K context, full MHA would need 344 GB of KV cache against 43 GB with GQA. The parameter savings (fewer K/V projection weights) is a bonus, but the KV cache reduction is the primary motivation.
You have an A100 80GB serving LLaMA 7B in BF16 (13.5 GB weights). Each user gets up to 4096 context. KV cache per user = 2.15 GB (from Exercise 4.1). How many concurrent users can you serve?
30 users at 4K context. An INT8 KV cache (1.07 GB/user) gives 61 users; INT4 (0.54 GB/user) gives 123. PagedAttention (vLLM) helps from the other side: it stops memory being wasted on fragmentation and over-reservation, so real batches get closer to this limit.
For LLaMA 7B (d=4096, L=32, MHA), how many bytes does each new token add to the KV cache in BF16?
Each generated token holds 524 KB of GPU memory until the request ends. At 100 tokens/second that is 52 MB/s per user. A 500-token response holds 262 MB of KV cache.
These are the two non-linear operations that every transformer token passes through repeatedly. Getting them wrong — numerically, conceptually, or implementationally — produces subtle bugs that corrupt outputs without crashing.
javascript function stableSoftmax(logits) { const maxL = Math.max(...logits); const exps = logits.map(l => Math.exp(l - maxL)); const sum = exps.reduce((a, b) => a + b, 0); return exps.map(e => e / sum); }
javascript function rmsNorm(x, gamma, eps) { const meanSq = x.reduce((s, v) => s + v * v, 0) / x.length; const rms = Math.sqrt(meanSq + eps); return x.map((v, i) => gamma[i] * v / rms); }
Temperature T divides logits before softmax: softmax(x/T). For logits [2.0, 1.0, 0.5] with T=0.5, what is the probability of the top token?
T < 1 makes the distribution sharper (more confident). At T=1, P(top) = exp(2)/(exp(2)+exp(1)+exp(0.5)) = 0.629. At T=0.5, it jumps to 0.844. At T→0, it approaches 1.0 (greedy). At T→∞, it approaches 1/3 (uniform).
Self-attention has no concept of order. Shuffle the input tokens and each token's output is the same, only shuffled: "The cat sat on the mat" and "mat the on sat cat the" look alike to it. Positional encoding injects position information so the model can distinguish token order.
For d=512, what is the wavelength (period) of the sinusoidal encoding at dimension i=0 (the fastest oscillating) and i=255 (the slowest)?
Wavelength = 2π × 100002i/d.
The fastest dimension (i=0) oscillates with period 2π ≈ 6.3 positions — it can distinguish adjacent tokens. The slowest (i=255) has a period of about 60,611 positions: it encodes coarse position over long sequences. The wavelengths form a geometric series from 2π to about 2π × 10,000, so every scale of distance has some dimension that tracks it.
RoPE has 0 learnable parameters. Learned positional embedding for T=4096, d=4096 has how many parameters?
16.8M saved parameters is one reason modern models use RoPE. But the bigger reason is that RoPE generalizes to sequence lengths longer than training context (with NTK-aware or YaRN scaling), while learned embeddings cannot — position 8193 has no learned vector if you trained on 8192.
You're serving a 70B model and the PM asks: "How many tokens per second can we generate?" The answer depends on whether you're compute-bound (prefill) or memory-bandwidth-bound (decode), your batch size, and your hardware. You need to derive these numbers, not guess.
LLaMA 7B in BF16 on an A100 (2 TB/s HBM bandwidth). During decode at batch=1, you read all weights once per token. What is the maximum tokens/second?
148 tokens/second at batch=1. But the A100 has 312 TFLOP/s BF16 — computing 2P = 13.5 GFLOP per token takes only 43 microseconds. The GPU is 99.4% idle during decode, just waiting for memory. This is why batching matters: at batch=8 one weight read serves 8 tokens, so total throughput is about 8× (while still memory-bound, and ignoring KV cache reads).
Same LLaMA 7B on A100 (312 TFLOP/s BF16). Prefilling a 2048-token prompt. Assuming 50% MFU (model FLOPs utilization), how long does prefill take?
~177 ms TTFT for a 2048-token prompt. Prefill is compute-bound because you're processing many tokens at once in large matrix multiplies that fully utilize the GPU's tensor cores. The 50% MFU stands for everything that keeps real kernels below peak: memory traffic, launch overhead and non-matmul operations.
At what batch size does decode become compute-bound instead of memory-bound on the A100? The crossover happens when compute time = memory time. Use: 312 TFLOP/s compute, 2 TB/s bandwidth, 6.74B params in BF16.
At batch B, one decode step does 2PB FLOPs and reads 2P bytes of weights, so its arithmetic intensity is B FLOPs per byte. The crossover is where B equals the GPU's ridge point (peak FLOP/s ÷ bandwidth). Ignore KV cache reads.
Below batch=156, you're memory-bound (wasting compute). Above 156, you're compute-bound (fully utilizing tensor cores). In practice, KV cache memory limits your batch size long before 156 — at 4K context each user needs 2.15 GB of KV cache, so 156 users would need 335 GB of KV cache alone.
If you INT4-quantize the weights (0.5 bytes/param), what is the new decode throughput at batch=1 on A100 (2 TB/s)?
4× speedup over BF16! INT4 quantization gives you 4× the decode throughput because you read 4× fewer bytes from memory, and decode is memory-bandwidth-bound. Quantizing for serving raises tokens/second, not only memory headroom. Real kernels get less than 4× because dequantization costs time.
You need to serve Llama 2 70B at 30 tokens/sec per user, for 100 concurrent users at 4096 context. BF16 weights (140 GB), KV cache 1.34 GB per user (Exercise 4.3), H100 80 GB with 3.35 TB/s bandwidth. How many H100s minimum? Find the count that holds weights + all KV caches, then check that it meets 30 tok/s.
Memory sets the count, not bandwidth: 2 GPUs would have the bandwidth for the weights (48 tok/s per user) but cannot hold 274 GB. 49 tok/s beats the 30 tok/s target with margin for all-reduce traffic, prefill and activations. Production fleets add replicas for redundancy and traffic peaks.
You've learned to count parameters, compute FLOPs, estimate memory, and measure throughput. Now put it all together: given a set of constraints (compute budget, memory, latency target), design the right transformer architecture.
Chinchilla's finding: optimal training uses ~20 tokens per parameter (D ≈ 20P). For a 7B model, how many training tokens and what total training FLOPs (using the 6ND rule: FLOPs = 6 × N × D)?
On 1024 A100s at 50% MFU: 1024 × 312 × 0.5 = 159,744 TFLOP/s = 1.60 × 1017 FLOP/s. Time = 5.88 × 1021 / 1.60 × 1017 ≈ 36,800 s ≈ 10.2 hours. LLaMA 7B was trained on 1T tokens, about 7× the Chinchilla amount: over-training gives a better small model, which is cheaper to serve.
You need a model that runs on a phone (6 GB RAM, ~50 GB/s memory bandwidth, 2 TOPS INT4 compute). Requirements: <3 GB model size (INT4), >10 tokens/sec decode. Design the architecture: how many parameters maximum? What d and L would you choose?
Max INT4 model size = 3 GB → max params = 3 GB / 0.5 bytes = 6B. But we need room for KV cache and OS overhead. A 3B model at INT4 = 1.5 GB is the sweet spot: leaves 4.5 GB headroom.
For 3B params: 12Ld² = 3B → with L=32, d = √(3B / 384) = √7.8M ≈ 2795. Round to d=2560 (multiple of 128 for hardware alignment) with L=32 gives 12×32×2560² = 2.52B layer params + 0.08B tied embeddings (V=32000) ≈ 2.6B total.
Decode throughput: memory-bound at batch=1. Phone bandwidth is ~50 GB/s (LPDDR5). 1.5 GB / 50 GB/s = 30 ms/token = 33 tok/s. Meets the 10 tok/s target with margin.
Standard transformers use dff = 4d. SwiGLU uses dff = 8d/3 (rounded). Show that SwiGLU with dff = 8d/3 has approximately the same parameter count as standard FFN with dff = 4d.
Fill in the missing values. Use 12Ld² + Vd for total params (tied embedding).
| Model | d | L | h | dk | Params (B) |
|---|---|---|---|---|---|
| GPT-2 XL | 1600 | 48 | 25 | 64 | ? |
| GPT-3 | 12288 | 96 | 96 | 128 | ? |
| LLaMA 13B | 5120 | 40 | 40 | 128 | ? |
Compute total params for GPT-3 (V=50257):
The capstone combines everything from Chapters 0-8 into a single multi-step design problem. This is the kind of analysis you'd do at a frontier lab when planning a new model or estimating serving costs for a customer.
LLaMA 13B uses d=5120, L=40, h=40 with full MHA. Your model keeps d=5120, h=40 (dk=128) but uses GQA with g=8, SwiGLU (dff = 8d/3), RoPE, V=32000 and an untied LM head. GQA shrinks attention, so you raise L to 48. Count the exact parameters.
Per layer: Q and O are [d, d]; K and V are [d, g·dk]; SwiGLU = 3 × d × (8d/3) = 8d². Ignore norms.
At L=40 the same design has only 11.2B: GQA cuts attention from 4d² to 2.4d². The 12Ld² shortcut assumes full MHA and would claim 12.9B at L=40, overcounting by 1.7B. The rest of the capstone rounds this model to 13B.
Train on 260B tokens (20 × 13B, Chinchilla optimal). Using 6ND: how many total FLOPs? On 64 H100s at 50% MFU (990 TFLOP/s BF16 peak), how many hours?
7.4 days on 64 H100s. In practice, communication overhead (allreduce, pipeline bubbles) and checkpointing add 20-40%, making it ~10 days. The 6ND rule is the first number to compute when scoping a training run.
Serving this 13B model in BF16 with 50 concurrent users at 4096 context, GQA g=8, h=40, d=5120, L=48. How much total GPU memory is needed (weights + KV cache)?
KV cache per user = 2 × L × s × g × d_k × 2 bytes.
66.3 GB fits on one H100 (80 GB) with about 14 GB left for activations and runtime overhead. GQA makes this work: with full MHA (g=h=40) the KV cache would be 5× larger, 201 GB, and need three more GPUs.
Can a single H100 (3.35 TB/s, 80 GB) serve this 13B model with 50 users at 30 tok/s each (1500 tok/s total)? Check both memory and throughput.
H100 cloud cost: ~$3/hour. If 1 H100 serves 50 users generating 1M tokens/day each (50M tokens/day total), what is the cost per 1M tokens?
$1.44 per 1M output tokens, at full use all day. Real cost is higher: prefill, idle hours and redundancy all add to it. If INT4 weights and an INT4 KV cache let one GPU serve 4× the users, the cost falls to $0.36.
| Topic | Lesson |
|---|---|
| Transformer fundamentals | Transformer — From Absolute Zero |
| GPT architecture | GPT — From Absolute Zero |
| Scaling & inference | Scaling Book Workbook |
| Distributed training | Distributed Training — From Absolute Zero |
| Inference optimization | ML Inference Engineer — Day In The Life |