Contents
Key concepts
Three regimes: compute, bandwidth, overhead
Time is spent on arithmetic, on moving tensors between HBM and on-chip memory, or on everything else (Python, dispatch, kernel launches, host–device syncs, data loading). Identify the regime before optimising: more FLOPs do not help a bandwidth-bound op, and fusing kernels does nothing if the GPU is idle waiting on the dataloader.
Arithmetic intensity and the roofline
Arithmetic intensity is FLOPs per byte moved. Attainable throughput is min(peak FLOPs, intensity × bandwidth); the ridge point is peak / bandwidth, about 295 FLOPs/byte for an H100 SXM in dense bf16 (989 TFLOP/s ÷ 3.35 TB/s). Large matmuls sit far above it (compute-bound); elementwise ops, normalisations and batch-1 decode (≈1 FLOP/byte for bf16 GEMV) sit far below (memory-bound).
FLOP accounting for transformers
A matmul of (m×k)(k×n) costs 2mkn FLOPs. A dense transformer’s forward pass costs about 2N FLOPs per token (N = parameters) plus attention terms that grow with context; training costs about 6N per token (forward plus twice for backward). Model FLOPs utilisation (MFU) = achieved model FLOPs ÷ peak; 35–55% is typical for well-tuned large-scale training.
CalculatorTransformer FLOP accounting
- matmul FLOPs
- 137,438,953,472 FLOPs
- training FLOPs
- 4.2 × 10²² FLOPs
matmul FLOPs = 2 × m × k × n = 137,438,953,472 FLOPs
training FLOPs = 6 × parameters × tokens ÷ 10 = 4.2 × 10²² FLOPs
| Case | m | k | n | parameters (billions) | tokens (trillions) | matmul FLOPs | training FLOPs |
|---|---|---|---|---|---|---|---|
| 4096 matmul, 7B, 1T tokens | 4,096 | 4,096 | 4,096 | 7 | 1 | 137,438,953,472 FLOPs | 4.2 × 10²² FLOPs |
Training memory: 16 bytes per parameter and activations
Mixed-precision Adam needs bf16 weights (2 B) + bf16 gradients (2 B) + fp32 master weights (4 B) + Adam first and second moments (4 B + 4 B) ≈ 16 B/parameter before activations. Activations scale with batch × sequence × hidden × layers and dominate at long sequence lengths; activation checkpointing stores only layer inputs and recomputes the rest (~30% more compute). ZeRO/FSDP shards optimiser state (stage 1), gradients (stage 2) and parameters (stage 3) across data-parallel ranks, dividing the 16 B term by the shard count at the cost of extra communication.
Stack · 5 layersMixed-precision Adam memory per parameter
bf16 weights cost 2 B per parameter.
bf16 gradients cost 2 B per parameter.
fp32 master weights cost 4 B per parameter.
Adam first and second moments cost 4 B + 4 B per parameter.
The sum is ≈ 16 B per parameter before activations.
Numerics: fp16, bf16, FP8 and 8-bit optimisers
bf16 keeps fp32’s exponent range with fewer mantissa bits, so it rarely needs loss scaling; fp16 has more precision but a narrow range and needs dynamic loss scaling to avoid gradient underflow. FP8 training (E4M3 forward, often E5M2 for gradients, with per-tensor or block scaling) roughly doubles matmul throughput on Hopper/Blackwell but needs careful scaling and monitoring for divergence. 8-bit optimisers cut Adam state from 8 B to about 2 B per parameter. Blackwell adds 4-bit microscaled formats: MXFP4 (32-value blocks, power-of-two scale, about 4.25 bits) and NVFP4 (16-value blocks, FP8 scale plus a per-tensor scale, about 4.5 bits). gpt-oss ships MXFP4 weights, and NVFP4 pretraining has reached 25T tokens (Nemotron 3 Super) with Hadamard transforms, stochastic rounding and a few BF16 layers.
Kernel fusion and FlashAttention
Unfused code writes every intermediate to HBM and reads it back. Fusion (hand-written kernels, torch.compile, Triton) keeps intermediates in registers or shared memory. FlashAttention tiles the attention computation and uses an online softmax so the N×N score matrix is never materialised in HBM: the result is exact, memory is linear in sequence length, and wall-clock speed improves because the op was bandwidth-bound.
Mixture of experts
A router sends each token to k of E expert MLPs, so compute per token scales with active parameters while memory scales with total parameters (Mixtral 8x7B: ~47B total, ~13B active). Costs: all-to-all communication under expert parallelism, load imbalance and dropped tokens (auxiliary balancing losses or bias-based balancing), and poor utilisation at small batch because each expert sees few tokens.
Profiling-first debugging
Start with a profiler trace (PyTorch profiler, Nsight Systems) and simple counters: step time split, dataloader wait, host–device syncs (.item(), prints, CPU-side shape logic), kernel launch gaps and communication time. nvidia-smi “utilisation” only says a kernel was running, not that SMs were busy. Typical fixes for 30% utilisation: more dataloader workers and pinned memory, larger micro-batches, removing syncs, CUDA graphs or torch.compile for launch-bound loops, overlapping communication.
Flow · 3 stepsProfiling-first debugging sequence
- Profile Start with a profiler trace.
- Read counters Read step time split, dataloader wait, host-device syncs, kernel launch gaps and communication time.
- Fix the cause Use more dataloader workers and pinned memory, larger micro-batches, removing syncs, CUDA graphs or torch.compile, and overlapping communication.
Data
| Step | Title | What happens |
|---|---|---|
| 1 | Profile | Start with a profiler trace. |
| 2 | Read counters | Read step time split, dataloader wait, host-device syncs, kernel launch gaps and communication time. |
| 3 | Fix the cause | Use more dataloader workers and pinned memory, larger micro-batches, removing syncs, CUDA graphs or torch.compile, and overlapping communication. |
Source: This page's text
| Box | Group | Detail |
|---|---|---|
| Profiler trace | Measure | PyTorch profiler, Nsight Systems |
| Counters | Measure | step time split |
| Dataloader wait | Diagnose | |
| Syncs | Diagnose | |
| Launch gaps | Diagnose | |
| Comm time | Diagnose | |
| Typical fixes | Fix | for 30% utilisation |
Source: This page's text
Worked examples
Memory to fully fine-tune a 70B model in mixed precision
Estimate accelerator memory for weights, gradients and Adam state for 70B parameters, then per GPU with ZeRO-3 across 64 GPUs. What changes with 8-bit Adam?
Per parameter: 2 (bf16 weights) + 2 (bf16 grads) + 4 (fp32 master) + 8 (Adam m, v) = 16 B.
Total: 70e9 × 16 B = 1.12 TB, before activations, buffers and fragmentation.
ZeRO-3 over 64 GPUs: 1.12 TB / 64 ≈ 17.5 GB per GPU of model state, leaving the rest of an 80 GB card for activations and communication buffers (gathered parameters for the current layer).
8-bit Adam: moments drop from 8 B to ~2 B → ~10 B/param → 0.70 TB total (~10.9 GB/GPU at 64).
Precision choices that change the bill: FP8 weights/activations shrink compute buffers, not the fp32 master copy; dropping the master copy (pure bf16 training with stochastic rounding or Kahan summation) saves 4 B/param at some stability risk.
How long does a 7B, 1T-token training run take?
Train a 7B dense model on 1 trillion tokens on 256 H100s (989 dense bf16 TFLOP/s each) at 40% MFU. Estimate wall-clock time.
Total FLOPs ≈ 6 × N × tokens = 6 × 7e9 × 1e12 = 4.2e22.
Cluster throughput = 256 × 989e12 × 0.40 ≈ 1.01e17 FLOP/s.
Time = 4.2e22 / 1.01e17 ≈ 4.15e5 s ≈ 115 hours ≈ 4.8 days.
Sanity checks: attention FLOPs add a few per cent at 4k context and much more at 32k+; restarts, evaluation and checkpointing typically add 5–15% wall-clock. Doubling MFU halves cost, which is why kernel and parallelism work pays off at this scale.
Is this op compute- or memory-bound?
Classify (a) a bf16 matmul of two 4096×4096 matrices, (b) GELU over a 4096×4096 bf16 tensor and (c) batch-1 decode through a 4096×4096 bf16 weight, against an H100 ridge point of ~295 FLOPs/byte.
(a) Matmul: FLOPs = 2 × 4096³ ≈ 1.37e11. Bytes ≈ read A, read B, write C = 3 × 4096² × 2 B ≈ 1.01e8. Intensity ≈ 1,365 FLOPs/byte > 295 → compute-bound.
(b) GELU: roughly 10 FLOPs per element, 4 bytes moved per element (2 read, 2 write) → ~2.5 FLOPs/byte → memory-bound; fuse it into the preceding matmul’s epilogue.
(c) Decode GEMV: each 2-byte weight is used for one multiply-add (2 FLOPs) → ~1 FLOP/byte → badly memory-bound; batching B sequences raises it to ~B FLOPs/byte, and INT4 weights cut the bytes.
What changed recently
A production model pretrained in NVFP4
NVIDIA’s Nemotron 3 Super, a 120B-total, 12B-active hybrid Mamba-attention MoE, was pretrained on 25 trillion tokens in NVFP4 and reported up to 2.2× the inference throughput of gpt-oss-120b. Four-bit pretraining has moved from a research recipe to a released model, so ‘FP8 is the lowest practical training precision’ is no longer true.
DeepSeek-V4: efficiency by co-designing attention and training
DeepSeek-V4 (1.6T-total Pro and 284B-total Flash MoE models) uses a hybrid of compressed sparse and heavily compressed attention; at a 1M-token context V4-Pro needs 27% of V3.2’s per-token inference FLOPs and 10% of its KV cache. Long-context cost now falls mainly through architecture, not just hardware, which is why interviewers ask where the FLOPs and bytes of attention go.
gpt-oss ships native MXFP4 weights
OpenAI’s open-weight gpt-oss-120b (117B total, 5.1B active) and gpt-oss-20b were released natively quantised in MXFP4, letting the larger model run within 80 GB and the smaller within 16 GB. Four-bit microscaled formats became a default distribution format, not a post-hoc compression step, so candidates should know how block scaling works and what it costs in accuracy.
Native Sparse Attention wins an ACL 2025 best paper award
DeepSeek’s Native Sparse Attention, which combines compressed coarse blocks, selected fine-grained blocks and a local window with kernels designed around GPU memory access, was one of four ACL 2025 best papers. It showed that sparse attention can be trained end to end and give real speed-ups; DeepSeek’s later production models use sparse attention too (DeepSeek Sparse Attention, applied inside DeepSeek-V4’s compressed sparse attention).
NVFP4: four-bit floating point with fine-grained scales
NVIDIA’s NVFP4 stores E2M1 values in 16-element blocks with an FP8 E4M3 scale per block plus a per-tensor FP32 scale (about 4.5 bits per value), against MXFP4’s 32-element blocks with power-of-two scales; it reported 1% or less accuracy loss quantising DeepSeek-R1 from FP8. Interviewers ask why block size and scale format matter for outliers and how to validate a 4-bit model.
Pitfalls
- Quoting peak FLOPs as achievable throughput and ignoring memory bandwidth.
- Counting only weights in training memory and forgetting gradients, the fp32 master copy and Adam state (the largest term).
- Treating an MoE model’s memory as if it were its active-parameter count.
- Believing FlashAttention approximates attention; it is exact and wins by reducing memory traffic.
- Optimising kernels before profiling, or reading nvidia-smi utilisation as SM occupancy.
- Using fp16 without loss scaling and blaming the optimiser for NaNs.
How interviewers probe it
- Do the 16-bytes-per-parameter accounting for a given model size, then ask how ZeRO stages, checkpointing and 8-bit optimisers change it.
- Explain why GPUs are fast and how you decide whether a kernel is compute- or memory-bound (roofline, arithmetic intensity).
- GPU utilisation is 30% and loss is flat: walk through your investigation.
- How does MoE change memory, compute and communication compared with a dense model of similar quality?
- Given a slow kernel on unfamiliar hardware with explicit memory management, how do you make it faster in a few hours (measure, tile for on-chip memory, vectorise, overlap transfers)?
- What are the transformer’s main efficiency weaknesses and which modifications address each (FlashAttention, GQA, sliding windows, linear-attention or state-space hybrids)?
Quiz
Three questions from this guide. Answer each in your head or out loud, show the model answer, then rate yourself. The cards join your practice deck and come back when they are due.
Roughly how much accelerator memory do weights, gradients and Adam state need for a 70-billion-parameter model trained in mixed precision? Show the accounting and say which precision choices change it.
Model answer, written in a candidate's voice
- bf16 weights 2 B + bf16 grads 2 B + fp32 master 4 B + Adam m/v 8 B = 16 B/param
- 70B params × 16 B = 1.12 TB (≈1.02 TiB), before activations and fragmentation
- bf16 vs fp16: same 2 B size, but fp16 needs loss scaling/range care; bf16 has fp32’s range with less mantissa
- FP8 (≈14 B/param) and 8-bit optimisers (≈10 B/param, ≈8 B with both) reduce parts of the total, but the fp32 master copy often remains
- Sharding (ZeRO/FSDP) divides per-device memory by the data-parallel degree (1.12 TB / 64 ≈ 17.5 GB); cluster total is unchanged
Explain why GPUs accelerate deep learning, and how you decide whether a kernel or model is compute-bound or memory-bound.
Model answer, written in a candidate's voice
- GPUs accelerate deep learning via massive SIMT parallelism, tensor cores for matmuls, and high memory bandwidth.
- Compute arithmetic intensity in FLOPs/byte and compare it to the roofline ridge point.
- Large-batch matmul is compute-bound; elementwise ops and batch-1 LLM decode are memory-bound.
- Raise intensity with kernel fusion, batching, tiling, and efficient data movement; watch host-device transfers and dataloader bottlenecks.
GPU utilisation sits at 30% and loss is not decreasing. How do you investigate?
Model answer, written in a candidate's voice
- Lead with correctness: overfit one batch first; if the model cannot drive that loss down, do not tune throughput yet.
- Check the training loop: zero_grad every step, loss/target shapes and dtypes, no softmax before CrossEntropyLoss, train() vs eval(), LR, shuffling and label correctness.
- Then profile throughput: dataloader workers, pinned memory, CPU-side decoding, host-device syncs such as .item(), small batches, and missing AMP.
- Use the profiler and per-layer gradient norms to separate a data/sync bottleneck from a model/optimisation problem.
You have finished this topic.
Reading
- Making Deep Learning Go Brrrr From First PrinciplesThe clearest framing of compute vs bandwidth vs overhead with practical diagnostics.
- GPU Performance Background User's GuideNVIDIA’s own explanation of arithmetic intensity, ops:byte ratios and operation categories.
- FlashAttention: Fast and Memory-Efficient Exact Attention with IO-AwarenessThe canonical example of winning by cutting memory traffic rather than FLOPs.
- Mixed Precision TrainingOrigin of the fp32 master weights and loss-scaling recipe behind the 16-byte accounting.
- Switch Transformers: Scaling to Trillion Parameter Models with Simple and Efficient SparsityClear treatment of top-1 routing, capacity factors and load balancing in MoE.
- How to Scale Your ModelRead the roofline, transformer-maths and inference chapters for rigorous scaling arithmetic.
- Introducing NVFP4 for Efficient and Accurate Low-Precision InferenceClear explanation of four-bit microscaling formats (NVFP4 versus MXFP4), block scales and the memory and accuracy trade-offs.
- Native Sparse Attention: Hardware-Aligned and Natively Trainable Sparse AttentionTrainable block-sparse attention designed around GPU memory access, with large long-context speed-ups.
Practise this topic
- Roughly how much accelerator memory do weights, gradients and Adam state need for a 70-billion-parameter model trained in mixed precision? Show the accounting and say which precision choices change it.
- Explain why GPUs accelerate deep learning, and how you decide whether a kernel or model is compute-bound or memory-bound.
- GPU utilisation sits at 30% and loss is not decreasing. How do you investigate?
- How does a mixture-of-experts layer work, what problems does routing introduce, and how does MoE change the memory, compute and communication profile compared with a dense model of similar quality?
- You are given a correct but slow kernel for an unfamiliar accelerator with explicitly managed memory and vector units. How do you make it much faster within a few hours?
- What are the main weaknesses of the standard transformer, and which modifications or alternatives address each (compute, memory, context length, reasoning)?
- What does a key–value cache store during autoregressive generation? Give the formula for its memory footprint, explain why decoding is usually memory-bandwidth-bound, and describe how grouped-query or multi-query attention changes this.
- Which inductive biases does a convolution build in, and what changes with a vision transformer? When would you expect each to win, including on-device?
- Roughly how much GPU memory does full fine-tuning of a 7B model with Adam in mixed precision need, compared with LoRA and QLoRA?
- Compare DeepSeek’s Native Sparse Attention and DeepSeek Sparse Attention (in V3.2-Exp). What does each make sparse, where does the speed-up come from, and how would you check that long-context quality survived?
- You are evaluating speculative decoding for production: an EAGLE-3 drafter versus the model’s own multi-token-prediction heads. Which metrics decide it, how does the answer change with batch size and with reasoning workloads, and how do you prove outputs are unchanged?
- Several 2025–2026 open models mix linear-attention layers (for example Gated DeltaNet or Kimi Delta Attention) with a minority of full-attention layers. Explain the design, its training and serving trade-offs, and how you would choose the ratio.
- NVIDIA reported pretraining a 12B model on 10 trillion tokens in NVFP4 with loss and accuracy comparable to FP8. Explain the format, why naive 4-bit training diverges, and the techniques that made it work. Which parts of a training step would you keep in higher precision?
- gpt-oss-120b (117B total, 5.1B active parameters) ships its weights in MXFP4 and runs within 80 GB. Check that claim with arithmetic, then compare MXFP4 with NVFP4 and explain what you would test before serving a model in either format.
- Your product serves a 70B model in FP8 on Hopper GPUs. Leadership asks whether moving to Blackwell with NVFP4 weights will halve the serving cost. Explain what NVFP4 is and how you would answer.
- Explain how EAGLE-3 differs from classic draft-model speculative decoding and from reusing a model’s own multi-token-prediction module, as DeepSeek-V3 does. When would you switch speculation off in production?
- Meta trains one LLM-scale ads foundation model (GEM) but serves hundreds of smaller vertical models under tight latency budgets. Design the knowledge-transfer path from a large recommendation foundation model to a production ranker, and explain how you would know the transfer is actually working.
- You are asked to move a pretraining run from FP8 to NVFP4 on Blackwell GPUs. Explain the NVFP4 format, what can go wrong numerically, and the recipe changes and monitoring you would put in place.
- Compare Native Sparse Attention, DeepSeek Sparse Attention and DeepSeek-V4’s compressed attention. What does each select or compress, what does it cost, how is it trained, and why do these methods train sparsity in rather than applying it to a finished dense model?
- You must halve serving cost for a large model without retraining it from scratch. Discuss quantisation (INT8/FP8/4-bit), speculative decoding and batching: what each buys you and which quality risks you would measure.