Dive into Deep Learning · §13.8
Case Study: Making a Transformer Fast Step by Step
profile-guided Amdahl bounds · fusion & CUDA graphs · bf16 & FlashAttention · batch sizing · multi-GPU scaling · MFU
Motivation
bf16).fp32 baseline (\sim 25\text{ ms}): Runs > 4\times slower than the bf16 compute floor (\sim 23\% MFU).tf32 vs. bf16 Tensor Core rate; the remaining \sim 13\text{ ms} comes from unfused bandwidth-bound kernels and dispatch gaps.Roofline Positioning
I \;=\; \frac{2 n d d'}{b\,(n d + d d' + n d')}
tf32 (> I^* = 82) and 250\text{--}370\text{ FLOP/B} in bf16 (> I^* = 164).tf32 to bf16 cuts GEMM time directly in half.Benchmark Discipline
To ensure every optimization is judged on equal footing, our benchmark holds the model, data pipeline, and timing protocol fixed across all rungs:
tokens_per_second): Runs 20 warm-up steps followed by 3 timed windows of 50 steps between device barriers, reporting median \text{tokens/s}, incremental speedup, and window spread (\textrm{range}/\textrm{median}).allclose on logits or weight updates) before entering the benchmark.Predictive Method
tf32 \to bf16): When GEMMs take share f of the step, doubling GEMM rate gives \ge \frac{1}{1 - f/2} (up to 2.0\times as activation traffic also halves).Baseline Profile
Profiling the eager float32 baseline (tf32 matmuls, fused AdamW) at batch size 64 (8{,}192 tokens/step) establishes where the \sim 25\text{ ms} goes:
wall clock 25.78 ms per step, device busy 24.44 ms (95%), matrix products 64%
3.28 ms 13% Kernel2<cutlass_80_tensorop_s1688gemm_128x128_32x3_n
3.08 ms 13% Kernel2<cutlass_80_tensorop_s1688gemm_128x128_32x3_t
2.84 ms 12% Kernel2<cutlass_80_tensorop_s1688gemm_128x128_32x3_n
2.41 ms 10% vectorized_elementwise_kernel<4, BinaryFunctor<float
Compiler & Replay
We compile the model with torch.compile(model, dynamic=False, mode='reduce-overhead'), combining Inductor operator fusion with static-shape CUDA graph replay:
relative difference of the compiled logits: 1.5e-05
+ compile: 368,688 tokens/s (1.16x), windows within 0.0%
Second Profile
Profiling the step after Rung 1 shows the GPU busy for 99\text{--}100\% of the step, with matrix products consuming f \approx 65\text{--}71\% of device time:
wall clock 22.22 ms per step, device busy 22.27 ms (100%), matrix products 71%
4.01 ms 18% Kernel2<cutlass_80_tensorop_s1688gemm_128x128_32x3_n
3.05 ms 14% Kernel2<cutlass_80_tensorop_s1688gemm_128x128_32x3_t
2.83 ms 13% Kernel2<cutlass_80_tensorop_s1688gemm_128x128_32x3_n
1.44 ms 6% fmha_cutlassB_f32_aligned_64x64_k64_sm80
bfloat16 mixed precision): Switching Tensor Core GEMMs from tf32 (82.6\text{ TFLOP/s}) to bfloat16 (165.2\text{ TFLOP/s}) halves matrix-product time.Reduced Precision
Enabling torch.autocast('cuda', torch.bfloat16) runs linear layers and fused FlashAttention (F.scaled_dot_product_attention) in bfloat16 while keeping master weights, norms, the residual stream, and the loss in float32:
relative difference of the bf16 logits: 2.0e-03
+ bf16: 643,350 tokens/s (1.74x), windows within 0.1%
bfloat16 GEMMs achieve higher Tensor Core efficiency than tf32 and intermediate fused kernels move 2-byte bfloat16 tensors instead of 4-byte float32 tensors.Precision & Bandwidth
Decomposing the 1.75\times speedup from torch.autocast('cuda', torch.bfloat16) highlights how reduced precision accelerates both roofline regimes simultaneously:
float32 (preventing a full 2.0\times): Master weights, gradients, AdamW moments (28\text{ B/param}), RMSNorm reductions, residual-stream additions, and cross-entropy log-probabilities remain 32-bit for numerical stability.Amortizing Fixed Work
Because the GPU is already 100\% busy, growing the batch 8\times from 64 \to 512 windows (65{,}536 tokens/step) can only amortize device work that scales with parameter count N = 19\text{M} rather than token count n:
fp32 weight, grad, two moments) and mixed precision casts weights/gradients between fp32 and bf16 (12\text{ B/param}), taking \sim 0.75\text{ ms} at 1\text{ TB/s} (\sim 6\% of a 12.5\text{ ms} batch-64 step).+ batch 512: 653,141 tokens/s (1.02x), windows within 0.0%
memory beyond weights and optimizer state: 8.6 GiB
Third Profile
At batch size 512, activation memory consumes \sim 8\text{ GiB} (leaving two-thirds of the 24\text{ GiB} GPU free), and the profile shows the step’s final single-GPU balance:
wall clock 100.34 ms per step, device busy 100.33 ms (100%), matrix products 57%
11.62 ms 12% ampere_bf16_s1688gemm_bf16_128x128_ldg8_f2f_stages_3
10.78 ms 11% ampere_bf16_s16816gemm_bf16_128x64_ldg8_f2f_tn
7.45 ms 7% Kernel2<cutlass_80_tensorop_bf16_s16816gemm_relu_bf1
5.62 ms 6% triton_poi_fused__unsafe_view_mm_mul_silu_silu_backw
fp32/bf16 casts) take the remaining \sim 40\%.Checkpointing Prediction
Even though batch size 512 easily fits in 24\text{ GiB}, what happens if we turn on per-block activation checkpointing (kept=False branch)? We can bound the throughput retention in two ways:
forward pass 30.8 ms of a 100.3 ms step: repeating it keeps at least 0.77 of the throughput
Checkpointing Measured
Wrapping all 6 Transformer blocks in Checkpointed cuts activation memory by two-thirds (7\text{--}9\text{ GiB} \to 2.6\text{--}3.2\text{ GiB}) while retaining 0.79\text{--}0.85\times of throughput—beating both the 0.75\times FLOP bound and the 0.77\times forward-timing bound:
+ checkpointing: 556,390 tokens/s (0.85x), windows within 0.0%
memory beyond weights and optimizer state: 3.2 GiB
forward pass alone: products 17.4 ms, other kernels 13.4 ms
added to the step: products 14.5 ms, other kernels 3.1 ms
Single-GPU Results
Summarizing all single-GPU rungs side by side converts token throughput into achieved TFLOP/s (6N\text{ FLOPs/token}) and Model FLOPs Utilization (\textrm{MFU} = \textrm{achieved FLOP/s} / 165.2\text{ TFLOP/s}):
configuration tokens/s step total TFLOP/s MFU
baseline 317,736 1.00x 1.00x 36.2 22%
+ compile 368,688 1.16x 1.16x 42.1 25%
+ bf16 643,350 1.74x 2.02x 73.4 44%
+ batch 512 653,141 1.02x 2.06x 74.5 45%
---------------------------------------------------------
+ checkpointing 556,390 0.85x 63.5 38% (not kept)
bfloat16 Tensor Cores and operator/attention fusion.Data-Parallel Cost Model
\textrm{Speedup}(k) \;\gtrsim\; \frac{k\, t_{\textrm{step}}(1)}{t_{\textrm{step}}(1) + t_{\textrm{allreduce}}(k)}
fp32 grads takes 31\text{ ms} (k=2) and 47\text{ ms} (k=4).Multi-GPU Measured
Running production data parallelism on k = 1, 2, 4 GPUs tests both predictions of opposite sign:
fp32, batch 64 per GPU: 364,947 tokens/s on one GPU
2 GPUs: allreduce 31 ms, speedup predicted 0.83x, measured 0.91x
4 GPUs: allreduce 48 ms, speedup predicted 1.27x, measured 1.36x
bf16, batch 512 per GPU: 662,971 tokens/s on one GPU
2 GPUs: allreduce 31 ms, speedup predicted 1.52x, measured 1.63x
4 GPUs: allreduce 48 ms, speedup predicted 2.69x, measured 2.92x
Both predictions hold: The standalone 76\text{ MB} allreduce measures 31\text{ ms} (k=2) and 48\text{ ms} (k=4). At batch 64, adding a second GPU slows training down (\sim 0.85\text{--}0.95\times); at batch 512 in bfloat16, 4 GPUs achieve \sim 2.9\text{--}3.2\times single-GPU throughput (\sim 1.9\text{--}2.3\text{M tokens/s}, or 6\text{--}7\times our single-GPU baseline), with backward-pass bucket overlap providing the margin above the no-overlap floor.
Numerical Verification
A 2\times faster single-GPU step is only valid if it learns the same representation as the float32 baseline. We train two identically initialized models (one using baseline and one using final, + batch 512 in bf16) on the exact same 200 minibatches of 512 windows (\sim 13\text{M} tokens, with a 50-step linear LR warm-up):
loss at step 1 50 100 200 mean of last 20 validation
baseline 5.66 2.52 2.03 1.49 1.52 1.47
final 5.66 2.51 2.06 1.50 1.53 1.47
Optimization Caveat
compile, bf16, FlashAttention, strong-scaling DP) always cut time-to-loss; batch-growing changes help only while b \lesssim b_{\textrm{noise}}.Final Accounting
Normalizing our kernel profiles to milliseconds per 8{,}192 tokens accounts for every millisecond of the baseline and final steps against ideal Tensor Core peak time (5.7\text{ ms} in bf16, 11.3\text{ ms} in tf32):
ms per 8,192 tokens step at peak products other
baseline (tf32) 25.8 11.3 15.6 8.8
+ batch 512 (bf16) 12.5 5.7 7.1 5.4
Check Your Understanding
Use the final millisecond accounting (7\text{ ms} in matrix products near bf16 peak + 5\text{ ms} in bandwidth-bound non-matmul kernels = 12\text{ ms} per 8{,}192 tokens) to answer three questions:
bfloat16 (165\text{ TFLOP/s}) to fp8 (330\text{ TFLOP/s}), halving matrix-product time from 7\text{ ms} \to 3.5\text{ ms} while leaving the 5\text{ ms} of non-matmul kernels unchanged. What is the step speedup?bfloat16 matrix products stay at 7\text{ ms}. What is the step speedup?Answers:
fp8 matmuls alone: Step time drops from 12\text{ ms} \to 3.5 + 5.0 = 8.5\text{ ms}, a speedup of 12 / 8.5 \approx 1.41\times (far below 2\times).fp8 matrix products (7 \to 3.5\text{ ms}) and narrower/fused activation memory traffic (5 \to 2.5\text{ ms}).Key Takeaways
| Optimization Rung | Bottleneck Targeted | Amdahl Prediction | Measured Gain | Cumulative Speedup / MFU |
|---|---|---|---|---|
0. Baseline (fp32/tf32) |
Reference (26\text{ ms} / 8192 tok) | — | 1.00\times | 1.00\times (\sim 22\% MFU) |
1. torch.compile |
Non-matmul traffic & host dispatch | \le 1.6\times | 1.16\times | 1.16\times (\sim 25\% MFU) |
2. bf16 (FlashAttention already on) |
Tensor Core GEMMs | 1.5\text{--}2.0\times | 1.74\times | \approx 2.0\times (\sim 44\% MFU) |
| 3. Batch 64 \to 512 | Fixed 40\text{ B/param} step work (0.75\text{ ms}) | \approx 1.05\times | 1.02\times | \approx 2.1\times (\sim 45\% MFU) |
| Branch: Checkpointing | Activation memory (8.6 \to 3.2\text{ GiB}) | \ge 0.77\times | 0.85\times | Memory saver (not kept) |
| 4. 4-GPU Data Parallel | Single-GPU ceiling (48\text{ ms} allreduce) | \approx 2.7\times (batch 512) | \approx 2.9\times over 1 GPU | \approx 6\times over 1-GPU baseline |