Pidoku

What Is Inference?

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

Before you start: five words#

This lesson assumes no machine-learning background. These five words are all you need, and every later lesson builds on them:

WordPlain meaning
ModelA file full of numbers, plus a fixed recipe for combining them with an input to produce an output.
Parameter (or weight)One of those numbers. A modern language model has billions of them.
TrainingThe expensive, one-time process that chose the values of the parameters.
TokenThe unit a language model reads and writes: roughly three-quarters of an English word. “Inference is fun” is about 4 tokens. Lesson 12.b explains exactly how text becomes tokens.
GPUA processor built to do huge amounts of simple arithmetic in parallel. Almost all inference runs on GPUs or similar chips; Module 2 explains why.

1. What is it?#

Inference is running a trained model to get an answer.

You have a model, you give it an input, it produces an output. That act is inference.

   input  ──────►  [ model ]  ──────►  output
 "translate:        billions        "bonjour"
  hello"            of numbers

The word comes from statistics: you are inferring an answer from evidence. In engineering it simply means “using the model on real requests”, as opposed to training it.

Every time you type into a chat assistant, ask a coding agent to fix a bug, get a product recommendation, have a photo tagged, or see a fraud score on a payment — that is inference. It is the part of AI that users actually touch.

Inference engineering is the discipline of making inference fast, cheap and reliable when millions of people use it at once. It is the subject of this whole learning material.


2. Why does it exist?#

A trained model sitting in a file is worth nothing. Its value appears only when it answers requests. To make that happen, somebody has to:

  1. Load tens to hundreds of gigabytes of parameters onto hardware that can do arithmetic quickly (GPUs).
  2. Accept requests from many users at the same time.
  3. Run the arithmetic for each request.
  4. Respond within a time users will tolerate — often the first word within a second.
  5. Pay less for all of this than the answers are worth.

Each step is a real engineering problem. For years, inference was an afterthought: you trained a model and someone wrapped it in a small web app. That worked when models were 50 MB and a request took 5 milliseconds.

It stopped working when models grew to hundreds of gigabytes, when one request could keep a GPU costing tens of thousands of dollars busy for many seconds, and when reasoning models and agents started generating thousands of tokens per task. At that scale, the difference between a naive setup and a well-engineered one is routinely 10–40x in cost — the same model, on the same hardware, giving the same answers. Lesson 1.d shows where that gap comes from.

That gap is why inference engineering exists as a specialty, and why in 2026 more money is spent running models than training them (lesson 1.e).


3. Simple analogy#

A model is a factory. Training built the factory. Inference is running the production line.

  • Building the factory (training) is a huge, one-time project. You do it once, with a big team, and it can take weeks.
  • Running the line (inference) happens millions of times a day, for as long as the model is in use. Every inefficiency is multiplied by every unit produced. Speeding up construction by 10% saves you once; speeding up the line by 10% saves you every day, forever.

That is why engineers fight over microseconds in inference: shaving 200 microseconds off an operation matters when it runs ten billion times a day.

A second picture, useful later: a model is an enormous lookup table that is computed instead of stored. It “contains” answers to more questions than could ever be written down, and the price of that compression is that every answer takes a lot of arithmetic to retrieve.


4. Tiny example#

Here is inference, complete, with no libraries. This model predicts a house price from its size:

Go
package main

import "fmt"

// The "trained model": two learned numbers (parameters).
const (
	weight = 150.0   // dollars per square foot
	bias   = 20000.0 // base price
)

func infer(squareFeet float64) float64 {
	return weight*squareFeet + bias
}

func main() {
	fmt.Println(infer(1500)) // 245000
}

That is a real model. It has 2 parameters, and inference is one multiplication and one addition. Training was the process that found 150 and 20,000; inference is using them.

Now scale the same idea up:

ModelParametersArithmetic per output
House price above22 operations
Small image classifier5 million~10 million operations per image
8B language model (dense)8 billion~16 billion operations per token
70B language model (dense)70 billion~140 billion operations per token
671B mixture-of-experts model, 37B active (DeepSeek-V3 class)671 billion stored~74 billion operations per token

Nothing conceptually changed: output = f(input, parameters). Only the size changed — by more than ten orders of magnitude. Almost every hard problem in this material comes from that scale, not from new ideas. Keep that in mind when things get dense in Module 12.

A rule of thumb you will use constantly (lesson 2.f derives it):

operations per token ≈ 2 × number of parameters used for that token

The 2 is there because each parameter takes part in one multiplication and one addition. Check it: 8B parameters → 16 billion operations per token.

