Practice problems in the spirit of the JAX Scaling Book (How to Scale Your Model). Work them with pencil and paper, then check them here.
Units: 1 GB = 109 bytes and 1 MB = 106 bytes everywhere, the same as vendor bandwidth figures. If a vendor lists capacity in GiB (230 bytes), we convert it.
You are an ML engineer staring at a GPU profiler trace. A matrix multiply that should take 0.14 ms is taking 0.8 ms. Is the bottleneck memory bandwidth? Compute throughput? Launch overhead? Without a mental model, you are guessing. The roofline model gives you that mental model.
Before you can optimize anything, you need to know what limits performance. Is your operation waiting for data to arrive from memory, or waiting for the arithmetic units to finish crunching? The roofline model answers this question with a single number: arithmetic intensity.
Arithmetic intensity (AI) is the ratio of floating-point operations to bytes moved from memory. If you do many FLOPs per byte loaded, you are compute-bound. If you do few FLOPs per byte, you are memory-bound. The dividing line is the hardware's ridge point — the arithmetic intensity where the processor's compute throughput exactly matches its memory bandwidth.
For a matrix multiplication C = A × B where A is [M, K] and B is [K, N]:
Compute the arithmetic intensity for a square matmul: [4096, 4096] × [4096, 4096] in BF16 (2 bytes per element).
Hint: FLOPs = 2 × 40963. Bytes = 3 × 40962 × 2.
For square matmuls, AI simplifies to 2N/6 = N/3 when element size = 2 bytes. So 4096/3 ≈ 1365. This is deeply compute-bound on any modern accelerator.
The H100 SXM has ~990 TFLOP/s BF16 Tensor Core throughput and ~3.35 TB/s HBM bandwidth. What is the ridge point?
Any operation with AI above ~296 is compute-bound on the H100. Our matmul from Exercise 0.1 (AI ≈ 1365) is well above this — solidly compute-bound. Element-wise ops like ReLU (AI = 0.125 in FP32, see Exercise 0.5) are deeply memory-bound.
Given the [4096, 4096] × [4096, 4096] BF16 matmul is compute-bound on the H100, predict the theoretical execution time assuming 990 TFLOP/s peak.
In practice, you will see ~0.15-0.2 ms due to kernel launch overhead and imperfect occupancy. The ratio of achieved to theoretical is your MFU (Model FLOPs Utilization). Getting above 50% MFU on real workloads is considered good.
Consider the QKT computation in self-attention: Q and K are both [batch, heads, seq, d_head]. With batch=1, heads=32, seq=2048, d_head=128, BF16. What is the arithmetic intensity of the QKT matmul (treating each head independently)?
Hint: Per head, this is a [2048, 128] × [128, 2048] matmul. Compute AI for one head.
Per head: M=2048, K=128, N=2048, element_size=2 bytes.
113.8 is below the H100 ridge point (~296), so even this one matmul is memory-bound. The output S = QKT [2048, 2048] is most of the bytes. Standard attention then reads S again for the softmax and the AV matmul, so the AI drops further. FlashAttention keeps S on chip: it computes attention in tiles and fuses QKT, softmax and AV into one kernel.
ReLU activation on a tensor of 10M elements in FP32 (4 bytes). ReLU does one comparison per element (1 FLOP). What is the arithmetic intensity?
This is 2,364× below the H100's ridge point of 296. ReLU is absurdly memory-bound. This is why optimized code usually fuses activation functions into the matmul before or after them.
During autoregressive decode, the main operation per layer is a matrix-vector product: [1, d] × [d, d] where d=8192. BF16. What is the arithmetic intensity? Is it compute-bound or memory-bound on H100?
AI ≈ 1 — deeply memory-bound (ridge point is 296). The weight matrix dominates the byte count. This is why decode is memory-bandwidth-limited: each token requires reading the entire weight matrix for a trivial number of FLOPs. Batching helps by amortizing the weight read across B tokens, raising AI to ~B.
Google's Tensor Processing Units (TPUs) are custom ASICs designed for one thing: dense matrix multiplication at massive scale. Unlike GPUs, which evolved from graphics workloads and carry a lot of general-purpose flexibility, TPUs are laser-focused on the matmul-softmax-matmul pipeline that dominates transformer training and inference.
The heart of a TPU is the MXU (Matrix Multiply Unit): a 128×128 systolic array of multiply-accumulate (MAC) cells. Each cycle, one MXU does 128×128 = 16,384 MACs, and each MAC is 2 FLOPs. A TPU v5e chip has one TensorCore with 4 MXUs (Scaling Book, TPU chapter).
A TPU v5e chip has 4 MXUs, each 128×128, and a peak of 197 TFLOP/s in BF16. What clock speed does that peak imply?
Hint: each MXU does 128 × 128 MACs per cycle. Each MAC = 2 FLOPs (multiply + add).
So one MXU gives about 49 TFLOP/s. An H100 gives ~990 TFLOP/s dense BF16 from 132 SMs. A v5e chip is much smaller, and a pod holds 256 of them.
TPU v5e specs: 197 TFLOP/s peak BF16 (4 MXUs) and 819 GB/s HBM bandwidth. What is the ridge point?
The TPU v5e has a lower ridge point than the H100 (~296), meaning operations become compute-bound at lower arithmetic intensity. This is because the TPU's ratio of compute-to-bandwidth is more balanced — relatively more bandwidth per FLOP.
You run a layer normalization on a tensor of shape [2048, 8192] in BF16 on a TPU v5e (819 GB/s bandwidth). LayerNorm reads the input once, writes the output once, plus reads/writes for mean and variance (negligible for large tensors). Approximate the minimum execution time.
Hint: LayerNorm is memory-bound. Total bytes = one read + one write = 2 × tensor bytes.
Real runs take longer: there is launch overhead, and LayerNorm also computes a reduction (mean, variance). The memory transfer still dominates. Fusing LayerNorm into the operation before or after it removes one full round-trip to HBM.
Fill in the comparison table from memory, then check your answers.
| Spec | TPU v5e | H100 SXM |
|---|---|---|
| BF16 peak TFLOP/s | ~197 | ~990 |
| HBM bandwidth | ~819 GB/s | ~3,350 GB/s |
| HBM capacity | 16 GiB (17.2 GB) | 80 GB |
| Ridge point | ~240 | ~296 |
| Interconnect (per chip, both directions) | ICI (400 GB/s) | NVLink (900 GB/s) |
Sources: Google Cloud TPU v5e page; the Scaling Book GPU chapter for the H100.
How many BF16 parameters fit in one TPU v5e's HBM (weights only)?
That is weights only: no KV cache, no activations. A 7B model leaves little room, so you shard it over several chips. A 256-chip v5e pod has 256 × 17.18 GB ≈ 4.4 TB of HBM.
A single accelerator can only hold so much data in HBM. A 70B parameter model in BF16 needs 140 GB just for weights — far more than an 80 GB H100 holds. The solution: shard the matrices across multiple devices and coordinate the computation.
There are three fundamental ways to shard a matmul C = A × B where A is [M, K] and B is [K, N]:
| Strategy | Shard A along | Shard B along | Communication needed |
|---|---|---|---|
| M-sharded (split the batch) | M (rows) | Replicated | None (outputs are independent) |
| N-sharded (split output columns) | Replicated | N (columns) | None (outputs are independent) |
| K-sharded (split the inner dim) | K (inner dim) | K (inner dim) | All-reduce on partial sums |
You have a weight matrix W of shape [8192, 32768] and input X of shape [2048, 8192]. You want to compute Y = X × W across 8 devices with no communication. Which sharding does that and uses the least memory per device?
N-sharding: replicate X (2048×8192×2 = 33.6 MB per device), shard W into 8 chunks of [8192, 4096] (67.1 MB each). Each device computes Y_chunk = X × W_chunk with no communication. Y comes out split by columns.
M-sharding: shard X into rows (each device gets [256, 8192]), replicate W (8192×32768×2 = 537 MB per device). Also no communication, but it wastes memory on copies of the big weight matrix.
K-sharding: needs an all-reduce, so it fails the no-communication rule.
N-sharding wins: zero communication, and the smaller matrix (X) is the one replicated.
You shard a [8192, 8192] × [8192, 8192] BF16 matmul along K across 8 devices. Each device computes a partial [8192, 8192] result that must be summed via all-reduce. Using the ring all-reduce algorithm, how many bytes does each device send in total?
Hint: Ring all-reduce sends 2 × (P-1)/P × tensor_size bytes per device, where P = number of devices.
The ring all-reduce has two phases: reduce-scatter (each device sends (P-1)/P of the data) and all-gather (the same volume again). As P grows, the total approaches 2× the tensor size. No all-reduce can send less per device, so the ring is bandwidth-optimal.
Using the same K-sharded matmul from 2.2 on 8 devices, each device computes a [8192, 1024] × [1024, 8192] matmul. Each device sends 234.9 MB in the all-reduce. Each device's matmul takes 0.139 ms (compute-bound at 990 TFLOP/s). Each device sends at 450 GB/s (NVLink, one direction). What is the communication time? Is the operation communication-bound?
Yes: communication takes 3.8× longer than compute. Each device does only 1/8 of the FLOPs but still all-reduces the full [8192, 8192] output. M-sharding or N-sharding avoids this for a single matmul, at the cost of replicating one matrix.
Consider one transformer layer of LLaMA 3 70B. The layer has ~856M parameters in BF16 = 1.71 GB of weights. Compare two strategies on 8 devices:
(A) FSDP: all-gather the full layer weights before forward. Volume = (P-1)/P × layer_size per device.
(B) TP: two all-reduces per layer (attention + MLP) on output tensors of shape [batch×seq, d]. With batch=4, seq=4096, d=8192, BF16.
Which transfers fewer bytes per device?
FSDP all-gather:
TP all-reduce (per operation):
FSDP transfers 1.50 GB, TP transfers 0.94 GB, so TP wins on volume here. But TP's all-reduces sit on the critical path of every layer, so TP needs fast NVLink inside a node. FSDP's all-gather can be prefetched one layer ahead, so it tolerates slower links between nodes. That is why TP usually stays inside a node and FSDP spans nodes.
Before you can estimate training cost, inference memory, or sharding strategy, you need to count parameters precisely. No approximations, no hand-waving. Every weight matrix, every bias, every embedding. This is the foundation of all scaling analysis.
One transformer block contains a self-attention layer and an MLP (feed-forward) layer, each with layer norms. Here is the parameter breakdown:
GPT-2 (small): 12 layers, d=768, 12 heads, d_head=64, d_ff=3072 (4×d), vocab=50257. Standard MHA (not GQA), standard MLP (not SwiGLU, so 2 projections not 3), with biases on all linear layers, and separate LN weight+bias.
Count total parameters. Include: 4 attention projections + biases, 2 MLP projections + biases, 2 LayerNorms (weight+bias each), token embedding, position embedding (1024×768), and final LN.
Per transformer block:
Global:
The released GPT-2 small checkpoint has exactly this count (the GPT-2 paper listed it as 117M). GPT-2 ties the output head to the token embedding, so the head adds no parameters.
LLaMA 3 70B: 80 layers, d=8192, 64 attention heads, 8 KV heads (GQA), d_head=128, d_ff=28672 (SwiGLU, so 3 projections), vocab=128256. No biases anywhere. RoPE (0 params). RMSNorm (weight only, no bias).
Count total parameters in billions.
Per block attention:
Per block MLP (SwiGLU):
Per block norms:
Total per block:
Global:
The standard approximation for forward pass FLOPs per token is 2N (where N = number of parameters), because each parameter participates in one multiply-add (2 FLOPs). For LLaMA 3 70B (N ≈ 70.6B), how many FLOPs per token in the forward pass?
This counts the weight matmuls only. The attention scores (QKT) and the weighted sum over V add about 2 × n_layers × seq_len × d FLOPs per token (Kaplan et al., 2020). At seq = 8192 that is 2 × 80 × 8192 × 8192 ≈ 1.07 × 1010, about 8% of 2N. For back-of-envelope work, 2N is enough.
The standard training FLOP estimate is 6ND: forward (2N) + backward (4N, because gradients require ~2× the forward FLOPs), times D tokens. LLaMA 3 70B was trained on 15T tokens. How many total FLOPs?
About 6.35 × 1024 FLOPs. Meta's model card reports 6.4M H100-hours for Llama 3 70B; you will compare against that in Exercise 5.1.
LLaMA 3 70B: 80 layers, GQA with 8 KV heads, d_head=128, batch=32, seq=8192, BF16. How many GB for the KV cache?
Formula: 2 (K and V) × n_layers × n_kv_heads × d_head × seq_len × batch × bytes_per_element
GQA helps a lot here. With 64 KV heads instead of 8, the cache would be 687 GB, 8× larger. The weights are 141 GB in BF16, so at this batch and length the cache is already 60% the size of the model.
You are training LLaMA 3 70B on 2048 H100s. You measure 1000 tokens/second/GPU. Each H100 has 990 TFLOP/s BF16 peak. What is your Model FLOPs Utilization (MFU)?
MFU = (actual model FLOPs/s per GPU) / (peak FLOPs/s per GPU). Model FLOPs per token = 6N (forward + backward).
Training MFU always uses 6N per token: the hardware does the backward pass too. Sanity check: an answer above 100% means a wrong FLOP count. The Llama 3 paper reports 38–43% BF16 MFU for its 405B runs. The gap to 100% comes from communication, pipeline bubbles and memory-bound ops (norms, softmax).
You cannot train a 70B model on one GPU. You need parallelism — splitting the work across many devices. There are four main flavors, and real training runs combine all of them.
| Strategy | What's split | Communication | Memory saving |
|---|---|---|---|
| Data Parallel (DP) | Batch | All-reduce gradients | None (each GPU has full model) |
| FSDP (ZeRO-3) | Batch + params/grads/optimizer | All-gather params, reduce-scatter grads | ~P× (P = # GPUs) |
| Tensor Parallel (TP) | Individual weight matrices | All-reduce per layer | ~TP_degree× |
| Pipeline Parallel (PP) | Layers across stages | Point-to-point activations | ~PP_degree× |
model_params + gradients + optimizer_states + activations. With Adam in BF16 mixed precision: params (2 bytes) + grads (2 bytes) + optimizer (master weights 4B + momentum 4B + variance 4B = 12 bytes) = 16 bytes per parameter, plus activation memory. FSDP shards all of these across GPUs.70B model, Adam optimizer, BF16 training. Without FSDP, per-GPU memory for params+grads+optimizer = 16 bytes × N. With FSDP across 64 GPUs, how much memory per GPU for these components?
This is just model state. Activation memory is additional and depends on sequence length, batch size, and whether you use activation checkpointing. An H100 has 80 GB HBM, so 17.5 GB for model state leaves ~62 GB for activations — comfortable.
In tensor-parallel attention with TP=8, each device computes 8 of 64 attention heads for LLaMA 3 70B. The output projection produces a partial result that requires an all-reduce. The output tensor per token has shape [1, 8192] in BF16. For a microbatch of 4 sequences, each of length 8192, how many bytes are transferred in the all-reduce?
Hint: all-reduce on the output of shape [batch × seq, d]. Use the ring formula: 2 × (P-1)/P × tensor_bytes.
The MLP output needs a second all-reduce of the same size, so a full block sends about 1.88 GB per device in the forward pass. At 450 GB/s per direction that is about 4.2 ms per block, which is why TP stays inside a node on NVLink.
Pipeline parallelism with PP=4 stages. If you use m microbatches, the bubble fraction (wasted time) is (PP-1)/(m+PP-1). What is the smallest m that keeps the bubble fraction strictly below 5%?
At m = 57 the bubble is exactly 3/60 = 5%, which is not below 5%. So you need 58 microbatches. Your global batch must be at least 58 × microbatch_size. This is why PP works best with large global batches.
Meta pre-trained Llama 3 405B on 16,384 H100s, 8 GPUs per node. Rules: TP must stay inside a node, PP adds bubbles, data parallelism (DP) covers the rest. TP × PP × DP = 16,384. Which configuration did the Llama 3 paper use?
The Llama 3 paper (Table 4) used TP=8, PP=16, DP=128 on 16,384 GPUs, at 41% BF16 MFU.
TP=8 uses all 8 GPUs of a node over NVLink. TP=16 (option B) would put the per-layer all-reduces on the slower links between nodes.
PP=16 is needed for memory: 405B BF16 weights are 810 GB, so TP=8 alone leaves 101 GB per GPU, more than 80 GB. With PP=16 each GPU holds about 6.3 GB of weights.
DP=128 covers the rest: 16,384 / (8 × 16) = 128. Option C would gather all 405B weights over the network for every layer. Option D needs DP to shard the 101 GB of weights per GPU, again with all-gathers across nodes.
Activation memory per layer (no activation checkpointing): you must store the input to each layer for the backward pass. For LLaMA 3 70B with batch=4, seq=4096, d=8192, BF16: how much activation memory per layer?
Simplified: store the input tensor [batch × seq, d] plus the attention intermediate [batch, n_heads, seq, seq] (for the backward through attention).
The attention scores dominate. For 80 layers: 80 × 8.86 ≈ 709 GB. Three fixes: (1) Activation checkpointing: keep only each layer's input and recompute the rest in the backward pass, for about one extra forward pass (~33% more compute). (2) FlashAttention: never stores the full score matrix, so the 8.59 GB term disappears. (3) Sequence parallelism: shard the activations across the TP group.
Now we combine everything: parameter count, FLOPs, hardware specs, and utilization to answer the question every ML lead asks: "How long will this take, and how much will it cost?"
Where N = parameters, D = tokens, n_GPUs = GPU count, peak_FLOPs = per-GPU peak FLOP/s, MFU = model FLOPs utilization (typically 0.35-0.50).
LLaMA 3 70B: N=70.6B, D=15T tokens, 2048 H100s at 990 TFLOP/s peak BF16, MFU=0.40. How many days to train?
That is 2048 × 90.7 × 24 ≈ 4.46M GPU-hours. Meta's model card reports 6.4M H100-hours for Llama 3 70B. If all of those hours went into 6.35 × 1024 FLOPs, the real MFU was about 28%. Some of the hours likely went to work outside the main run, so treat that as a lower bound.
Using your answer from 5.1 (~91 days), at $2/GPU-hour for H100 cloud pricing, what is the total training cost?
Roughly $9M for the final run alone. A real project also pays for failed runs, hyperparameter sweeps, evaluations and data processing, so the total is higher.
The Chinchilla scaling law says the compute-optimal number of tokens D is about 20 × N. For a 70B model, what is the Chinchilla-optimal token count?
But Meta trained on 15T tokens — more than 10× the Chinchilla optimal! Why? Because Chinchilla optimizes for training compute efficiency (best model per FLOP). But inference cost depends on model size. A smaller model trained on more tokens (the "over-trained" regime) gives better inference cost per quality. LLaMA's philosophy: spend more on training (one-time cost) to get a smaller, cheaper-to-serve model. This is the inference-optimal scaling regime.
You have a fixed compute budget C = 1022 FLOPs. Under Chinchilla scaling (C = 6ND, D = 20N), what is the compute-optimal model size?
Hint: Substitute D = 20N into C = 6ND.
A 9B model trained on 183B tokens (20 × 9.13B). This is remarkably close to LLaMA 3 8B, which Meta trained on 15T tokens (way past Chinchilla-optimal, for inference efficiency).
One common rule for learning rate versus batch size: when you double the batch size, multiply the LR by √2 (square-root scaling). If your base LR is 3 × 10-4 at batch=256, what LR should you use at batch=2048?
Krizhevsky (2014) proposed square-root scaling, and Malladi et al. (2022) derive it for Adam. The linear rule (multiply LR by 8) is more aggressive; Goyal et al. (2017) used it with SGD and warmup. In practice, labs pick the peak LR with a sweep and use warmup plus a decay schedule.
Inference has two distinct phases with completely different performance characteristics. Prefill processes the entire prompt in parallel — it is a batch matmul, compute-bound. Decode generates one token at a time — it is a matrix-vector product per layer, memory-bound.
A 70B model in BF16 (141 GB) does not fit in one 80 GB H100. In this chapter, split its layers across two H100s that run one after the other. Each token still reads 141 GB at 3.35 TB/s, so the per-token times equal a single imaginary H100 that holds everything.
70B model (N = 70.6B), H100 at 990 TFLOP/s BF16, layers split as described above. Using 2N FLOPs per token for prefill, what is the theoretical prefill throughput?
Real kernels reach only part of peak, and attention adds FLOPs. The next exercises assume a realistic 4,000 tokens/s.
You send a 4096-token prompt to the 70B model on the two-H100 setup. Assuming a realistic prefill throughput of 4000 tokens/s, what is the time to first token (TTFT)?
Over a second before the first token. Servers use chunked prefill (split the prompt so decode steps of other users run in between) and prefix caching (reuse the KV cache of a shared system prompt).
70B model in BF16, H100 bandwidth 3.35 TB/s, layers split as described above. At batch_size=1, each decode step reads all model weights once. What is the decode speed (tokens/s) and inter-token latency? Ignore the KV cache reads.
At batch_size=1, decode is entirely memory-bandwidth-bound — the MXU/Tensor Cores sit mostly idle! This is why batching is critical: at batch_size=32, you read the weights once but generate 32 tokens, giving 32 × 23.7 = 758 tokens/s total throughput (though per-user latency stays ~42 ms until you become compute-bound).
Prefill is compute-bound, decode is memory-bound. At what batch size does decode become compute-bound on an H100 with a 70B BF16 model? Ignore the KV cache reads.
Hint: decode becomes compute-bound when its arithmetic intensity, B × 2N FLOPs / 2N bytes, reaches the ridge point.
The crossover point is the ridge point! At the crossover, FLOPs per byte equals the H100's ridge point.
Below a batch of ~296, decode leaves the Tensor Cores partly idle. Prefill and decode want such different batch sizes that some systems run them on separate GPU pools (disaggregated serving). In practice, KV cache memory limits the batch long before 296, and the KV reads themselves lower the arithmetic intensity.
With static batching (batch=32, all sequences decode together), if the shortest response is 50 tokens and the longest is 500, the GPU sits idle for finished sequences. Average output length is 200 tokens. What is the effective utilization compared to continuous batching (which immediately fills empty slots)?
Hint: In static batching, all sequences run for max_length steps. GPU utilization = average_length / max_length.
60% of the batch slots do no useful work. Continuous batching (iteration-level scheduling, from the Orca paper) removes a finished sequence at once and inserts a new one, so slots stay nearly full. Here that is up to 2.5× more throughput. With PagedAttention, which stops KV cache fragmentation, it is the core of servers like vLLM.
Training is a one-time expense. Serving is forever. The cost to serve one million tokens determines whether your model is a viable product or a science experiment. Let's do the math.
70B model in BF16 on 2× H100s, layers split across them (as in Chapter 6). Achievable decode throughput at batch=64: ~1500 tokens/s. GPU utilization: 70% (includes time waiting for requests). Cost: $4/hour for the 2-GPU setup. What is the cost per million output tokens?
About $1 of hardware per million output tokens. An API price also has to cover idle capacity, engineering, margins and the training cost.
You need to serve at $0.50/1M tokens to be competitive. Same setup as 7.1 ($4/hour for 2× H100, 70% utilization). At batch=1, throughput is 24 tok/s. Throughput scales linearly with batch until the compute-bound crossover. What minimum batch size do you need?
You need a batch of at least 133. But each sequence needs its own KV cache. At seq_len = 8192 with GQA, that is 2.68 GB per sequence (Exercise 3.5), so 133 × 2.68 ≈ 357 GB. Add 141 GB of weights and you need about 500 GB; two H100s have 160 GB. At this price you need shorter contexts, more GPUs, or a quantized KV cache.
Speculative decoding uses a small "draft" model to propose K tokens, then the large model verifies all K in one forward pass. The draft model is 10× faster, and each drafted token is accepted with probability α. Use the simple model below. With K=5, what acceptance rate α do you need for a 2× overall speedup?
Simplified: expected accepted tokens per step = Kα. Cost per step = 1 (verify) + K/10 (draft). Speedup = Kα / (1 + K/10). Set this ≥ 2.
The simple model says 60%. It is optimistic: a rejection discards every later draft token. Leviathan et al. (2023) give the expected tokens per step as (1 − αK+1) / (1 − α). At α = 0.6 and K = 5 that is 2.38 tokens, or a 2.38 / 1.5 ≈ 1.6× speedup. Acceptance depends on how well the draft matches the target on the text at hand.
API providers charge differently for input (prefill) and output (decode) tokens. For a 70B model on H100:
Prefill throughput: ~4000 tok/s (compute-bound, high GPU utilization).
Decode throughput at batch=64: ~1500 tok/s (memory-bound).
Same $4/hour GPU cost, 70% utilization for both. What is the cost per 1M input tokens vs output tokens?
Output tokens cost ~2.7× more than input tokens here. Prefill is compute-bound and fast; decode is memory-bound and slower. This is one reason API providers charge more for output tokens.
You quantize the 70B model from BF16 to INT4 (4 bits per weight). This cuts the model to a quarter of its size (from 141 GB to ~35 GB), so it fits on a single H100. Decode throughput scales with bandwidth/model_size: about 3.35 TB/s / 35 GB ≈ 95 tokens/s at batch=1, or ~6000 tok/s at batch=64. GPU cost is now $2/hour (single GPU). What is the new $/1M output tokens?
INT4 cuts the cost ~8× (from $1.06 to $0.13 per 1M tokens). Two factors multiply: 4× fewer bytes to read per token, and one GPU instead of two. The catch is quality: check that the quantized model still passes your evals.
A profile tells you where time goes. Without a profile, optimization is guessing. With one, you can calculate exactly how much speedup is possible and where to focus.
Here is a simplified profile of one LLaMA 3 70B layer's forward pass on one H100 of a TP=8 group (each GPU holds 1/8 of every weight). Batch=2, seq=2048, so M = 4096 tokens.
| Kernel | Time (ms) | Category |
|---|---|---|
| QKV projection (fused gemm) | 0.10 | Compute |
| FlashAttention fwd | 0.05 | Compute |
| Output projection | 0.08 | Compute |
| RMSNorm + residual add | 0.12 | Memory |
| MLP up + gate (fused gemm) | 0.51 | Compute |
| SiLU × gate | 0.08 | Memory |
| MLP down projection | 0.26 | Compute |
| RMSNorm + residual add | 0.12 | Memory |
| NCCL all-reduce × 2 (TP, not overlapped) | 0.52 | Communication |
Total: 1.84 ms per layer. Which target is worth the most time?
Each all-reduce moves [4096, 8192] BF16 = 67.1 MB, so 2 × 7/8 × 67.1 ≈ 117 MB per device. At 450 GB/s that is 0.26 ms, twice per layer: 0.52 ms, the largest non-matmul cost. Fusion (0.32 ms, 17%) is the second target; Exercise 8.4 measures it. FlashAttention is only 0.05 ms, so speeding it up barely matters. INT8 gemms would shrink compute, which is already near peak (Exercise 8.2).
The MLP up+gate projection is a [batch×seq, d] × [d, 2×d_ff] matmul with batch=2, seq=2048, d=8192, d_ff=28672. With TP=8, each GPU computes 1/8 of the output columns. BF16 on H100. What is the theoretical minimum time per GPU (compute-bound at 990 TFLOP/s)?
The profile measured 0.51 ms, so the kernel runs at 0.486 / 0.51 ≈ 95% of peak: near-optimal. Rule of thumb: if measured time is more than 2× the minimum, there is headroom; within 1.2×, look elsewhere. The same check on the down projection gives 0.243 ms against 0.26 ms measured.
An H100 has 132 SMs, each supporting up to 2048 threads (64 warps of 32 threads). Your kernel uses 128 threads per block and 48 KB of shared memory per block. Each SM has 228 KB of shared memory, and CUDA reserves 1 KB more per block. Ignore register limits. How many blocks can run per SM, and what is the occupancy?
Shared memory limit: 228 KB / (48 + 1) KB = 4.65 → 4 blocks per SM
Thread limit: 2048 / 128 = 16 blocks per SM
Limiting factor: shared memory → 4 blocks per SM
25% occupancy is low. To improve: reduce shared memory per block (use tiling to process in smaller chunks), increase threads per block (if the algorithm allows), or restructure the kernel to use less shared memory. Low occupancy is not always bad — if the kernel is compute-bound and achieves high IPC, occupancy matters less than if it is memory-bound.
From the profile in Exercise 8.1, the total layer time is 1.84 ms. If you perfectly fuse all memory-bound ops (0.32 ms total) into adjacent compute kernels, eliminating them entirely, what is the speedup for the full layer?
This is Amdahl's Law: removing 17.4% of the time gives 1/(1 − 0.174) = 1.21×. The other 82.6% is unchanged, so no fusion can beat 1.21× here. Over 80 layers, it saves 80 × 0.32 ms = 25.6 ms per forward pass.
The two TP all-reduces in the profile take 0.52 ms. They cannot overlap the next layer's QKV, because the QKV needs their result. So you split the batch into two microbatches: one microbatch's all-reduces run while the other's matmuls run. Say this gives 0.42 ms of independent matmul time to overlap with. What fraction of the communication is hidden?
Overlap can hide communication only up to the length of the independent work beside it. The layer drops from 1.84 to 1.42 ms. To hide the last 0.10 ms you need more independent work, or overlap inside the matmul itself (a collective matmul splits the communication into chunks; see the Scaling Book's sharded-matmul chapter).
JAX is the framework of choice for scaling research at Google, DeepMind, and many frontier labs. It is not PyTorch with a different API. JAX is a functional transformation system: you write pure functions, and JAX transforms them (differentiation, compilation, parallelization, vectorization).
jax.jit traces your Python function into XLA HLO (an intermediate representation), which XLA compiles into optimized device code. jax.grad transforms the traced graph by adding backward nodes. jax.pmap runs one copy of the graph on each device. All transforms compose.Here is the simplest possible JAX training loop. Study each line — the patterns here scale to billion-parameter models.
jax import jax import jax.numpy as jnp # 1. Generate synthetic data: y = 3x + 1 + noise key = jax.random.PRNGKey(42) key_x, key_noise = jax.random.split(key) # never reuse a key: same key = same random numbers X = jax.random.normal(key_x, (100, 1)) y = 3.0 * X + 1.0 + 0.1 * jax.random.normal(key_noise, (100, 1)) # 2. Initialize parameters (JAX uses explicit state, no hidden .grad) params = {'w': jnp.zeros((1, 1)), 'b': jnp.zeros((1,))} # 3. Define loss as a PURE FUNCTION of params (no side effects!) def loss_fn(params, X, y): pred = X @ params['w'] + params['b'] return jnp.mean((pred - y) ** 2) # 4. jax.grad returns a FUNCTION that computes gradients grad_fn = jax.grad(loss_fn) # differentiates w.r.t. first arg (params) # 5. Training loop — functional update, no in-place mutation lr = 0.1 for step in range(100): grads = grad_fn(params, X, y) params = jax.tree.map(lambda p, g: p - lr * g, params, grads) if step % 20 == 0: print(f"Step {step}: loss={loss_fn(params, X, y):.4f}") print(f"Learned: w={params['w'][0,0]:.3f}, b={params['b'][0]:.3f}") # Expected: w≈3.0, b≈1.0
jax.grad differentiates pure functions — no .backward() on tensors. (2) jax.tree.map applies a function across all leaves of a pytree (nested dict/list of arrays). (3) No in-place updates — every step creates new arrays. (4) jax.jit wraps the training step for compilation.jax import functools import jax import jax.numpy as jnp n_devices = jax.local_device_count() # the batch (100) must divide by this # Replicate params to all devices params = jax.tree.map(lambda x: jnp.stack([x] * n_devices), params) # Define one step: forward, backward, all-reduce, update @functools.partial(jax.pmap, axis_name='batch') # name the device axis for pmean def train_step(params, X_shard, y_shard): grads = jax.grad(loss_fn)(params, X_shard, y_shard) # All-reduce: average gradients across devices grads = jax.lax.pmean(grads, axis_name='batch') return jax.tree.map(lambda p, g: p - 0.1 * g, params, grads) # Split data across devices (axis 0 = device dimension) X_sharded = X.reshape(n_devices, -1, 1) y_sharded = y.reshape(n_devices, -1, 1) # Train! for step in range(100): params = train_step(params, X_sharded, y_sharded)
jax.pmap maps the function across devices. jax.lax.pmean inserts an all-reduce over the axis named 'batch'; without axis_name, JAX raises an unbound-axis error. This is plain data parallelism: every device holds a full copy of the parameters (FSDP would shard them). Newer JAX code does the same with jax.jit plus shardings or shard_map.
Pallas is JAX's kernel language. You write kernels in Python, and they compile to GPU and TPU kernels. Here is a vector addition kernel, the "hello world" of custom kernels. On a CPU, pass interpret=True to pallas_call to test it.
jax/pallas import jax import jax.numpy as jnp from jax.experimental import pallas as pl def add_kernel(x_ref, y_ref, o_ref): """Pallas kernel: reads from x_ref and y_ref, writes to o_ref. Refs are BlockSpec views — they point to a tile of the full array.""" o_ref[...] = x_ref[...] + y_ref[...] def add_vectors(x, y): return pl.pallas_call( add_kernel, out_shape=jax.ShapeDtypeStruct(x.shape, x.dtype), grid=(8,), # launch 8 blocks in_specs=[ pl.BlockSpec((128,), lambda i: (i,)), # each block gets 128 elements pl.BlockSpec((128,), lambda i: (i,)), ], out_specs=pl.BlockSpec((128,), lambda i: (i,)), )(x, y) # Test x = jnp.arange(1024, dtype=jnp.float32) y = jnp.ones(1024, dtype=jnp.float32) result = add_vectors(x, y) # result == jnp.arange(1024) + 1
jax.vmap automatically vectorizes a function that operates on a single example to work on a batch. This is how you write clean, single-example logic and get batched execution for free.
jax import jax import jax.numpy as jnp # Function that works on ONE example (no batch dim) def predict_single(params, x): """x: shape [D], returns scalar""" return jnp.dot(params['w'], x) + params['b'] # vmap it to handle batches: x now shape [B, D] predict_batch = jax.vmap(predict_single, in_axes=(None, 0)) # in_axes=(None, 0): don't batch over params, batch over axis 0 of x # This compiles to the SAME efficient batched matmul as manual batching params = {'w': jnp.ones(768), 'b': jnp.zeros(())} x_batch = jax.random.normal(jax.random.PRNGKey(0), (32, 768)) out = predict_batch(params, x_batch) # shape [32]
vmap composes with jit and grad: jax.jit(jax.vmap(jax.grad(loss_fn), in_axes=(None, 0, 0))) gives one gradient per example, compiled into a single XLA graph. Feed it X and y with shape [B, 1, 1] so each example is a batch of one.
jax.jit(f) do?Vlad Feinberg's post "How to Land a Job at a Frontier Lab" (2026) suggests this exercise: code a ~10M parameter transformer with only JAX, Flax and Optax, and have it learn addition. It tests tokenization, model sizing, scaling laws, training dynamics and JAX fluency at once.
The vocabulary is tiny: digits 0-9, plus sign, equals sign, and a padding token. That is 13 tokens total. (The post uses a space token where we use padding.)
The model sees the entire string but only predicts the answer portion (after the = sign). During training, you mask the loss on the prompt tokens.
For addition of up to 3-digit numbers, what is the maximum input sequence length? Consider: "999+999=1998". Count each character as one token.
The maximum result of 3-digit addition is 999+999=1998, which is 4 digits. So max_len = 3 + 1 + 3 + 1 + 4 = 12. Pad all sequences to length 12. Shorter examples (like "1+2=3") get padded: "1+2=3<pad><pad><pad><pad><pad><pad><pad>".
You want ~10M parameters. For a decoder-only transformer with:
Target 10M parameters. Try L=6 layers. What value of d (model dimension) gets you closest to 10M? Use the simplified formula: Params ≈ L × 12d2.
Round to d=384 (divisible by common head counts). With 6 heads, d_head = 384/6 = 64. The formula gives 6 × 12 × 3842 = 10,616,832 ≈ 10.6M. The Flax model below, with biases, norms and embeddings, has 10,662,157.
A practical config: L=6, d=384, n_heads=6, d_head=64, d_ff=1536, vocab=13, max_seq=12.
Here is the core transformer in Flax (linen API). It runs as written; initialising it on [2, 12] tokens gives [2, 12, 13] logits.
python/flax import jax import jax.numpy as jnp import flax.linen as nn import optax class CausalSelfAttention(nn.Module): n_heads: int d_model: int @nn.compact def __call__(self, x): B, T, C = x.shape d_head = C // self.n_heads # Fused QKV projection qkv = nn.Dense(3 * C)(x) # [B, T, 3C] q, k, v = jnp.split(qkv, 3, axis=-1) # Reshape for multi-head: [B, T, C] -> [B, n_heads, T, d_head] q = q.reshape(B, T, self.n_heads, d_head).transpose(0,2,1,3) k = k.reshape(B, T, self.n_heads, d_head).transpose(0,2,1,3) v = v.reshape(B, T, self.n_heads, d_head).transpose(0,2,1,3) # Scaled dot-product attention with causal mask attn = (q @ k.transpose(0,1,3,2)) / jnp.sqrt(d_head) mask = jnp.tril(jnp.ones((T, T)))[None, None, :, :] attn = jnp.where(mask == 0, -1e9, attn) attn = jax.nn.softmax(attn, axis=-1) out = (attn @ v).transpose(0,2,1,3).reshape(B, T, C) return nn.Dense(C)(out) # output projection class TransformerBlock(nn.Module): n_heads: int d_model: int d_ff: int @nn.compact def __call__(self, x): # Pre-norm architecture (like GPT-2, LLaMA) x = x + CausalSelfAttention(self.n_heads, self.d_model)(nn.LayerNorm()(x)) x = x + nn.Dense(self.d_model)(nn.gelu(nn.Dense(self.d_ff)(nn.LayerNorm()(x)))) return x class AdditionTransformer(nn.Module): vocab: int = 13 d_model: int = 384 n_heads: int = 6 n_layers: int = 6 d_ff: int = 1536 max_len: int = 12 @nn.compact def __call__(self, tokens): B, T = tokens.shape # Token + positional embeddings tok_emb = nn.Embed(self.vocab, self.d_model)(tokens) pos_emb = nn.Embed(self.max_len, self.d_model)(jnp.arange(T)) x = tok_emb + pos_emb # [B, T, d_model] # Transformer blocks for _ in range(self.n_layers): x = TransformerBlock(self.n_heads, self.d_model, self.d_ff)(x) x = nn.LayerNorm()(x) logits = nn.Dense(self.vocab)(x) # [B, T, vocab] return logits
Using D = 20N, how many tokens should you train your 10M model on? How many 3-digit addition examples is that (each example ~12 tokens)?
With operands from 0 to 999 there are only 1,000 × 1,000 = 1,000,000 distinct problems, so the model sees each one ~17 times. Chinchilla's 20N rule was fit on web text, not on a small closed task, so treat 200M tokens as a starting budget and watch held-out accuracy.
Your 10.6M parameter model will train on 200M tokens. What is the total training compute in PFLOP (1015 FLOPs)? How long will this take on a single T4 GPU (65 TFLOP/s FP16, assuming 30% MFU)?
Under 11 minutes on a Colab T4, so you can run many experiments in an afternoon. If training takes much longer, check your batch size and your data pipeline first.
The post also asks you to derive Chinchilla laws for this model and see how they differ for dense and MoE (Mixture of Experts) models. An MoE model has more total parameters (N_total) but uses only some of them per token (N_active). Training compute depends on the active count.
You have a compute budget of 6 × 1020 FLOPs. Compare two options:
(A) Dense 1B model, trained on D_A tokens.
(B) MoE with 8 experts, top-2 routing, N_active = 1B (but total params = ~3.5B). Trained on D_B tokens.
Using C = 6 × N_active × D, how many tokens can each train on?
Both get 100B tokens, because both have N_active = 1B. The MoE has 3.5B total parameters, so more capacity, for the same training compute. At inference it needs 3.5× the weight memory but the same FLOPs per token. (Router and load-balancing FLOPs are ignored here.)
MoE routing creates "ragged" batches: each expert gets a different number of tokens. jax.lax.ragged_dot does one grouped matmul over such groups. The post asks you to "write a pallas kernel that beats ragged dot for F > D by fusing the up/down projections". It does not define F and D. We read D as the model width and F as each expert's hidden (FFN) width.
Each expert computes down(act(up(x))): up maps [tokens, D] to [tokens, F], down maps back to [tokens, D]. With ragged_dot you call it twice: once for up, once for down. Take D = 1024 and F = 4096. Why can a fused Pallas kernel win when F > D?
Per routed token in BF16: the input and output are D × 2 bytes each (2 KB each). The hidden activation is F × 2 = 8 KB, written once and read once: 16 KB of extra traffic, 4× the input plus output. Fusion removes it; the FLOPs stay the same.
The gain only shows when activations matter. Reading the expert weights (2 × D × F × 2 bytes = 16.8 MB per expert here) is a fixed cost. With few tokens per expert, weight reads dominate and fusion barely helps. The post asks you to find a setting with a measurable speedup and explain it; this traffic count is where to start.
Here is every skill this workbook covers. Be honest with yourself: can you do each of these from scratch, with paper and pencil, without looking up the formula? Check off each one as you master it.
Click checklist items above to track your progress.
0 / 41 mastered
| Topic | Lesson |
|---|---|
| Transformer internals | Transformer — From Absolute Zero |
| GPT architecture | GPT — From Absolute Zero |
| Diffusion models | Diffusion — From Absolute Zero |
| Reward & alignment | RLHF — From Absolute Zero |
| Inference engineering | ML Inference Engineer — Day In The Life |
Here is the protocol that maximizes retention from this workbook. It is based on spaced retrieval practice — the most evidence-backed learning technique in cognitive science.