Pidoku

Training vs Inference

Module 1 Lesson 1.b 45 min Difficulty 1/5

Prerequisites 1.a


Before you start#

Lesson 1.a defined model, parameter, training, token and GPU. This lesson adds four words:

WordPlain meaning
Forward passRunning the model once: input in, output out. Inference is only forward passes.
LossA number measuring how wrong the model’s output was on a training example.
GradientFor every parameter, the direction and size of the change that would reduce the loss. Computing gradients is called the backward pass.
OptimizerThe rule that turns gradients into parameter updates. Adam is the most common; it keeps two extra running averages per parameter.

1. What is it?#

A model lives through two phases:

  • Training decides what the parameters should be. The model sees an example, makes a prediction, the loss measures how wrong it was, the backward pass computes gradients, and the optimizer nudges every parameter slightly. This repeats trillions of times.
  • Inference uses the finished parameters. Input in, output out, nothing changes.

They share the mathematics of the forward pass and almost nothing else in how they are run.


2. Why does it exist?#

The distinction matters because the two phases have opposite engineering constraints, and mixing them up produces bad systems.

Training is a batch job. You own the data, you choose how many examples to process at once, nobody is waiting, and you optimise for one thing: finishing as cheaply as possible. If a step takes 900 ms instead of 800 ms, you shrug.

Inference is a service. Someone is waiting, you do not control what they send, traffic rises and falls through the day, and a 100 ms slowdown can break a promise to customers.

Most tooling, tutorials and machine-learning instincts come from training. Applying them unchanged to inference is the most common cause of bad deployments.

The line is also blurring in useful ways in 2026: reasoning models spend extra compute at inference time to think longer, and reinforcement-learning pipelines run inference engines inside training to generate practice answers (lesson 24.j). You need to understand both sides to see why.


3. Simple analogy#

Training is writing a textbook. Inference is answering students’ questions with it.

Writing the textbook takes a year, a team and a large library, and nobody is standing at your desk. Answering a question takes seconds, happens constantly, and the student is right there. You need the book open on the desk (the weights loaded in GPU memory), you need to find the right page fast, and you need to do it for thirty students at once without making any of them wait.

Engineers often use a second framing: training is compiling; inference is running the binary. You compile once, expensively, and run billions of times. Nobody accepts a program that recompiles itself on every request — yet naive deployments do the equivalent by reloading models or rebuilding computation graphs per request.


4. Tiny example#

The two-parameter house-price model from 1.a, now with training shown:

Go
package main

import "fmt"

func main() {
	// ---------- TRAINING ----------
	w, b := 0.0, 0.0 // start with nothing learned
	// inputs are in units of 1000 sqft so one learning rate suits both w and b
	data := [][2]float64{{1.0, 170000}, {1.5, 245000}, {2.0, 320000}}
	const lr = 0.05

	for epoch := 0; epoch < 20000; epoch++ {
		for _, d := range data {
			x, price := d[0], d[1]
			pred := w*x + b     // FORWARD  (this is inference!)
			err := pred - price // LOSS
			dw := 2 * err * x   // BACKWARD (gradient)
			db := 2 * err
			w -= lr * dw // UPDATE
			b -= lr * db
		}
	}
	fmt.Printf("w=%.1f per 1000 sqft, b=%.1f\n", w, b) // ≈ 150000, ≈ 20000

	// ---------- INFERENCE ----------
	infer := func(sqft float64) float64 {
		return w*(sqft/1000) + b // FORWARD only. No loss. No gradient. No update.
	}
	fmt.Printf("%.0f\n", infer(1500)) // ≈ 245000
}

Count the work per example:

PhaseStepsMemory needed
Inferenceforwardthe weights, plus the current intermediate values
Trainingforward + loss + backward + updateweights + gradients + optimizer state + every intermediate value of the forward pass

The last item is why training needs so much more memory: the backward pass needs every intermediate value the forward pass produced, so all of them must be kept. Inference can discard each one as soon as the next layer has used it. Inference is cheap in memory per token but must always hold the weights; training is expensive in memory but spreads that cost over huge batches.


5. Technical explanation#

The full comparison#

DimensionTrainingInference
Directionforward + backwardforward only
Weightschange every stepfrozen
Memory for weights (8B model, 16-bit)16 GB16 GB
Plus gradients+16 GB—
Plus optimizer state (Adam, with 32-bit master copy)+96 GB—
Plus saved intermediate valueslarge, grows with batch × length × layerssmall, discarded immediately
Typical total (8B)~130+ GB, spread over several GPUs~18–25 GB on one GPU
Batch sizeyou choose (millions of tokens per step)set by whatever traffic arrives
Input lengthfixed or bucketedanything users send
Optimises forthroughput and cost to finishlatency and throughput and cost
A failed stepretry, nobody noticesa user sees an error
Number formatBF16 or FP8 arithmetic, 32-bit master weights; FP4 pretraining emergingas low as quality allows: FP8 standard, FP4 on Blackwell-class GPUs (13.e, 13.g)
Durationweeks, then donefor as long as the model is in use
Hardwarethe biggest tightly connected cluster you can getwhatever gives the cheapest token at the latency target

The memory arithmetic (do it yourself)#

For a model with P parameters trained in mixed precision with Adam:

weights (BF16)          2P bytes
gradients (BF16)        2P bytes
Adam first moment m     4P bytes   (FP32)
Adam second moment v    4P bytes   (FP32)
FP32 master weights     4P bytes
                       ---------
                       16P bytes  ≈ 16 bytes per parameter

