Skip to content
AI systems and infrastructure Core 30 min read

Compute maths: FLOPs, memory and cost

Every question about training or serving a model — will it fit, how long will it take, what will it cost, why is it slow — reduces to four counts: floating-point operations, bytes held, bytes moved and bytes sent. This page teaches you to do that arithmetic on a napkin, to within a factor that matters, for any transformer.

10,000 ft

The AI boom is, physically, a very large number of multiply-adds paid for in electricity and GPU rental. Scaling laws say how much loss you buy with compute; this page says how much compute, memory and money a given model actually needs. It is the bridge between the architecture pages (what a transformer block computes) and the hardware pages (what a GPU can do per second). The same handful of formulas — \(6ND\) for training, \(2N\) per generated token, 16 bytes per parameter for Adam, \(2\,L\,n_{kv}\,d_h\) values per token of KV cache, and "decode is bandwidth-bound" — explain why labs over-train small models, why quantisation speeds up chat, why serving is a batching problem, and why distributed training has to shard optimiser state. Practitioners who can do this arithmetic make better decisions than those who can only run benchmarks, because they know what the benchmark should say.

2,000 ft

Any workload is described by four quantities, each divided by a matching hardware number:

  1. FLOPs — a matrix product of \((m\times k)\) by \((k\times n)\) costs \(2mkn\). A dense transformer does about \(2N\) FLOPs per token forward and \(6N\) per token in training.
  2. Bytes held — weights, gradients, optimiser state, activations, KV cache. They must fit in device memory (80 GB on an H100), or be sharded.
  3. Bytes moved — every step reads its operands from HBM. Time \(\ge\) bytes / bandwidth.
  4. Bytes on the wire — gradients and activations exchanged between GPUs.
  5. Time is set by whichever of FLOPs/peak, bytes/bandwidth or wire/link is largest; the ratio FLOPs/bytes (arithmetic intensity) tells you which.
  6. Cost is GPU-hours × price, and energy is GPU-hours × power.

From a model to a bill
From a model to a bill. Workload N params · D tokens batch · context, FLOPs 6ND to train 2N per generated token, Bytes held weights, optimiser state, activations, KV cache, Bytes moved HBM reads per step, Bytes on the wire gradients, activations, Hardware sheet FLOP/s · GB · GB/s · link GB/s, Time the slowest of the three, Cost GPU-hours × price, kWh, must fit, divide byFrom a model to a bill. Workload N params · D tokens batch · context, FLOPs 6ND to train 2N per generated token, Bytes held weights, optimiser state, activations, KV cache, Bytes moved HBM reads per step, Bytes on the wire gradients, activations, Hardware sheet FLOP/s · GB · GB/s · link GB/s, Time the slowest of the three, Cost GPU-hours × price, kWh, must fit, divide by

Ground level

The hardware sheet you divide by

