LearnTopic guide

Compute and memory efficiency

Efficiency questions ask whether you can reason about where time and memory actually go on an accelerator: FLOPs versus bytes moved versus framework overhead, the memory bill for weights, gradients, optimiser state and activations, and the architectural choices (FlashAttention, mixed precision, MoE, sharding) that change those bills. Interviewers want back-of-envelope arithmetic done out loud, the roofline model applied correctly, and a profiling-first debugging method rather than a list of tricks. The same reasoning underpins training-cost estimates, kernel optimisation and inference serving.

Research · ML engineering · Applied LLM8 key concepts20 questions

Start: Key concepts 6 lessons · about 15 min
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 = 2 × m × k × n

training FLOPs = 6 × parameters × tokens ÷ 10

Worked cases
Casemknparameters (billions)tokens (trillions)matmul FLOPstraining FLOPs
4096 matmul, 7B, 1T tokens4,0964,0964,09671137,438,953,472 FLOPs4.2 × 10²² FLOPs
Change the matmul shape and the model size and token count to see the FLOP cost of a matmul and a dense training run.Diagram drafted by a local AI model (Inkling 2 Mini) from this page's text and drawn from data. Checked by an independent reviewer.

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

  1. bf16 weights cost 2 B per parameter.

  2. bf16 gradients cost 2 B per parameter.

  3. fp32 master weights cost 4 B per parameter.

  4. Adam first and second moments cost 4 B + 4 B per parameter.

  5. The sum is ≈ 16 B per parameter before activations.

The ≈16 B per-parameter bill is built from bf16 weights and gradients, an fp32 master copy and two fp32 Adam moments, before activations.Diagram drafted by a local AI model (Inkling 2 Mini) from this page's text and drawn from data. Checked by an independent reviewer.

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

Profiling-first debugging sequenceA profiler trace feeds simple counters, which branch to four causes: dataloader wait, host-device syncs, kernel launch gaps and communication time. Each cause points to the typical fixes for 30% utilisation.Profiler tracePyTorch profiler, Nsight SystemsCountersstep time splitDataloaderwaitSyncsLaunchgapsCommtimeTypical fixesfor 30% utilisation123MeasureDiagnoseFix
  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.

Start with a profiler trace, read the simple counters, then fix the cause rather than the symptom.Diagram drafted by a local AI model (Inkling 2 Mini) from this page's text and drawn from data. Checked by an independent reviewer.
Data
Steps
StepTitleWhat happens
1ProfileStart with a profiler trace.
2Read countersRead step time split, dataloader wait, host-device syncs, kernel launch gaps and communication time.
3Fix the causeUse more dataloader workers and pinned memory, larger micro-batches, removing syncs, CUDA graphs or torch.compile, and overlapping communication.

Source: This page's text

Boxes
BoxGroupDetail
Profiler traceMeasurePyTorch profiler, Nsight Systems
CountersMeasurestep time split
Dataloader waitDiagnose
SyncsDiagnose
Launch gapsDiagnose
Comm timeDiagnose
Typical fixesFixfor 30% utilisation

Source: This page's text

Next: Worked examples Lesson 3 of 6 · about 3 min

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.

Next: What changed Lesson 4 of 6 · about 2 min

What changed recently

  1. 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.

    Source

  2. 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.

    Source

  3. 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.

    Source

  4. 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).

    Source

  5. 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.

    Source

Next: Pitfalls and interview angles Lesson 5 of 6 · about 2 min

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)?
Next: Quiz Lesson 6 of 6 · about 3 min

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.

  1. Question 1 of 3 · Research · Technical · Medium

    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.

  2. Question 2 of 3 · ML engineering · Technical · Medium

    Explain why GPUs accelerate deep learning, and how you decide whether a kernel or model is compute-bound or memory-bound.

  3. Question 3 of 3 · ML engineering · Technical · Medium

    GPU utilisation sits at 30% and loss is not decreasing. How do you investigate?

Reading

Practise this topic

  1. 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.Research · Technical · Medium
  2. Explain why GPUs accelerate deep learning, and how you decide whether a kernel or model is compute-bound or memory-bound.ML engineering · Technical · Medium
  3. GPU utilisation sits at 30% and loss is not decreasing. How do you investigate?ML engineering · Technical · Medium
  4. 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?Research · Technical · Hard
  5. 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?Research · Technical · Hard
  6. What are the main weaknesses of the standard transformer, and which modifications or alternatives address each (compute, memory, context length, reasoning)?Research · Technical · Medium
  7. 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.Research · Technical · Hard
  8. 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?Research · Technical · Easy
  9. Roughly how much GPU memory does full fine-tuning of a 7B model with Adam in mixed precision need, compared with LoRA and QLoRA?Applied LLM · Technical · Medium
  10. 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?Research · Technical · Hard
  11. 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?Applied LLM · Technical · Hard
  12. 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.Research · Technical · Hard
  13. 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?Research · Technical · Very hard
  14. 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.Research · Technical · Medium
  15. 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.Applied LLM · Technical · Medium
  16. 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?Applied LLM · Technical · Medium
  17. 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.ML engineering · System design · Hard
  18. 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.ML engineering · Technical · Hard
  19. 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?Research · Technical · Hard
  20. 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.Research · System design · Medium

Study material compiled with AI: drafted by a local model (Inkling 2 Mini) from public sources, then checked against those sources by independent AI reviewers (Claude) in November 2026. Not reviewed line by line by a person.