Case Study: Optimizing a Transformer

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

A GPT Step Needs 6 ms of Math but Takes 25 ms

Motivation

  • Hardware speed limit (5.7\text{ ms}): One step of our 6-block, width-512 GPT (N = 19\text{M}, n = 8{,}192 tokens) performs 6Nn \approx 0.93\text{ TFLOP}, requiring only 5.7\text{ ms} at 165.2\text{ TFLOP/s} (bf16).
  • Measured fp32 baseline (\sim 25\text{ ms}): Runs > 4\times slower than the bf16 compute floor (\sim 23\% MFU).
  • Decomposing the 19\text{ ms} gap: About 6\text{ ms} comes from the tf32 vs. bf16 Tensor Core rate; the remaining \sim 13\text{ ms} comes from unfused bandwidth-bound kernels and dispatch gaps.

Choosing Model Width 512: Placing Matmuls Above I*

Roofline Positioning

I \;=\; \frac{2 n d d'}{b\,(n d + d d' + n d')}

  • Clearing the ridge point: At d = 512 and n = 8{,}192 tokens, block projections achieve I = 125\text{--}185\text{ FLOP/B} in tf32 (> I^* = 82) and 250\text{--}370\text{ FLOP/B} in bf16 (> I^* = 164).
  • Why width 512 matters: Because every GEMM sits firmly on the compute roof, doubling Tensor Core P from tf32 to bf16 cuts GEMM time directly in half.

End-to-End Experimental Setup and Timing Protocol

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:

  • Zero host-transfer noise: The entire 270\text{ MB} WikiText-103 byte corpus resides in GPU DRAM; each step samples random 128-byte windows directly on the device.
  • Compact parameter state: At 16\text{ B/param}, the 19\text{M}-parameter AdamW state occupies only 0.3\text{ GiB}, requiring neither gradient accumulation nor FSDP sharding.
  • Synchronized multi-window measurement (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}).
  • Correctness gate before timing: Every rung asserts numerical agreement (allclose on logits or weight updates) before entering the benchmark.

Using the Previous Profile to Bound the Next Speedup

Predictive Method

  • Host dispatch & fusion bounds: Removing idle launch gaps bounds speedup by t_{\textrm{step}}/t_{\textrm{busy}}, while fusing non-matmul kernels (t_{\textrm{other}}) bounds speedup by t_{\textrm{step}}/t_{\textrm{products}}.
  • Precision (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).
  • Batch sizing & remat: Growing B \to 8B amortizes only fixed 40\text{ B/param} work (\le 1.05\times), while remat costs +2N\text{ FLOPs/tok} (\ge 0.75\times).

Rung 0 (Baseline): Profiling the Eager fp32 Step

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
  • Diagnosis: The GPU is busy for nearly 100\% of the 25\text{ ms} step (not overhead-bound), with matrix products taking \sim 64\% (15.6\text{ ms}) and short bandwidth-bound elementwise/norm kernels taking the remaining \sim 36\% (8.8\text{ ms}).
  • Amdahl bound for compilation: Even if fusion and CUDA graphs eliminated all non-matmul kernels and launch gaps, the step could shrink at most from 25\text{ ms} \to 15.6\text{ ms} (\le 1.6\times speedup).

Rung 1: Inductor Fusion and CUDA Graph Replay

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:

compiled = torch.compile(model, dynamic=False, mode='reduce-overhead')
high = model(X)
error = ((compiled(X) - high).norm() / high.norm()).item()
assert error < 1e-4      # verify numerical equivalence before timing
step = make_step(model, compiled)
relative difference of the compiled logits: 1.5e-05
+ compile: 368,688 tokens/s (1.16x), windows within 0.0%
  • Result (1.16\times speedup): Logits match to 1.5 \times 10^{-5}; fusion shaves 2.2\text{ ms} off non-matmul kernels (24.5 \to 22.3\text{ ms}) and CUDA graphs close \sim 1\text{ ms} of inter-kernel launch gaps.