The last row of the table shows why the rule says used for that token. A mixture-of-experts (MoE) model stores many separate sub-networks (“experts”) but sends each token through only a few of them. It must store all 671 billion parameters but computes with only about 37 billion per token. Most of the largest open models in 2026 are built this way (lesson 14.g), and it splits two questions you will keep separate for the rest of this material: how much memory a model needs (all its parameters) and how much arithmetic each token costs (only the active ones).

note

Operation counts are written in FLOPs (floating-point operations). A FLOP/s figure is a rate — how many a chip can do per second. “This model costs 16 GFLOPs per token” divided by “this GPU does 1,000 TFLOP/s” gives a time. Mixing the two up breaks every estimate.


5. Technical explanation#

Formally, inference evaluates a function:

y = f(x; θ)
  • x is the input (a prompt, an image, a list of numbers describing a transaction),
  • θ (theta) is the set of parameters — fixed while serving,
  • f is the model’s architecture — the fixed sequence of operations,
  • y is the output (the next token, a category, a score).

Three properties make this unlike calling an ordinary function:

1. θ is huge and must stay in fast memory. A 70B model stored at 16 bits (2 bytes) per parameter occupies 140 GB. You cannot read that from disk on every request; it has to sit in the GPU’s own memory the whole time. That immediately limits which hardware can run the model and how many models fit on one machine. Storing parameters in fewer bits — 8 or 4 instead of 16 — shrinks this, which is called quantization (lesson 10.l).

2. f is a fixed sequence of operations, not a program with arbitrary logic. There are no open-ended loops, no network calls in the middle, no “if the user is in France, do this”. Because the shape of the computation is known in advance, it can be planned, merged and compiled ahead of time. Modules 11 and 13 exploit this.

3. Language models apply f again and again, feeding each output back in. To write a 500-token answer, the model runs 500 times, one token at a time, and each run must wait for the previous token. This is called autoregressive generation, and it is the source of most of the difficulty in Module 12.

That third point is the fork in the road for the whole field:

Non-generative inference (image classifier, search ranker, embedding model):
    request ──► one pass through the model ──► answer          [ like a function call ]

Generative inference (language model):
    request ──► pass ──► token 1
            ──► pass ──► token 2
            ──► pass ──► token 3
            ...                                                [ a loop that keeps state ]
            ──► pass ──► token 500 ──► answer

The first is an ordinary, if expensive, request. The second is a long-lived session with state that only looks like a request. Most of what is strange about serving language models follows from that.


6. Under the hood#

Here is one chat request travelling through a real serving system. Each step names the lesson that explains it; for now, just see the shape.

1.  An HTTP request arrives at a gateway                     "Explain gravity"
2.  Authentication, rate limits, choosing a server           Module 20, 21
3.  Tokenization: text → numbers                             12.b
       "Explain gravity" → [50, 8161, 15883]
4.  The request waits in a queue                             20.c
5.  A scheduler groups it with other requests (batching)     2.d, 12.j
6.  The token numbers are copied from CPU memory to the GPU  9.b
7.  PREFILL: the whole prompt goes through the model at once  12.c
       → produces the first output token
       → and saves intermediate results for every prompt token
         in the "KV cache", so they are never recomputed     12.e
8.  DECODE: a loop, once per output token                    12.d
       - run the model for ONE new token, reusing the KV cache
       - pick the next token from the model's probabilities  12.o
       - send it to the user immediately (streaming)         12.p
       - repeat until the answer is finished
9.  Turn the tokens back into text, close the stream,
    free the KV cache memory

Steps 7 and 8 use more than 95% of the time and money, and they behave completely differently: prefill is limited by how fast the GPU can do arithmetic, decode by how fast it can read memory. That split (lesson 12.c) is the central fact of serving language models.

Physically, in steps 7 and 8 billions of numbers are read out of GPU memory, multiplied and added by tens of thousands of arithmetic units working in parallel, and written back. The GPU is not “thinking”; it is doing linear algebra at around 10^15 operations per second. The interesting engineering question is almost always whether those arithmetic units are busy, or idle waiting for data.


7. Performance implications#

Four numbers describe any inference service. Learn to ask for all four:

MetricMeaningTypical target for a chat product
TTFT — time to first tokenHow long until the user sees anything0.2 – 1 s
ITL — inter-token latencyThe gap between one token and the next10 – 50 ms (20–100 tokens/s per user)
ThroughputTokens per second across all users togetheras high as possible
CostDollars per million tokensas low as possible

