Pidoku

Training vs Inference: The Math

Module 10 Lesson 10.j 45 min Difficulty 2/5

Prerequisites 10.d, 10.i, 1.b


Before you start: words you need#

WordPlain meaning
PThe number of parameters (weights) in the model: 8 billion for an 8B model.
Forward passRunning inputs through the model to get outputs. The only thing inference does.
Backward passWorking out, for every weight, how the loss would change if that weight changed (the gradient). Training only.
LossOne number saying how wrong the model’s prediction was. Training tries to make it smaller.
Optimizer stateExtra numbers the training algorithm keeps per weight. Adam, the usual optimizer, keeps two: a running average of gradients (m) and of squared gradients (v).
ActivationsThe intermediate results inside the model during a forward pass. Training must keep them for the backward pass; inference can throw them away.

1. What is it?#

A precise accounting, in FLOPs and bytes, of what training does that inference does not. Lesson 1.b gave the operational differences; this lesson gives the arithmetic behind the two numbers everyone quotes: 6P FLOPs per token to train, 2P to serve, and 16 bytes per parameter to train, 1–2 to serve.


2. Why does it exist?#

Because the “3x rule” (the backward pass costs twice the forward) and the “16 bytes per parameter” rule come up in every capacity discussion. If you can derive them, you can also tell when someone has used a training number to size an inference cluster, which is a common and expensive mistake.


3. Simple analogy#

Building a road versus driving on it. Driving (inference) goes along the route once. Building (training) means surveying the route, laying it, then walking back along it to check and adjust every segment: roughly three passes for every one the driver makes, and a lot more equipment parked along the way (gradients, optimizer state, stored activations).


4. Tiny example#

Take one layer, y = W x, where W is an M × K matrix and x a vector of length K. One multiply-add is 2 FLOPs, so the forward pass is 2·M·K. Training needs two more products of the same size:

FORWARD:
  y = W x                          FLOPs: 2·M·K  (for W: M×K, x: K)

BACKWARD (two things needed):
  dL/dx = Wᵀ (dL/dy)               FLOPs: 2·M·K   ← to propagate to earlier layers
  dL/dW = (dL/dy) xᵀ               FLOPs: 2·M·K   ← to update this layer

  Total backward: 4·M·K = 2× forward

Hence:

Training step ≈ 3 × forward pass       (1 forward + 2 backward)
FLOPs per token, training ≈ 6P
FLOPs per token, inference ≈ 2P

Every weight takes part in one multiply-add per token going forward, which is where 2P comes from, and in two more going backward. That is the whole derivation of the two most-quoted numbers in the field: 6P for training, 2P for inference.

A worked check for an 8B model generating 1,000 tokens: 2 × 8×10⁹ × 1,000 = 1.6×10¹³ FLOPs, about 16 milliseconds of an H100’s peak BF16 compute. Real decode takes far longer than that, because it is waiting on memory, not arithmetic (2.e).


5. Technical explanation#

Memory accounting for training#

Weights (BF16)              2P
Gradients (BF16)            2P
Optimizer m (FP32)          4P
Optimizer v (FP32)          4P
FP32 master weights         4P
                          ─────
                           16P    bytes

Plus activations stored for backward:
  ≈ L · B · S · d · (10 to 30) bytes, depending on what's recomputed

For a 7B model that is 112 GB of state before a single activation, more than one 80 GB GPU. That is why training shards this state across GPUs (the ZeRO / FSDP family). Activation checkpointing trades compute for memory: keep only the layer boundaries and recompute the rest during the backward pass. It costs roughly 30% more FLOPs and saves most activation memory.

Low-precision training (FP8 since DeepSeek-V3 in 2024, and NVFP4 pre-training demonstrated by NVIDIA in 2025) shrinks the compute and the activations, but the optimizer state and master weights still dominate memory, so 12–16 bytes per parameter remains the right estimate.

Memory accounting for inference#

Weights                     P · bytes_per_weight     (1-4 bytes)
KV cache                    2 · L · h_kv · d_head · bytes · S · B
Activations                 transient, small (decode) or large (long prefill)
Framework overhead          1-3 GB