For 8B parameters that is 128 GB before a single intermediate value — more than one 80 GB GPU. Inference needs:

weights (16-bit)         2P bytes   (1P at 8-bit, 0.5P at 4-bit)
KV cache                 grows with every token of every active request (12.e, 12.f)
intermediate values      small, short-lived
                        ---------
                        ~2P + KV cache

For 8B: 16 GB plus KV cache. On an 80 GB GPU about 60 GB is left, and that leftover memory decides how many users you can serve at once (12.f, 12.q). In inference, memory not spent on weights is capacity. That one idea motivates quantization (Module 13), compact attention designs such as GQA and MLA (12.g) and PagedAttention (12.l).

For a mixture-of-experts model (1.a), both phases must hold all parameters in memory, but inference computes with only the active ones per token. That is why MoE models are cheap to run per token yet still need many GPUs just to store them (14.g).

What carries over and what does not#

Carries over: the operations (matrix multiplication, attention, normalisation — Module 11), the knowledge of number formats, the model architecture.

Does not carry over: batch-size intuitions, memory profiles, freedom to retry, fixed input shapes, the assumption that every request costs the same, and — critically — the belief that more GPUs always help (14.m).


6. Under the hood#

During training, the framework records every operation it performs so gradients can later flow backward through them. This recording is called the autograd graph, and it keeps every intermediate value alive.

For inference you switch it off. In PyTorch:

Python
with torch.inference_mode():      # stronger than torch.no_grad()
    out = model(x)

inference_mode skips the recording and some bookkeeping on tensors. Forgetting it is a classic bug: memory grows request after request until the process runs out, because every intermediate value of every request is being kept for a backward pass that will never happen.

Some layers also behave differently in the two phases:

Python
model.eval()   # Dropout turns off; BatchNorm uses its stored statistics

Forgetting model.eval() gives slightly wrong, non-repeatable outputs. Inference engines such as vLLM (Module 16) do both for you; you meet these bugs when someone serves a model with hand-written code.


7. Performance implications#

Training cares only about throughput, so every trick that raises it is good. Bigger batches, accumulating gradients over several steps, slower steps that use the hardware better — all fine.

Inference has a latency limit, so throughput tricks have a price. A batch of 256 requests gives excellent tokens per second per GPU and terrible time-to-first-token if each request must wait for the batch to fill. Continuous batching (12.j) was invented to get most of the throughput without the wait.

Training does a lot of arithmetic for every byte it reads (huge batches, long sequences). Inference decoding does very little — one new token per request per step — so the GPU spends most of its time waiting for memory. This is the biggest single performance difference between the two phases; lesson 2.f makes it precise.


8. Production implications#

  • Do not size inference hardware from training hardware. A model trained on thousands of GPUs may serve happily on two. The reverse also happens: a model that trained fine may be impossible to serve at your latency target because of its attention design.
  • Model design is an inference lever. Grouped-query attention cuts the KV cache 4–8x compared with standard attention; a shorter maximum context lowers worst-case memory; a mixture-of-experts design cuts compute per token. These are training-time choices with permanent inference consequences, so inference engineers should be in the room when they are made.
  • Two teams, two kinds of on-call. Training failures are failed batch jobs. Inference failures are outages.
  • Fine-tuning blurs the line. LoRA adapters let one server host many fine-tuned variants of one base model (18.g, 20.i) — an inference-architecture question, not a training one.

9. Common mistakes#

Deploying training code as serving code. Training code carries gradient tracking, checkpointing hooks, distributed wrappers and data-loading machinery. In production all of it is overhead or a bug. Serve with an inference engine, or export a clean inference path.

Forgetting eval() / inference_mode(). Causes memory leaks and wrong numbers. Check it first whenever memory grows over time.

Assuming the training number format must be the serving format. A model trained in BF16 usually serves well in FP8, and often in FP4, with proper calibration (Module 13). Insisting on training precision leaves 2–4x on the table.

Benchmarking with training-shaped inputs. Fixed length 2,048, batch 32, identical sequences: that tells you nothing about production, where lengths vary 100x and requests arrive at random. Benchmark with realistic traffic (22.g).

“It scored 95% in evaluation, so it will in production.” Quantization, batching effects and a different mix of real prompts all change quality. Always evaluate the configuration you actually deploy.


10. Hands-on exercise#

A. Memory arithmetic. For a 14B-parameter model, compute:

  1. Training memory with Adam mixed precision (16 bytes per parameter). Does it fit on one 80 GB GPU? On one 288 GB B300?
  2. Inference memory for the weights at 16-bit, 8-bit and 4-bit.
  3. The memory left for KV cache on an 80 GB GPU in each case.

B. Prove the autograd leak. In PyTorch, run a small model 100 times in a loop, once with torch.inference_mode() and once without, printing torch.cuda.memory_allocated() (or process memory on a CPU) each time. Plot both and explain each curve’s shape.

C. See what eval() changes. Take any model with dropout. Run one input 10 times in train() mode and 10 times in eval() mode. Compare the outputs and explain the difference.


11. Interview questions#

  1. Why does training need about 8x more memory per parameter than 16-bit inference?
  2. What does torch.inference_mode() do that torch.no_grad() does not?
  3. Your inference service’s memory grows steadily until it crashes after two hours. Give three hypotheses, most likely first.
  4. When would you serve at a different number format than the model was trained in? What could go wrong?
  5. Name an architecture decision made at training time that you cannot undo at inference time, and its cost.
  6. Why does a mixture-of-experts model need lots of GPU memory but little compute per token?

12. Further reading#

↑↓ navigate↵ openesc close

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