You need four numbers per accelerator. For the two GPUs that trained most 2020–2025 frontier models (from NVIDIA's H100 and A100 data sheets):

H100 SXM A100 SXM 80 GB
Dense BF16 tensor-core peak 989 TFLOP/s (the sheet's 1,979 is "with sparsity") 312 TFLOP/s
HBM capacity 80 GB 80 GB
HBM bandwidth 3.35 TB/s 2.04 TB/s
NVLink (per GPU, total) 900 GB/s 600 GB/s
Max power 700 W 400 W

Two warnings that save beginners a factor of two each. Marketing peaks with an asterisk assume 2:4 structured sparsity, which ordinary dense training does not use: halve them. And peaks assume the tensor cores are fed perfectly, which no real model achieves; you will multiply by a utilisation factor below.

The single most useful derived number is the ridge point, peak FLOP/s divided by bandwidth: \(989\times10^{12} / 3.35\times10^{12} \approx 295\) FLOPs per byte on an H100 (153 on an A100). A kernel that does fewer than ~295 FLOPs for every byte it reads from HBM cannot keep the tensor cores busy; it is memory-bound. Above it, compute-bound. This is the roofline model; everything below is applying it.

Counting FLOPs: one multiply-add per weight per token

A matrix product \(C = AB\) with \(A\in\mathbb{R}^{m\times k}\), \(B\in\mathbb{R}^{k\times n}\) has \(mn\) outputs, each a dot product of length \(k\): \(k\) multiplies and \(k-1\) adds, so \(\approx 2mkn\) FLOPs. Convention: one multiply-accumulate (MAC) = 2 FLOPs.

Now put a batch of \(T\) tokens through a linear layer with weight \(W\in\mathbb{R}^{d_{in}\times d_{out}}\): the product \((T\times d_{in})(d_{in}\times d_{out})\) costs \(2\,T\,d_{in}d_{out}\) FLOPs. The layer has \(d_{in}d_{out}\) parameters, so the cost is 2 FLOPs per parameter per token. Every weight in a dense network meets every token exactly once in the forward pass, in one multiply-add. Summing over all layers:

\[ C_{\text{forward}} \approx 2N \ \text{FLOPs per token}. \]

Everything that is not a matmul — layer norms, softmax, activations, residual adds — is \(O(d)\) per token rather than \(O(d^2)\), so it is a rounding error in FLOPs (but, as you will see, not in bytes moved).

Counting parameters of a transformer

A standard block with model width \(d\) has four attention projections (\(W_Q, W_K, W_V, W_O\), each \(d\times d\), so \(4d^2\)) and an MLP of two \(d\times 4d\) matrices (\(8d^2\)): \(12d^2\) per layer, so \(N \approx 12\,L\,d^2\) non-embedding parameters for \(L\) layers. GPT-3 175B has \(L=96\), \(d=12{,}288\): \(12\times96\times12288^2 = 1.74\times10^{11}\). The formula recovers the headline number to within 1%.

Modern models change the constants but not the method. Llama 3 8B (Llama 3 paper) has \(L=32\), \(d=4096\), 32 query heads but only 8 key/value heads (grouped-query attention, so \(W_K, W_V\) are \(4096\times1024\)), a SwiGLU MLP with three \(4096\times14336\) matrices, and a 128,256-token vocabulary with separate input and output embeddings. The calculator in Build it counts it as 8.03 B parameters (6.98 B of them outside the embeddings), matching the published count.

Training costs 6N per token

The backward pass needs, for every weight matrix, two matmuls of the same size as the forward one: the gradient with respect to the layer's input (to keep backpropagating) and the gradient with respect to the weight (to update it). So backward ≈ \(2\times\) forward ≈ \(4N\), and

\[ C_{\text{train}} \approx 6\,N\,D \quad\text{FLOPs for } D \text{ training tokens.} \]

Check it against published numbers:

  • GPT-3: \(6\times175\times10^9\times300\times10^9 = 3.15\times10^{23}\); the paper reports \(3.14\times10^{23}\) (Brown et al. 2020, Appendix D).
  • Llama 3 405B: \(6\times405\times10^9\times15.6\times10^{12} = 3.79\times10^{25}\); the paper says "3.8 × 10²⁵ FLOPs".

The formula is reliable enough that Epoch AI uses it — alongside GPU-time × utilisation — to estimate the compute of models whose labs publish only parameter and token counts.

When 6N is wrong: the attention term

\(2N\) counts weight matmuls. Attention also multiplies activations by activations: the scores \(QK^\top\) and the weighted sum \(AV\). One query attending to \(s\) earlier positions costs \(2sd\) FLOPs for the scores and \(2sd\) for the sum, \(4sd\) per layer. With causal masking the average token sees \(s = n_{ctx}/2\) positions, giving the extra forward cost

\[ C_{\text{attn}} \approx 2\,L\,n_{ctx}\,d \quad\text{FLOPs per token} \]

which is the term in Kaplan et al. (2020), Table 1. Relative to \(2N \approx 24Ld^2\) it is \(n_{ctx}/(12d)\): negligible when the context is short compared with \(12d\), dominant when it is not. For Llama 3 405B (\(L=126\), \(d=16{,}384\)) it adds 4% at an 8,192-token context and 67% at 131,072. That is why long-context training stages are so expensive per token, and why FlashAttention matters: it does not cut these FLOPs, but it stops them from also being memory-bound.

From FLOPs to days: utilisation

Real training reaches a fraction of peak. The standard measure, introduced in the PaLM paper, is model FLOPs utilisation:

\[ \text{MFU} = \frac{\text{tokens per second} \times 6N}{\text{number of chips} \times \text{peak FLOP/s}}. \]

It counts only the FLOPs the model needs, so recomputing activations (which burns real FLOPs) does not inflate it; the inflated version is hardware FLOPs utilisation (HFU). PaLM 540B reached 46.2% MFU (57.8% HFU) on TPU v4. Llama 3 405B reports 38–43% BF16 MFU on 8,192–16,384 H100s, i.e. 380–430 TFLOP/s per GPU (Llama 3 paper, §3.3). A well-tuned large dense run lands at 35–50%; a small model on many GPUs, or a poorly overlapped pipeline, much lower.

Worked example, Llama 3 405B:

\[ \text{GPU-hours} = \frac{3.8\times10^{25}}{989\times10^{12}\times0.40\times3600} \approx 26.6\ \text{M}, \qquad \frac{26.6\text{ M}}{16{,}384\times24} \approx 68\ \text{days}. \]

Meta's model card reports 30.84 M H100 GPU-hours for the 405B model. Our estimate is 14% low, and the gap is instructive. The card does not itemise its total, but a real run includes things the ideal formula omits: stages at lower utilisation (the 128k-context stage ran at 38% MFU), lost work and restarts after the 419 unexpected interruptions the paper logs in one 54-day window, and time not spent training. \(6ND/\text{MFU}\) is the ideal. For the 8B model the gap is larger: the same formula gives 0.51 M GPU-hours at 40% MFU, the card says 1.46 M. Small models on large clusters run at lower utilisation. Treat \(6ND/(\text{peak}\times\text{MFU})\) as a lower bound and expect a 1.2–3× overhead in practice.

From days to dollars and kilowatt-hours

\[ \text{cost} = \text{GPU-hours}\times\text{price per GPU-hour},\qquad \text{energy} \approx \text{GPU-hours}\times P_{\text{GPU}}\times\text{PUE}. \]

Prices move monthly and differ by contract length, so this site never quotes one as fact; plug in your own quote. At an assumed USD 2 per H100-hour, 30.84 M GPU-hours is about USD 62 M of compute for the final 405B run — and frontier labs typically spend several times the final run on experiments, ablations and failed attempts. Energy: \(30.84\,\text{M}\times700\,\text{W} \approx 21.6\) GWh at the GPUs' rated power, before host CPUs, networking and cooling (the data-centre PUE, typically 1.1–1.4). The model card's location-based emissions for the 405B run are 8,930 tCO₂eq; Patterson et al. (2021) explain why the same FLOPs can differ ~100× in carbon depending on hardware, data centre and grid.

How big should the model be? Compute-optimal and over-trained

Fix the compute \(C = 6ND\). A bigger model sees fewer tokens. The Chinchilla paper fitted loss as a function of \(N\) and \(D\) and found the optimum scales both roughly as \(\sqrt{C}\), with \(D/N \approx 20\) tokens per parameter. Substituting \(D = 20N\) into \(C = 6ND\):

\[ N^\star \approx \sqrt{C/120},\qquad D^\star \approx 20N^\star. \]

At \(C=10^{23}\) that is a 29 B model on 0.58 T tokens; at Llama 3 405B's \(3.8\times10^{25}\), a 563 B model on 11 T tokens. Meta chose 405 B on 15.6 T — close to compute-optimal. But Llama 3 8B saw ~15 T tokens, about 1,900 tokens per parameter, nearly 100× "optimal". That is not a mistake: compute-optimal minimises training cost for a given loss, while a model that will serve billions of tokens should minimise training plus inference cost, which favours a smaller model trained much longer (Sardana et al. 2023). Every token the 8B model generates costs \(2\times8\times10^9\) FLOPs instead of \(2\times70\times10^9\).

Memory for training: 16 bytes per parameter, plus activations

With mixed-precision Adam (ZeRO paper, §3), each parameter carries:

Item Precision Bytes
Weight (for compute) BF16 2
Gradient BF16 2
Master weight FP32 4
Adam first moment \(m\) FP32 4
Adam second moment \(v\) FP32 4
Total 16

A 70 B model therefore needs 1.12 TB of model state before a single activation is stored: fourteen 80 GB GPUs just to hold it. This number is the reason ZeRO/FSDP exists — see distributed training — and why LoRA is so popular for fine-tuning (frozen weights carry no gradients or Adam state).

Activations are what the backward pass needs from the forward pass. Korthikanti et al. (2022, §4) count, for one transformer layer in 16-bit with sequence length \(s\), micro-batch \(b\), width \(h\) and \(a\) heads:

\[ \text{activation bytes per layer} = s\,b\,h\left(34 + 5\,\frac{a\,s}{h}\right). \]

The \(34\,sbh\) comes from the inputs saved for each linear layer, the norms, GELU and dropout masks; the \(5as^2b\) is the attention score and softmax matrices, quadratic in \(s\). For a 70 B-like layer (\(h=8192\), \(a=64\)) at \(s=4096\), \(b=1\): 6.5 GB per layer, 521 GB over 80 layers — more than the model state. Two standard remedies: never materialise the \(s\times s\) matrices (FlashAttention recomputes them in the backward pass, which removes the \(5as/h\) term), and activation checkpointing, which stores only each layer's input and recomputes the rest, trading roughly one extra forward pass (+33% FLOPs) for most of the memory.

Memory for inference: weights plus the KV cache

Serving needs the weights (\(N\times\) bytes per weight: 2 in BF16, ~0.5 in 4-bit) and, for every sequence in flight, the KV cache: each layer's keys and values for every past token, so attention need not recompute them (KV cache page). Per token:

\[ \text{KV bytes per token} = 2 \times L \times n_{kv} \times d_{head} \times \text{bytes}. \]
Model (BF16 cache) \(L\) \(n_{kv}\) per token 8k sequence 128k sequence
Llama 3 8B 32 8 128 KiB 1.0 GiB 16 GiB
Llama 3 70B 80 8 320 KiB 2.5 GiB 40 GiB
Llama 3 405B 126 8 504 KiB 3.9 GiB 63 GiB

With full multi-head attention (64 KV heads) the 70B would need 2,560 KiB per token, eight times more; grouped-query attention is a memory decision as much as a modelling one. The KV cache, not the weights, is what limits how many users one GPU can serve at long context — the problem PagedAttention attacks.

Decode is a bandwidth problem

Generating one token for each of \(B\) sequences needs \(2NB\) FLOPs, but it must read every weight from HBM once (\(2N\) bytes in BF16) plus each sequence's KV cache. Arithmetic intensity is therefore about

\[ \frac{2NB}{2N} = B \ \text{FLOPs per byte (ignoring the cache)}, \]

and the ridge is ~295. At batch 1 the tensor cores idle 99% of the time, and the step time is simply bytes divided by bandwidth: for Llama 3 8B on an H100, \(16.1\text{ GB}/3.35\text{ TB/s} \approx 4.8\) ms, an upper bound of ~200 tokens/s for a single user, regardless of FLOPs.

One decode step: every weight is read once and used B times
One decode step: every weight is read once and used B times. HBM weights 2N bytes + KV cache B·s·k bytes, Tensor cores 2N·B FLOPs, B new tokens, bytes / bandwidth, FLOPs / peak, intensity ≈ B FLOP per byte H100 ridge ≈ 295 → decode is memory-bound until B is in the hundredsOne decode step: every weight is read once and used B times. HBM weights 2N bytes + KV cache B·s·k bytes, Tensor cores 2N·B FLOPs, B new tokens, bytes / bandwidth, FLOPs / peak, intensity ≈ B FLOP per byte H100 ridge ≈ 295 → decode is memory-bound until B is in the hundreds

Batching amortises the weight reads: 64 sequences cost barely more time per step than one. But each sequence also brings its own KV cache, which is read in full every step and is not amortised. The figure plots the model from Build it for Llama 3 8B at a 4,096-token context on one H100.

02,5005,0000125250 1326496112batch size (sequences decoded together) total tokens/s (left axis)tokens/s per sequence (right axis)
Bandwidth-only model of Llama 3 8B (BF16 weights and cache, 4,096-token context) on one H100. Batch 1: 202 tokens/s. Batch 64: 4,252 tokens/s in total but 66 per user, because each step now reads 34 GB of KV cache on top of 16 GB of weights. Real engines land below these bounds; the shape is what matters.

Prefill — processing the prompt — is the opposite: all \(s\) prompt tokens go through each weight matrix at once, so intensity is about \(s\) and a 2,000-token prompt is comfortably compute-bound. Time to first token ≈ \(2Ns/(\text{peak}\times\text{MFU})\): for the 8B model and a 2,000-token prompt at 50% utilisation, \(2\times8\times10^9\times2000/(0.5\times989\times10^{12}) \approx 65\) ms. This prefill/decode asymmetry drives the whole design of LLM serving.

Bytes on the wire

When work is split over GPUs, data must move between them. The workhorse collective is the ring all-reduce: each of \(p\) GPUs ends with the sum of everyone's buffer of \(M\) bytes, and each sends and receives

\[ 2\,\frac{p-1}{p}\,M \ \text{bytes}, \]

independent of \(p\) for large \(p\). In data-parallel training \(M\) is the gradient: \(2N\) bytes in BF16. For an 8 B model that is 32 GB moved per GPU per step; at an effective 400 GB/s it costs 80 ms, which must hide behind the backward pass. Tensor parallelism exchanges activations twice per layer and needs NVLink-class bandwidth; pipeline parallelism sends only boundary activations but creates idle "bubbles". The trade-offs are the subject of distributed training; the point here is that the wire is a fourth budget with its own roofline.

What a million tokens costs to serve

Serving cost per token is GPU price divided by throughput. With the bandwidth model above, one H100 decoding Llama 3 8B at batch 64 produces ~4,250 tokens/s, so at an assumed USD 2/GPU-hour,

\[ \frac{2}{3600\times4250}\times10^6 \approx \text{USD } 0.13 \text{ per million output tokens}, \]

a floor that real systems approach within 2–3× once prefill, idle capacity and scheduling overheads are counted. Quantising weights to 4 bits cuts the weight bytes by 4×; the cache still dominates at long context — which is why providers price long prompts and cached prefixes separately.

First principles

Why 2 FLOPs per parameter per token. A dense layer is a bilinear map: each output is a sum of products of one weight and one input. Each weight participates in exactly one product per token, and each product is followed by one addition. Nothing about depth, width or architecture changes this; only weight sharing breaks it (a convolution reuses each weight at every spatial position, which is why CNN FLOPs are not \(2N\) per image), and so does sparsity (mixture of experts uses only the active parameters, so the rule becomes \(2N_{\text{active}}\)).

Why the backward pass is twice the forward. For \(Y = XW\) with upstream gradient \(G = \partial \mathcal{L}/\partial Y\), the chain rule gives \(\partial\mathcal{L}/\partial X = GW^\top\) and \(\partial\mathcal{L}/\partial W = X^\top G\). Each is a matmul with the same three dimensions as \(XW\), so each costs the same FLOPs. Hence forward : backward = 1 : 2. (The first layer does not need \(\partial\mathcal{L}/\partial X\), and frozen layers do not need \(\partial\mathcal{L}/\partial W\) — which is why LoRA fine-tuning costs closer to \(4N\) than \(6N\) per token.)

Why decode cannot be fixed by a faster chip alone. Peak FLOP/s has grown faster than HBM bandwidth for a decade, so ridge points keep rising (A100 153, H100 295). A workload whose intensity is set by the batch size falls further below the ridge every generation. The only levers are: increase intensity (batch more sequences, decode several tokens per weight read with speculative decoding), or move fewer bytes (quantised weights, smaller KV cache via GQA/MLA or cache quantisation).

Why bytes matter even when FLOPs are tiny. Element-wise operations do \(O(1)\) FLOPs per element read, intensity ~0.25–1, hundreds of times below the ridge. In an unfused transformer they take a share of runtime far out of proportion to their FLOPs — Ivanov et al. (2020) measured this on BERT and titled the paper Data Movement Is All You Need. Kernel fusion (one kernel that reads once, does several operations, writes once) is the fix; see kernels.

Why everything is a lower bound. Each formula here assumes perfect overlap and full utilisation of one resource. Reality adds launch overheads, communication that does not hide, load imbalance and failures. The useful habit is to compute the bound first, measure second, and treat the ratio as a diagnosis: 80% of the bandwidth bound in decode is excellent, 20% means something is wrong.

The maths

Matmul intensity. For \(C = AB\) with \(A\) \(m\times k\), \(B\) \(k\times n\) in \(b\)-byte numbers, reading both inputs and writing the output once moves \(b(mk + kn + mn)\) bytes for \(2mkn\) FLOPs:

\[ I = \frac{2mkn}{b\,(mk+kn+mn)}. \]

For square \(n\times n\times n\) in BF16, \(I = 2n^3/(2\cdot3n^2) = n/3\): an H100 needs \(n \gtrsim 900\) to reach its ridge. For a linear layer applied to \(T\) tokens (\(m = T\), \(k = d_{in}\), \(n = d_{out}\), with \(T \ll d\)), \(I \approx 2Td_{in}d_{out}/(2d_{in}d_{out}) = T\): intensity equals the number of tokens in flight. That one line is the decode result.

Derivation: the transformer parameter and FLOP count

Take \(L\) layers, width \(d\), MLP width \(4d\), vocabulary \(V\), context \(n_{ctx}\); ignore biases and norms (\(O(Ld)\)).

Attention: \(W_Q, W_K, W_V \in \mathbb{R}^{d\times d}\) and \(W_O\in\mathbb{R}^{d\times d}\) give \(4d^2\). MLP: \(W_1\in\mathbb{R}^{d\times4d}\), \(W_2\in\mathbb{R}^{4d\times d}\) give \(8d^2\). So \(N = 12Ld^2\) (non-embedding), plus \(Vd\) for the embedding.

Forward FLOPs per token: each of those weights contributes 2, giving \(24Ld^2 = 2N\). The output projection to logits adds \(2Vd\) (Kaplan et al. keep it separate, since it does not grow with depth). Attention scores and the value sum add \(2Ln_{ctx}d\) under causal masking, as derived above. So

\[ C_{\text{fwd}} = 2N + 2Vd + 2Ln_{ctx}d,\qquad \frac{2Ln_{ctx}d}{2N} = \frac{n_{ctx}}{12d}. \]

For GQA with \(n_{kv}\) key/value heads of size \(d_h\), replace \(2d^2\) (for \(W_K, W_V\)) by \(2d\,n_{kv}d_h\); for a SwiGLU MLP of width \(d_{ff}\), replace \(8d^2\) by \(3d\,d_{ff}\). Training multiplies the matmul terms by 3 (one forward + two backward matmuls).

Derivation: why compute-optimal N grows as a power of C

Hoffmann et al. model loss as \(L(N,D) = E + A N^{-\alpha} + B D^{-\beta}\). Minimise subject to \(6ND = C\). Substituting \(D = C/(6N)\):

\[ L(N) = E + AN^{-\alpha} + B\left(\tfrac{6N}{C}\right)^{\beta}. \]

Setting \(dL/dN = 0\): \(\alpha A N^{-\alpha-1} = \beta B\,6^\beta C^{-\beta}N^{\beta-1}\), so

\[ N^\star = G\left(\tfrac{C}{6}\right)^{\frac{\beta}{\alpha+\beta}},\quad D^\star = G^{-1}\left(\tfrac{C}{6}\right)^{\frac{\alpha}{\alpha+\beta}},\quad G = \left(\tfrac{\alpha A}{\beta B}\right)^{\frac{1}{\alpha+\beta}}. \]

With \(\alpha\approx\beta\) both exponents are ≈ 0.5: double the compute, multiply both \(N\) and \(D\) by \(\sqrt2\). The ratio \(D^\star/N^\star\) is then roughly constant — the "20 tokens per parameter" rule. It is fragile: with Hoffmann's published fit (\(\alpha=0.339\), \(\beta=0.285\)) the ratio drifts from 34 at \(10^{21}\) FLOPs to 85 at \(3.8\times10^{25}\); with Besiroglu et al.'s (2024) refit of the same data it stays near 17–22 (computed in Build it). Use 20 as a planning number, not a law.

Memory–time identity for decode. With \(W\) bytes of weights, \(k\) bytes of KV per token, \(B\) sequences at context \(s\), bandwidth \(\beta\) and peak \(P\):

\[ t_{\text{step}} \ge \max\left(\frac{W + Bsk}{\beta},\ \frac{2NB}{P}\right),\qquad \text{throughput} = \frac{B}{t_{\text{step}}}. \]

As \(B\to\infty\) with the memory term dominant, throughput → \(\beta/(sk)\): the cache, not the model, sets the ceiling. For the 8B at \(s=4096\), \(\beta/(sk) = 3.35\times10^{12}/(4096\times131072) \approx 6{,}240\) tokens/s, which the curve above approaches.

Checkpointing interval (used in MLOps). If a checkpoint takes \(\delta\) seconds and failures arrive at rate \(1/M\), the expected waste per unit time is \(\delta/\tau + \tau/(2M)\); minimising over \(\tau\) gives Young's interval \(\tau^\star = \sqrt{2\delta M}\).

Build it

NumPy, no frameworks: a calculator for parameters, training compute and cost, KV cache and decode throughput. Hardware numbers are the dense data-sheet figures above; the price is an assumption you should replace.

import numpy as np

GPU = {"H100-SXM": dict(flops=989e12, bw=3.35e12, mem=80e9),   # dense BF16, HBM3
       "A100-SXM": dict(flops=312e12, bw=2.039e12, mem=80e9)}

def params(L, d, V, d_ff=None, kv_heads=None, heads=None, gated=False):
    """Parameter count of a decoder-only transformer (no biases)."""
    d_ff = d_ff or 4 * d
    d_kv = d if kv_heads is None else d * kv_heads // heads
    attn = d * d * 2 + 2 * d * d_kv               # W_q, W_o, W_k, W_v
    mlp = (3 if gated else 2) * d * d_ff          # SwiGLU has three matrices
    return L * (attn + mlp), V * d                # (non-embedding, embedding)

def train(N, D, gpu="H100-SXM", n_gpu=1024, mfu=0.40, usd_per_gpu_hour=2.0):
    C = 6 * N * D
    gpu_h = C / (GPU[gpu]["flops"] * mfu) / 3600
    return dict(C=C, gpu_hours=gpu_h, days=gpu_h / n_gpu / 24,
                usd=gpu_h * usd_per_gpu_hour, state_GB=16 * N / 1e9)

def kv_bytes_per_token(L, kv_heads, d_head, bytes_=2):
    return 2 * L * kv_heads * d_head * bytes_

def decode(N, kv_tok, ctx, batch, gpu="H100-SXM", w_bytes=2):
    g = GPU[gpu]
    t_mem = (N * w_bytes + batch * ctx * kv_tok) / g["bw"]   # read weights once + every KV
    t_cmp = batch * 2 * N / g["flops"]
    t = max(t_mem, t_cmp)
    return dict(ms=1e3 * t, tok_s_seq=1 / t, tok_s_total=batch / t,
                bound="memory" if t_mem > t_cmp else "compute",
                mem_GB=(N * w_bytes + batch * ctx * kv_tok) / 1e9)

# Llama 3 8B: 32 layers, d=4096, 32 heads, 8 KV heads, d_ff=14336, vocab 128256
ne, emb = params(32, 4096, 128256, d_ff=14336, kv_heads=8, heads=32, gated=True)
N = ne + 2 * emb                                   # untied input and output embeddings
print(f"Llama-3-8B params: {N/1e9:.2f} B (non-embedding {ne/1e9:.2f} B)")
r = train(N, 15e12, n_gpu=1024)
print(f"train 15T tokens: C={r['C']:.2e} FLOPs, {r['gpu_hours']/1e6:.2f} M GPU-h, "
      f"{r['days']:.0f} days on 1024 GPUs, USD {r['usd']/1e6:.1f} M, states {r['state_GB']:.0f} GB")
kv = kv_bytes_per_token(32, 8, 128)
print(f"KV cache: {kv/1024:.0f} KiB/token, {kv*8192/2**30:.1f} GiB per 8k sequence")
for b in (1, 16, 64, 128):
    r = decode(N, kv, ctx=4096, batch=b)
    print(f"batch {b:4d}: {r['ms']:6.2f} ms/step  {r['tok_s_seq']:6.1f} tok/s/seq "
          f"{r['tok_s_total']:7.0f} tok/s total  {r['mem_GB']:5.1f} GB  {r['bound']}")
r = decode(N, kv, ctx=4096, batch=64)
print(f"USD per 1M output tokens at USD 2/GPU-h, batch 64: {2.0/3600/r['tok_s_total']*1e6:.3f}")

Output:

Llama-3-8B params: 8.03 B (non-embedding 6.98 B)
train 15T tokens: C=7.23e+23 FLOPs, 0.51 M GPU-h, 21 days on 1024 GPUs, USD 1.0 M, states 128 GB
KV cache: 128 KiB/token, 1.0 GiB per 8k sequence
batch    1:   4.95 ms/step   201.8 tok/s/seq     202 tok/s total   16.6 GB  memory
batch   16:   7.36 ms/step   135.9 tok/s/seq    2174 tok/s total   24.6 GB  memory
batch   64:  15.05 ms/step    66.4 tok/s/seq    4252 tok/s total   50.4 GB  memory
batch  128:  25.31 ms/step    39.5 tok/s/seq    5058 tok/s total   84.8 GB  memory
USD per 1M output tokens at USD 2/GPU-h, batch 64: 0.131

Batch 128 needs 84.8 GB and does not fit on one 80 GB card — the calculator tells you before the out-of-memory error does. The second snippet finds the compute-optimal model size under the two published fits of the Chinchilla loss surface by brute-force search:

import numpy as np
fits = {"Hoffmann 2022": (1.6934, 406.4, 410.7, 0.3392, 0.2849),
        "Besiroglu 2024": (1.8172, 482.01, 2085.43, 0.3478, 0.3658)}
for C in (1e21, 1e23, 3.8e25):
    for name, (E, A, B, a, b) in fits.items():
        N = np.logspace(7, 13, 200001)
        D = C / (6 * N)
        L = E + A / N**a + B / D**b
        i = L.argmin()
        print(f"C={C:.0e} {name:15s} N*={N[i]/1e9:8.1f} B  D*={D[i]/1e12:7.2f} T  D/N={D[i]/N[i]:6.1f}  L={L[i]:.3f}")
C=1e+21 Hoffmann 2022   N*=     2.2 B  D*=   0.08 T  D/N=  34.0  L=2.295
C=1e+21 Besiroglu 2024  N*=     2.8 B  D*=   0.06 T  D/N=  21.6  L=2.306
C=1e+23 Hoffmann 2022   N*=    18.1 B  D*=   0.92 T  D/N=  50.7  L=1.988
C=1e+23 Besiroglu 2024  N*=    29.4 B  D*=   0.57 T  D/N=  19.2  L=2.032
C=4e+25 Hoffmann 2022   N*=   272.9 B  D*=  23.21 T  D/N=  85.1  L=1.811
C=4e+25 Besiroglu 2024  N*=   618.7 B  D*=  10.24 T  D/N=  16.5  L=1.892

Same paper's data, two fits, a 2× disagreement about the optimal size of a frontier model. The loss differences at the optimum are small, which is exactly why the optimum is hard to pin down: the valley is flat.

Things to try

  • Add Llama 3 70B (\(L=80\), \(d=8192\), 64 heads, 8 KV heads, \(d_{ff}=28{,}672\)) and check you get ~70.6 B parameters. How many H100s does it need for weights alone in BF16? In 4-bit?
  • Set w_bytes=0.5 (4-bit weights) in decode and rerun. Which batch sizes benefit most, and why does the gain shrink as the batch grows?
  • Add a prefill function and compute time-to-first-token for 500, 8,000 and 100,000-token prompts, including the attention term \(2Ln_{ctx}d\). Where does attention start to dominate?
  • Estimate MFU from a real measurement: if your training loop reports tokens/s, MFU is tok_s * 6 * N / (n_gpu * peak). Karpathy's GPT-2 reproduction video does exactly this.
  • Price a fine-tune: 8 B with LoRA on 100 M tokens at \(4N\) per token, 30% MFU, on one A100.

In practice

  • Measure MFU, not "GPU utilisation". nvidia-smi's utilisation is the fraction of time any kernel was running; a memory-bound kernel at 5% of peak reports 100%. MFU (or achieved bandwidth for decode) is the honest number.
  • Budget memory top-down: model state (16 B/param, or sharded), then activations (pick micro-batch and checkpointing to fit), then fragmentation headroom (~10%). For inference: weights, then KV cache for (concurrent sequences × context), then activations for the largest prefill chunk.
  • Overheads are real. Budget 1.2–3× the ideal GPU-hours, as the Llama 3 model-card comparison shows; a frontier lab's total compute is a multiple of its final run.
  • Tokens per parameter is a business decision. Compute-optimal is for research comparisons; a product model is trained far past it because inference dominates lifetime cost.

Common misconceptions

\"A 70 B model needs 70 GB.\"

Only in 8-bit, and only for the weights. BF16 needs 140 GB; training with Adam needs 1.12 TB of state plus activations; serving needs weights plus a KV cache that can exceed the weights at long context.

\"Twice the TFLOP/s means twice the tokens per second.\"

For decode at small batch, tokens/s tracks memory bandwidth, not FLOP/s. A chip with more FLOP/s and the same bandwidth generates no faster.

\"Attention is quadratic, so it dominates cost.\"

Only when \(n_{ctx}\) is comparable to \(12d\). For a large model at a few thousand tokens the MLP and projections dominate FLOPs; attention's quadratic memory traffic was the bigger problem, and FlashAttention solved most of it.

Check yourself

A dense model has 13 B parameters. How many FLOPs does it take to train on 2 T tokens, and how many H100-days at 45% MFU?

\(6\times13\times10^9\times2\times10^{12} = 1.56\times10^{23}\) FLOPs. Per H100-day at 45% MFU: \(989\times10^{12}\times0.45\times86400 = 3.85\times10^{19}\). So ~4,050 H100-days — about 16 days on 256 GPUs, before overheads.

Why does a forward pass cost 2N FLOPs per token but a CNN's forward pass does not cost 2N per image?

In a dense layer each weight is used once per token. A convolution kernel is reused at every spatial position, so each weight participates in \(H\times W\) multiply-adds per image. Weight sharing breaks the one-use-per-token assumption; the rule becomes 2 × (weights × reuse).

Llama 3 70B in BF16 on an H100-class system: what is the KV cache for 32 concurrent 8k-token conversations, and how does it compare with the weights?

320 KiB/token × 8,192 tokens × 32 = 80 GiB (≈ 86 GB): smaller than the 141 GB of weights but in the same league. At 32k tokens each it would be 320 GiB, more than twice the weights. Long context turns serving into a KV-cache problem.

What is the arithmetic intensity of decoding at batch 16 in BF16, and roughly what fraction of an H100's peak can it use?

About 16 FLOPs per byte of weights (less once the KV cache is counted). The ridge is ~295, so at most 16/295 ≈ 5% of peak. The rest of the time the tensor cores wait for HBM.

Why is MFU defined with 6N per token even when you use activation checkpointing?

Checkpointing recomputes the forward pass during backward, executing ~8N FLOPs per token. Counting those would reward wasted work. MFU counts only the FLOPs the model mathematically requires, so it compares systems fairly; HFU counts what the hardware actually executed.

Hard: show that for a fixed compute budget, a model trained at 10× compute-optimal tokens per parameter can be cheaper overall. What do you need to know?

Lifetime cost = \(6ND\) (training) + \(2N\cdot T_{\text{inf}}\) (inference tokens). Shrinking \(N\) below \(N^\star\) and raising \(D\) to recover the same loss costs extra training FLOPs (the loss valley is flat, so not many), but every inference token gets cheaper in proportion to \(N\). If \(T_{\text{inf}}\) is comparable to or larger than \(D\), the inference saving dominates. You need the loss surface \(L(N,D)\) near the optimum and the expected inference volume — exactly the analysis in Sardana et al.

Hard: in a ring all-reduce of M bytes over p GPUs, why is per-GPU traffic 2(p−1)M/p rather than growing with p?

The buffer is split into \(p\) chunks. In the reduce-scatter phase, \(p-1\) steps each pass one chunk (\(M/p\)) to the neighbour while accumulating, after which each GPU owns one fully summed chunk. The all-gather phase circulates those in another \(p-1\) steps. Total sent per GPU: \(2(p-1)M/p\), bounded by \(2M\). Bandwidth-optimal; latency grows with \(p\), which is why large clusters use trees or hierarchical rings.

Go deeper

Papers

Videos and lectures

Articles and blog posts

Courses and books

Code

Where this leads

  • How a GPU works — where the peak FLOP/s and bandwidth numbers come from, and the roofline in detail.
  • Distributed training — what to do when 16 bytes per parameter does not fit, and how the wire budget is spent.
  • Quantisation — the most direct way to cut bytes held and bytes moved.
  • Serving LLMs — batching, KV-cache management and speculative decoding as answers to the decode roofline.
  • Scaling laws — what the compute buys.