The ratios#

                        Training        Inference (decode)
FLOPs per token         6P              2P
Memory per parameter    16 bytes        1-2 bytes
Batch size              huge (1M+ tok)  small (1-256 sequences)
Arithmetic intensity    very high       very low
Bottleneck              compute         memory bandwidth

Training is compute-bound; decode is memory-bound. That single inversion explains why training hardware (maximise FLOPs) and inference hardware (maximise bandwidth and capacity) diverge, and why an H200 (the same FLOPs as an H100, 43% more bandwidth and 76% more memory) is a clearly better inference chip and only a slightly better training chip (7.b).

Why inference can use lower precision#

Training needs precision because gradients are tiny and are added up over millions of steps, so rounding errors pile up. Inference does one forward pass per token: errors do not accumulate across optimizer steps, and the output is then turned into a single discrete choice by sampling anyway.

Training:  BF16 compute, FP32 master weights, FP32 optimizer states
Inference: FP8 weights and activations: usually under 1% quality loss
           4-bit weights (INT4, NVFP4, MXFP4): 1-3%, method-dependent (13.b)

Caveat for autoregressive generation: errors do compound across tokens, since each token conditions the next. This is why aggressive quantization can degrade long generations more than short ones — a real effect that short benchmarks miss (13.b).


6. Under the hood#

Why the backward pass is exactly 2x: each weight matrix takes part in two matrix multiplies during backward (the gradient with respect to its input, and with respect to the weight itself) and one during forward. The chain rule needs both: one to pass the error on to earlier layers, one to update this layer.

Activation memory is the other half of the story. During the forward pass, PyTorch’s autograd keeps every tensor that an operation will need for its backward. For attention that used to include the full (B, h, S, S) score matrix, which is why FlashAttention’s memory savings (13.l) mattered even more for training than for inference. Inference keeps none of this; its large “activation” is the KV cache (12.e), which training never needs to keep across requests.


7. Performance implications#

  • Training clusters are FLOP-optimized; inference fleets should be bandwidth-optimized.
  • Inference can run on much smaller hardware than training. Do not size from training.
  • Precision choices diverge. Serving at training precision (BF16) leaves 2-4x on the table.
  • Fine-tuning sits in between. LoRA fine-tuning has training’s structure but inference-like memory (base weights frozen, only small adapters have gradients and optimizer state).

8. Production implications#

  • Multi-LoRA serving exploits this: one base model in memory, many small adapters chosen per request. Serving 50 fine-tuned variants costs barely more than serving one (18.g, 20.i).
  • Do not let the training team size your inference cluster with 6P FLOPs and 16P bytes.
  • Evaluate quantized models on long generations, not just short benchmarks, because of error compounding.

9. Common mistakes#

  1. Using 6P for inference FLOPs. It is 2P (plus attention, which grows with context).
  2. Sizing inference memory at 16 bytes per parameter. It is 0.5–2, plus the KV cache.
  3. Assuming inference precision must match training precision.
  4. Evaluating quantization only on short-answer benchmarks. That misses errors that compound over long generations.

10. Hands-on exercise#

A. Derive it. For a 2-layer MLP, write out forward and backward by hand and confirm backward is 2x the forward FLOPs.

B. Memory table. For 7B, 13B, 70B: compute training memory (16P + activations) and inference memory (2P + KV at 8k, batch 32). How many GPUs for each?

C. Compounding. Take a model, quantize it to INT4, and compare outputs against FP16 for generations of 10, 100, and 1000 tokens. Measure divergence (e.g. fraction of matching tokens, or perplexity on the generated text). Does degradation grow with length?


11. Interview questions#

  1. Derive why the backward pass costs 2x the forward pass.
  2. Where does “16 bytes per parameter” for training come from?
  3. Why is training compute-bound and decode memory-bound?
  4. Why can inference use lower precision than training?
  5. What is the caveat about error compounding in autoregressive generation?
  6. How does LoRA change the serving economics of many fine-tuned models?

12. Further reading#

↑↓ navigate↵ openesc close

100% drag to pan · scroll or pinch to zoom · double-click to zoom in