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”:

TemperatureChance of “␣sat”Tokens kept by top-p 0.9
0.5100%1 of 269
1.098.9%1 of 269
3.013.0%232 of 269
8.01.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 tokensCache off (tokens/s)Cache on (tokens/s)Speed-upCache memory
50~350~1,2403.5×400 KB
200~210~1,0805×1.6 MB
500~104~9409×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:

ServerMedian wait for first tokenTotal tokens/s
One request at a time~290 ms~1,090
Batches of up to 1670 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.

MetricKindTells you
Requests, by statuscountertraffic and errors
Tokens read and writtencounterload, and tokens per second as a rate
Queue length and requests runninggaugewhether the server is keeping up
Time to first token and full request timehistogramhow long users wait
python server.py --max-batch 8
curl -s localhost:8000/metrics

6 · Fewer bits per weight

BitsSize of weightsLossWrites the sentence?
3286.4 KB0.008yes
1644.1 KB0.008yes
823.0 KB0.008yes
412.5 KB0.015yes
39.8 KB0.311no
27.2 KB3.115no

This saves storage only; the maths still runs in 32 bits. Recalling one memorised sentence is an easy test.

7 · Where the time goes

WorkCPUMac GPU
Reading a 256-token prompt, per token0.037 ms0.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

Download all the files (zip)