Profile After Rung 1: Matrix Products Take Two-Thirds

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
  • Predicting Rung 2 (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.
  • Theoretical bounds: If only matrix products (f \approx 0.68) double in speed, the speedup is \frac{1}{1 - f/2} \approx \mathbf{1.52\times}; if non-matmul kernels also halve their memory traffic by moving 2-byte activations, the speedup approaches 2.0\times.

Rung 2: Mixed-Precision bf16 Speeds Up the Step 1.75×

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%
  • Why 1.74\times sits cleanly inside [1.55\times, 2.0\times]: Logits agree within 0.2\% (< 1\% gate). The speedup exceeds the 1.55\times matmul-only bound because bfloat16 GEMMs achieve higher Tensor Core efficiency than tf32 and intermediate fused kernels move 2-byte bfloat16 tensors instead of 4-byte float32 tensors.

Why bf16 Beat the Matmul-Only Amdahl Bound

Precision & Bandwidth

Decomposing the 1.75\times speedup from torch.autocast('cuda', torch.bfloat16) highlights how reduced precision accelerates both roofline regimes simultaneously:

  • Compute-bound kernels (GEMMs & FlashAttention): Tensor Core peak throughput doubles from 82.6 \to 165.2\text{ TFLOP/s}, and smaller 16-bit operands reduce register-file pressure and shared-memory bank conflicts.
  • Bandwidth-bound kernels (SwiGLU, rotary embeddings, views): Halving activation element size from 4\text{ B} \to 2\text{ B} cuts DRAM read/write traffic in half for every intermediate tensor between linear projections.
  • What stays in 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.

Rung 3: Growing the Minibatch to 512 Windows

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:

  • Fixed per-step memory traffic (40\text{ B/param} = 0.76\text{ GB}): Fused AdamW reads/writes 28\text{ B/param} (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).
  • Prediction (\le 5\% gain): Amortizing 7/8 of 0.75\text{ ms} predicts a few percent throughput gain, while lengthening the step to \sim 95\text{ ms} so multi-GPU allreduce can scale.
+ batch 512: 653,141 tokens/s (1.02x), windows within 0.0%
memory beyond weights and optimizer state: 8.6 GiB

Profile at Batch 512: 60% Matmuls, 40% Memory Traffic

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
  • Where the time goes: The GPU is busy for 100\% of the \sim 91\text{--}100\text{ ms} step; matrix products and fused attention take \sim 57\text{--}60\% of the step, while fused bandwidth-bound kernels (RMSNorm, SwiGLU, RoPE, and fp32/bf16 casts) take the remaining \sim 40\%.

Branch Test: Predicting Activation Checkpointing Cost

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:

  1. By FLOP count: Recomputing each block’s forward pass during backpropagation increases block arithmetic from 6N \to 8N\text{ FLOPs/token}, predicting 6/8 = \mathbf{0.75\times} throughput.
  2. By standalone forward-pass time (t_{\textrm{fwd}}): Timing the forward pass alone predicts \frac{1}{1 + t_{\textrm{fwd}} / t_{\textrm{step}}} \approx \mathbf{0.76\text{--}0.77\times} throughput.
forward pass 30.8 ms of a 100.3 ms step: repeating it keeps at least 0.77 of the throughput

Measuring Checkpointing: Fused Remat Beats the Floor

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
  • Why recomputation costs less than a standalone forward pass: While the block matrix products must be re-executed in full (+14\text{ ms}), the compiler fuses the recomputed elementwise kernels (SwiGLU, RoPE, norms) directly into the backward kernels that consume them, saving most of their 13\text{ ms} of standalone DRAM traffic.

Cumulative Single-GPU Waterfall: ~2× Speedup, 45–50% MFU

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)
  • Takeaway: Cumulative single-GPU optimizations double throughput (\sim 2.0\text{--}2.1\times), reaching \sim 45\text{--}50\% MFU on the RTX 4090—driven overwhelmingly by bfloat16 Tensor Cores and operator/attention fusion.

Measured Scaling: Batch 64 Loses, Batch 512 Hits 3×

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.

End-to-End Training Gate: Matching Baseline Convergence

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
  • Passed gate: Both curves start at \ln 256 \approx 5.55, track within 0.05\text{ nats/byte} across all 200 steps, and reach the same validation loss (1.5\text{--}1.6, well below the 2.45 bigram threshold).

Throughput vs. Time-to-Target-Loss

Optimization Caveat

  • The critical batch size (b_{\textrm{noise}}): Training at batch size b requires E(b) = E_{\min}(1 + b/b_{\textrm{noise}}) total tokens to reach a target validation loss.
  • Diminishing returns past b_{\textrm{noise}}: When b \gg b_{\textrm{noise}}, cleaner gradient estimates make nearly the same parameter progress per step as smaller batches, needing more total tokens.
  • Systems rule: Batch-preserving speedups (compile, bf16, FlashAttention, strong-scaling DP) always cut time-to-loss; batch-growing changes help only while b \lesssim b_{\textrm{noise}}.

Millisecond Accounting of the Final Step

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
  • Why the final step runs at \sim 50\% MFU (11.5\text{--}12\text{ ms} vs. 5.7\text{ ms} ideal):
    • Matrix products (\sim 7\text{ ms}): Run at > 80\% of the 5.7\text{ ms} hardware peak while performing > 99\% of all arithmetic.
    • Bandwidth-bound kernels (\sim 5\text{ ms}): Norms, SwiGLU, RoPE, casts, and AdamW perform < 1\% of the FLOPs but consume \sim 40\% of the step time moving bytes through DRAM.

Concept Check: Amdahl Bounds, Scaling, and Next Steps

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:

  1. Suppose we switch the matrix products from 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?
  2. Conversely, suppose custom hand-written mega-kernels fuse away all 5\text{ ms} of non-matmul memory traffic while bfloat16 matrix products stay at 7\text{ ms}. What is the step speedup?
  3. What would it take to achieve another 2\times single-GPU speedup (12\text{ ms} \to 6\text{ ms})?

Answers:

  1. 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).
  2. Eliminating all non-matmul kernels alone: Step time drops from 12\text{ ms} \to 7.0\text{ ms}, a speedup of 12 / 7.0 \approx 1.71\times (also below 2\times).
  3. Both are required simultaneously: Because the 12\text{ ms} step is split 58\% compute-bound (7\text{ ms}) and 42\% bandwidth-bound (5\text{ ms}), halving it to 6\text{ ms} requires both faster fp8 matrix products (7 \to 3.5\text{ ms}) and narrower/fused activation memory traffic (5 \to 2.5\text{ ms}).

Summary: Step-by-Step Transformer Optimization

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