Every number a language model engineer must be able to derive cold: tokenization tradeoffs, 6ND FLOPs, AdamW memory, RoPE geometry, MoE routing, roofline arithmetic intensity, ZeRO stages, Chinchilla scaling, KV-cache sizing, and alignment math. All verifiable in-browser with instant feedback.
Every byte that enters a language model passes through a tokenizer first. The tokenizer's job is to map raw text to a sequence of integer IDs. The choices here — vocabulary size, merge count, coverage — cascade through every other number in the system: sequence length, embedding table size, and softmax cost.
A byte-level BPE tokenizer starts with a 256-symbol base alphabet and learns 32,000 merges. What is the final vocabulary size?
Each BPE merge adds exactly one new token (the merged pair) to the vocabulary. Starting from 256 bytes, 32,000 merges give 32,256 tokens.
A tokenizer encodes 1,200 characters of English text into 300 tokens. What is the compression ratio (characters per token)?
About 4 characters per token is typical for English with a GPT-style BPE tokenizer. Code and non-English text usually get fewer characters per token.
You have a corpus of 400 billion characters. Your tokenizer has a compression ratio of 4 chars/token. How many tokens is the corpus (in billions)?
The compression ratio converts raw text size into training tokens. You need it to plan a dataset.
The embedding table is shape [|V|, dmodel] and the output projection is [dmodel, |V|]. Both scale linearly with |V|. Going from 32K to 128K makes both tensors 4× larger. With d=4096 in bf16, the embedding table grows from 32,000×4096×2 bytes = 262 MB to 128,000×4096×2 bytes = 1.05 GB. In return, text in rare scripts needs fewer tokens, so sequences get shorter and attention gets cheaper. Which effect wins depends on your data.
GPT-2 uses byte-level BPE. Its vocabulary has 50,257 tokens: the 256 base bytes, the learned merges, and 1 special token (<|endoftext|>). How many merges did GPT-2 learn?
GPT-3 reused this tokenizer. GPT-4 uses a different one, cl100k_base, with about 100K tokens. When you train BPE yourself, the merge count is the main setting you control.
BPE training begins by counting all adjacent token pairs. Write a function that counts all bigrams in a list of token sequences.
javascript function count_pairs(sequences) { const counts = {}; for (const seq of sequences) { for (let i = 0; i < seq.length - 1; i++) { const key = seq[i] + "," + seq[i+1]; counts[key] = (counts[key] || 0) + 1; } } return counts; }
Before writing a single line of training code, you must know how much memory and compute your model will consume. The numbers come from first principles: matrix shapes, dtype widths, and the 6ND rule.
Units in this workbook: 1 KB = 103 bytes, 1 MB = 106 bytes, 1 GB = 109 bytes (decimal, like GPU spec sheets).
A linear layer multiplies [1024, 4096] by [4096, 4096]. How many FLOPs? (Give your answer in millions, i.e. divide by 106.)
Use 2MKN for a [M×K] × [K×N] matmul.
Each output element requires K=4096 multiply-adds = 2K FLOPs. Total output elements = M×N = 1024×4096 = 4,194,304. Total = 2×4096×4,194,304 ≈ 34.4 GFLOPs for a batch of 1024 tokens.
You train a 1.3B parameter model on 26 billion tokens. How many FLOPs does training take? Give the answer as a power of 10 (what is the exponent x such that C ≈ 10x)?
C = 6ND. Then compute log10(C).
D = 26B = 20 × 1.3B, so this run follows the Chinchilla rule D = 20N. The exponent is 20.3.
Training a 7 billion parameter model with mixed-precision AdamW (16 bytes/param total). How many GB of GPU memory does the optimizer state + weights + gradients occupy?
Breakdown: bf16 weights (14 GB) + bf16 gradients (14 GB) + fp32 master weights (28 GB) + fp32 Adam m (28 GB) + fp32 Adam v (28 GB) = 112 GB. This alone exceeds one A100 (80 GB), which is why multi-GPU training is non-negotiable even for a "small" 7B model.
A Transformer layer processes batch size B=4, sequence length T=2048, hidden dim d=4096, in bf16 (2 bytes/element). Attention activations require storing Q, K, V: three tensors of shape [B, T, d]. How many MB (106 bytes) just for these three tensors?
(In binary units this is 192 MiB; watch which unit a tool reports.) This is just the projection outputs — the attention score matrix [B, H, T, T] adds more, and you need to store all activations for the backward pass. This is why activation checkpointing trades recomputation for memory.
13B params × 16 bytes/param = 208 GB. Without sharding, every data-parallel GPU holds a full copy, and one A100 has only 80 GB. So the run fails before the first activation. Sharding (ZeRO, tensor or pipeline parallelism) spreads the 208 GB over the 8 GPUs.
You have 1022 FLOPs to spend and a 3B parameter model. Using the Chinchilla-optimal recipe (D = 20N), how many tokens should you train on? (Give in billions.)
This uses only about 1/10 of the 1022 budget. To spend the full budget at D=20N, train a larger model: C = 6N × 20N = 120N2, so N = √(1022/120) ≈ 9.1B.
Modern transformers differ from the original in four ways: RMSNorm, SwiGLU, RoPE, and GQA. Each changes a number you must be able to compute.
dmodel=4096, 32 layers, 2 norm modules per layer. LayerNorm has γ+β (2d params); RMSNorm has only γ (d params). How many fewer parameters per layer?
dmodel=2048. What is dff under the iso-FLOP SwiGLU constraint? Round up to the next multiple of 256 (as Llama does).
θbase=10000, d=128, k=0, m=1. Compute θ0 = m × θbase−2k/d in radians.
At k=0 the exponent is 0, giving 1. At k=63: 10000−126/128≈0.000115 — extremely slow rotation for long-range position encoding.
32 query heads, nkv=8 KV heads, dhead=128, T=4096, L=32 layers, bf16 (2 bytes). KV cache in MB (106 bytes)?
Bytes = 2 × L × nkv × T × dhead × 2.
Full MHA (nkv=32) would be 2147.5 MB. GQA cuts the cache by 4×.
Order the four steps of one Pre-Norm Transformer decoder layer.
Pre-Norm: normalize before each sublayer (not after). The residual stream x is never directly normalized — only sublayer inputs are. This enables stable training at large scale because gradients flow through the residual path unobstructed.
MoE decouples total parameters from active parameters. A dense model uses all N params for every token. A MoE model routes each token to a sparse subset of experts — active params < total params.
16 experts, 2B params each, 1B shared, top-k=2. Active params per token (in billions)?
dmodel=4096, dff=8192, top-k=2. Two projections per expert (each: 2 × dmodel × dff FLOPs). Total MFLOPs/token?
n=8 experts, top-k=2, T=1024 tokens, Cf=1.5. Token capacity per expert?
fi is a hard count with zero gradient. Pi is the mean softmax probability — differentiable. When expert i is overloaded (high fi), the loss term fi×Pi is large; gradient pushes Pi down, reducing future assignment to expert i.
The config sets top_k=2, but each token reaches only one expert and every gate equals 1.0. Click the buggy line.
function route(x_flat, W_router, top_k) { const logits = matmul(x_flat, W_router); // [B*T, n_experts] const probs = softmax(logits, dim=-1); // [B*T, n_experts] const topk = probs.topk(1, dim=-1); // [B*T, k] const gates = topk.values / topk.values.sum(dim=-1, keepdim=true); return { topk_idx: topk.indices, gates }; }
Line 4: topk(1, dim=-1) ignores the top_k argument, so each token keeps one expert. Line 5 then renormalizes a single value, which is always 1.0. Fix: probs.topk(top_k, dim=-1).
Every GPU has two limits: how fast it can compute (peak FLOP/s) and how fast it can move data (memory bandwidth). The roofline model tells you which limit controls your workload. The number that bridges them is arithmetic intensity: FLOPs per byte transferred.
H100 SXM5 peak: 989 TFLOPs/s (bf16 Tensor Core), bandwidth: 3.35 TB/s. Compute the ridge point I* in FLOPs/byte (round to nearest integer).
Any workload with I < 295 FLOPs/byte is memory-bound on the H100. Any workload with I > 295 is compute-bound. Prefill is compute-bound; decode is deeply memory-bound.
During decode: B=1 (batch size), T=1 (token). A weight matrix has shape [D, F]. FLOPs = 2×1×D×F. Bytes read ≈ 2×D×F (bf16 weights). What is the arithmetic intensity?
Exactly 1 FLOPs per byte — 295× below the H100 ridge. Each weight is loaded once and used for exactly one multiply. To reach the ridge: batch B=295 tokens simultaneously (I≈295). This is why batching is so critical for decode throughput.
Prefill: B=1, T=2048 tokens, weight matrix [D=4096, F=4096]. FLOPs = 2×B×T×D×F. Bytes ≈ 2×D×F (weight reads dominate). What is the arithmetic intensity?
I=2048 ≫ 295 (H100 ridge) → prefill is compute-bound. Each weight is used for 2048 multiply-accumulates (one per input token), amortizing the load cost. Compute-bound is good — the GPU stays fully utilized.
Warp size is always 32 on NVIDIA GPUs (A100, H100). 256/32 = 8 warps per block. All threads in the same block share the SM's SRAM — this is how threads communicate without going to HBM. Threads in different blocks cannot share SRAM directly.
A simple two-pass RMSNorm kernel reads d=4096 bf16 values (2 bytes each) twice: once to compute the RMS, once to normalize. How many bytes does it read from HBM per token? (Count only the two reads of x.)
A fused kernel keeps the row in fast on-chip memory and reads x from HBM once: 8,192 bytes. Flash Attention uses the same idea: fuse steps so data is not re-read from HBM.
When a model doesn't fit on one GPU, you distribute it. There are three orthogonal strategies: data parallelism (replicate model, split batch), tensor parallelism (split weight matrices), and pipeline parallelism (split layers). ZeRO eliminates redundant optimizer state across data-parallel replicas.
7B model, 8 GPUs, ZeRO Stage 1 (shards optimizer state only). Stage 1: Adam m+v+fp32 master = 12 bytes/param sharded, plus bf16 weights (2 bytes) and bf16 gradients (2 bytes) unsharded. How many GB per GPU?
Per-GPU = (12/8 + 2 + 2) bytes/param × 7B params.
Compare to 112 GB without ZeRO (16 bytes/param). ZeRO-1 cuts memory 2.9× by sharding the 12 bytes/param of optimizer state. Each of the 8 GPUs now fits in an A100-80GB with room for activations.
7B parameter model, bf16 gradients (2 bytes/param), 8 GPUs. Ring all-reduce sends 2×(P−1)/P×M bytes per GPU. How many GB does each GPU send/receive? (P=8, M = 7B × 2 bytes.)
Each GPU sends/receives 24.5 GB per training step. At about 600 GB/s (A100 NVLink): 24.5/600 ≈ 41 ms for the all-reduce. At about 25 GB/s (one 200 Gb/s InfiniBand link): 24.5/25 = 980 ms, almost a second per step.
Pipeline parallelism: P=4 stages, m=8 microbatches. What fraction of time is the pipeline idle (bubble fraction)?
Bubble = (P−1) / (m + P − 1).
27.3% idle. To halve the bubble: double m to 16 → 3/19 ≈ 15.8%. More microbatches = smaller bubble but larger effective batch size, which can hurt convergence. Interleaved schedules (Megatron-LM) give each GPU V chunks of layers and cut the bubble by a factor of V, to about (P−1)/(mV).
Megatron-style TP runs two all-reduces per layer in the forward pass (after attention and after the MLP) and two more in the backward pass. A 32-layer model does 128 per step. Cross-node at 25 GB/s makes each one about 24× slower than NVLink, and compute waits for every one.
ZeRO-3 shards all 16 bytes/param across P=8 GPUs. For a 7B parameter model, how many GB does each GPU hold?
112 GB total / 8 GPUs = 14 GB per GPU — an 8× reduction. But parameters must be all-gathered for each forward/backward layer pass, adding communication overhead. ZeRO-3 trades memory for communication latency.
Scaling laws let you predict model performance before spending the compute. The key formulas: C = 6ND (compute from parameters and tokens), L(N, D) = E + A/Nα + B/Dβ (loss from both), and the Chinchilla optimal allocation D* = 20N.
GPT-3: N=175B params, D=300B tokens. Compute C=6ND. Express as X×1023 — what is X to 2 decimal places?
OpenAI reported 3.14×1023 FLOPs — our formula is within 0.3%. The 6ND rule works because attention-score FLOPs are small next to the weight matmuls when the context is short relative to dmodel.
Given GPT-3's compute budget C=3.15×1023 FLOPs, what is the Chinchilla-optimal number of parameters? Use N* = √(C/120). Give in billions.
Chinchilla-optimal: ~51B params × 20 = ~1.02T tokens. GPT-3 at 175B has about 3.4× more parameters than this budget calls for. (Chinchilla itself, 70B on 1.4T tokens, used Gopher's larger budget.)
A model is trained on D=100B tokens. The data term of the loss is B/Dβ with B=410.7, β=0.28. Compute the data term at D=100B, then at D=200B. How much does the data term decrease? (Express as fraction of the D=100B value; round to 2 decimal places.)
Doubling data cuts the data term by 17.6%, whatever D is. That is the power law: each doubling gives the same proportional gain. Because β=0.28 is small, each gain is modest.
L(N,D) = E + A/Nα + B/Dβ. As N→∞ (and D→0), B/Dβ→∞ (data starvation). As N→0 (and D→∞), A/Nα→∞ (capacity starvation). There's an optimum in between where the gradient of both terms balance. The IsoFLOP plot is U-shaped — the bottom is the Chinchilla optimum.
Inference has two distinct phases: prefill (process the prompt in parallel — compute-bound) and decode (generate one token at a time — memory-bound). The KV cache eliminates redundant recomputation during decode.
7B LLaMA (32 layers, 32 KV heads, dhead=128), T=8192 tokens, bf16. How many GB is the KV cache for one request?
Bytes = 2 × 32 × 32 × 8192 × 128 × 2.
4.29 GB for one 8K request. With 16 concurrent requests: 16×4.29 = 68.7 GB — nearly one full A100-80GB just for KV caches. Long-context serving is fundamentally a memory management problem.
H100 ridge: I*=295 FLOPs/byte. During decode, I≈batch_size B. What minimum batch size makes decode compute-bound on an H100?
Batch 295+ requests together for compute-bound decode. In practice you'd use B=256 or B=512 (powers of 2). This is why LLM serving systems (vLLM, TensorRT-LLM) invest heavily in continuous batching — to maintain large effective batch sizes even with different request lengths.
A 7B model in bf16 weights = 14 GB. Quantizing weights to int8 (1 byte/param). How many GB are saved, and what is the percentage reduction?
int8 halves weight memory. Decode intensity doubles too: the same FLOPs, half the bytes. Methods such as GPTQ and AWQ go to 4 bits (a 75% saving) with a small rise in perplexity.
Arithmetic intensity ≈ B×T (tokens processed). Prefill: T=500 ≫ 295 → compute-bound. Decode: T=1 at each step → I=1 ≪ 295 → memory-bound. Different hardware metrics matter for each: prefill optimization targets TFLOP/s utilization; decode optimization targets memory bandwidth and batching.
After pretraining comes alignment: teaching the model to be helpful, harmless, and honest. SFT fine-tunes on curated demonstrations. RLHF uses a reward model + PPO. DPO removes the reward model by training on preference pairs directly. GRPO keeps a reward but drops PPO's value network: it compares each sample with its group.
A reward model gives r(x, ywin)=3.0 and r(x, ylose)=1.5. Using P(yw≻yl) = σ(Δr) = 1/(1+e−Δr), what is the probability the winner is preferred? (Round to 2 decimal places.)
A reward gap of 1.5 nats gives 82% preference probability. At Δr=0 the model is indifferent (50%). At Δr=4.6 (ln99) the probability is 99%. The Bradley-Terry model is essentially a logistic regression on reward differences.
A group of 4 samples has rewards [1, 3, 2, 6]. Compute the normalized advantage Ai = (ri − mean) / std for r4=6. (Use population std, not sample std.)
The best response (r=6) gets advantage +1.60. The worst (r=1) gets (1-3)/1.871 = -1.07. Normalization keeps gradient magnitudes stable regardless of the absolute reward scale — crucial because reward functions differ wildly across tasks.
During SFT, the prompt tokens are fed as context with their loss masked (loss_mask=0). Only response tokens have loss_mask=1. This focuses learning signal on the quality of the completion. Prompt tokens in the loss would spend capacity on predicting user prompts instead of good answers.
β controls how strongly the KL divergence from reference penalizes large policy updates. At β→0, the model is free to exploit any pattern that increases preference margin, even degenerate ones. Typical practice: β=0.1 to 0.5. Too large (β→∞) and the model barely moves from reference. Too small risks training instability and reward hacking.
Deduplication uses Bloom filters to check if a document was already seen. A Bloom filter with m=108 bits (10 bits per item), n=107 items, and k=7 hash functions has false positive rate ≈ (1−e−kn/m)k. Compute it. Round to 4 decimal places.
About 0.8% of new documents are wrongly flagged as seen. Ten bits per item with k=7 is near the best k for that size (k = (m/n) ln 2 ≈ 6.9). With 100 bits per item (m=109) the rate drops to about 6×10−9.
You have a budget of $1M. H100-SXM5: 989 TFLOPs/s bf16 peak, or 8.54×1019 FLOPs/GPU/day. At MFU=0.45 that is 3.85×1019 effective FLOPs/GPU/day. Rental cost: $2/GPU/hour. Design a training run end-to-end: pick a model size, compute required training time, verify it fits the budget, and estimate serving cost.
An H100 peaks at 989 TFLOPs/s (bf16). At MFU=0.45, what is the effective throughput in TFLOPs/s? (Round to nearest integer.)
MFU (Model FLOP Utilization) is the fraction of peak spent on the model's own FLOPs; communication, data loading and idle time eat the rest. Well-tuned large runs report roughly 0.35 to 0.55, so 0.45 is a fair planning number.
N=1.3B, D=26B (Chinchilla-optimal). C=6ND≈2.03×1020 FLOPs. Using 8 H100s at 445 TFLOPs/s each. How many hours does training take?
t = C / (n × 445×1012 FLOPs/s) / 3600 seconds/hour.
About 16 hours on 8 H100s for a Chinchilla-optimal 1.3B model.
Using the result from 9.2: 8 H100s for 16 hours at $2/GPU/hour. What is the total training cost in dollars?
For scale: the Llama 2 paper reports 184,320 A100 GPU-hours for the 7B model, about $370K at $2/GPU-hour. That model trained on 2T tokens, far past D=20N.
Arrange the five stages of building a language model from scratch in the correct order.
Data first (raw corpus defines vocabulary coverage). Tokenizer second (must be trained on the final data to capture its distribution). Pretraining third (costs the most compute). SFT + alignment fourth (orders of magnitude cheaper than pretraining, fine-tunes behavior). Serving last (inference optimization: quantization, KV cache, batching).
Decode throughput: an H100 at effective 445 TFLOPs/s, serving a 1.3B model (N=1.3B). Each token costs 2N=2.6B FLOPs (forward pass only, half of training). How many tokens per second can one H100 generate if fully loaded?
171K tokens/s is the compute-bound ceiling. At batch=1, decode is memory-bound: each token reads all 2.6 GB of bf16 weights, so 3.35 TB/s ÷ 2.6 GB ≈ 1,300 tokens/s. Only a large batch (a few hundred) approaches the ceiling. That gap is why servers use continuous batching.
A transformer with d=1024, n_heads=16, d_ff=2730 (SwiGLU iso-FLOP), L=24 layers, vocab=32256. Count parameters: (a) embedding table [V,d], tied with the LM head (no separate output matrix); (b) each layer: Q,K,V,O projections [d,d] each, FFN W1,W2,Wgate [d,d_ff],[d_ff,d],[d,d_ff], 2 RMSNorms [d] each. Total = (a) + 24 × (b). Give it in millions. (Ignore biases and the final norm.)
An untied LM head adds another [d, V] = 33.0M, for 368.1M.
| Topic | Lesson |
|---|---|
| Tokenization & BPE | CS336 L1: Overview & Tokenization |
| Resource accounting | CS336 L2: PyTorch & Resource Accounting |
| Architectures | CS336 L3: Architectures & Hyperparameters |
| Scaling laws | CS336 L9: Scaling Laws |
| Inference | CS336 L10: Inference |