Home › Learn › Small model from scratch › Inference
Serving the tiny model
Training makes the model. Inference is running it. Here the one-sentence model is saved, loaded, sampled, cached, batched, served over HTTP, squeezed into fewer bits and timed.
Two networks. Behaviour is shown on the trained toy (22,112 parameters: one end marker more than on the first page). The toy is too small to time, so speed uses the same code with a larger network and random weights (width 256, 4 blocks). It writes nonsense but costs the same to run. Measured on an Apple M2 laptop; treat speeds as rough.
1 · Save and load
Training and inference become separate programs. The model file holds three things: the shape, the tokenizer rules and the weights.
def save(path, model, tok):
"""A model file is: the shape, the tokenizer rules and the weights."""
torch.save({"config": model.config, "merges": [list(m) for m in tok.merges],
"weights": model.state_dict()}, path)
def load(path, device="cpu"):
data = torch.load(path, map_location=device, weights_only=True)
model = TinyGPT(**data["config"])
model.load_state_dict(data["weights"])
return model.to(device).eval(), Tokenizer(data["merges"])2 · Sampling
Temperature controls how adventurous the choice is. Top-p throws away the unlikely tail before choosing. Chances for the token after “the cat”:
| Temperature | Chance of “␣sat” | Tokens kept by top-p 0.9 |
|---|---|---|
| 0.5 | 100% | 1 of 269 |
| 1.0 | 98.9% | 1 of 269 |
| 3.0 | 13.0% | 232 of 269 |
| 8.0 | 1.5% | 241 of 269 |
At temperature 2 the toy writes broken text. At temperature 2 with top-p 0.5 it is nearly correct again.
def chances(scores, temperature=1.0, top_p=1.0):
"""Turn scores into the chances we will pick from.
temperature 0 : only the top choice
below 1 : favour the top choices more
above 1 : give unlikely choices more room
top_p : keep the smallest set of top choices whose chances reach top_p
"""
if temperature == 0:
p = torch.zeros_like(scores)
p[scores.argmax()] = 1.0
return p
p = torch.softmax(scores / temperature, dim=-1)
if top_p < 1:
ordered, index = p.sort(descending=True)
before = ordered.cumsum(0) - ordered # total chance of the better choices
ordered[before >= top_p] = 0
p = torch.zeros_like(p).scatter_(0, index, ordered)
return p / p.sum()3 · Knowing when to stop
One extra lesson teaches the model to produce an end marker after the full stop. A reply then reports why it ended: stop (the model finished) or length (it ran out of room). Given “the dog”, which it never saw, the toy never finds its end.
4 · KV cache: do not redo old work
Without a cache, every new token pushes the whole text through the model again: 276 positions for our sentence. With it, each position goes through once: 23. The cost is memory.
| New tokens | Cache off (tokens/s) | Cache on (tokens/s) | Speed-up | Cache memory |
|---|---|---|---|---|
| 50 | ~350 | ~1,240 | 3.5× | 400 KB |
| 200 | ~210 | ~1,080 | 5× | 1.6 MB |
| 500 | ~104 | ~940 | 9× | 4 MB |
5 · Batching and a server
A server accepts requests over HTTP, streams tokens back and lets several requests share each pass through the model. Sixteen users at once:
| Server | Median wait for first token | Total tokens/s |
|---|---|---|
| One request at a time | ~290 ms | ~1,090 |
| Batches of up to 16 | 70 to 160 ms | ~1,900 to 2,400 |
With one or four users, batching gave no gain. This is simple static batching: a newcomer waits for the running batch to finish.
@torch.inference_mode()
def generate_batch(model, tok, requests, use_cache=True):
"""Several requests share each pass through the model (static batching).
Prompts differ in length, so shorter ones are padded on the left and the
model is told to ignore the padding. A finished request leaves the batch;
new requests wait for the next batch.
"""
for r in requests:
r.prepare(model, tok)
device = next(model.parameters()).device
longest = max(len(r.ids) for r in requests)
grid = torch.tensor([[0] * (longest - len(r.ids)) + r.ids for r in requests], device=device)
real = torch.tensor([[False] * (longest - len(r.ids)) + [True] * len(r.ids) for r in requests], device=device)
active, cache = list(requests), None
while active:
feed = grid if cache is None else grid[:, -1:]
scores, present = model(feed, cache, real)
cache = present if use_cache else None
tokens = []
for r, row in zip(active, scores[:, -1].cpu()):
tokens.append(pick(row, r.temperature, r.top_p, r.rng))
r.accept(tokens[-1], model, tok)
keep = [i for i, r in enumerate(active) if r.finish_reason is None]
active = [active[i] for i in keep]
if not active:
break
new = torch.tensor([[tokens[i]] for i in keep], device=device)
grid = torch.cat([grid[keep], new], dim=1)
real = torch.cat([real[keep], torch.ones_like(new, dtype=torch.bool)], dim=1)
if cache is not None: # drop finished rows from the cache too
cache = [(k[keep], v[keep]) for k, v in cache]
return [r.result(tok) for r in requests]Watching it: metrics
The server also answers GET /metrics in the text format that Prometheus, a common open source monitoring tool, reads. A counter only goes up, a gauge goes up and down, and a histogram counts how many requests finished within each time limit.
| Metric | Kind | Tells you |
|---|---|---|
| Requests, by status | counter | traffic and errors |
| Tokens read and written | counter | load, and tokens per second as a rate |
| Queue length and requests running | gauge | whether the server is keeping up |
| Time to first token and full request time | histogram | how long users wait |
python server.py --max-batch 8 curl -s localhost:8000/metrics
6 · Fewer bits per weight
| Bits | Size of weights | Loss | Writes the sentence? |
|---|---|---|---|
| 32 | 86.4 KB | 0.008 | yes |
| 16 | 44.1 KB | 0.008 | yes |
| 8 | 23.0 KB | 0.008 | yes |
| 4 | 12.5 KB | 0.015 | yes |
| 3 | 9.8 KB | 0.311 | no |
| 2 | 7.2 KB | 3.115 | no |
This saves storage only; the maths still runs in 32 bits. Recalling one memorised sentence is an easy test.
7 · Where the time goes
| Work | CPU | Mac GPU |
|---|---|---|
| Reading a 256-token prompt, per token | 0.037 ms | 0.023 ms |
| Writing one token | ~1.35 ms | ~3.3 to 3.9 ms |
Attention takes the largest share. For one user and one token the GPU is slower, because the work is too small to repay the cost of sending it there.
What a real serving system adds
Continuous batching, careful management of cache memory, reuse of shared prompt beginnings, faster attention code, several GPUs, and around all of it: access keys, rate limits and safety checks. None of these is here yet.
Run it
pip install torch python train.py python engine.py python -m unittest -v test_inference.py