---
title: Compute and memory efficiency
url: https://gurkanozkan.ai/learn/topics/efficiency/
markdown: https://gurkanozkan.ai/learn/topics/efficiency.md
kind: topic
tracks:
  - Research
  - ML engineering
  - Applied LLM
json: https://gurkanozkan.ai/api/learn/topics/efficiency.json
---

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

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

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

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

## 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?

**Solution**

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

**Solution**

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

**Solution**

**(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

- **Apr 2026: 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](https://arxiv.org/abs/2604.12374)
- **Apr 2026: 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](https://arxiv.org/abs/2606.19348)
- **Aug 2025: 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](https://openai.com/index/introducing-gpt-oss/)
- **Jul 2025: 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](https://2025.aclweb.org/program/awards/)
- **Jun 2025: 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](https://developer.nvidia.com/blog/introducing-nvfp4-for-efficient-and-accurate-low-precision-inference/)

## 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)?

## Reading

- [Making Deep Learning Go Brrrr From First Principles](https://horace.io/brrr_intro.html) (Blog, 40 min, Intro): The clearest framing of compute vs bandwidth vs overhead with practical diagnostics.
- [GPU Performance Background User's Guide](https://docs.nvidia.com/deeplearning/performance/dl-performance-gpu-background/index.html) (Docs, 30 min, Core): NVIDIA's own explanation of arithmetic intensity, ops:byte ratios and operation categories.
- [FlashAttention: Fast and Memory-Efficient Exact Attention with IO-Awareness](https://arxiv.org/abs/2205.14135) (Paper, 45 min, Core): The canonical example of winning by cutting memory traffic rather than FLOPs.
- [Mixed Precision Training](https://arxiv.org/abs/1710.03740) (Paper, 30 min, Core): Origin 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 Sparsity](https://arxiv.org/abs/2101.03961) (Paper, 60 min, Deep): Clear treatment of top-1 routing, capacity factors and load balancing in MoE.
- [How to Scale Your Model](https://jax-ml.github.io/scaling-book/) (Book, 180 min, Deep): Read the roofline, transformer-maths and inference chapters for rigorous scaling arithmetic.
- [Introducing NVFP4 for Efficient and Accurate Low-Precision Inference](https://developer.nvidia.com/blog/introducing-nvfp4-for-efficient-and-accurate-low-precision-inference/) (Blog, 12 min, Core): Clear 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 Attention](https://arxiv.org/abs/2502.11089) (Paper, 45 min, Deep): Trainable 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…](https://gurkanozkan.ai/learn/questions/research-memory-arithmetic-for-training-041.md)
- [Explain why GPUs accelerate deep learning, and how you decide whether a kernel or model is compute-bound or memory-bound.](https://gurkanozkan.ai/learn/questions/mle-why-gpus-are-fast-and-compute-vs-memory-bound-workloads-57.md)
- [GPU utilisation sits at 30% and loss is not decreasing. How do you investigate?](https://gurkanozkan.ai/learn/questions/mle-diagnosing-a-slow-or-broken-training-job-59.md)
- [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…](https://gurkanozkan.ai/learn/questions/research-mixture-of-experts-038.md)
- [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…](https://gurkanozkan.ai/learn/questions/research-optimising-a-kernel-045.md)
- [What are the main weaknesses of the standard transformer, and which modifications or alternatives address each (compute, memory, context length, reasoning)?](https://gurkanozkan.ai/learn/questions/research-weaknesses-of-the-transformer-037.md)
- [What does a key–value cache store during autoregressive generation? Give the formula for its memory footprint, explain why decoding is usually…](https://gurkanozkan.ai/learn/questions/research-kv-cache-035.md)
- [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?](https://gurkanozkan.ai/learn/questions/research-cnn-vs-vision-transformers-030.md)
- [Roughly how much GPU memory does full fine-tuning of a 7B model with Adam in mixed precision need, compared with LoRA and QLoRA?](https://gurkanozkan.ai/learn/questions/applied-llm-ft-09.md)
- [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…](https://gurkanozkan.ai/learn/questions/recent-a-eff-01.md)
- [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…](https://gurkanozkan.ai/learn/questions/recent-a-inference-02.md)
- [Several 2025–2026 open models mix linear-attention layers (for example Gated DeltaNet or Kimi Delta Attention) with a minority of full-attention layers…](https://gurkanozkan.ai/learn/questions/recent-a-dl-03.md)
- [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…](https://gurkanozkan.ai/learn/questions/recent-a-dist-01.md)
- [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…](https://gurkanozkan.ai/learn/questions/recent-a-eff-02.md)
- [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…](https://gurkanozkan.ai/learn/questions/recent-b-serving-02.md)
- [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…](https://gurkanozkan.ai/learn/questions/recent-b-serving-03.md)
- [Meta trains one LLM-scale ads foundation model (GEM) but serves hundreds of smaller vertical models under tight latency budgets. Design the knowledge-transfer…](https://gurkanozkan.ai/learn/questions/recent-b-recommendation-03.md)
- [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…](https://gurkanozkan.ai/learn/questions/recent-b-training-02.md)
- [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…](https://gurkanozkan.ai/learn/questions/recent-b-long-context-02.md)
- [You must halve serving cost for a large model without retraining it from scratch. Discuss quantisation (INT8/FP8/4-bit), speculative decoding and batching…](https://gurkanozkan.ai/learn/questions/research-cutting-inference-cost-039.md)
---

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