They pull against each other (lessons 2.c and 2.d):

  • Bigger batches (more users served together) → more throughput and lower cost, but each user waits a little longer.
  • More GPUs per model → lower latency, but lower efficiency, because the GPUs spend time talking to each other.
  • Fewer bits per number → faster and cheaper, with a risk to answer quality.

No setting wins everywhere. Inference engineering is choosing your losses deliberately instead of by accident.


8. Production implications#

Things that surprise engineers coming from ordinary backend work:

Requests are not alike. In a normal web service, requests take roughly similar time. Here one request may produce 5 tokens and the next 20,000 (a reasoning model thinking hard) — a 4,000x difference in cost, unknown in advance. Queueing, load balancing and autoscaling all need rethinking.

Capacity runs out in memory, not CPU. You rarely run out of processor; you run out of GPU memory for the KV cache, usually suddenly, usually under load (lesson 12.f).

Starting a server takes minutes. Loading hundreds of gigabytes of weights is slow, so you cannot add servers in seconds during a traffic spike the way you can with web servers. This changes capacity planning (Module 23).

Keeping GPUs busy is the whole economics. A GPU costs the same per hour whether it does 5% or 95% useful work. An inference platform’s business is keeping that expensive silicon busy with useful work.


9. Common mistakes#

“Inference is just the forward half of training.” The maths is shared; almost nothing else is. Training processes fixed batches it controls, cares only about throughput, and can wait minutes. Inference handles unpredictable requests it does not control, under latency targets, with a person waiting. Lesson 1.b compares them.

“We’ll optimise inference later.” Some of the biggest inference costs — the attention design, the context length, the vocabulary size, whether the model is MoE — are fixed when the model is trained. Inference needs shape model choice from the start (Module 24).

“The GPU shows 100% utilisation, so it is fully used.” nvidia-smi’s utilisation figure means “some work was running”, not “the chip was doing useful work”. A GPU stalled waiting for memory also shows 100%. Lesson 22.d explains this; the misunderstanding has wasted more GPU-hours than any other.

Tuning for throughput when users care about latency, or the reverse. Decide which one your product needs before tuning anything. A nightly batch job and an interactive assistant want opposite settings of the same engine.


10. Hands-on exercise#

Part A — the world’s smallest inference server.

Go
// infer.go — run with: go run infer.go
package main

import (
	"fmt"
	"time"
)

const weight, bias = 150.0, 20000.0

func infer(sqft float64) float64 { return weight*sqft + bias }

func main() {
	const n = 100_000_000
	var sink float64 // use every result so the compiler cannot delete the loop
	t0 := time.Now()
	for i := 0; i < n; i++ {
		sink += infer(float64(i % 3000))
	}
	dt := time.Since(t0)
	fmt.Printf("%.0f inferences/sec, %.2f ns each (checksum %.0f)\n",
		n/dt.Seconds(), float64(dt.Nanoseconds())/n, sink)
}

Run it (any language works — the point is the measurement). A compiled language reaches several hundred million inferences per second on one core. Then answer:

  1. Each inference is 2 FLOPs. What FLOP/s did you measure?
  2. A modern CPU core can do roughly 10^11 FLOP/s. Why are you far below that?
  3. Change infer to process a slice of 1,000,000 inputs in one call, then split the slice across all CPU cores. Measure both. How much faster is each, and why?

The answer to question 3 previews this whole material: removing per-item overhead and letting the hardware do many operations at once. Batching and parallelism are the same idea at different scales.

Part B — estimates without a computer.

  • A 13B-parameter model at 16 bits per parameter: how many GB for the weights alone?
  • A GPU with 80 GB of memory: how many copies fit? What else must fit beside the weights?
  • At 2 FLOPs per parameter per token, how many FLOPs per generated token?
  • If the GPU sustains 300 TFLOP/s, what is the shortest possible time per token?
  • Real systems are far slower than that for one user. Guess why, then read lesson 2.f.

Part C — a numbers journal. Start a numbers.md file and record your CPU model and the results of Part A. You will add to it throughout this material; by the end it is your personal reference of real measurements.


11. Interview questions#

  1. Explain inference to a backend engineer who has never touched machine learning, in one minute.
  2. Which four metrics would you put on a dashboard for a language-model service, and why?
  3. Why does running a model usually cost more than training it over its lifetime? When is that not true?
  4. A colleague says “we’ll autoscale it like any other service”. What do you tell them?
  5. For a model with P parameters, estimate the FLOPs per token and the memory for weights. Do it for P = 70B at 16 bits and at 4 bits. How does the answer change for an MoE model with 400B total and 20B active parameters?
  6. Name three things that make a generative model harder to serve than an image classifier.

12. Further reading#

↑↓ navigate↵ openesc close

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