Inference & Serving
Run a trained language model for real users: time a request, count the memory it holds, shrink the weights and keep the hardware busy. Everything is arithmetic and small simulations you can check, then a service designed around them.
- Advanced
- 4 units, 12 lessons, 154 exercises
- Python, diagrams
- Builds on How LLMs Work
Unit 01 · 3 lessons
Where the time goes
Time one request, and count the memory it holds while it runs
- 01Tokens and time
Prefill, decode and the two numbers users feel
- 02The KV cache
What decode would recompute, and what it stores instead
- BOSSWill it fit?
Size a model, its caches and its users against a memory budget
Read the unit guide
A request to a language model has two phases. Prefill reads the whole prompt in one pass: every prompt token is known, so all positions are processed in parallel. Decode then writes the answer one token per pass, because each new token depends on the one before it. Prefill runs at thousands of tokens per second; decode at tens.
Two numbers describe what the user feels. Time to first token is the prefill wait (plus any queue), and it grows with the prompt. Tokens per second is the speed of one decode step. Total time is the first plus the answer length divided by the second. Long prompts delay the start; long answers dominate the total. That is also why an output token costs more than an input token: it occupies a whole pass of its own.
The KV cache is what makes decode one position per step instead of a full re-read. Under a causal mask the keys and values of earlier tokens never change, so each layer keeps one key and one value vector per token. The cost is memory: 2 × layers × width numbers per token, times the bytes per number, for every token of every conversation in flight.
Kept between requests, the same cache becomes prompt caching: a later request that starts with exactly the same tokens skips prefilling them. The match runs from the first token to the first difference, so fixed text goes first and anything that changes goes last.
Memory is therefore a bill with three lines. Weights are fixed: parameters × bytes each, shared by everyone. The KV cache grows with tokens in flight. Working memory for the pass is small but never zero. Size a deployment by subtracting the weights and a margin from the budget, then dividing what is left by the cache cost of one conversation.
The pitfall: sizing for the model file alone. A model that loads is not a model that serves. Thirty long conversations can need more memory than the weights, and the context limit you allow is also the number of users you can hold.
Unit 02 · 3 lessons
Smaller numbers
Store weights in fewer bits on purpose, and know what it costs
- 01Precision
Bits per weight, and what each format can represent
- 02Quantising by hand
Scale, zero point, rounding and the error that comes back
- BOSSPick a precision
Memory, speed and quality for one job on one device
Read the unit guide
A weight is a number, and a number needs bits. Models are trained in 32-bit floats; to run them, 16-bit floats, 8-bit integers or even 4 bits per weight are common. Memory falls in exact proportion: a billion weights take 4 GB, 2 GB, 1 GB or half a gigabyte.
Floats spend their bits on significant digits, so their levels crowd together near zero, which is where weights live. That is why half precision costs so little. Integer formats are a plain grid of evenly spaced levels, and need a rule to map them onto real values.
That rule is the scale: the real distance between neighbouring integers. Quantise by dividing by the scale and rounding; read back by multiplying. The result is the nearest grid point, at most half a step away. A zero point shifts the grid for values that are not centred on zero, and anything outside the grid is clipped to its edge.
The scale is set by the largest value, so one outlier makes the grid coarse for everything else. Giving each row (channel) its own scale buys back much of that precision. Rounding a finished model is post-training quantisation; simulating the rounding while training continues is quantisation-aware training, which lets the weights settle where rounding hurts least.
Each bit removed doubles the step, so error grows fast while memory shrinks slowly. Quality tends to hold and then fall off a cliff, and the edge is different for every model and task. Memory and speed can be calculated; quality has to be measured, on an eval set built for the job.
The pitfall: choosing a precision by file size. The weights share the device with the KV cache, and a smaller model at higher precision may beat a larger one squeezed harder. Fit the whole memory bill first, then let the eval choose.
Unit 03 · 3 lessons
Many requests
Keep the hardware busy without making any one user wait too long
- 01Batching
One pass for many requests, and what it costs each of them
- 02Continuous batching
Requests join and leave between decode steps
- BOSSPlan the capacity
From requests per second to a fleet that survives its peak
Read the unit guide
A model serving one request at a time wastes most of its hardware. A batch is one more dimension on the same matrix multiply: the weights are read once and applied to every request together, so a pass over eight requests takes little longer than a pass over one. Throughput rises several times over, while each user's stream gets a little slower.
Batches have costs. Every sequence in a batch is padded to the longest, and padded positions are computed for nothing, so requests of similar length should share a batch. Waiting to fill a batch adds latency that only pays off when traffic is there. And every request brings its own KV cache, so memory usually caps the batch before compute does.
A static batch stays together until its slowest member finishes, leaving slots idle while new requests queue. Continuous batching rebuilds the batch between decode steps: finished requests leave at once and waiting ones take their slots after a prefill. Tokens are streamed to each user as they are made, so what the user feels is the time to first token.
Capacity planning starts from output tokens per second: requests per second times answer length, at peak. Divide by what one replica sustains under load, then leave headroom, because a server at 100% turns every burst into a queue that grows without limit. Add a spare so one machine can fail.
Judge latency by percentiles, not averages. The p50 is the typical request; the p99 is the one in a hundred that waited longest, and at scale that is a crowd. New replicas take time to start and load weights (the cold start), so spare capacity must exist before the spike, not after it.
The pitfall: planning from the average. Averages hide the peak that fills the queue and the tail that users remember.
Unit 04 · 3 lessons
The service around the model
Wrap a model in a service that stays fast, honest and affordable
- 01Why GPUs
Parallel arithmetic, and the two limits of a device
- 02The serving API
Streaming, stop reasons, retries and pushing back
- BOSSDesign an inference service
Route, cache, fail over, and watch cost, latency and quality together
Read the unit guide
A model is mostly large matrix multiplies, and a matrix multiply is thousands of dot products that do not depend on each other. That is work a GPU is built for: thousands of simple cores doing the same arithmetic at once, with their own memory. Memory decides whether a model fits; compute decides how fast it runs. They are separate limits, and it pays to know which one you have hit.
Copies between main memory and the device cost time. Token ids and results are tiny; the weights are not, so a server loads them once and keeps them resident. A model too big for one device can be split by layers across several, with the activations crossing once per pass.
The API around the model streams tokens as they are made, so users start reading after the time to first token. A generation stops for a reason (the model's end token, the token limit you set, a stop sequence, a disconnect), and a client should read which. A cut-off answer looks finished otherwise.
Things fail, so clients retry, but only what can succeed later (too many requests, a server briefly unavailable), with waits that double, a random jitter and a cap. Servers push back: bounded queues, limits counted in tokens as well as requests, and a fast, honest refusal instead of accepting work nobody will wait for.
A production service stacks the levers. A router sends easy requests to a small model and escalates when unsure. A cache answers what repeats, keyed on everything the answer depends on. Health checks and spare replicas absorb failures. And three dials are watched together: cost, latency and quality.
The pitfall: optimising one dial alone. Cost and latency are easy to measure and quality is not, so quality is what quietly gets spent. Keep an eval running on live samples, next to the bill.
Learn Inference & Serving on your phone.
Bitpath is an iOS app in development. Join the waitlist and you get one email when it is ready to try.