AI from scratch · Serving a model · Stage 7: production

Serving a model

A model in a notebook answers one person: you. A served model answers thousands of requests from code that never sees a notebook, and each request has a deadline and a cost. Start 4 put a model behind a demo page. This lesson is the engineering behind a real service: an API around the model, latency measured the way users feel it, batching that trades a little waiting for a lot of throughput, smaller and faster models through quantization, caching, and the arithmetic of what each prediction costs.

1. From notebook to API

A prediction service is a small program: load the model once when it starts, check every request's input, run the model, return the answer. In Python the common tool is FastAPI; pydantic types describe the input, so malformed requests are rejected with a clear error before they reach the model.

from fastapi import FastAPI
from pydantic import BaseModel
import joblib, pandas as pd

model = joblib.load("outage_model.joblib")            # once, at startup: loading per request would cost seconds
app = FastAPI()

class Outage(BaseModel):                                # the contract: these fields, these types
    kind: str
    reason: str
    ada: int
    hour: int
    n_lines: int

@app.post("/predict")
def predict(o: Outage):
    p = model.predict_proba(pd.DataFrame([o.model_dump()]))[0, 1]
    return {"p_long": float(p), "model_version": "2026-10-15"}

@app.get("/health")
def health():
    return {"ok": True}

Three habits: return the model version with every answer (so a bad prediction can be traced, the experiments lesson); use the same preprocessing code in training and serving (Start 4's most common deployment bug, "training-serving skew"); and expose a health check so the platform can restart a stuck service.

A service loads the model once, validates every input against a schema, and returns the prediction with the model version that made it.

2. Latency is a distribution

"Average latency 40 ms" hides what users feel. Report percentiles: p50 (the median request), p95 and p99 (the slow tail). Tails matter more than they look: a page that calls 10 services waits for the slowest, so if each has a 1% chance of a slow answer, \(1 - 0.99^{10} \approx 9.6\%\) of pages are slow.

A request fans out to 50 backend calls, each slow 1% of the time. What percent of requests hit at least one slow call? (One decimal.)

\(1 - 0.99^{50} \approx 0.395\): 39.5%. At scale, the p99 of each part becomes the typical experience of the whole, which is why services watch p99, not the mean.

Measure latency as percentiles; a service's p99 is what fan-out turns into everybody's experience.

3. Batching: wait a little, serve a lot

Running the model on 64 inputs at once costs barely more than on one: the fixed costs (launching the computation, reading the weights from memory) are shared. On a laptop CPU, the toolkit's digit network does about 68,000 predictions a second one at a time and 680,000 in batches of 256. Dynamic batching collects requests for up to a few milliseconds, then runs them together. The simulator below serves requests arriving at random; the model takes 20 ms per batch plus 1 ms per request in it.

Set max batch to 1 and push the rate past 45 requests a second: the queue grows without end, because one request at a time can't keep up (each costs 21 ms). With batches of 16 the same server handles hundreds a second. Then raise the wait: the batches get fuller but each request waits longer, which raises p50 at low load. Real servers (NVIDIA Triton, vLLM, TorchServe) tune exactly these two knobs.

Batching shares each model run's fixed cost across many requests, multiplying throughput for a few milliseconds of waiting.

Why a batch is almost free, up to a point
  1. A model run has a fixed part (launching kernels, reading every weight from memory) and a per-input part (the arithmetic for that input).
  2. For small inputs the fixed part dominates: the GPUs lesson's memory-bound work. Reading a 14 GB model once per request or once per batch of 32 is the difference between 1 and 1/32 of that cost per request.
  3. So time per batch is roughly \(t_0 + c\,b\): with \(t_0 = 20\) ms and \(c = 1\) ms, one request takes 21 ms (48 a second at most), a batch of 16 takes 36 ms (444 a second).
  4. The per-input part eventually dominates (once the arithmetic keeps the cores busy), and throughput stops growing: the toolkit's throughput-vs-batch curve flattened the same way.
  5. The price is waiting: a request may sit up to the max wait for its batch to fill, then for the batch to run. That's the latency-throughput trade every serving system tunes.

4. Smaller, faster, cached

Quantization stores weights in fewer bits: each row of a weight matrix gets one scale, and every weight becomes the nearest of 255 (8-bit) or 15 (4-bit) levels. Measured in the practice notebook on the toolkit's digit network (91.7% accurate in float32):

WeightsSizeAccuracy
float321.2 MB91.7%
8-bit0.3 MB91.7%
4-bit0.15 MB91.4%
2-bit0.08 MB43%

Down to 4 bits almost nothing is lost; at 2 bits the model falls apart. Large language models are routinely served in 8 or 4 bits for exactly this reason (the using-LLMs lesson's 137 MB browser model is 8-bit). Other tools: distillation (train a small model to copy a big one's outputs), compilation (ONNX Runtime, TensorRT fuse operations, the GPUs lesson's fusion), and caching: an identical request gets the stored answer, and language models cache the attention keys and values of a prompt's shared beginning (a KV cache, and providers' prompt caching).

Which request is safe to answer from a cache?

A cache key must include everything the answer depends on: the input, the model version, the settings, and for live data, a time limit (expire entries after a few seconds).

Quantization, distillation and compilation make each prediction cheaper; caching skips the prediction when the inputs and model haven't changed.

5. What a prediction costs

\[ \text{cost per 1,000 predictions} = \frac{\text{price of the machine per hour}}{\text{predictions per hour}} \times 1{,}000 \]

A machine at \$1.20 an hour serving 100 predictions a second does 360,000 an hour: \$0.0033 per thousand. If batching lifts it to 1,000 a second, the price per thousand falls tenfold. But a machine kept up for traffic that peaks at noon and idles at night is paid for all day, so the real cost includes idle time: autoscaling adds and removes machines with the load.

Cost per prediction is machine cost over throughput, so batching, smaller models and scaling with traffic are cost tools as much as speed tools.

Where it breaks: the service, not the model

6. What to carry forward

All lessons: AI from scratch. Made With ML's serving lessons and the FastAPI tutorial are good companions; Jeff Dean and Luiz Barroso's "The Tail at Scale" is the classic on section 2.

Last updated